Changeset: 763548c30bdd for MonetDB
URL: https://dev.monetdb.org/hg/MonetDB/rev/763548c30bdd
Added Files:
        sql/test/BugTracker-2026/Tests/8123-row-number-limit-pushdown.test
Modified Files:
        sql/server/rel_optimize_others.c
        sql/server/rel_statistics.c
        sql/server/rel_statistics.h
        sql/server/rel_statistics_functions.c
        sql/storage/bat/bat_storage.c
        sql/test/BugTracker-2026/Tests/8066-semijoin-reducing-nested-select.test
        sql/test/BugTracker-2026/Tests/All
Branch: default
Log Message:

fixes for issue #8123. ie keep property that row_number will be unique (if 
there is no partition argument).


diffs (truncated from 331 to 300 lines):

diff --git a/sql/server/rel_optimize_others.c b/sql/server/rel_optimize_others.c
--- a/sql/server/rel_optimize_others.c
+++ b/sql/server/rel_optimize_others.c
@@ -14,6 +14,7 @@
 #include "rel_optimizer.h"
 #include "rel_exp.h"
 #include "rel_select.h"
+#include "rel_statistics.h"
 
 static void
 rel_no_rename_exps( list *exps )
@@ -1231,6 +1232,48 @@ sum_limit_offset(mvc *sql, sql_rel *rel)
        return list_append(sa_list(sql->sa), add);
 }
 
+/* A row_number() without PARTITION BY/ORDER BY does not impose an ordering on
+ * the projection.  Early function-statistics propagation marks it unique; a
+ * plain LIMIT can then be moved below the project and the window function is
+ * evaluated on the limited result. */
+static bool
+topn_safe_analytic_exp(sql_exp *e)
+{
+       list *args;
+       sql_subfunc *f;
+
+       if (e->type != e_func || !is_analytic(e) || !is_unique(e) || !(f = 
e->f) ||
+               !f->func || strcmp(f->func->base.name, "row_number") != 0)
+               return false;
+       args = e->l;
+       return args && list_length(args) >= 3 &&
+                  exp_is_false(list_fetch(args, 1)) &&
+                  exp_is_false(list_fetch(args, 2));
+}
+
+static bool
+topn_safe_project(sql_rel *rel, bool topn)
+{
+       sql_rel *sub = rel->l;
+       node *n;
+
+       if (need_distinct(rel) || !list_empty(rel->r))
+               return false;
+       if (list_empty(rel->exps))
+               return true;
+       if (!sub || sub->op == op_ddl)
+               return false;
+       for (n = rel->exps->h; n; n = n->next) {
+               sql_exp *e = n->data;
+
+               if (exp_unsafe(e, 1, false) && !(topn && 
topn_safe_analytic_exp(e)))
+                       return false;
+               if (is_selfref(e))
+                       return false;
+       }
+       return true;
+}
+
 /*
  * Push TopN (only LIMIT, no ORDER BY) down through projections underneath 
crossproduct, i.e.,
  *
@@ -1327,11 +1370,11 @@ rel_push_topn_and_sample_down_(visitor *
                        }
                }
 
-               if (r && is_simple_project(r->op) && (need_distinct(r) || 
project_unsafe(r, 1)))
+               if (r && is_simple_project(r->op) && !topn_safe_project(r, 
is_topn(rel->op)))
                        return rel;
 
                /* push topn/sample under projections */
