From 5131c4485b7e94f1e2bef6ac1b83e8287f12ab18 Mon Sep 17 00:00:00 2001 From: Richard Guo Date: Tue, 17 Nov 2026 14:44:10 +0900 Subject: [PATCH v6 4/8] Teach UniqueKeys about outer joins So far a join relation could be proven distinct only if it involved no outer joins. This commit removes that restriction for left and full joins, both for detecting unique inner sides of joins and for skipping DISTINCT and GROUP BY steps. UniqueKeys continue to describe the rows that a base relation really has. A null-extended row is treated as one more possible row of the relation, so the existing procedure applies as it stands, with three additions. An expression that is nulled by outer joins is looked up by the EquivalenceClass of its un-nulled form, provided it is certain to be NULL when its relation is null-extended. A left join emits either the matching right-hand rows or a null-extended row for each left-hand row, so the right-hand EquivalenceClasses of its mergejoinable clauses are treated as fixed from the start, and as non-NULL in the matching rows. A full join emits null-extended rows for both of its sides, so its clauses are not used, and a relation that it nulls must also have a member in one of the fixed EquivalenceClasses, which must be a column that cannot be NULL when NULLs are considered equal. See src/backend/optimizer/README for the reasoning and examples. Join relations that involve semijoins or antijoins are still not handled. --- src/backend/optimizer/README | 72 +++- src/backend/optimizer/path/uniquekeys.c | 434 ++++++++++++++++++++--- src/backend/optimizer/util/relnode.c | 2 + src/include/nodes/pathnodes.h | 8 +- src/test/regress/expected/uniquekeys.out | 328 +++++++++++++++++ src/test/regress/sql/uniquekeys.sql | 82 +++++ 6 files changed, 881 insertions(+), 45 deletions(-) diff --git a/src/backend/optimizer/README b/src/backend/optimizer/README index a07aebf2262..728620bdb08 100644 --- a/src/backend/optimizer/README +++ b/src/backend/optimizer/README @@ -1047,9 +1047,9 @@ so that a query that never needs them does not pay for them. UniqueKeys are used to detect unique inner sides of joins when the inner side is itself a join, and to skip DISTINCT and GROUP BY steps whose input -is already distinct. The following describes each of these in turn. For -now only plain tables get UniqueKeys, and only joins that involve no outer -joins, semijoins or antijoins are handled. +is already distinct. The following describes each of these in turn, and +then how outer joins fit in. For now only plain tables get UniqueKeys, and +only joins that involve no semijoins or antijoins are handled. We do not keep UniqueKeys for join relations. A join relation would typically have many of them, most of which would never be used. And since @@ -1108,6 +1108,72 @@ no GROUP BY. Window functions neither add nor remove rows, so their output is distinct if the relation below them is distinct for the DISTINCT columns (see is_redundant_distinct). +Outer joins fit into this as follows. UniqueKeys always describe the rows +that a base relation really has, and their ECs are those of the relation's +columns as they are when it is scanned. In the output of a join relation +that includes outer joins, a base relation can also be represented by a +null-extended row. We regard that as one more possible row of the +relation, so that the procedure above still shows that only one combination +is possible. This takes three additions. + +1. Nulled expressions. A question can be about an expression that is +nulled by outer joins, such as b.y in + + SELECT DISTINCT a.id, b.y FROM a LEFT JOIN b ON a.x = b.z + +which is in a different EC than the un-nulled b.y that a UniqueKey would +use. We start with the EC of the un-nulled expression instead, creating it +if there is none. That is valid because the two are equal wherever the +nulled one is not NULL. It is done only for expressions that are certain +to be NULL when their relation is null-extended, which rules out something +like COALESCE(b.y, 0). + +2. Left joins. For a given left-hand row, a left join emits either the +right-hand rows that satisfy its clauses or a single null-extended row, +never both. So every matching right-hand row has the same values in the +right-hand ECs of the join's mergejoinable clauses, and we treat those ECs +as fixed from the start. In + + SELECT ... FROM a LEFT JOIN b ON a.x = b.id + +with a unique index on b.id, a row of a leaves one row of b or the +null-extended row. + +Those clauses are assumed to be strict too, so the right-hand rows that +match are not NULL in those ECs. When NULLs are considered equal, a +UniqueKey that is not marked null_aware can therefore still be used if its +ECs are among them: it holds for the matching rows, and the null-extended +row is the only other possibility. + +3. Full joins. A full join emits null-extended rows for both of its sides, +so none of that holds, and its clauses are not used. Moreover, showing +that a relation has at most one row is not enough: the join's output can +contain both that row and a null-extended row for the relation, and fixing +the other relations does not tell us which one we get. In + + SELECT ... FROM c LEFT JOIN + ((SELECT * FROM a WHERE id = 1) a FULL JOIN + (SELECT * FROM b WHERE id = 1) b ON a.x = b.x) + ON c.x = COALESCE(a.y, b.y) + +a and b have at most one row each, yet the full join can emit both a's row +with b null-extended and b's row with a null-extended, and both can match +the same row of c. So for a relation that is nulled by a full join we +require that one of the fixed ECs have a member of the relation. A join +clause on that member is not satisfied by a null-extended row. + +When NULLs are considered equal, that is still not enough, because a +null-extended row looks the same as a row of the relation's own that is +NULL in all the columns in question. In + + SELECT DISTINCT a.v, b.v FROM a FULL JOIN b ON a.x = b.w + +an unmatched row of a whose a.v is NULL yields (NULL, NULL), and so does an +unmatched row of b whose b.v is NULL. So the required EC must then have a +column of the relation that cannot be NULL, due to a NOT NULL constraint or +a strict restriction clause. Such a column is NULL in the join's output +only when the relation is null-extended, which tells the two cases apart. + Order of processing for EquivalenceClasses and PathKeys ------------------------------------------------------- diff --git a/src/backend/optimizer/path/uniquekeys.c b/src/backend/optimizer/path/uniquekeys.c index 4ef18c1b82a..1ec7b469dd2 100644 --- a/src/backend/optimizer/path/uniquekeys.c +++ b/src/backend/optimizer/path/uniquekeys.c @@ -15,6 +15,12 @@ * hand, consider NULLs equal to each other, so for them only UniqueKeys that * hold on those terms can be used. * + * UniqueKeys always describe the rows that a base relation really has, and + * the ECs in them are those of the relation's columns as they are when it is + * scanned. A join relation that includes outer joins can also emit + * null-extended rows for its base relations; joinrel_is_distinct_for_ecs() + * explains how that is dealt with. + * * See src/backend/optimizer/README for more information. * * @@ -30,24 +36,39 @@ #include "access/sysattr.h" #include "nodes/multibitmapset.h" #include "optimizer/clauses.h" +#include "optimizer/optimizer.h" #include "optimizer/pathnode.h" #include "optimizer/paths.h" +#include "rewrite/rewriteManip.h" #include "utils/lsyscache.h" static bool joinrel_is_distinct_for_ecs(PlannerInfo *root, RelOptInfo *joinrel, Bitmapset *known_ecs, bool nulls_equal); -static Bitmapset *get_joined_ecs(PlannerInfo *root, RelOptInfo *joinrel); +static Bitmapset *get_left_join_ecs(PlannerInfo *root, RelOptInfo *joinrel); +static Bitmapset *get_joined_ecs(PlannerInfo *root, RelOptInfo *joinrel, + Bitmapset *left_join_ecs); static void build_base_rel_uniquekeys(PlannerInfo *root); +static void build_base_eclasses(PlannerInfo *root); static void build_plain_rel_uniquekeys(PlannerInfo *root, RelOptInfo *rel); +static void build_notnull_eclass_indexes(PlannerInfo *root, RelOptInfo *rel); static void add_uniquekey(RelOptInfo *rel, Bitmapset *eclass_indexes, bool null_aware); static int find_ec_index(PlannerInfo *root, RelOptInfo *rel, Expr *expr, List *opfamilies, Oid collation); +static Bitmapset *add_base_ec_index(PlannerInfo *root, + Bitmapset *eclass_indexes, + EquivalenceClass *ec); +static Expr *get_base_expr(PlannerInfo *root, Expr *expr, RelOptInfo **rel); static bool rel_has_uniquekey_in(PlannerInfo *root, RelOptInfo *rel, Bitmapset *eclass_indexes, Bitmapset *joined_ecs, bool nulls_equal); +static bool full_nullable_rel_is_marked(PlannerInfo *root, RelOptInfo *rel, + Bitmapset *eclass_indexes, + bool nulls_equal); +static bool rel_has_notnull_column_in(PlannerInfo *root, RelOptInfo *rel, + Bitmapset *eclass_indexes); static Bitmapset *get_own_eclass_indexes(PlannerInfo *root, RelOptInfo *rel); @@ -67,14 +88,6 @@ joinrel_supports_distinctness(PlannerInfo *root, RelOptInfo *joinrel) if (IS_GROUPED_REL(joinrel)) return false; - /* - * We don't handle join rels that include outer joins. A left join pushed - * down per outer-join identity 3 is missed here, which is harmless since - * its clauses are in no EC. - */ - if (bms_overlap(joinrel->relids, root->outer_join_rels)) - return false; - build_base_rel_uniquekeys(root); /* Every base rel in the join must have a UniqueKey */ @@ -103,18 +116,11 @@ joinrel_is_distinct_for(PlannerInfo *root, RelOptInfo *joinrel, foreach_node(RestrictInfo, rinfo, clause_list) { - EquivalenceClass *ec; - /* caller identified the side belonging to this relation for us */ - ec = rinfo->outer_is_left ? rinfo->right_ec : rinfo->left_ec; - if (ec == NULL) - continue; - - /* the cached EC might be non-canonical, so chase up to the top */ - while (ec->ec_merged) - ec = ec->ec_merged; - - known_ecs = bms_add_member(known_ecs, ec->ec_index); + if (rinfo->outer_is_left) + known_ecs = add_base_ec_index(root, known_ecs, rinfo->right_ec); + else + known_ecs = add_base_ec_index(root, known_ecs, rinfo->left_ec); } /* The clauses are mergejoinable, hence strict, so NULLs don't matter */ @@ -154,7 +160,7 @@ rel_is_distinct_for_pathkeys(PlannerInfo *root, RelOptInfo *rel, foreach_node(PathKey, pathkey, pathkeys) { - known_ecs = bms_add_member(known_ecs, pathkey->pk_eclass->ec_index); + known_ecs = add_base_ec_index(root, known_ecs, pathkey->pk_eclass); } if (IS_JOIN_REL(rel)) @@ -181,26 +187,60 @@ rel_is_distinct_for_pathkeys(PlannerInfo *root, RelOptInfo *rel, * are added to the set. We repeat this until all base relations are * accounted for or we can make no more progress. * + * If outer joins are performed within the join relation, a base relation can + * also be represented by a null-extended row. We regard that as one more + * possible row, which needs extra care only under a full join (see + * full_nullable_rel_is_marked). The known ECs are always those of un-nulled + * expressions (see add_base_ec_index). + * + * A left join emits, for each left-hand row, either the matching right-hand + * rows or a null-extended row, never both. So the right-hand ECs of its + * mergejoinable clauses are fixed once the left-hand row is, and we treat + * them as known from the start (see get_left_join_ecs). That is safe because + * the left-hand rels must still be fixed by other means: no EC has un-nulled + * members on both sides of a left join. + * * The caller must have checked joinrel_supports_distinctness(). */ static bool joinrel_is_distinct_for_ecs(PlannerInfo *root, RelOptInfo *joinrel, Bitmapset *known_ecs, bool nulls_equal) { + Bitmapset *left_join_ecs; Bitmapset *joined_ecs = NULL; + Relids full_join_relids = NULL; Relids remaining; bool found; + left_join_ecs = get_left_join_ecs(root, joinrel); + known_ecs = bms_add_members(known_ecs, left_join_ecs); + /* * When NULLs are considered equal, a UniqueKey that is not null_aware can * still be used if join clauses keep its ECs from being NULL; see * rel_has_uniquekey_in(). So find those ECs. */ if (nulls_equal) - joined_ecs = get_joined_ecs(root, joinrel); + joined_ecs = get_joined_ecs(root, joinrel, left_join_ecs); + + /* + * Relations that are nulled by a full join need extra care; see + * full_nullable_rel_is_marked(). So find the full joins performed within + * the join relation. + */ + if (bms_overlap(joinrel->relids, root->outer_join_rels)) + { + foreach_node(SpecialJoinInfo, sjinfo, root->join_info_list) + { + if (sjinfo->jointype == JOIN_FULL && + bms_is_member(sjinfo->ojrelid, joinrel->relids)) + full_join_relids = bms_add_member(full_join_relids, + sjinfo->ojrelid); + } + } - /* There are no outer join relids, so all the relids are base relations */ - remaining = bms_copy(joinrel->relids); + /* The relids of outer joins are not relations to account for */ + remaining = bms_difference(joinrel->relids, root->outer_join_rels); do { @@ -212,6 +252,12 @@ joinrel_is_distinct_for_ecs(PlannerInfo *root, RelOptInfo *joinrel, { RelOptInfo *rel = find_base_rel(root, relid); + /* A rel nulled by a full join within this join rel needs more */ + if (bms_overlap(rel->nulling_relids, full_join_relids) && + !full_nullable_rel_is_marked(root, rel, known_ecs, + nulls_equal)) + continue; + if (!rel_has_uniquekey_in(root, rel, known_ecs, joined_ecs, nulls_equal)) continue; @@ -226,28 +272,76 @@ joinrel_is_distinct_for_ecs(PlannerInfo *root, RelOptInfo *joinrel, return remaining == NULL; } +/* + * get_left_join_ecs + * Get the indexes of the ECs on the nullable side of the mergejoinable + * clauses of the left joins performed within the join relation. + * + * See joinrel_is_distinct_for_ecs() for what these are good for. + */ +static Bitmapset * +get_left_join_ecs(PlannerInfo *root, RelOptInfo *joinrel) +{ + Bitmapset *result = NULL; + + /* + * A left join pushed down per outer-join identity 3 has no relid in the + * join relation yet, so its clauses are missed here. That is safe. + */ + if (!bms_overlap(joinrel->relids, root->outer_join_rels)) + return NULL; + + /* In left_join_clauses, the nullable side is on the right */ + foreach_node(OuterJoinClauseInfo, ojcinfo, root->left_join_clauses) + { + if (ojcinfo->sjinfo->jointype == JOIN_LEFT && + bms_is_member(ojcinfo->sjinfo->ojrelid, joinrel->relids)) + result = add_base_ec_index(root, result, + ojcinfo->rinfo->right_ec); + } + + /* In right_join_clauses, the nullable side is on the left */ + foreach_node(OuterJoinClauseInfo, ojcinfo, root->right_join_clauses) + { + if (ojcinfo->sjinfo->jointype == JOIN_LEFT && + bms_is_member(ojcinfo->sjinfo->ojrelid, joinrel->relids)) + result = add_base_ec_index(root, result, + ojcinfo->rinfo->left_ec); + } + + return result; +} + /* * get_joined_ecs * Get the indexes of the ECs that are known to be non-NULL in the join - * relation, because a join clause within it equates two of their - * members. + * relation, because of the join clauses performed within it. * * The members of an EC are equated using mergejoinable operators, which we * assume to be strict (as nodeMergejoin.c does). So an EC with two members - * that can be computed within the join relation cannot be NULL there. + * that can be computed within the join relation cannot be NULL there. The + * same goes for the ECs on the nullable side of mergejoinable left-join + * clauses, which are passed in as left_join_ecs. (A null-extended row + * doesn't pass the clause, but such a row is not one of the relation's own + * rows.) * * This is only of interest for UniqueKeys that are not null_aware, so to * save work we look at just the ECs in those. */ static Bitmapset * -get_joined_ecs(PlannerInfo *root, RelOptInfo *joinrel) +get_joined_ecs(PlannerInfo *root, RelOptInfo *joinrel, + Bitmapset *left_join_ecs) { Bitmapset *result = NULL; int relid = -1; while ((relid = bms_next_member(joinrel->relids, relid)) >= 0) { - RelOptInfo *rel = find_base_rel(root, relid); + RelOptInfo *rel; + + if (bms_is_member(relid, root->outer_join_rels)) + continue; + rel = find_base_rel(root, relid); foreach_node(UniqueKey, ukey, rel->uniquekeys) { @@ -264,6 +358,12 @@ get_joined_ecs(PlannerInfo *root, RelOptInfo *joinrel) if (bms_is_member(i, result)) continue; + if (bms_is_member(i, left_join_ecs)) + { + result = bms_add_member(result, i); + continue; + } + /* The members of a broken EC are not known to be equal */ ec = list_nth_node(EquivalenceClass, root->eq_classes, i); if (ec->ec_broken) @@ -298,6 +398,7 @@ build_base_rel_uniquekeys(PlannerInfo *root) { MemoryContext oldcontext; Relids no_uniquekey_relids = NULL; + Relids full_join_relids = NULL; int rti; if (root->uniquekeys_built) @@ -309,6 +410,25 @@ build_base_rel_uniquekeys(PlannerInfo *root) /* Be sure to keep the results in the planner_cxt even if within GEQO */ oldcontext = MemoryContextSwitchTo(root->planner_cxt); + /* The UniqueKeys can only use ECs that exist, so do this first */ + if (root->outer_join_rels != NULL) + build_base_eclasses(root); + + /* + * We don't handle semijoins and antijoins. Rather than checking for them + * in each join relation, treat their right-hand relations as having no + * UniqueKeys. Also note the full joins, for use below. + */ + foreach_node(SpecialJoinInfo, sjinfo, root->join_info_list) + { + if (sjinfo->jointype == JOIN_SEMI || sjinfo->jointype == JOIN_ANTI) + no_uniquekey_relids = bms_add_members(no_uniquekey_relids, + sjinfo->syn_righthand); + else if (sjinfo->jointype == JOIN_FULL) + full_join_relids = bms_add_member(full_join_relids, + sjinfo->ojrelid); + } + for (rti = 1; rti < root->simple_rel_array_size; rti++) { RelOptInfo *rel = root->simple_rel_array[rti]; @@ -320,30 +440,69 @@ build_base_rel_uniquekeys(PlannerInfo *root) /* Currently we only know about plain relations */ if (rel->reloptkind == RELOPT_BASEREL && rel->rtekind == RTE_RELATION) + { build_plain_rel_uniquekeys(root, rel); + /* full_nullable_rel_is_marked() needs this for such rels only */ + if (rel->uniquekeys != NIL && + bms_overlap(rel->nulling_relids, full_join_relids)) + build_notnull_eclass_indexes(root, rel); + } + if (rel->uniquekeys == NIL) no_uniquekey_relids = bms_add_member(no_uniquekey_relids, rti); } - /* - * We don't handle semijoins and antijoins. Rather than checking for them - * in each join relation, treat their right-hand relations as having no - * UniqueKeys. - */ - foreach_node(SpecialJoinInfo, sjinfo, root->join_info_list) - { - if (sjinfo->jointype == JOIN_SEMI || sjinfo->jointype == JOIN_ANTI) - no_uniquekey_relids = bms_add_members(no_uniquekey_relids, - sjinfo->syn_righthand); - } - root->no_uniquekey_relids = no_uniquekey_relids; root->uniquekeys_built = true; MemoryContextSwitchTo(oldcontext); } +/* + * build_base_eclasses + * Make sure that the un-nulled form of each expression that is nulled + * by outer joins has an EC. + * + * A column that is only referenced above an outer join that nulls it, say in + * DISTINCT or in the clause of an upper join, is only in the EC of its nulled + * form. UniqueKeys need the EC of the column itself, so create that if it + * doesn't exist yet. + */ +static void +build_base_eclasses(PlannerInfo *root) +{ + int nclasses = list_length(root->eq_classes); + + /* ECs created here are appended to the list; no need to visit them */ + for (int i = 0; i < nclasses; i++) + { + EquivalenceClass *ec = list_nth_node(EquivalenceClass, + root->eq_classes, i); + EquivalenceMember *em; + RelOptInfo *rel; + Expr *expr; + + if (ec->ec_has_volatile || + !bms_overlap(ec->ec_relids, root->outer_join_rels)) + continue; + + /* We can only do this for an EC that is a single expression */ + if (list_length(ec->ec_members) != 1) + continue; + em = linitial_node(EquivalenceMember, ec->ec_members); + + expr = get_base_expr(root, em->em_expr, &rel); + if (expr == NULL) + continue; + + /* This finds the EC if it exists, else creates it */ + (void) get_eclass_for_sort_expr(root, expr, ec->ec_opfamilies, + em->em_datatype, ec->ec_collation, + 0, NULL, true); + } +} + /* * build_plain_rel_uniquekeys * Build UniqueKeys for a plain relation from its unique indexes. @@ -449,6 +608,57 @@ build_plain_rel_uniquekeys(PlannerInfo *root, RelOptInfo *rel) } } +/* + * build_notnull_eclass_indexes + * Find the ECs that have a member that is a column of the relation that + * cannot be NULL, and save them in rel->notnull_eclass_indexes. + * + * A column cannot be NULL if it has a NOT NULL constraint or if a strict + * restriction clause of the relation filters out the NULLs. + */ +static void +build_notnull_eclass_indexes(PlannerInfo *root, RelOptInfo *rel) +{ + List *nonnullable_vars = NIL; + Bitmapset *result = NULL; + int i = -1; + + foreach_node(RestrictInfo, rinfo, rel->baserestrictinfo) + { + nonnullable_vars = + mbms_add_members(nonnullable_vars, + find_nonnullable_vars((Node *) rinfo->clause)); + } + + while ((i = bms_next_member(rel->eclass_indexes, i)) >= 0) + { + EquivalenceClass *ec = list_nth_node(EquivalenceClass, + root->eq_classes, i); + + foreach_node(EquivalenceMember, em, ec->ec_members) + { + Var *var = (Var *) em->em_expr; + + if (!IsA(var, Var) || + var->varno != rel->relid || + var->varnullingrels != NULL) + continue; + + if ((var->varattno > 0 && + bms_is_member(var->varattno, rel->notnullattnums)) || + mbms_is_member(var->varno, + var->varattno - FirstLowInvalidHeapAttributeNumber, + nonnullable_vars)) + { + result = bms_add_member(result, i); + break; + } + } + } + + rel->notnull_eclass_indexes = result; +} + /* * add_uniquekey * Add a UniqueKey for the given set of ECs to the relation, unless it @@ -518,6 +728,96 @@ find_ec_index(PlannerInfo *root, RelOptInfo *rel, Expr *expr, return -1; } +/* + * add_base_ec_index + * Add the index of the given EC to the given set. If it is the EC of + * an expression that is nulled by outer joins, add the index of the EC + * of the un-nulled expression instead. + * + * Wherever the nulled expression is not NULL, it is equal to the un-nulled + * one. Where it is NULL, either the un-nulled one is NULL too or the + * relation it belongs to is null-extended; joinrel_is_distinct_for_ecs() + * sees to that when it matters. + * + * Nothing is added if the un-nulled expression cannot be identified or has + * no EC. The caller then has less to work with, which is always safe. + */ +static Bitmapset * +add_base_ec_index(PlannerInfo *root, Bitmapset *eclass_indexes, + EquivalenceClass *ec) +{ + EquivalenceMember *em; + RelOptInfo *rel; + Expr *expr; + int ec_index; + + if (ec == NULL) + return eclass_indexes; + + /* the given EC might be non-canonical, so chase up to the top */ + while (ec->ec_merged) + ec = ec->ec_merged; + + if (!bms_overlap(ec->ec_relids, root->outer_join_rels)) + return bms_add_member(eclass_indexes, ec->ec_index); + + /* We can only do this for an EC that is a single expression */ + if (list_length(ec->ec_members) != 1) + return eclass_indexes; + em = linitial_node(EquivalenceMember, ec->ec_members); + + expr = get_base_expr(root, em->em_expr, &rel); + if (expr == NULL) + return eclass_indexes; + + ec_index = find_ec_index(root, rel, expr, + ec->ec_opfamilies, ec->ec_collation); + if (ec_index < 0) + return eclass_indexes; + + return bms_add_member(eclass_indexes, ec_index); +} + +/* + * get_base_expr + * Get the un-nulled form of the given expression, which is the + * expression itself if it is not nulled by any outer join. Also return + * the base relation the expression belongs to in *rel. + * + * Returns NULL if the expression does not belong to a single base relation. + * Also returns NULL if the expression is nulled by outer joins but is not + * certain to be NULL when the relation is null-extended, in which case the + * un-nulled form doesn't stand for it. A Var is always NULL then, and so is + * a strict expression. + */ +static Expr * +get_base_expr(PlannerInfo *root, Expr *expr, RelOptInfo **rel) +{ + Relids relids = pull_varnos(root, (Node *) expr); + Expr *arg = expr; + int relid; + + if (!bms_get_singleton_member(bms_difference(relids, + root->outer_join_rels), + &relid)) + return NULL; + *rel = find_base_rel_noerr(root, relid); + if (*rel == NULL) + return NULL; + + if (!bms_overlap(relids, root->outer_join_rels)) + return expr; + + while (IsA(arg, RelabelType)) + arg = ((RelabelType *) arg)->arg; + if (!IsA(arg, Var) && + contain_nonstrict_functions((Node *) expr)) + return NULL; + + return (Expr *) remove_nulling_relids((Node *) expr, + root->outer_join_rels, NULL); +} + /* * rel_has_uniquekey_in * Does the relation have a UniqueKey that is a subset of the given set @@ -564,6 +864,58 @@ rel_has_uniquekey_in(PlannerInfo *root, RelOptInfo *rel, return false; } +/* + * full_nullable_rel_is_marked + * Does one of the given ECs tell whether the relation, which is nulled + * by a full join within the join relation being considered, is + * null-extended? + * + * Under a full join, nothing else decides whether the relation is represented + * by its own row or by a null-extended row, so one of the given ECs must tell + * them apart. If nulls_equal is false, any EC with a member of the relation + * does. Otherwise it must have a column of the relation that cannot be NULL, + * since a null-extended row looks like a row that is NULL in all the ECs. + */ +static bool +full_nullable_rel_is_marked(PlannerInfo *root, RelOptInfo *rel, + Bitmapset *eclass_indexes, bool nulls_equal) +{ + if (nulls_equal) + return rel_has_notnull_column_in(root, rel, eclass_indexes); + + return bms_overlap(get_own_eclass_indexes(root, rel), eclass_indexes); +} + +/* + * rel_has_notnull_column_in + * Does any of the given ECs have a member that is a column of the + * relation that cannot be NULL? + * + * This relies on rel->notnull_eclass_indexes, which is only set up for + * relations that are nulled by a full join. + */ +static bool +rel_has_notnull_column_in(PlannerInfo *root, RelOptInfo *rel, + Bitmapset *eclass_indexes) +{ + int i = -1; + + while ((i = bms_next_member(rel->notnull_eclass_indexes, i)) >= 0) + { + EquivalenceClass *ec; + + if (!bms_is_member(i, eclass_indexes)) + continue; + + /* An EC can be found to be broken after the set was built */ + ec = list_nth_node(EquivalenceClass, root->eq_classes, i); + if (!ec->ec_broken) + return true; + } + + return false; +} + /* * get_own_eclass_indexes * Get the indexes of the ECs that have a member belonging to the given diff --git a/src/backend/optimizer/util/relnode.c b/src/backend/optimizer/util/relnode.c index 850098ff4bc..04da325bf48 100644 --- a/src/backend/optimizer/util/relnode.c +++ b/src/backend/optimizer/util/relnode.c @@ -293,6 +293,7 @@ build_simple_rel(PlannerInfo *root, int relid, RelOptInfo *parent) rel->unique_for_rels = NIL; rel->non_unique_for_rels = NIL; rel->uniquekeys = NIL; + rel->notnull_eclass_indexes = NULL; rel->own_eclass_indexes = NULL; rel->unique_rel = NULL; rel->unique_pathkeys = NIL; @@ -916,6 +917,7 @@ build_join_rel(PlannerInfo *root, joinrel->unique_for_rels = NIL; joinrel->non_unique_for_rels = NIL; joinrel->uniquekeys = NIL; + joinrel->notnull_eclass_indexes = NULL; joinrel->own_eclass_indexes = NULL; joinrel->unique_rel = NULL; joinrel->unique_pathkeys = NIL; diff --git a/src/include/nodes/pathnodes.h b/src/include/nodes/pathnodes.h index 63ba6ea39a5..8d0b84514a1 100644 --- a/src/include/nodes/pathnodes.h +++ b/src/include/nodes/pathnodes.h @@ -882,12 +882,16 @@ typedef struct PartitionSchemeData *PartitionScheme; * other rels for which we have tried and failed to prove * this one unique * - * Two fields hold the information that such proofs for join rels are based + * Three fields hold the information that such proofs for join rels are based * on (see uniquekeys.c). They are only used for base rels: * * uniquekeys - list of UniqueKeys, each one being a set of * EquivalenceClasses that no two rows of this rel agree on * (filled when first needed) + * notnull_eclass_indexes - EquivalenceClasses that have a member that + * is a column of this rel that cannot be NULL (filled along + * with uniquekeys, but only if the rel is nulled by a full + * join) * own_eclass_indexes - EquivalenceClasses that have a member belonging * to this rel alone (filled when first needed) * @@ -1146,6 +1150,8 @@ typedef struct RelOptInfo */ /* sets of ECs that no two rows of this rel agree on */ List *uniquekeys; + /* indexes in root->eq_classes of ECs with a non-NULL column of this rel */ + Bitmapset *notnull_eclass_indexes; /* indexes in root->eq_classes of ECs with a member of this rel alone */ Bitmapset *own_eclass_indexes; diff --git a/src/test/regress/expected/uniquekeys.out b/src/test/regress/expected/uniquekeys.out index b102bfeee0f..f21a54cb892 100644 --- a/src/test/regress/expected/uniquekeys.out +++ b/src/test/regress/expected/uniquekeys.out @@ -153,8 +153,200 @@ select * from uk_a a left join Index Cond: ((d.a = c.x) AND (d.b = c.y)) (20 rows) +-- a left join's clause leaves one row of its nullable side. Keep the +-- planner from rearranging the left joins, so that the join relation of +-- interest remains the inner side. +set join_collapse_limit = 1; +explain (verbose, costs off) +select * from uk_a a left join + (uk_b b left join uk_c c on b.x = c.id) on a.x = b.id; + QUERY PLAN +---------------------------------------------------------- + Nested Loop Left Join + Output: a.id, a.x, a.y, b.id, b.x, b.y, c.id, c.x, c.y + Inner Unique: true + -> Seq Scan on public.uk_a a + Output: a.id, a.x, a.y + -> Nested Loop Left Join + Output: b.id, b.x, b.y, c.id, c.x, c.y + Inner Unique: true + -> Index Scan using uk_b_pkey on public.uk_b b + Output: b.id, b.x, b.y + Index Cond: (b.id = a.x) + -> Index Scan using uk_c_pkey on public.uk_c c + Output: c.id, c.x, c.y + Index Cond: (c.id = b.x) +(14 rows) + +-- but not if it doesn't cover a key of the nullable side +explain (verbose, costs off) +select * from uk_a a left join + (uk_b b left join uk_c c on b.x = c.x) on a.x = b.id; + QUERY PLAN +---------------------------------------------------------- + Nested Loop Left Join + Output: a.id, a.x, a.y, b.id, b.x, b.y, c.id, c.x, c.y + -> Seq Scan on public.uk_a a + Output: a.id, a.x, a.y + -> Nested Loop Left Join + Output: b.id, b.x, b.y, c.id, c.x, c.y + Join Filter: (b.x = c.x) + -> Index Scan using uk_b_pkey on public.uk_b b + Output: b.id, b.x, b.y + Index Cond: (b.id = a.x) + -> Seq Scan on public.uk_c c + Output: c.id, c.x, c.y +(12 rows) + +reset join_collapse_limit; reset enable_hashjoin; reset enable_mergejoin; +-- A clause on a column that is nulled by an outer join works like one on the +-- column itself. The join of interest is put under a full join, because a +-- left join's clause would let the planner reduce the outer join below it. +explain (verbose, costs off) +select * from uk_a a full join + (uk_b b left join uk_c c on b.x = c.x) on a.x = b.id and a.y = c.id; + QUERY PLAN +---------------------------------------------------------- + Hash Full Join + Output: a.id, a.x, a.y, b.id, b.x, b.y, c.id, c.x, c.y + Inner Unique: true + Hash Cond: ((a.x = b.id) AND (a.y = c.id)) + -> Seq Scan on public.uk_a a + Output: a.id, a.x, a.y + -> Hash + Output: b.id, b.x, b.y, c.id, c.x, c.y + -> Merge Left Join + Output: b.id, b.x, b.y, c.id, c.x, c.y + Merge Cond: (b.x = c.x) + -> Sort + Output: b.id, b.x, b.y + Sort Key: b.x + -> Seq Scan on public.uk_b b + Output: b.id, b.x, b.y + -> Sort + Output: c.id, c.x, c.y + Sort Key: c.x + -> Seq Scan on public.uk_c c + Output: c.id, c.x, c.y +(21 rows) + +-- but not if the expression can be non-NULL in a null-extended row +explain (verbose, costs off) +select * from uk_a a full join + (uk_b b left join uk_c c on b.x = c.x) + on a.x = b.id and a.y = coalesce(c.id, 0); + QUERY PLAN +----------------------------------------------------------- + Hash Full Join + Output: a.id, a.x, a.y, b.id, b.x, b.y, c.id, c.x, c.y + Hash Cond: ((a.x = b.id) AND (a.y = COALESCE(c.id, 0))) + -> Seq Scan on public.uk_a a + Output: a.id, a.x, a.y + -> Hash + Output: b.id, b.x, b.y, c.id, c.x, c.y + -> Merge Left Join + Output: b.id, b.x, b.y, c.id, c.x, c.y + Merge Cond: (b.x = c.x) + -> Sort + Output: b.id, b.x, b.y + Sort Key: b.x + -> Seq Scan on public.uk_b b + Output: b.id, b.x, b.y + -> Sort + Output: c.id, c.x, c.y + Sort Key: c.x + -> Seq Scan on public.uk_c c + Output: c.id, c.x, c.y +(20 rows) + +-- a full join's clauses do not limit either of its sides +explain (verbose, costs off) +select * from uk_a a full join + (uk_b b full join uk_c c on b.x = c.x) on a.x = b.id; + QUERY PLAN +---------------------------------------------------------- + Hash Full Join + Output: a.id, a.x, a.y, b.id, b.x, b.y, c.id, c.x, c.y + Hash Cond: (a.x = b.id) + -> Seq Scan on public.uk_a a + Output: a.id, a.x, a.y + -> Hash + Output: b.id, b.x, b.y, c.id, c.x, c.y + -> Merge Full Join + Output: b.id, b.x, b.y, c.id, c.x, c.y + Merge Cond: (b.x = c.x) + -> Sort + Output: b.id, b.x, b.y + Sort Key: b.x + -> Seq Scan on public.uk_b b + Output: b.id, b.x, b.y + -> Sort + Output: c.id, c.x, c.y + Sort Key: c.x + -> Seq Scan on public.uk_c c + Output: c.id, c.x, c.y +(20 rows) + +explain (verbose, costs off) +select * from uk_a a full join + (uk_b b full join uk_c c on b.x = c.x) on a.x = b.id and a.y = c.id; + QUERY PLAN +---------------------------------------------------------- + Hash Full Join + Output: a.id, a.x, a.y, b.id, b.x, b.y, c.id, c.x, c.y + Inner Unique: true + Hash Cond: ((a.x = b.id) AND (a.y = c.id)) + -> Seq Scan on public.uk_a a + Output: a.id, a.x, a.y + -> Hash + Output: b.id, b.x, b.y, c.id, c.x, c.y + -> Merge Full Join + Output: b.id, b.x, b.y, c.id, c.x, c.y + Merge Cond: (b.x = c.x) + -> Sort + Output: b.id, b.x, b.y + Sort Key: b.x + -> Seq Scan on public.uk_b b + Output: b.id, b.x, b.y + -> Sort + Output: c.id, c.x, c.y + Sort Key: c.x + -> Seq Scan on public.uk_c c + Output: c.id, c.x, c.y +(21 rows) + +-- a relation nulled by a full join needs a clause of its own, even if it +-- has at most one row +explain (verbose, costs off) +select * from uk_c c left join + ((select * from uk_a where id = 1) a full join + (select * from uk_b where id = 1) b on a.x = b.x) + on c.x = coalesce(a.y, b.y); + QUERY PLAN +---------------------------------------------------------------------------- + Hash Left Join + Output: c.id, c.x, c.y, uk_a.id, uk_a.x, uk_a.y, uk_b.id, uk_b.x, uk_b.y + Hash Cond: (c.x = COALESCE(uk_a.y, uk_b.y)) + -> Seq Scan on public.uk_c c + Output: c.id, c.x, c.y + -> Hash + Output: uk_a.id, uk_a.x, uk_a.y, uk_b.id, uk_b.x, uk_b.y + -> Hash Full Join + Output: uk_a.id, uk_a.x, uk_a.y, uk_b.id, uk_b.x, uk_b.y + Inner Unique: true + Hash Cond: (uk_a.x = uk_b.x) + -> Index Scan using uk_a_pkey on public.uk_a + Output: uk_a.id, uk_a.x, uk_a.y + Index Cond: (uk_a.id = 1) + -> Hash + Output: uk_b.id, uk_b.x, uk_b.y + -> Index Scan using uk_b_pkey on public.uk_b + Output: uk_b.id, uk_b.x, uk_b.y + Index Cond: (uk_b.id = 1) +(19 rows) + -- -- Test skipping DISTINCT and GROUP BY steps when the input is already -- distinct @@ -274,6 +466,17 @@ select distinct a.id, n.w from uk_a a join uk_n n on a.x = n.u; -> Seq Scan on uk_n n (5 rows) +explain (costs off) +select distinct a.id, n.w from uk_a a left join uk_n n on a.x = n.u; + QUERY PLAN +-------------------------------- + Hash Left Join + Hash Cond: (a.x = n.u) + -> Seq Scan on uk_a a + -> Hash + -> Seq Scan on uk_n n +(5 rows) + -- but that takes a join clause on each column of the key explain (costs off) select distinct a.id, n.u from uk_a a join uk_n n on a.x = n.w; @@ -291,6 +494,131 @@ select distinct a.id, n.u from uk_a a join uk_n n on a.x = n.w; -> Seq Scan on uk_a a (10 rows) +-- outer joins +explain (costs off) +select distinct a.id, b.y from uk_a a left join uk_b b on a.x = b.id; + QUERY PLAN +-------------------------------- + Hash Left Join + Hash Cond: (a.x = b.id) + -> Seq Scan on uk_a a + -> Hash + -> Seq Scan on uk_b b +(5 rows) + +explain (costs off) +select distinct a.id, b.y from uk_a a left join uk_b b on a.x = b.x; + QUERY PLAN +-------------------------------------- + HashAggregate + Group Key: a.id, b.y + -> Merge Left Join + Merge Cond: (a.x = b.x) + -> Sort + Sort Key: a.x + -> Seq Scan on uk_a a + -> Sort + Sort Key: b.x + -> Seq Scan on uk_b b +(10 rows) + +explain (costs off) +select distinct a.id, b.id from uk_a a left join uk_b b on a.x = b.x; + QUERY PLAN +-------------------------------- + Merge Left Join + Merge Cond: (a.x = b.x) + -> Sort + Sort Key: a.x + -> Seq Scan on uk_a a + -> Sort + Sort Key: b.x + -> Seq Scan on uk_b b +(8 rows) + +explain (costs off) +select distinct a.id, b.id from uk_a a full join uk_b b on a.x = b.x; + QUERY PLAN +-------------------------------- + Merge Full Join + Merge Cond: (a.x = b.x) + -> Sort + Sort Key: a.x + -> Seq Scan on uk_a a + -> Sort + Sort Key: b.x + -> Seq Scan on uk_b b +(8 rows) + +-- a left join's null-extended row cannot be mistaken for a row that has a +-- NULL in its key +explain (costs off) +select distinct a.id, n.v from uk_a a left join uk_n n on a.x = n.w; + QUERY PLAN +-------------------------------- + Merge Right Join + Merge Cond: (n.w = a.x) + -> Sort + Sort Key: n.w + -> Seq Scan on uk_n n + -> Sort + Sort Key: a.x + -> Seq Scan on uk_a a +(8 rows) + +-- but a full join's can +explain (costs off) +select distinct n1.v, n2.v from uk_n n1 full join uk_n n2 on n1.w = n2.w; + QUERY PLAN +--------------------------------------- + HashAggregate + Group Key: n1.v, n2.v + -> Merge Full Join + Merge Cond: (n1.w = n2.w) + -> Sort + Sort Key: n1.w + -> Seq Scan on uk_n n1 + -> Sort + Sort Key: n2.w + -> Seq Scan on uk_n n2 +(10 rows) + +-- unless a NOT NULL column tells them apart +explain (costs off) +select distinct n1.v, n1.id, n2.v, n2.id +from uk_n n1 full join uk_n n2 on n1.w = n2.w; + QUERY PLAN +--------------------------------- + Merge Full Join + Merge Cond: (n1.w = n2.w) + -> Sort + Sort Key: n1.w + -> Seq Scan on uk_n n1 + -> Sort + Sort Key: n2.w + -> Seq Scan on uk_n n2 +(8 rows) + +-- or a strict restriction clause filters out the NULLs +explain (costs off) +select distinct n1.v, n2.v +from (select * from uk_n where v > 0) n1 full join + (select * from uk_n where v > 0) n2 on n1.w = n2.w; + QUERY PLAN +--------------------------------------------------- + Hash Full Join + Hash Cond: (uk_n.w = uk_n_1.w) + -> Bitmap Heap Scan on uk_n + Recheck Cond: (v > 0) + -> Bitmap Index Scan on uk_n_v_idx + Index Cond: (v > 0) + -> Hash + -> Bitmap Heap Scan on uk_n uk_n_1 + Recheck Cond: (v > 0) + -> Bitmap Index Scan on uk_n_v_idx + Index Cond: (v > 0) +(11 rows) + -- GROUP BY without aggregates is handled likewise explain (costs off) select a.id, a.y from uk_a a join uk_b b on a.x = b.id group by a.id, a.y; diff --git a/src/test/regress/sql/uniquekeys.sql b/src/test/regress/sql/uniquekeys.sql index 7883ae76166..106a1c35b32 100644 --- a/src/test/regress/sql/uniquekeys.sql +++ b/src/test/regress/sql/uniquekeys.sql @@ -47,9 +47,55 @@ select * from uk_a a left join (uk_b b join uk_c c on b.x = c.id join uk_d d on c.x = d.a and c.y = d.b) on a.x = b.id; +-- a left join's clause leaves one row of its nullable side. Keep the +-- planner from rearranging the left joins, so that the join relation of +-- interest remains the inner side. +set join_collapse_limit = 1; + +explain (verbose, costs off) +select * from uk_a a left join + (uk_b b left join uk_c c on b.x = c.id) on a.x = b.id; + +-- but not if it doesn't cover a key of the nullable side +explain (verbose, costs off) +select * from uk_a a left join + (uk_b b left join uk_c c on b.x = c.x) on a.x = b.id; + +reset join_collapse_limit; + reset enable_hashjoin; reset enable_mergejoin; +-- A clause on a column that is nulled by an outer join works like one on the +-- column itself. The join of interest is put under a full join, because a +-- left join's clause would let the planner reduce the outer join below it. +explain (verbose, costs off) +select * from uk_a a full join + (uk_b b left join uk_c c on b.x = c.x) on a.x = b.id and a.y = c.id; + +-- but not if the expression can be non-NULL in a null-extended row +explain (verbose, costs off) +select * from uk_a a full join + (uk_b b left join uk_c c on b.x = c.x) + on a.x = b.id and a.y = coalesce(c.id, 0); + +-- a full join's clauses do not limit either of its sides +explain (verbose, costs off) +select * from uk_a a full join + (uk_b b full join uk_c c on b.x = c.x) on a.x = b.id; + +explain (verbose, costs off) +select * from uk_a a full join + (uk_b b full join uk_c c on b.x = c.x) on a.x = b.id and a.y = c.id; + +-- a relation nulled by a full join needs a clause of its own, even if it +-- has at most one row +explain (verbose, costs off) +select * from uk_c c left join + ((select * from uk_a where id = 1) a full join + (select * from uk_b where id = 1) b on a.x = b.x) + on c.x = coalesce(a.y, b.y); + -- -- Test skipping DISTINCT and GROUP BY steps when the input is already -- distinct @@ -97,10 +143,46 @@ select distinct v from uk_n; explain (costs off) select distinct a.id, n.w from uk_a a join uk_n n on a.x = n.u; +explain (costs off) +select distinct a.id, n.w from uk_a a left join uk_n n on a.x = n.u; + -- but that takes a join clause on each column of the key explain (costs off) select distinct a.id, n.u from uk_a a join uk_n n on a.x = n.w; +-- outer joins +explain (costs off) +select distinct a.id, b.y from uk_a a left join uk_b b on a.x = b.id; + +explain (costs off) +select distinct a.id, b.y from uk_a a left join uk_b b on a.x = b.x; + +explain (costs off) +select distinct a.id, b.id from uk_a a left join uk_b b on a.x = b.x; + +explain (costs off) +select distinct a.id, b.id from uk_a a full join uk_b b on a.x = b.x; + +-- a left join's null-extended row cannot be mistaken for a row that has a +-- NULL in its key +explain (costs off) +select distinct a.id, n.v from uk_a a left join uk_n n on a.x = n.w; + +-- but a full join's can +explain (costs off) +select distinct n1.v, n2.v from uk_n n1 full join uk_n n2 on n1.w = n2.w; + +-- unless a NOT NULL column tells them apart +explain (costs off) +select distinct n1.v, n1.id, n2.v, n2.id +from uk_n n1 full join uk_n n2 on n1.w = n2.w; + +-- or a strict restriction clause filters out the NULLs +explain (costs off) +select distinct n1.v, n2.v +from (select * from uk_n where v > 0) n1 full join + (select * from uk_n where v > 0) n2 on n1.w = n2.w; + -- GROUP BY without aggregates is handled likewise explain (costs off) select a.id, a.y from uk_a a join uk_b b on a.x = b.id group by a.id, a.y; -- 2.53.0