From 63da1dd2b5fc82faa1b1a91271948b8a591858d4 Mon Sep 17 00:00:00 2001 From: shihao zhong Date: Sun, 29 Nov 2026 23:11:38 -0500 Subject: [PATCH 1/2] Fix pattern_ops sort keys under nondeterministic collations The planner treated x and x USING ~<~ as one sort key, losing merge join rows and splitting groups. Reported-by: chunling qin <303677365@qq.com> Reported-by: Zsolt Parragi Discussion: https://postgr.es/m/19873-2b5e1e0dd7b9eac0@postgresql.org Discussion: https://postgr.es/m/19869-6cb4aeabc803c3a6@postgresql.org --- src/backend/optimizer/path/pathkeys.c | 28 +++- src/backend/optimizer/plan/planner.c | 123 +++++++++++++++++- src/include/optimizer/paths.h | 2 + .../regress/expected/collate.icu.utf8.out | 117 +++++++++++++++++ src/test/regress/sql/collate.icu.utf8.sql | 41 ++++++ 5 files changed, 302 insertions(+), 9 deletions(-) diff --git a/src/backend/optimizer/path/pathkeys.c b/src/backend/optimizer/path/pathkeys.c index 50651813a11..99c1fdec3dc 100644 --- a/src/backend/optimizer/path/pathkeys.c +++ b/src/backend/optimizer/path/pathkeys.c @@ -18,6 +18,7 @@ #include "postgres.h" #include "access/stratnum.h" +#include "catalog/pg_collation.h" #include "catalog/pg_opfamily.h" #include "nodes/nodeFuncs.h" #include "optimizer/cost.h" @@ -31,7 +32,6 @@ /* Consider reordering of GROUP BY keys? */ bool enable_group_by_reordering = true; -static bool pathkey_is_redundant(PathKey *new_pathkey, List *pathkeys); static bool matches_boolean_partition_clause(RestrictInfo *rinfo, RelOptInfo *partrel, int partkeycol); @@ -155,7 +155,7 @@ append_pathkeys(List *target, List *source) * Because the equivclass.c machinery forms only one copy of any EC per query, * pointer comparison is enough to decide whether canonical ECs are the same. */ -static bool +bool pathkey_is_redundant(PathKey *new_pathkey, List *pathkeys) { EquivalenceClass *new_ec = new_pathkey->pk_eclass; @@ -177,6 +177,23 @@ pathkey_is_redundant(PathKey *new_pathkey, List *pathkeys) return false; } +/* + * is_nondet_pattern_ops + * Is this a pattern_ops opfamily used with a nondeterministic collation? + * + * The pattern_ops opfamilies sort by bytes, but their equality operator + * follows the collation. These disagree if it's nondeterministic. Like + * index_create(), we have no better way to identify those opfamilies. + */ +bool +is_nondet_pattern_ops(Oid opfamily, Oid collation) +{ + return (opfamily == TEXT_PATTERN_BTREE_FAM_OID || + opfamily == BPCHAR_PATTERN_BTREE_FAM_OID) && + OidIsValid(collation) && + !get_collation_isdeterministic(collation); +} + /* * make_pathkey_from_sortinfo * Given an expression and sort-order information, create a PathKey. @@ -231,6 +248,13 @@ make_pathkey_from_sortinfo(PlannerInfo *root, elog(ERROR, "could not find opfamilies for equality operator %u", equality_op); + /* + * A pattern_ops sort key that disagrees with its collation's equality is + * really a sort by C collation, whose equality does agree. + */ + if (is_nondet_pattern_ops(opfamily, collation)) + collation = C_COLLATION_OID; + /* Now find or (optionally) create a matching EquivalenceClass */ eclass = get_eclass_for_sort_expr(root, expr, opfamilies, opcintype, collation, diff --git a/src/backend/optimizer/plan/planner.c b/src/backend/optimizer/plan/planner.c index 568a1b2a346..aa55aa9120f 100644 --- a/src/backend/optimizer/plan/planner.c +++ b/src/backend/optimizer/plan/planner.c @@ -63,6 +63,7 @@ #include "utils/lsyscache.h" #include "utils/rel.h" #include "utils/selfuncs.h" +#include "utils/typcache.h" /* GUC parameters */ double cursor_tuple_fraction = DEFAULT_CURSOR_TUPLE_FRACTION; @@ -171,6 +172,10 @@ static double preprocess_limit(PlannerInfo *root, double tuple_fraction, int64 *offset_est, int64 *count_est); static List *preprocess_groupclause(PlannerInfo *root, List *force); +static void fix_pattern_ops_grouping(Query *parse); +static void fix_pattern_ops_sortops(List *clauses, List *tlist); +static List *get_presort_distinct_clauses(PlannerInfo *root, Aggref *aggref); +static Oid get_grouping_sortop(SortGroupClause *sgc, List *tlist); static List *extract_rollup_sets(List *groupingSets); static List *reorder_grouping_sets(List *groupingSets, List *sortclause); static void standard_qp_callback(PlannerInfo *root, void *extra); @@ -1855,6 +1860,8 @@ grouping_planner(PlannerInfo *root, double tuple_fraction, /* A recursive query should always have setOperations */ Assert(!root->hasRecursion); + fix_pattern_ops_grouping(parse); + /* Preprocess grouping sets and GROUP BY clause, if any */ if (parse->groupingSets) { @@ -3105,6 +3112,105 @@ limit_needed(Query *parse) return false; /* don't need a Limit plan node */ } +/* + * fix_pattern_ops_grouping + * Don't group by a pattern_ops ordering under a nondeterministic collation. + * + * The parser copies ORDER BY operators into GROUP BY, DISTINCT and PARTITION + * BY items. Grouping sorts by the sort operator and compares neighbors with + * the equality operator, but is_nondet_pattern_ops() orderings sort apart + * values that are equal. Use the default ordering for those instead. + */ +static void +fix_pattern_ops_grouping(Query *parse) +{ + fix_pattern_ops_sortops(parse->groupClause, parse->targetList); + fix_pattern_ops_sortops(parse->distinctClause, parse->targetList); + foreach_node(WindowClause, wc, parse->windowClause) + fix_pattern_ops_sortops(wc->partitionClause, parse->targetList); +} + +/* + * fix_pattern_ops_sortops + * Subroutine for fix_pattern_ops_grouping, for one list of clauses. + */ +static void +fix_pattern_ops_sortops(List *clauses, List *tlist) +{ + foreach_node(SortGroupClause, sgc, clauses) + sgc->sortop = get_grouping_sortop(sgc, tlist); +} + +/* + * get_presort_distinct_clauses + * Get the items of the Aggref's DISTINCT list that presorting must sort by. + * + * This leaves out any pattern_ops item whose default ordering is redundant, + * given GROUP BY and the preceding items. Sorting by it would only separate + * values that are equal. + */ +static List * +get_presort_distinct_clauses(PlannerInfo *root, Aggref *aggref) +{ + List *result = NIL; + + foreach_node(SortGroupClause, sgc, aggref->aggdistinct) + { + Oid sortop = get_grouping_sortop(sgc, aggref->args); + + if (sortop != sgc->sortop) + { + SortGroupClause *newsgc = copyObject(sgc); + List *newkeys; + List *oldkeys; + + newsgc->sortop = sortop; + newkeys = make_pathkeys_for_sortclauses(root, list_make1(newsgc), + aggref->args); + oldkeys = make_pathkeys_for_sortclauses(root, result, + aggref->args); + if (newkeys == NIL || + pathkey_is_redundant(linitial(newkeys), root->group_pathkeys) || + pathkey_is_redundant(linitial(newkeys), oldkeys)) + continue; + } + result = lappend(result, sgc); + } + return result; +} + +/* + * get_grouping_sortop + * Get the sort operator to use when grouping by the given clause. + * + * This is the clause's own operator, unless that is a pattern_ops operator + * that mustn't be used for grouping. + */ +static Oid +get_grouping_sortop(SortGroupClause *sgc, List *tlist) +{ + Oid collation = exprCollation(get_sortgroupclause_expr(sgc, tlist)); + Oid opfamily; + Oid opcintype; + CompareType cmptype; + TypeCacheEntry *typentry; + + /* Avoid the pg_amop lookup in the usual case */ + if (!OidIsValid(collation) || + get_collation_isdeterministic(collation)) + return sgc->sortop; + + if (!OidIsValid(sgc->sortop) || + !get_ordering_op_properties(sgc->sortop, + &opfamily, &opcintype, &cmptype) || + !is_nondet_pattern_ops(opfamily, collation)) + return sgc->sortop; + + typentry = lookup_type_cache(opcintype, + TYPECACHE_LT_OPR | TYPECACHE_GT_OPR); + return (cmptype == COMPARE_GT) ? typentry->gt_opr : typentry->lt_opr; +} + /* * preprocess_groupclause - do preparatory work on GROUP BY clause * @@ -3645,7 +3751,7 @@ adjust_group_pathkeys_for_groupagg(PlannerInfo *root) List *pathkeys; if (aggref->aggdistinct != NIL) - sortlist = aggref->aggdistinct; + sortlist = get_presort_distinct_clauses(root, aggref); else sortlist = aggref->aggorder; @@ -3934,7 +4040,8 @@ standard_qp_callback(PlannerInfo *root, void *extra) * that might just leave us failing to exploit an available sort order at * all. Needs more thought. The choice for DISTINCT versus ORDER BY is * much easier, since we know that the parser ensured that one is a - * superset of the other. + * superset of the other. (fix_pattern_ops_grouping may have changed + * that, but this is only a hint, so it's fine to choose either.) */ if (root->group_pathkeys) root->query_pathkeys = root->group_pathkeys; @@ -5405,18 +5512,20 @@ create_final_distinct_paths(PlannerInfo *root, RelOptInfo *input_rel, * Also, if we do have to do an explicit sort, we might as well use * the more rigorous ordering to avoid a second sort later. (Note * that the parser will have ensured that one clause is a prefix of - * the other.) + * the other. fix_pattern_ops_grouping may have changed that, so sort + * by the DISTINCT keys followed by any other ORDER BY keys.) */ List *needed_pathkeys; ListCell *lc; double limittuples = root->distinct_pathkeys == NIL ? 1.0 : -1.0; - if (parse->hasDistinctOn && - list_length(root->distinct_pathkeys) < - list_length(root->sort_pathkeys)) + if (!parse->hasDistinctOn) + needed_pathkeys = root->distinct_pathkeys; + else if (root->distinct_pathkeys == NIL) needed_pathkeys = root->sort_pathkeys; else - needed_pathkeys = root->distinct_pathkeys; + needed_pathkeys = append_pathkeys(list_copy(root->distinct_pathkeys), + root->sort_pathkeys); foreach(lc, input_rel->pathlist) { diff --git a/src/include/optimizer/paths.h b/src/include/optimizer/paths.h index 64f87da1674..5a805134c71 100644 --- a/src/include/optimizer/paths.h +++ b/src/include/optimizer/paths.h @@ -223,6 +223,8 @@ typedef enum PATHKEYS_DIFFERENT, /* neither pathkey includes the other */ } PathKeysComparison; +extern bool pathkey_is_redundant(PathKey *new_pathkey, List *pathkeys); +extern bool is_nondet_pattern_ops(Oid opfamily, Oid collation); extern PathKeysComparison compare_pathkeys(List *keys1, List *keys2); extern bool pathkeys_contained_in(List *keys1, List *keys2); extern bool pathkeys_count_contained_in(List *keys1, List *keys2, int *n_common); diff --git a/src/test/regress/expected/collate.icu.utf8.out b/src/test/regress/expected/collate.icu.utf8.out index 636f0dfefc3..4fd557e583a 100644 --- a/src/test/regress/expected/collate.icu.utf8.out +++ b/src/test/regress/expected/collate.icu.utf8.out @@ -3985,6 +3985,123 @@ SELECT count(*) FROM (SELECT NULLIF(a, NULL::text COLLATE case_insensitive) FROM (1 row) DROP TABLE simplify_collation_t; +-- sort keys using ~<~ must not be merged with "=" or other sort keys +SELECT f1 FROM outer_text ORDER BY f1 USING <, f1 USING ~<~; + f1 +---- + A + a + B + b +(4 rows) + +SELECT f1 FROM outer_text WHERE f1 = 'a' ORDER BY f1 USING ~<~; + f1 +---- + A + a +(2 rows) + +SET enable_hashjoin = off; +SET enable_nestloop = off; +SELECT count(*) FROM (SELECT t1.f1 FROM outer_text t1 + JOIN outer_text t2 ON t1.f1 = t2.f1 ORDER BY t1.f1 USING ~<~) s; + count +------- + 8 +(1 row) + +RESET enable_hashjoin; +RESET enable_nestloop; +-- an incremental sort must not treat "A" and "a" as one presorted group +SET enable_sort = off; +SELECT f1 FROM (SELECT f1 FROM outer_text, generate_series(1, 100) + WHERE f1 < 'b' ORDER BY f1 USING ~<~ OFFSET 0) s + ORDER BY f1 USING ~<~, f1 USING <, f1 COLLATE "C" = 'A' LIMIT 1; + f1 +---- + A +(1 row) + +RESET enable_sort; +-- grouping must not take ~<~ from ORDER BY +SET enable_hashagg = off; +SELECT count(*) FROM (SELECT f1::char(1) FROM outer_text + GROUP BY 1 ORDER BY 1 USING ~>~) s; + count +------- + 2 +(1 row) + +SELECT count(*) FROM (SELECT DISTINCT f1 FROM outer_text + ORDER BY f1 USING ~<~) s; + count +------- + 2 +(1 row) + +RESET enable_hashagg; +SELECT f1, count(*) OVER (PARTITION BY f1 ORDER BY f1 USING ~<~ + ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) + FROM outer_text ORDER BY f1 USING ~<~; + f1 | count +----+------- + A | 2 + B | 2 + a | 2 + b | 2 +(4 rows) + +-- DISTINCT ON must not either, but must still choose rows by ORDER BY +SELECT DISTINCT ON (f1) f1 FROM outer_text ORDER BY f1 USING ~<~; + f1 +---- + A + B +(2 rows) + +SELECT DISTINCT ON (f1, y) f1, y FROM outer_text, generate_series(1, 2) y + ORDER BY f1 USING <, f1 USING ~<~, y; + f1 | y +----+--- + A | 1 + A | 2 + B | 1 + B | 2 +(4 rows) + +-- presorting for DISTINCT must not use a ~<~ key that "=" makes redundant +SELECT length(string_agg(DISTINCT f1, y::text ORDER BY f1 USING <, f1 USING ~<~, y::text)) + FROM outer_text, generate_series(1, 2) y; + length +-------- + 7 +(1 row) + +SELECT length(string_agg(DISTINCT f1, y::text ORDER BY f1 USING ~<~, y::text)) + FROM outer_text, generate_series(1, 2) y WHERE f1 = 'a'; + length +-------- + 3 +(1 row) + +SELECT length(string_agg(DISTINCT f1, y::text ORDER BY f1 USING ~<~, y::text)) + FROM outer_text, generate_series(1, 2) y GROUP BY f1; + length +-------- + 3 + 3 +(2 rows) + +-- but the aggregate's own sort must use it +SELECT string_agg(DISTINCT f1, y::text ORDER BY f1 USING ~<~, y::text) + FILTER (WHERE (f1 COLLATE "C", y) IN (('a', 1), ('A', 2))) + FROM outer_text, generate_series(1, 2) y WHERE f1 = 'a'; + string_agg +------------ + A1a +(1 row) + -- virtual generated columns CREATE TABLE t5 ( a int, diff --git a/src/test/regress/sql/collate.icu.utf8.sql b/src/test/regress/sql/collate.icu.utf8.sql index b2d6f7d64ca..759a078149e 100644 --- a/src/test/regress/sql/collate.icu.utf8.sql +++ b/src/test/regress/sql/collate.icu.utf8.sql @@ -1571,6 +1571,47 @@ SELECT count(*) FROM (SELECT NULLIF(a, NULL::text COLLATE case_insensitive) FROM DROP TABLE simplify_collation_t; +-- sort keys using ~<~ must not be merged with "=" or other sort keys +SELECT f1 FROM outer_text ORDER BY f1 USING <, f1 USING ~<~; +SELECT f1 FROM outer_text WHERE f1 = 'a' ORDER BY f1 USING ~<~; +SET enable_hashjoin = off; +SET enable_nestloop = off; +SELECT count(*) FROM (SELECT t1.f1 FROM outer_text t1 + JOIN outer_text t2 ON t1.f1 = t2.f1 ORDER BY t1.f1 USING ~<~) s; +RESET enable_hashjoin; +RESET enable_nestloop; +-- an incremental sort must not treat "A" and "a" as one presorted group +SET enable_sort = off; +SELECT f1 FROM (SELECT f1 FROM outer_text, generate_series(1, 100) + WHERE f1 < 'b' ORDER BY f1 USING ~<~ OFFSET 0) s + ORDER BY f1 USING ~<~, f1 USING <, f1 COLLATE "C" = 'A' LIMIT 1; +RESET enable_sort; +-- grouping must not take ~<~ from ORDER BY +SET enable_hashagg = off; +SELECT count(*) FROM (SELECT f1::char(1) FROM outer_text + GROUP BY 1 ORDER BY 1 USING ~>~) s; +SELECT count(*) FROM (SELECT DISTINCT f1 FROM outer_text + ORDER BY f1 USING ~<~) s; +RESET enable_hashagg; +SELECT f1, count(*) OVER (PARTITION BY f1 ORDER BY f1 USING ~<~ + ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) + FROM outer_text ORDER BY f1 USING ~<~; +-- DISTINCT ON must not either, but must still choose rows by ORDER BY +SELECT DISTINCT ON (f1) f1 FROM outer_text ORDER BY f1 USING ~<~; +SELECT DISTINCT ON (f1, y) f1, y FROM outer_text, generate_series(1, 2) y + ORDER BY f1 USING <, f1 USING ~<~, y; +-- presorting for DISTINCT must not use a ~<~ key that "=" makes redundant +SELECT length(string_agg(DISTINCT f1, y::text ORDER BY f1 USING <, f1 USING ~<~, y::text)) + FROM outer_text, generate_series(1, 2) y; +SELECT length(string_agg(DISTINCT f1, y::text ORDER BY f1 USING ~<~, y::text)) + FROM outer_text, generate_series(1, 2) y WHERE f1 = 'a'; +SELECT length(string_agg(DISTINCT f1, y::text ORDER BY f1 USING ~<~, y::text)) + FROM outer_text, generate_series(1, 2) y GROUP BY f1; +-- but the aggregate's own sort must use it +SELECT string_agg(DISTINCT f1, y::text ORDER BY f1 USING ~<~, y::text) + FILTER (WHERE (f1 COLLATE "C", y) IN (('a', 1), ('A', 2))) + FROM outer_text, generate_series(1, 2) y WHERE f1 = 'a'; + -- virtual generated columns CREATE TABLE t5 ( a int, -- 2.37.1 (Apple Git-137.1)