-               if (!rel_is_ref(rel) && r && is_simple_project(r->op) && 
!need_distinct(r) && !rel_is_ref(r) && r->l && list_empty(r->r)) {
+               if (!rel_is_ref(rel) && r && is_simple_project(r->op) && 
!rel_is_ref(r) && r->l) {
                        sql_rel *x = r, *px = x;
 
                        while (is_simple_project(x->op) && !need_distinct(x) && 
!rel_is_ref(x) && x->l && list_empty(x->r)) {
@@ -1551,6 +1594,10 @@ static sql_rel *
 rel_push_topn_and_sample_down(visitor *v, global_props *gp, sql_rel *rel)
 {
        (void) gp;
+       /* Function properties needed by the pushdown (row_number() uniqueness)
+        * are normally propagated only post-optimization; run that small part
+        * here so the decision can use it. */
+       rel = rel_propagate_function_uniqueness(v, rel);
        return rel_visitor_topdown(v, rel, &rel_push_topn_and_sample_down_);
 }
 
diff --git a/sql/server/rel_statistics.c b/sql/server/rel_statistics.c
--- a/sql/server/rel_statistics.c
+++ b/sql/server/rel_statistics.c
@@ -593,6 +593,34 @@ rel_propagate_statistics(visitor *v, sql
        return e;
 }
 
+static sql_exp *
+rel_propagate_function_uniqueness_exp(visitor *v, sql_rel *rel, sql_exp *e, 
int depth)
+{
+       (void) rel;
+       (void) depth;
+       sql_propagate_function_uniqueness(v->sql, e);
+       return e;
+}
+
+static sql_rel *
+rel_propagate_function_uniqueness_(visitor *v, sql_rel *rel)
+{
+       if (!list_empty(rel->exps))
+               rel->exps = exps_exp_visitor_bottomup(v, rel, rel->exps, 0,
+                       &rel_propagate_function_uniqueness_exp, false);
+       if ((is_simple_project(rel->op) || is_groupby(rel->op)) && 
!list_empty(rel->r))
+               rel->r = exps_exp_visitor_bottomup(v, rel, rel->r, 0,
+                       &rel_propagate_function_uniqueness_exp, false);
+       return rel;
+}
+
+/* Run before the topn optimizer: function properties, later generalize by 
introduction of static function properties */
+sql_rel *
+rel_propagate_function_uniqueness(visitor *v, sql_rel *rel)
+{
+       return rel_visitor_bottomup(v, rel, 
&rel_propagate_function_uniqueness_);
+}
+
 static list * /* Remove predicates always false from min/max values */
 rel_prune_predicates(visitor *v, sql_rel *rel)
 {
diff --git a/sql/server/rel_statistics.h b/sql/server/rel_statistics.h
--- a/sql/server/rel_statistics.h
+++ b/sql/server/rel_statistics.h
@@ -93,7 +93,9 @@ set_minmax_property(mvc *sql, sql_exp *e
 
 extern sql_hash *sql_functions_lookup ATTR_VISIBILITY_HIDDEN;
 extern void initialize_sql_functions_lookup(allocator *sa) 
ATTR_VISIBILITY_HIDDEN;
+extern void sql_propagate_function_uniqueness(mvc *sql, sql_exp *e) 
ATTR_VISIBILITY_HIDDEN;
 extern sql_rel * rel_get_statistics_(visitor *v, sql_rel *rel);
 extern sql_exp * rel_propagate_statistics(visitor *v, sql_rel *rel, sql_exp 
*e, int depth);
+extern sql_rel * rel_propagate_function_uniqueness(visitor *v, sql_rel *rel) 
ATTR_VISIBILITY_HIDDEN;
 
 #endif /*_REL_STATISTICS_H_*/
diff --git a/sql/server/rel_statistics_functions.c 
b/sql/server/rel_statistics_functions.c
--- a/sql/server/rel_statistics_functions.c
+++ b/sql/server/rel_statistics_functions.c
@@ -933,7 +933,36 @@ sql_rank_propagate_statistics(mvc *sql, 
        }
 }
 
-static struct function_properties functions_list[40] = {
+static void
+sql_row_number_propagate_statistics(mvc *sql, sql_exp *e)
+{
+       list *args = e->l;
+
+       (void)sql;
+       /* row_number() is only globally unique without PARTITION BY.  The
+        * second and third arguments are the partition/order "diff" chains;
+        * both are the false atom for OVER (). */
+       if (args && list_length(args) >= 3 &&
+               exp_is_false(list_fetch(args, 1)) &&
+               exp_is_false(list_fetch(args, 2)))
+               e->unique = true;
+}
+
+void
+sql_propagate_function_uniqueness(mvc *sql, sql_exp *e)
+{
+       sql_subfunc *f;
+
+       if (!e || (e->type != e_func && e->type != e_aggr) || !(f = e->f) ||
+               !f->func || f->func->s)
+               return;
+       /* Only function properties that hold without any column statistics are
+        * propagated this early.  Add new cases here with care. */
+       if (strcmp(f->func->base.name, "row_number") == 0)
+               sql_row_number_propagate_statistics(sql, e);
+}
+
+static struct function_properties functions_list[] = {
        /* arithmetic functions */
        {"sql_add", &sql_add_propagate_statistics},
        {"sql_sub", &sql_sub_propagate_statistics},
@@ -982,7 +1011,8 @@ static struct function_properties functi
 
        /* window functions */
        {"rank", &sql_rank_propagate_statistics},
-       {"dense_rank", &sql_rank_propagate_statistics}
+       {"dense_rank", &sql_rank_propagate_statistics},
+       {"row_number", &sql_row_number_propagate_statistics},
 };
 
 void
diff --git a/sql/storage/bat/bat_storage.c b/sql/storage/bat/bat_storage.c
--- a/sql/storage/bat/bat_storage.c
+++ b/sql/storage/bat/bat_storage.c
@@ -2398,6 +2398,7 @@ static int
 append_col_execute(sql_trans *tr, sql_delta **delta, sql_column *c, BUN 
offset, BAT *offsets, void *incoming_data, BUN cnt, bool isbat, int tt, char 
*storage_type)
 {
        int ok = LOG_OK;
+       sql_delta *obat = *delta;
 
        if ((*delta)->cs.merged)
                (*delta)->cs.merged = false; /* TODO needs to move */
@@ -2410,6 +2411,10 @@ append_col_execute(sql_trans *tr, sql_de
        } else {
                ok = delta_append_val(tr, delta, offset, offsets, 
incoming_data, cnt, storage_type, tt);
        }
+       if (obat != *delta) {
+               (*delta)->next = obat;
+               c->data = *delta;
+       }
        unlock_column(tr->store, c);
        return ok;
 }
@@ -2442,6 +2447,7 @@ static int
 append_idx_execute(sql_trans *tr, sql_delta **delta, sql_idx *c, BUN offset, 
BAT *offsets, void *incoming_data, BUN cnt, bool isbat, int tt, char 
*storage_type)
 {
        int ok = LOG_OK;
+       sql_delta *obat = *delta;
 
        if ((*delta)->cs.merged)
                (*delta)->cs.merged = false; /* TODO needs to move */
@@ -2454,6 +2460,10 @@ append_idx_execute(sql_trans *tr, sql_de
        } else {
                ok = delta_append_val(tr, delta, offset, offsets, 
incoming_data, cnt, storage_type, tt);
        }
+       if (obat != *delta) {
+               (*delta)->next = obat;
+               c->data = *delta;
+       }
        unlock_idx(tr->store, c);
        return ok;
 }
diff --git 
a/sql/test/BugTracker-2026/Tests/8066-semijoin-reducing-nested-select.test 
b/sql/test/BugTracker-2026/Tests/8066-semijoin-reducing-nested-select.test
--- a/sql/test/BugTracker-2026/Tests/8066-semijoin-reducing-nested-select.test
+++ b/sql/test/BugTracker-2026/Tests/8066-semijoin-reducing-nested-select.test
@@ -83,6 +83,24 @@ project (
 | ) [  ] [ "sys"."count"() as "%1"."%1" ]
 ) [ "%1"."%1" ]
 
+skipif pipeline
+query T nosort
+EXPLAIN SELECT COUNT(*) FROM s8066b s JOIN (SELECT * FROM b8066b WHERE low_key 
< 10) b ON s.id = b.skey JOIN a8066b a ON b.low_key = a.low_key JOIN c8066b c 
ON b.id = c.id
+----
+project (
+| group by (
+| | join (
+| | | semijoin (
+| | | | table("sys"."su8066b") [ "su8066b"."id", "su8066b"."fk" ],
+| | | | table("sys"."ps8066b") [ "ps8066b"."id" ]
+| | | ) [ ("su8066b"."id") = ("ps8066b"."id") ],
+| | | select (
+| | | | table("sys"."na8066b") [ "na8066b"."id" ]
+| | | ) [ ("na8066b"."id") < (int(4) "5") ]
+| | ) [ ("su8066b"."fk") = ("na8066b"."id") ]
+| ) [  ] [ "sys"."count"() as "%1"."%1" ]
+) [ "%1"."%1" ]
+
 query I
 SELECT COUNT(*) FROM s8066b s JOIN (SELECT * FROM b8066b WHERE low_key < 10) b 
ON s.id = b.skey JOIN a8066b a ON b.low_key = a.low_key JOIN c8066b c ON b.id = 
c.id
 ----
@@ -90,6 +108,7 @@ SELECT COUNT(*) FROM s8066b s JOIN (SELE
 
 # a semijoin must not be pushed below a join whose other side is reducing,
 # otherwise the push-up rule undoes the rewrite forever (TPCH q20)
+onlyif pipeline
 query T nosort
 EXPLAIN SELECT COUNT(*) FROM su8066b JOIN (SELECT * FROM na8066b WHERE id < 5) 
n ON su8066b.fk = n.id JOIN ps8066b ON su8066b.id = ps8066b.id
 ----
diff --git a/sql/test/BugTracker-2026/Tests/8123-row-number-limit-pushdown.test 
b/sql/test/BugTracker-2026/Tests/8123-row-number-limit-pushdown.test
new file mode 100644
--- /dev/null
+++ b/sql/test/BugTracker-2026/Tests/8123-row-number-limit-pushdown.test
@@ -0,0 +1,51 @@
+statement ok
+CREATE TABLE t8123 (payload VARCHAR(40) NOT NULL)
+
+statement ok rowcount 9
+INSERT INTO t8123
+SELECT CAST('same-payload-for-every-row-0000000000' AS VARCHAR(40))
+FROM sys.generate_series(1, 10)
+
+# row_number() OVER () does not impose an ordering, so the LIMIT must be
+# applied before the (expensive) projection expressions are evaluated.
+query T
+explain
+SELECT sys.md5(payload) AS digest, row_number() OVER () AS row_num
+FROM t8123 LIMIT 1
+----
+project (
+| top N (
+| | table("sys"."t8123") [ "t8123"."payload" ]
+| ) [ bigint(63) "1" ]
+) [ "sys"."md5"("t8123"."payload") as "digest", 
"sys"."row_number"(varchar["sys"."star"()], boolean(1) "false", boolean(1) 
"false") as "row_num" ]
+
+query TT
+SELECT sys.md5(payload) AS digest, row_number() OVER () AS row_num
+FROM t8123 LIMIT 1
+----
+fd94f3d4b63a819e265e2ad7be1586ba       1
+
+query III
+SELECT count(*), min(row_num), max(row_num)
+FROM (SELECT row_number() OVER () AS row_num FROM t8123 LIMIT 3) q
+----
_______________________________________________
checkin-list mailing list -- [email protected]
To unsubscribe send an email to [email protected]

Reply via email to