=== Applying patches on top of PostgreSQL commit ID 9f07de2053163cda9acb68c34d8be4b56f9659d4 === /etc/rc.d/jail: WARNING: Per-jail configuration via jail_* variables is obsolete. Please consider migrating to /etc/jail.conf. Mon Oct 5 05:53:32 UTC 2026 On branch cf/6720 nothing to commit, working tree clean === using 'git am' to apply patch ./v6-0001-Remove-inner-joins-based-on-foreign-keys.patch === Applying: Remove inner joins based on foreign keys Using index info to reconstruct a base tree... M src/backend/optimizer/path/equivclass.c M src/backend/optimizer/plan/analyzejoins.c M src/backend/optimizer/plan/initsplan.c M src/backend/optimizer/plan/planmain.c M src/backend/optimizer/util/plancat.c M src/backend/utils/cache/relcache.c M src/backend/utils/misc/guc_parameters.dat M src/backend/utils/misc/postgresql.conf.sample M src/include/nodes/pathnodes.h M src/include/optimizer/paths.h M src/include/optimizer/planmain.h M src/include/utils/rel.h M src/test/regress/expected/join.out M src/test/regress/expected/sysviews.out M src/test/regress/sql/join.sql Falling back to patching base and 3-way merge... Auto-merging src/test/regress/sql/join.sql Auto-merging src/test/regress/expected/sysviews.out Auto-merging src/test/regress/expected/join.out Auto-merging src/include/utils/rel.h Auto-merging src/include/optimizer/planmain.h CONFLICT (content): Merge conflict in src/include/optimizer/planmain.h Auto-merging src/include/optimizer/paths.h Auto-merging src/include/nodes/pathnodes.h Auto-merging src/backend/utils/misc/postgresql.conf.sample Auto-merging src/backend/utils/misc/guc_parameters.dat Auto-merging src/backend/utils/cache/relcache.c Auto-merging src/backend/optimizer/util/plancat.c Auto-merging src/backend/optimizer/plan/planmain.c Auto-merging src/backend/optimizer/plan/initsplan.c Auto-merging src/backend/optimizer/plan/analyzejoins.c CONFLICT (content): Merge conflict in src/backend/optimizer/plan/analyzejoins.c Auto-merging src/backend/optimizer/path/equivclass.c error: Failed to merge in the changes. hint: Use 'git am --show-current-patch=diff' to see the failed patch Patch failed at 0001 Remove inner joins based on foreign keys When you have resolved this problem, run "git am --continue". If you prefer to skip this patch, run "git am --skip" instead. To restore the original branch and stop patching, run "git am --abort". === using patch(1) to apply patch ./v6-0001-Remove-inner-joins-based-on-foreign-keys.patch === patching file src/backend/optimizer/path/equivclass.c Hunk #1 succeeded at 2670 (offset -31 lines). Hunk #2 succeeded at 2747 (offset -31 lines). patching file src/backend/optimizer/plan/analyzejoins.c Hunk #1 FAILED at 23. Hunk #2 succeeded at 61 (offset 9 lines). Hunk #3 FAILED at 82. Hunk #4 FAILED at 437. Hunk #5 FAILED at 458. Hunk #6 succeeded at 1294 with fuzz 2 (offset 776 lines). Hunk #7 FAILED at 527. Hunk #8 FAILED at 545. Hunk #9 FAILED at 586. Hunk #10 FAILED at 615. Hunk #11 FAILED at 644. Hunk #12 FAILED at 674. Hunk #13 FAILED at 686. Hunk #14 FAILED at 705. Hunk #15 FAILED at 761. Hunk #16 FAILED at 793. Hunk #17 FAILED at 817. Hunk #18 FAILED at 2138. Hunk #19 succeeded at 2154 with fuzz 2 (offset -513 lines). 16 out of 19 hunks FAILED -- saving rejects to file src/backend/optimizer/plan/analyzejoins.c.rej patching file src/backend/optimizer/plan/initsplan.c Hunk #1 succeeded at 3843 (offset -234 lines). patching file src/backend/optimizer/plan/planmain.c Hunk #1 succeeded at 246 with fuzz 2 (offset 5 lines). patching file src/backend/optimizer/util/plancat.c Hunk #1 succeeded at 661 (offset -1 lines). patching file src/backend/utils/cache/relcache.c Hunk #1 succeeded at 4775 (offset 1 line). patching file src/backend/utils/misc/guc_parameters.dat Hunk #1 succeeded at 890 (offset -2 lines). patching file src/backend/utils/misc/postgresql.conf.sample Hunk #1 succeeded at 451 (offset 4 lines). patching file src/include/nodes/pathnodes.h patching file src/include/optimizer/paths.h Hunk #1 succeeded at 171 (offset -1 lines). patching file src/include/optimizer/planmain.h Hunk #2 FAILED at 121. 1 out of 2 hunks FAILED -- saving rejects to file src/include/optimizer/planmain.h.rej patching file src/include/utils/rel.h Hunk #1 succeeded at 293 (offset 9 lines). patching file src/test/regress/expected/join.out Hunk #1 succeeded at 11635 (offset 1470 lines). patching file src/test/regress/expected/sysviews.out Hunk #1 succeeded at 159 with fuzz 1. Hunk #2 FAILED at 181. 1 out of 2 hunks FAILED -- saving rejects to file src/test/regress/expected/sysviews.out.rej patching file src/test/regress/sql/join.sql Hunk #1 succeeded at 4475 (offset 572 lines). Unstaged changes after reset: M src/backend/optimizer/path/equivclass.c M src/backend/optimizer/plan/analyzejoins.c M src/backend/optimizer/plan/initsplan.c M src/backend/optimizer/plan/planmain.c M src/backend/optimizer/util/plancat.c M src/backend/utils/cache/relcache.c M src/backend/utils/misc/guc_parameters.dat M src/backend/utils/misc/postgresql.conf.sample M src/include/nodes/pathnodes.h M src/include/optimizer/paths.h M src/include/optimizer/planmain.h M src/include/utils/rel.h M src/test/regress/expected/join.out M src/test/regress/expected/sysviews.out M src/test/regress/sql/join.sql Removing src/backend/optimizer/plan/analyzejoins.c.rej Removing src/include/optimizer/planmain.h.rej Removing src/test/regress/expected/sysviews.out.rej === using 'git apply' to apply patch ./v6-0001-Remove-inner-joins-based-on-foreign-keys.patch === Applied patch to 'src/backend/optimizer/path/equivclass.c' cleanly. Applied patch to 'src/backend/optimizer/plan/analyzejoins.c' with conflicts. Applied patch to 'src/backend/optimizer/plan/initsplan.c' cleanly. Applied patch to 'src/backend/optimizer/plan/planmain.c' cleanly. Applied patch to 'src/backend/optimizer/util/plancat.c' cleanly. Applied patch to 'src/backend/utils/cache/relcache.c' cleanly. Applied patch to 'src/backend/utils/misc/guc_parameters.dat' cleanly. Applied patch to 'src/backend/utils/misc/postgresql.conf.sample' cleanly. Applied patch to 'src/include/nodes/pathnodes.h' cleanly. Applied patch to 'src/include/optimizer/paths.h' cleanly. Applied patch to 'src/include/optimizer/planmain.h' with conflicts. Applied patch to 'src/include/utils/rel.h' cleanly. Applied patch to 'src/test/regress/expected/join.out' cleanly. Applied patch to 'src/test/regress/expected/sysviews.out' cleanly. Applied patch to 'src/test/regress/sql/join.sql' cleanly. U src/backend/optimizer/plan/analyzejoins.c U src/include/optimizer/planmain.h diff --cc src/backend/optimizer/plan/analyzejoins.c index 1fafca57004,7085bde6b2a..00000000000 --- a/src/backend/optimizer/plan/analyzejoins.c +++ b/src/backend/optimizer/plan/analyzejoins.c @@@ -33,11 -28,12 +33,16 @@@ #include "optimizer/optimizer.h" #include "optimizer/pathnode.h" #include "optimizer/paths.h" ++<<<<<<< ours ++======= + #include "optimizer/placeholder.h" + #include "optimizer/plancat.h" ++>>>>>>> theirs #include "optimizer/planmain.h" +#include "optimizer/prep.h" #include "optimizer/restrictinfo.h" #include "parser/parse_agg.h" +#include "parser/parse_relation.h" #include "rewrite/rewriteManip.h" #include "utils/lsyscache.h" @@@ -88,14 -81,13 +94,23 @@@ static bool is_innerrel_unique_for(Plan JoinType jointype, List *restrictlist, List **extra_clauses); +static Node *remove_rel_from_jointree(Node *jtnode, int relid, + Node **orphan_quals, int *nremoved); +static Node *merge_quals(Node *quals1, Node *quals2); +static void fixup_selfjoin_jointree(PlannerInfo *root, Node *jtnode, int relid, + Node **hoist_quals, bool *found_relid); +static List *fixup_selfjoin_quals(PlannerInfo *root, List *quals, int relid); +static Node *replace_selfjoin_qual(Node *qual); static int self_join_candidates_cmp(const void *a, const void *b); ++<<<<<<< ours ++======= + static bool replace_relid_callback(Node *node, + ChangeVarNodes_context *context); + static bool inner_join_is_removable(PlannerInfo *root, ForeignKeyOptInfo *fkinfo); + static void inject_fk_not_null_quals(PlannerInfo *root, ForeignKeyOptInfo *fkinfo); + static void remove_referenced_rel_from_query(PlannerInfo *root, + ForeignKeyOptInfo *fkinfo); ++>>>>>>> theirs /* @@@ -363,90 -324,671 +378,513 @@@ join_is_removable(PlannerInfo *root, Sp } /* - * Remove the target relid and references to the target join from the - * planner's data structures, having determined that there is no need - * to include them in the query. + * remove_join_from_jointree + * Delete the JoinExpr with the given RT index, along with everything + * below its righthand side, from the query's jointree. * - * We are not terribly thorough here. We only bother to update parts of - * the planner's data structures that will actually be consulted later. - */ -static void -remove_leftjoinrel_from_query(PlannerInfo *root, int relid, - SpecialJoinInfo *sjinfo) -{ - RelOptInfo *rel = find_base_rel(root, relid); - int ojrelid = sjinfo->ojrelid; - Relids joinrelids; - Relids join_plus_commute; - List *joininfos; - ListCell *l; - - /* Compute the relid set for the join we are considering */ - joinrelids = bms_union(sjinfo->min_lefthand, sjinfo->min_righthand); - Assert(ojrelid != 0); - joinrelids = bms_add_member(joinrelids, ojrelid); - - remove_rel_from_query(root, relid, -1, sjinfo, joinrelids); - - /* - * Remove any joinquals referencing the rel from the joininfo lists. - * - * In some cases, a joinqual has to be put back after deleting its - * reference to the target rel. This can occur for pseudoconstant and - * outerjoin-delayed quals, which can get marked as requiring the rel in - * order to force them to be evaluated at or above the join. We can't - * just discard them, though. Only quals that logically belonged to the - * outer join being discarded should be removed from the query. - * - * We might encounter a qual that is a clone of a deletable qual with some - * outer-join relids added (see deconstruct_distribute_oj_quals). To - * ensure we get rid of such clones as well, add the relids of all OJs - * commutable with this one to the set we test against for - * pushed-down-ness. - */ - join_plus_commute = bms_union(joinrelids, - sjinfo->commute_above_r); - join_plus_commute = bms_add_members(join_plus_commute, - sjinfo->commute_below_l); - - /* - * We must make a copy of the rel's old joininfo list before starting the - * loop, because otherwise remove_join_clause_from_rels would destroy the - * list while we're scanning it. - */ - joininfos = list_copy(rel->joininfo); - foreach(l, joininfos) - { - RestrictInfo *rinfo = (RestrictInfo *) lfirst(l); - - remove_join_clause_from_rels(root, rinfo, rinfo->required_relids); - - if (RINFO_IS_PUSHED_DOWN(rinfo, join_plus_commute)) - { - /* - * There might be references to relid or ojrelid in the - * RestrictInfo's relid sets, as a consequence of PHVs having had - * ph_eval_at sets that include those. We already checked above - * that any such PHV is safe (and updated its ph_eval_at), so we - * can just drop those references. - */ - remove_rel_from_restrictinfo(rinfo, relid, ojrelid); - - /* - * Cross-check that the clause itself does not reference the - * target rel or join. - */ -#ifdef USE_ASSERT_CHECKING - { - Relids clause_varnos = pull_varnos(root, - (Node *) rinfo->clause); - - Assert(!bms_is_member(relid, clause_varnos)); - Assert(!bms_is_member(ojrelid, clause_varnos)); - } -#endif - /* Now throw it back into the joininfo lists */ - distribute_restrictinfo_to_rels(root, rinfo); - } - } - - /* - * There may be references to the rel in root->fkey_list, but if so, - * match_foreign_keys_to_quals() will get rid of them. - */ - - /* - * Now remove the rel from the baserel array to prevent it from being - * referenced again. (We can't do this earlier because - * remove_join_clause_from_rels will touch it.) - */ - root->simple_rel_array[relid] = NULL; - root->simple_rte_array[relid] = NULL; - - /* And nuke the RelOptInfo, just in case there's another access path */ - pfree(rel); - - /* - * Now repeat construction of attr_needed bits coming from all other - * sources. - */ - rebuild_placeholder_attr_needed(root); - rebuild_joinclause_attr_needed(root); - rebuild_eclass_attr_needed(root); - rebuild_lateral_attr_needed(root); -} - -/* - * Remove the target relid and references to the target join from the - * planner's data structures, having determined that there is no need - * to include them in the query. Optionally replace references to the - * removed relid with subst if this is a self-join removal. ++<<<<<<< ours + * The JoinExpr is replaced by its lefthand input. Its ON conditions can just + * be dropped: since this is a left join, they could only have determined + * which righthand rows join to a given lefthand row, and there are no + * righthand rows anymore. * + * *nremoved is incremented by the number of JoinExprs removed (there should + * be exactly one, but the caller checks that). ++======= + * This function serves as the common infrastructure for three distinct + * optimization passes: left-join removal, inner-join removal, and self-join + * elimination. It is intentionally scoped to update only the shared planner + * data structures that are universally affected by relation removal. Each + * specific caller remains responsible for updating any remaining data + * structures required by its unique removal logic. + * + * The specific type of removal being performed is dictated by the combination + * of the sjinfo and subst parameters. A non-NULL sjinfo indicates left-join + * removal. When sjinfo is NULL, a positive subst value indicates self-join + * elimination (where references are replaced with subst), while a negative + * subst value indicates inner-join removal. ++>>>>>>> theirs */ -static void -remove_rel_from_query(PlannerInfo *root, int relid, - int subst, SpecialJoinInfo *sjinfo, - Relids joinrelids) +static Node * +remove_join_from_jointree(Node *jtnode, int ojrelid, int *nremoved) { ++<<<<<<< ours + if (jtnode == NULL) + return NULL; + if (IsA(jtnode, RangeTblRef)) ++======= + int ojrelid = sjinfo ? sjinfo->ojrelid : 0; + Index rti; + ListCell *l; + bool is_outer_join = (sjinfo != NULL); + bool is_self_join = (!is_outer_join && subst > 0); + bool is_inner_join = (!is_outer_join && subst < 0); + + Assert(is_outer_join || is_self_join || is_inner_join); + Assert(!is_outer_join || ojrelid > 0); + Assert(is_self_join || joinrelids != NULL); + + /* + * Update all_baserels and related relid sets. + */ + root->all_baserels = adjust_relid_set(root->all_baserels, relid, subst); + root->all_query_rels = adjust_relid_set(root->all_query_rels, relid, subst); + + if (is_outer_join) ++>>>>>>> theirs { - root->outer_join_rels = bms_del_member(root->outer_join_rels, ojrelid); - root->all_query_rels = bms_del_member(root->all_query_rels, ojrelid); + /* nothing to do here */ } + else if (IsA(jtnode, FromExpr)) + { + FromExpr *f = (FromExpr *) jtnode; + ListCell *l; - /* - * Likewise remove references from SpecialJoinInfo data structures. - * - * This is relevant in case the relation we're deleting is part of the - * relid sets of special joins: those sets have to be adjusted. If we are - * removing an outer join, the RHS of the target outer join will be made - * empty here, but that's OK since the caller will delete that - * SpecialJoinInfo entirely. - */ - foreach(l, root->join_info_list) ++<<<<<<< ours + foreach(l, f->fromlist) + lfirst(l) = remove_join_from_jointree((Node *) lfirst(l), + ojrelid, nremoved); + } + else if (IsA(jtnode, JoinExpr)) { - SpecialJoinInfo *sjinf = (SpecialJoinInfo *) lfirst(l); + JoinExpr *j = (JoinExpr *) jtnode; + if (j->rtindex == ojrelid) ++======= + /* + * initsplan.c is fairly cavalier about allowing SpecialJoinInfos' + * lefthand/righthand relid sets to be shared with other data + * structures. Ensure that we don't modify the original relid sets. + * (The commute_xxx sets are always per-SpecialJoinInfo though.) + */ + sjinf->min_lefthand = bms_copy(sjinf->min_lefthand); + sjinf->min_righthand = bms_copy(sjinf->min_righthand); + sjinf->syn_lefthand = bms_copy(sjinf->syn_lefthand); + sjinf->syn_righthand = bms_copy(sjinf->syn_righthand); + + /* Now adjust relid bit in the sets: */ + sjinf->min_lefthand = adjust_relid_set(sjinf->min_lefthand, relid, subst); + sjinf->min_righthand = adjust_relid_set(sjinf->min_righthand, relid, subst); + sjinf->syn_lefthand = adjust_relid_set(sjinf->syn_lefthand, relid, subst); + sjinf->syn_righthand = adjust_relid_set(sjinf->syn_righthand, relid, subst); + + if (is_outer_join) + { + /* Remove ojrelid bit from the sets: */ + sjinf->min_lefthand = bms_del_member(sjinf->min_lefthand, ojrelid); + sjinf->min_righthand = bms_del_member(sjinf->min_righthand, ojrelid); + sjinf->syn_lefthand = bms_del_member(sjinf->syn_lefthand, ojrelid); + sjinf->syn_righthand = bms_del_member(sjinf->syn_righthand, ojrelid); + /* relid cannot appear in these fields, but ojrelid can: */ + sjinf->commute_above_l = bms_del_member(sjinf->commute_above_l, ojrelid); + sjinf->commute_above_r = bms_del_member(sjinf->commute_above_r, ojrelid); + sjinf->commute_below_l = bms_del_member(sjinf->commute_below_l, ojrelid); + sjinf->commute_below_r = bms_del_member(sjinf->commute_below_r, ojrelid); + } + else if (is_self_join) + { + /* + * For self-join removal, replace relid references in + * semi_rhs_exprs. + */ + ChangeVarNodesExtended((Node *) sjinf->semi_rhs_exprs, relid, subst, + 0, replace_relid_callback); + } + else if (is_inner_join) + { + /* + * For inner-join removal, no additional modifications are needed. + * inner_join_is_removable() has already guaranteed that the + * target relation's columns do not leak into semi_rhs_exprs. + */ + } + } + + /* + * Likewise remove references from PlaceHolderVar data structures, + * removing any no-longer-needed placeholders entirely. We remove PHVs + * for left-join and inner-join removal. With self-join elimination, PHVs + * already get moved to the remaining relation, where they might still be + * needed. It might also happen that we skip the removal of some PHVs + * that could be removed. However, the overhead of extra PHVs is small + * compared to the complexity of analysis needed to remove them. + * + * Removal is a bit trickier than it might seem: we can remove PHVs that + * are used at the target rel and/or in the join qual, but not those that + * are used at join partner rels or above the join. It's not that easy to + * distinguish PHVs used at partner rels from those used in the join qual, + * since they will both have ph_needed sets that are subsets of + * joinrelids. However, a PHV used at a partner rel could not have the + * target rel in ph_eval_at, so we check that while deciding whether to + * remove or just update the PHV. There are no corresponding tests in the + * callers (like join_is_removable or inner_join_is_removable) because + * they don't need to distinguish those cases. + */ + foreach(l, root->placeholder_list) + { + PlaceHolderInfo *phinfo = (PlaceHolderInfo *) lfirst(l); + + Assert(is_self_join || !bms_is_member(relid, phinfo->ph_lateral)); + + if (!is_self_join && + bms_is_subset(phinfo->ph_needed, joinrelids) && + bms_is_member(relid, phinfo->ph_eval_at) && + (is_inner_join || !bms_is_member(ojrelid, phinfo->ph_eval_at))) + { + root->placeholder_list = foreach_delete_current(root->placeholder_list, + l); + root->placeholder_array[phinfo->phid] = NULL; + } + else + { + PlaceHolderVar *phv = phinfo->ph_var; + + phinfo->ph_eval_at = adjust_relid_set(phinfo->ph_eval_at, relid, subst); + if (is_outer_join) + phinfo->ph_eval_at = bms_del_member(phinfo->ph_eval_at, ojrelid); + Assert(!bms_is_empty(phinfo->ph_eval_at)); /* checked previously */ + + /* Reduce ph_needed to contain only "relation 0"; see below */ + if (bms_is_member(0, phinfo->ph_needed)) + phinfo->ph_needed = bms_make_singleton(0); + else + phinfo->ph_needed = NULL; + + phv->phrels = adjust_relid_set(phv->phrels, relid, subst); + if (is_outer_join) + phv->phrels = bms_del_member(phv->phrels, ojrelid); + Assert(!bms_is_empty(phv->phrels)); + + /* + * For self-join removal, update Var nodes within the PHV's + * expression to reference the replacement relid, and adjust + * ph_lateral for the relid substitution. (For left-join and + * inner-join removal, we're removing rather than replacing, and + * any surviving PHV shouldn't reference the removed rel in its + * expression. Also, relid can't appear in ph_lateral for outer + * joins and inner joins.) + */ + if (is_self_join) + { + ChangeVarNodesExtended((Node *) phv->phexpr, relid, subst, 0, + replace_relid_callback); + phinfo->ph_lateral = adjust_relid_set(phinfo->ph_lateral, relid, subst); + + /* + * ph_lateral might contain rels mentioned in ph_eval_at after + * the replacement, remove them. + */ + phinfo->ph_lateral = bms_difference(phinfo->ph_lateral, phinfo->ph_eval_at); + /* ph_lateral might or might not be empty */ + } + + Assert(phv->phnullingrels == NULL); /* no need to adjust */ + } + } + + /* + * Likewise remove references from EquivalenceClasses. + * + * For self-join removal, the caller has already updated the + * EquivalenceClasses, so we can skip this step. + */ + if (is_outer_join || is_inner_join) + { + foreach(l, root->eq_classes) ++>>>>>>> theirs { - EquivalenceClass *ec = (EquivalenceClass *) lfirst(l); - - remove_rel_from_eclass(root, ec, relid, ojrelid); + (*nremoved)++; + return j->larg; } + j->larg = remove_join_from_jointree(j->larg, ojrelid, nremoved); + j->rarg = remove_join_from_jointree(j->rarg, ojrelid, nremoved); } + else + elog(ERROR, "unrecognized jointree node type: %d", + (int) nodeTag(jtnode)); + ++<<<<<<< ours + return jtnode; +} +/* + * remove_rels_from_query_tree + * Delete all remaining references to the given relids from the query. ++======= + /* + * Finally, we must prepare for the caller to recompute per-Var + * attr_needed and per-PlaceHolderVar ph_needed relid sets. These have to + * be known accurately, else we may fail to remove other now-removable + * joins. Because the caller removes the join clause(s) associated with + * the removed join, Vars that were formerly needed may no longer be. + * + * The actual reconstruction of these relid sets is performed by the + * specific caller. Here, we simply clear out the existing attr_needed + * sets (we already did this above for ph_needed) to ensure they are + * rebuilt from scratch. We can cheat to one small extent: we can avoid + * re-examining the targetlist and HAVING qual by preserving "relation 0" + * bits from the existing relid sets. This is safe because we'd never + * remove such references. + * + * Additionally, if we are performing self-join elimination, we must + * replace references to the removed relid with subst within the + * lateral_vars lists. + * + * Also, for left-join and inner-join removal, we strip the removed rel + * and join from any PlaceHolderVar embedded in the surviving rels' + * restriction clauses (see remove_rel_from_phvs); we needn't bother with + * the rel being removed, nor when the query has no PlaceHolderVars. + */ + for (rti = 1; rti < root->simple_rel_array_size; rti++) + { + RelOptInfo *otherrel = root->simple_rel_array[rti]; + int attroff; + + /* there may be empty slots corresponding to non-baserel RTEs */ + if (otherrel == NULL) + continue; + + Assert(otherrel->relid == rti); /* sanity check on array */ + + for (attroff = otherrel->max_attr - otherrel->min_attr; + attroff >= 0; + attroff--) + { + if (bms_is_member(0, otherrel->attr_needed[attroff])) + otherrel->attr_needed[attroff] = bms_make_singleton(0); + else + otherrel->attr_needed[attroff] = NULL; + } + + if (is_self_join) + ChangeVarNodesExtended((Node *) otherrel->lateral_vars, relid, + subst, 0, replace_relid_callback); + + if ((is_outer_join || is_inner_join) && + rti != relid && + root->glob->lastPHId != 0) + { + foreach_node(RestrictInfo, rinfo, otherrel->baserestrictinfo) + { + rinfo->clause = (Expr *) + remove_rel_from_phvs((Node *) rinfo->clause, relid, ojrelid); + } + } + } + } + + /* + * Remove any references to relid or ojrelid from the RestrictInfo. If + * ojrelid is <= 0, it is ignored (used for inner-join removal). + * + * We only bother to clean out bits in the RestrictInfo's various relid sets, + * not nullingrel bits in contained Vars and PHVs. (This might have to be + * improved sometime.) However, if the RestrictInfo contains an OR clause + * we have to also clean up the sub-clauses. + */ + static void + remove_rel_from_restrictinfo(RestrictInfo *rinfo, int relid, int ojrelid) + { + /* + * initsplan.c is fairly cavalier about allowing RestrictInfos to share + * relid sets with other RestrictInfos, and SpecialJoinInfos too. Make + * sure this RestrictInfo has its own relid sets before we modify them. + * (In present usage, clause_relids is probably not shared, but + * required_relids could be; let's not assume anything.) + */ + rinfo->clause_relids = bms_copy(rinfo->clause_relids); + rinfo->clause_relids = bms_del_member(rinfo->clause_relids, relid); + if (ojrelid > 0) + rinfo->clause_relids = bms_del_member(rinfo->clause_relids, ojrelid); + /* Likewise for required_relids */ + rinfo->required_relids = bms_copy(rinfo->required_relids); + rinfo->required_relids = bms_del_member(rinfo->required_relids, relid); + if (ojrelid > 0) + rinfo->required_relids = bms_del_member(rinfo->required_relids, ojrelid); + /* Likewise for incompatible_relids */ + rinfo->incompatible_relids = bms_copy(rinfo->incompatible_relids); + rinfo->incompatible_relids = bms_del_member(rinfo->incompatible_relids, relid); + if (ojrelid > 0) + rinfo->incompatible_relids = bms_del_member(rinfo->incompatible_relids, ojrelid); + /* Likewise for outer_relids */ + rinfo->outer_relids = bms_copy(rinfo->outer_relids); + rinfo->outer_relids = bms_del_member(rinfo->outer_relids, relid); + if (ojrelid > 0) + rinfo->outer_relids = bms_del_member(rinfo->outer_relids, ojrelid); + /* Likewise for left_relids */ + rinfo->left_relids = bms_copy(rinfo->left_relids); + rinfo->left_relids = bms_del_member(rinfo->left_relids, relid); + if (ojrelid > 0) + rinfo->left_relids = bms_del_member(rinfo->left_relids, ojrelid); + /* Likewise for right_relids */ + rinfo->right_relids = bms_copy(rinfo->right_relids); + rinfo->right_relids = bms_del_member(rinfo->right_relids, relid); + if (ojrelid > 0) + rinfo->right_relids = bms_del_member(rinfo->right_relids, ojrelid); + + /* If it's an OR, recurse to clean up sub-clauses */ + if (restriction_is_or_clause(rinfo)) + { + ListCell *lc; + + Assert(is_orclause(rinfo->orclause)); + foreach(lc, ((BoolExpr *) rinfo->orclause)->args) + { + Node *orarg = (Node *) lfirst(lc); + + /* OR arguments should be ANDs or sub-RestrictInfos */ + if (is_andclause(orarg)) + { + List *andargs = ((BoolExpr *) orarg)->args; + ListCell *lc2; + + foreach(lc2, andargs) + { + RestrictInfo *rinfo2 = lfirst_node(RestrictInfo, lc2); + + remove_rel_from_restrictinfo(rinfo2, relid, ojrelid); + } + } + else + { + RestrictInfo *rinfo2 = castNode(RestrictInfo, orarg); + + remove_rel_from_restrictinfo(rinfo2, relid, ojrelid); + } + } + } + } + + /* + * Remove any references to relid or ojrelid from the EquivalenceClass. If + * ojrelid is <= 0, it is ignored (used for inner-join removal). ++>>>>>>> theirs * - * We fix the EC and EM relid sets to ensure that implied join equalities will - * be generated at the appropriate join level(s). We also strip the removed - * rel from PlaceHolderVars embedded in member expressions; a member's - * em_relids reflects ph_eval_at rather than the PHV's phrels, so the latter - * can still mention the removed rel even when em_relids does not. Like - * remove_rel_from_restrictinfo, we don't bother with nullingrel bits in - * contained plain Vars. + * Having removed some relations and outer joins from the jointree, we must + * get rid of any references to them that are left behind elsewhere. There + * should be no ordinary Vars of a removed relation left, but OJ relids can + * still appear in the nullingrels sets of surviving Vars and PlaceHolderVars, + * and both regular and OJ relids can appear in the phrels sets of + * PlaceHolderVars. ChangeVarNodes knows how to strip a relid out of all of + * those. */ static void -remove_rel_from_eclass(PlannerInfo *root, EquivalenceClass *ec, - int relid, int ojrelid) +remove_rels_from_query_tree(PlannerInfo *root, Relids removed_relids) { ++<<<<<<< ours + int relid = -1; ++======= + ListCell *lc; + + /* + * Strip the removed rel/join from PlaceHolderVars in member expressions. + * This is needed even when the EC's relids don't mention the removed rel. + * Plain Vars and Consts can't contain a PlaceHolderVar, so skip them. + */ + if (root->glob->lastPHId != 0) + { + foreach_node(EquivalenceMember, em, ec->ec_members) + { + if (!IsA(em->em_expr, Var) && !IsA(em->em_expr, Const)) + em->em_expr = (Expr *) + remove_rel_from_phvs((Node *) em->em_expr, relid, ojrelid); + } + } + + if (!bms_is_member(relid, ec->ec_relids) && + (ojrelid == 0 || !bms_is_member(ojrelid, ec->ec_relids))) + return; + + /* Fix up the EC's overall relids */ + ec->ec_relids = bms_del_member(ec->ec_relids, relid); + if (ojrelid > 0) + ec->ec_relids = bms_del_member(ec->ec_relids, ojrelid); + + /* + * We don't expect any EC child members to exist at this point. Ensure + * that's the case, otherwise, we might be getting asked to do something + * this function hasn't been coded for. + */ + Assert(ec->ec_childmembers == NULL); + + /* + * Fix up the member expressions. Any non-const member that ends with + * empty em_relids must be a Var or PHV of the removed relation. We don't + * need it anymore, so we can drop it. + */ + foreach(lc, ec->ec_members) + { + EquivalenceMember *cur_em = (EquivalenceMember *) lfirst(lc); + + if (bms_is_member(relid, cur_em->em_relids) || + (ojrelid > 0 && bms_is_member(ojrelid, cur_em->em_relids))) + { + Assert(!cur_em->em_is_const); + /* em_relids is likely to be shared with some RestrictInfo */ + cur_em->em_relids = bms_copy(cur_em->em_relids); + cur_em->em_relids = bms_del_member(cur_em->em_relids, relid); + if (ojrelid > 0) + cur_em->em_relids = bms_del_member(cur_em->em_relids, ojrelid); + if (bms_is_empty(cur_em->em_relids)) + ec->ec_members = foreach_delete_current(ec->ec_members, lc); + } + } + + /* Fix up the source clauses, in case we can re-use them later */ + foreach(lc, ec->ec_sources) + { + RestrictInfo *rinfo = (RestrictInfo *) lfirst(lc); + + remove_rel_from_restrictinfo(rinfo, relid, ojrelid); + } + + /* + * Rather than expend code on fixing up any already-derived clauses, just + * drop them. (At this point, any such clauses would be base restriction + * clauses, which we'd not need anymore anyway.) + */ + ec_clear_derived_clauses(ec); + } + + /* + * Remove any references to the specified RT index(es) from the phrels (and + * phnullingrels) of every PlaceHolderVar in the given expression. + * + * remove_rel_from_query() fixes up the relid sets of RestrictInfos and + * EquivalenceMembers, but not the PlaceHolderVars embedded in their + * expressions. That's normally fine, but such an expression may later be + * translated for an appendrel child and have its relids recomputed by + * pull_varnos(). A leftover removed relid in phrels would then make + * pull_varnos() reference a nonexistent rel, so we strip it here to match the + * canonical PlaceHolderVar. + */ + static Node * + remove_rel_from_phvs(Node *node, int relid, int ojrelid) + { + Relids removable = bms_add_member(bms_make_singleton(relid), ojrelid); + + return remove_rel_from_phvs_mutator(node, removable); + } ++>>>>>>> theirs -static Node * -remove_rel_from_phvs_mutator(Node *node, Relids removable) -{ - if (node == NULL) - return NULL; - if (IsA(node, PlaceHolderVar)) + while ((relid = bms_next_member(removed_relids, relid)) >= 0) { - PlaceHolderVar *phv = (PlaceHolderVar *) node; - Relids newphrels; - - /* Upper-level PlaceHolderVars should be long gone at this point */ - Assert(phv->phlevelsup == 0); - - /* Copy the PlaceHolderVar and mutate what's below ... */ - phv = (PlaceHolderVar *) - expression_tree_mutator(node, - remove_rel_from_phvs_mutator, - removable); + ChangeVarNodes((Node *) root->parse, relid, INVALID_VAR, 0); /* - * ... then strip the removed rels from its relid sets. - * - * If stripping would empty phrels, the PHV is evaluated only at the - * removed relation(s); it then belongs to an EquivalenceMember that - * the caller drops immediately afterwards. Leave such a PHV - * untouched rather than build one with empty phrels, which the rest - * of the planner assumes never occurs. + * processed_tlist shares some but not all of its nodes with + * parse->targetList, so it has to be processed separately. (That's + * harmless: ChangeVarNodes works in-place, and removing a relid that + * isn't there is idempotent.) */ - newphrels = bms_difference(phv->phrels, removable); - if (!bms_is_empty(newphrels)) - { - phv->phrels = newphrels; - phv->phnullingrels = bms_difference(phv->phnullingrels, - removable); - } + ChangeVarNodes((Node *) root->processed_tlist, relid, INVALID_VAR, 0); - return (Node *) phv; + /* There could be references in the append_rel_list, too */ + if (root->append_rel_list != NIL) + ChangeVarNodes((Node *) root->append_rel_list, relid, INVALID_VAR, 0); } - return expression_tree_mutator(node, - remove_rel_from_phvs_mutator, - removable); } -/* - * Remove any occurrences of the target relid from a joinlist structure. - * - * It's easiest to build a whole new list structure, so we handle it that - * way. Efficiency is not a big deal here. - * - * *nremoved is incremented by the number of occurrences removed (there - * should be exactly one, but the caller checks that). - */ -static List * -remove_rel_from_joinlist(List *joinlist, int relid, int *nremoved) -{ - List *result = NIL; - ListCell *jl; - - foreach(jl, joinlist) - { - Node *jlnode = (Node *) lfirst(jl); - - if (IsA(jlnode, RangeTblRef)) - { - int varno = ((RangeTblRef *) jlnode)->rtindex; - - if (varno == relid) - (*nremoved)++; - else - result = lappend(result, jlnode); - } - else if (IsA(jlnode, List)) - { - /* Recurse to handle subproblem */ - List *sublist; - - sublist = remove_rel_from_joinlist((List *) jlnode, - relid, nremoved); - /* Avoid including empty sub-lists in the result */ - if (sublist) - result = lappend(result, sublist); - } - else - { - elog(ERROR, "unrecognized joinlist node type: %d", - (int) nodeTag(jlnode)); - } - } - - return result; -} - - /* * reduce_unique_semijoins * Check for semijoins that can be simplified to plain inner joins @@@ -1537,103 -1978,205 +1975,106 @@@ fixup_selfjoin_jointree(PlannerInfo *ro } /* - * Remove a relation after we have proven that it participates only in an - * unneeded unique self-join. + * fixup_selfjoin_quals + * Clean up one qual list after self-join elimination. * - * Replace any links in planner info structures. + * Two things need fixing here. First, a join clause such as "t1.a = t2.a" + * has turned into "t1.a = t1.a". For a strict mergejoinable operator that + * means "t1.a IS NOT NULL", and we should make the substitution, for two + * reasons: + * 1. It will typically result in better selectivity estimates. + * 2. EquivalenceClass processing is likely to make the substitution + * if we don't. While not directly harmful, we'd then fail to + * recognize it as a duplicate of a user-written "t1.a IS NOT NULL" + * clause, again leading to bad selectivity estimates. + * Second, conditions that were written against the two relations separately + * may now be identical, and we don't want to apply the same condition twice + * (much less double-count its selectivity). * - * Transfer join and restriction clauses from the removed relation to the - * remaining one. We change the Vars of the clause to point to the - * remaining relation instead of the removed one. The clauses that require - * a subset of joinrelids become restriction clauses of the remaining - * relation, and others remain join clauses. We append them to - * baserestrictinfo and joininfo, respectively, trying not to introduce - * duplicates. + * We only touch the top-level conjuncts of the list. There, turning a NULL + * result into FALSE makes no difference, whereas below a NOT it would, + * invalidating the IS NOT NULL substitution. EquivalenceClass processing + * will not be applied to sub-clauses, and cleaning up duplicates in them + * seems like more trouble than it's worth. Also, we only consider clauses + * that mention the relation we merged into, so that we don't change the + * treatment of anything we didn't touch. * - * We also have to process the 'joinclauses' list here, because it - * contains EC-derived join clauses which must become filter clauses. It - * is not enough to just correct the ECs because the EC-derived - * restrictions are generated before join removal (see - * generate_base_implied_equalities). - * - * NOTE: Remember to keep the code in sync with PlannerInfo to be sure all - * cached relids and relid bitmapsets can be correctly cleaned during the - * self-join elimination procedure. + * Since this is not a correctness issue but just an optimization opportunity, + * we likewise don't worry about recognizing duplicates that appear in + * different qual lists. */ -static void -remove_self_join_rel(PlannerInfo *root, PlanRowMark *kmark, PlanRowMark *rmark, - RelOptInfo *toKeep, RelOptInfo *toRemove, - List *restrictlist) +static List * +fixup_selfjoin_quals(PlannerInfo *root, List *quals, int relid) { - List *joininfos; - ListCell *lc; - int i; - List *jinfo_candidates = NIL; - List *binfo_candidates = NIL; - - Assert(toKeep->relid > 0); - Assert(toRemove->relid > 0); - - /* - * Replace the index of the removing table with the keeping one. The - * technique of removing/distributing restrictinfo is used here to attach - * just appeared (for keeping relation) join clauses and avoid adding - * duplicates of those that already exist in the joininfo list. - */ - joininfos = list_copy(toRemove->joininfo); - foreach_node(RestrictInfo, rinfo, joininfos) - { - remove_join_clause_from_rels(root, rinfo, rinfo->required_relids); - ChangeVarNodesExtended((Node *) rinfo, toRemove->relid, toKeep->relid, - 0, replace_relid_callback); - - if (bms_membership(rinfo->required_relids) == BMS_MULTIPLE) - jinfo_candidates = lappend(jinfo_candidates, rinfo); - else - binfo_candidates = lappend(binfo_candidates, rinfo); - } - - /* - * Concatenate restrictlist to the list of base restrictions of the - * removing table just to simplify the replacement procedure: all of them - * weren't connected to any keeping relations and need to be added to some - * rels. - */ - toRemove->baserestrictinfo = list_concat(toRemove->baserestrictinfo, - restrictlist); - foreach_node(RestrictInfo, rinfo, toRemove->baserestrictinfo) - { - ChangeVarNodesExtended((Node *) rinfo, toRemove->relid, toKeep->relid, - 0, replace_relid_callback); - - if (bms_membership(rinfo->required_relids) == BMS_MULTIPLE) - jinfo_candidates = lappend(jinfo_candidates, rinfo); - else - binfo_candidates = lappend(binfo_candidates, rinfo); - } - - /* - * Now, add all non-redundant clauses to the keeping relation. - */ - add_non_redundant_clauses(root, binfo_candidates, - &toKeep->baserestrictinfo, toRemove->relid); - add_non_redundant_clauses(root, jinfo_candidates, - &toKeep->joininfo, toRemove->relid); - - list_free(binfo_candidates); - list_free(jinfo_candidates); - - /* - * Arrange equivalence classes, mentioned removing a table, with the - * keeping one: varno of removing table should be replaced in members and - * sources lists. Also, remove duplicated elements if this replacement - * procedure created them. - */ - i = -1; - while ((i = bms_next_member(toRemove->eclass_indexes, i)) >= 0) - { - EquivalenceClass *ec = (EquivalenceClass *) list_nth(root->eq_classes, i); - - update_eclasses(ec, toRemove->relid, toKeep->relid); - toKeep->eclass_indexes = bms_add_member(toKeep->eclass_indexes, i); - } - - /* - * Transfer the targetlist and attr_needed flags. - */ - - foreach(lc, toRemove->reltarget->exprs) - { - Node *node = lfirst(lc); - - ChangeVarNodesExtended(node, toRemove->relid, toKeep->relid, 0, - replace_relid_callback); - if (!list_member(toKeep->reltarget->exprs, node)) - toKeep->reltarget->exprs = lappend(toKeep->reltarget->exprs, node); - } - - for (i = toKeep->min_attr; i <= toKeep->max_attr; i++) - { - int attno = i - toKeep->min_attr; - - toRemove->attr_needed[attno] = adjust_relid_set(toRemove->attr_needed[attno], - toRemove->relid, toKeep->relid); - toKeep->attr_needed[attno] = bms_add_members(toKeep->attr_needed[attno], - toRemove->attr_needed[attno]); - } + List *result = NIL; + ListCell *l; - /* - * If the removed relation has a row mark, transfer it to the remaining - * one. - * - * If both rels have row marks, just keep the one corresponding to the - * remaining relation because we verified earlier that they have the same - * strength. - */ - if (rmark) + foreach(l, quals) { - if (kmark) - { - Assert(kmark->markType == rmark->markType); + Node *qual = (Node *) lfirst(l); - root->rowMarks = list_delete_ptr(root->rowMarks, rmark); - } - else + if (bms_is_member(relid, pull_varnos(root, qual))) { - /* Shouldn't have inheritance children here. */ - Assert(rmark->rti == rmark->prti); - - rmark->rti = rmark->prti = toKeep->relid; + qual = replace_selfjoin_qual(qual); + /* Drop it if the substitution has made it a duplicate */ + if (list_member(result, qual)) + continue; } + result = lappend(result, qual); } - /* - * Replace varno in all the query structures, except nodes RangeTblRef - * otherwise later remove_rel_from_joinlist will yield errors. - */ - ChangeVarNodesExtended((Node *) root->parse, toRemove->relid, toKeep->relid, - 0, replace_relid_callback); - - /* Replace links in the planner info */ - remove_rel_from_query(root, toRemove->relid, toKeep->relid, NULL, NULL); - - /* Replace varno in the fully-processed targetlist */ - ChangeVarNodesExtended((Node *) root->processed_tlist, toRemove->relid, - toKeep->relid, 0, replace_relid_callback); - - /* - * No need to touch all_result_relids or leaf_result_relids: at this point - * those sets contain only parse->resultRelation; inheritance children - * have not been added yet; that happens later in add_other_rels_to_query. - * And remove_self_joins_recurse rejects parse->resultRelation as an SJE - * candidate to preserve the EPQ mechanism. So toRemove->relid cannot be - * a member. - */ - Assert(!bms_is_member(toRemove->relid, root->all_result_relids)); - Assert(!bms_is_member(toRemove->relid, root->leaf_result_relids)); - - /* - * There may be references to the rel in root->fkey_list, but if so, - * match_foreign_keys_to_quals() will get rid of them. - */ - - /* - * Finally, remove the rel from the baserel array to prevent it from being - * referenced again. (We can't do this earlier because - * remove_join_clause_from_rels will touch it.) - */ - root->simple_rel_array[toRemove->relid] = NULL; - root->simple_rte_array[toRemove->relid] = NULL; - - /* And nuke the RelOptInfo, just in case there's another access path. */ - pfree(toRemove); + return result; +} ++<<<<<<< ours +/* + * replace_selfjoin_qual + * Replace one "X = X" qual by "X IS NOT NULL", if it is one. + */ +static Node * +replace_selfjoin_qual(Node *qual) +{ + OpExpr *opexpr; + Node *leftop; + Node *rightop; + NullTest *ntest; + + /* See if it looks like "X op X" */ + if (!is_opclause(qual)) + return qual; + opexpr = (OpExpr *) qual; + if (list_length(opexpr->args) != 2) + return qual; + leftop = get_leftop((Expr *) opexpr); + rightop = get_rightop((Expr *) opexpr); + if (!equal(leftop, rightop)) + return qual; + ++======= ++>>>>>>> theirs /* - * Now repeat construction of attr_needed bits coming from all other - * sources. + * The operator must be strict and behave like btree equality, else we + * can't conclude that it yields true for any non-null input. And the + * input had better not be volatile, else the two evaluations might not + * agree. If either condition doesn't hold, the clause is not a candidate + * to be an equivalence, so we needn't worry about it getting replaced by + * equivclass.c. */ - rebuild_placeholder_attr_needed(root); - rebuild_joinclause_attr_needed(root); - rebuild_eclass_attr_needed(root); - rebuild_lateral_attr_needed(root); + set_opfuncid(opexpr); + if (!func_strict(opexpr->opfuncid)) + return qual; + if (!op_mergejoinable(opexpr->opno, exprType(leftop))) + return qual; + if (contain_volatile_functions(leftop)) + return qual; + + /* OK, replace it */ + ntest = makeNode(NullTest); + ntest->arg = (Expr *) leftop; + ntest->nulltesttype = IS_NOT_NULL; + ntest->argisrow = false; /* correct even if composite arg */ + ntest->location = -1; + return (Node *) ntest; } /* @@@ -2130,26 -2655,605 +2571,586 @@@ self_join_candidates_cmp(const void *a * go over each set with the same Oid, and consider each pair of relations * in this set. * - * To remove the join, we mark one of the participating relations as dead - * and rewrite all references to it to point to the remaining relation. - * This includes modifying RestrictInfos, EquivalenceClasses, and - * EquivalenceMembers. We also have to modify the row marks. The join clauses - * of the removed relation become either restriction or join clauses, based on - * whether they reference any relations not participating in the removed join. + * To remove the join, we delete one of the participating relations from the + * query's jointree and rewrite all references to it to point to the remaining + * relation. We also have to modify their row marks. * - * 'joinlist' is the top-level joinlist of the query. If it has any - * references to the removed relations, we update them to point to the - * remaining ones. + * 'joinlist' is the top-level joinlist of the query; we use it to identify + * groups of relations that could be joined to each other. + * + * We return true if we removed any self-joins. If so, the caller must + * recompute everything that was derived from the jointree, and should then + * try join simplifications again since we might have exposed opportunities + * for additional simplifications. */ -List * +bool remove_useless_self_joins(PlannerInfo *root, List *joinlist) { - Relids toRemove = NULL; - int relid = -1; - + /* Skip if SJE is disabled, or if the joinlist has less than 2 members. */ if (!enable_self_join_elimination || joinlist == NIL || (list_length(joinlist) == 1 && !IsA(linitial(joinlist), List))) - return joinlist; - - /* - * Merge pairs of relations participated in self-join. Remove unnecessary - * range table entries. - */ - toRemove = remove_self_joins_recurse(root, joinlist, toRemove); - - if (unlikely(toRemove != NULL)) - { - /* At the end, remove orphaned relation links */ - while ((relid = bms_next_member(toRemove, relid)) >= 0) - { - int nremoved = 0; - - joinlist = remove_rel_from_joinlist(joinlist, relid, &nremoved); - if (nremoved != 1) - elog(ERROR, "failed to find relation %d in joinlist", relid); - } - } + return false; - return joinlist; + /* Try to merge pairs of self-joined relations. */ + return remove_self_joins_recurse(root, joinlist); } + + /* + * remove_useless_inner_joins + * Scans all foreign keys in the query to find and remove referenced + * relations that act only to duplicate referential integrity guarantees. + * + * We are passed the current joinlist and return the updated list. Other + * data structures that have to be updated are accessible via "root". + */ + List * + remove_useless_inner_joins(PlannerInfo *root, List *joinlist) + { + Relids removed_relids = NULL; + + restart: + foreach_node(ForeignKeyOptInfo, fkinfo, root->fkey_list) + { + int nremoved; + + /* + * Skip if either the referencing or the referenced relation has + * already been removed by a prior FK removal in this loop. + */ + if (bms_is_member(fkinfo->con_relid, removed_relids) || + bms_is_member(fkinfo->ref_relid, removed_relids)) + continue; + + /* Skip if not removable */ + if (!inner_join_is_removable(root, fkinfo)) + continue; + + /* Inject IS NOT NULL clauses for nullable foreign key columns */ + inject_fk_not_null_quals(root, fkinfo); + + /* Remove the referenced relation */ + remove_referenced_rel_from_query(root, fkinfo); + + /* We verify that exactly one reference gets removed from joinlist */ + nremoved = 0; + joinlist = remove_rel_from_joinlist(joinlist, fkinfo->ref_relid, &nremoved); + if (nremoved != 1) + elog(ERROR, "failed to find relation %d in joinlist", fkinfo->ref_relid); + + removed_relids = bms_add_member(removed_relids, fkinfo->ref_relid); + + /* + * Restart the scan. This is necessary to ensure we find all + * removable joins independently of ordering of the fkey_list: a just- + * completed removal can collapse another EC to a single rel, which + * makes a previously-rejected FK pass inner_join_is_removable's + * multi-rel-EC count check. + */ + goto restart; + } + + bms_free(removed_relids); + + return joinlist; + } + + /* + * inner_join_is_removable + * Check whether an inner join to the referenced relation of a foreign key + * can be safely removed from the query tree. + * + * To be removable, the referenced relation must act only as a structural + * anchor. The inner join must be mathematically guaranteed to produce exactly + * one matching row for each referencing relation's row. The foreign key + * constraint guarantees existence (at least one match), and the referenced + * relation's unique constraint guarantees non-duplication (at most one match). + * + * The referenced relation's non-key columns cannot be used anywhere in the + * query. Because the referenced relation will be removed, we would have no + * way to read their values. Even if used strictly within the join condition, + * they would act as local filters, violating the exact-match guarantee. + * + * Theoretically, the referenced relation's key columns represent the exact + * same logical values as the referencing relation's columns due to the foreign + * key equality. However, they are not strictly interchangeable in the query + * tree. Substituting them requires preserving exact data types, collations, + * and operator family semantics. Because the planner currently lacks a + * mechanism to safely perform this variable substitution across differing + * schemas, their usage is strictly limited. They cannot be used in contexts + * that require rewriting Var references, such as targetlist, restriction + * clauses, lateral_vars, or righthand-side expressions of semijoins. They + * are, however, permitted to bridge multi-hop joins via EquivalenceClasses. + * Removing the relation safely drops its members from the ECs, and the planner + * natively deduces the remaining transitive equalities. + * + * NOTE: This function assumes the caller will inject IS NOT NULL filters for + * the referencing relation's FK columns if they are not strictly enforced by + * the schema to prevent partial-match ghost rows. + */ + static bool + inner_join_is_removable(PlannerInfo *root, ForeignKeyOptInfo *fkinfo) + { + RelOptInfo *con_rel; + RelOptInfo *ref_rel; + int attroff; + Relids inputrelids; + Bitmapset *fk_attnums = NULL; + int colno; + int multirel_ec_count = 0; + int i; + + /* User has disabled this optimization. */ + if (!enable_fk_inner_join_removal) + return false; + + /* + * If the constraint is deferrable, the physical tables may temporarily + * violate the FK during an active transaction. The inner join must be + * executed to filter out uncommitted orphaned rows. + */ + if (fkinfo->con_deferrable) + return false; + + /* + * If the constraint is not validated (NOT VALID), existing data may + * violate the FK even though new modifications are enforced. We cannot + * rely on such a constraint for join removal. + */ + if (!fkinfo->con_validated) + return false; + + /* + * Never try to eliminate the query's result relation. UPDATE, DELETE, + * and MERGE can all build a join tree where the target relation appears + * as the FK referenced rel. + */ + if (fkinfo->ref_relid == root->parse->resultRelation) + return false; + + /* + * Either relid might identify a rel that is in the query's rtable but + * isn't referenced by the jointree, or has been removed by join removal, + * so that it won't have a RelOptInfo. Hence we use find_base_rel_noerr() + * here. We can ignore such FKs. + */ + con_rel = find_base_rel_noerr(root, fkinfo->con_relid); + if (con_rel == NULL) + return false; + ref_rel = find_base_rel_noerr(root, fkinfo->ref_relid); + if (ref_rel == NULL) + return false; + + /* + * Ignore FK unless both rels are baserels. This gets rid of FKs that + * link to inheritance child rels (otherrels). + */ + if (con_rel->reloptkind != RELOPT_BASEREL || + ref_rel->reloptkind != RELOPT_BASEREL) + return false; + + /* + * If the referenced relation has any restriction clauses, they act as + * explicit filters. Since we cannot perform variable substitution to + * rewrite these clauses, we must abort. + */ + if (ref_rel->baserestrictinfo) + return false; + + /* + * If the referenced relation is being sampled via TABLESAMPLE, the join + * would normally restrict the result to child rows whose parent landed in + * the sample. Removing the join would lose that restriction and return + * all child rows with a non-null FK, which is more than the joined form + * would return. Since we have no way to preserve the sampling effect + * when the referenced rel is removed, we must skip the optimization. + */ + if (root->simple_rte_array[fkinfo->ref_relid]->tablesample != NULL) + return false; + + /* + * For joininfo, we look at clause_relids rather than at the joininfo list + * itself. required_relids may exceed clause_relids when an outer join ON + * clause needs to be forced to evaluate exactly at the level of the outer + * join; that can place a clause on ref_rel->joininfo even though ref_rel + * doesn't appear in the clause's expression at all. Reject only when a + * join clause actually references ref_rel. + */ + foreach_node(RestrictInfo, rinfo, ref_rel->joininfo) + { + if (bms_is_member(ref_rel->relid, rinfo->clause_relids)) + return false; + } + + /* + * Build a fast lookup bitmap for the referenced relation's foreign key + * attributes to optimize the subsequent attribute usage checks. + */ + for (colno = 0; colno < fkinfo->nkeys; colno++) + { + fk_attnums = bms_add_member(fk_attnums, + fkinfo->confkey[colno] - ref_rel->min_attr); + } + + /* + * Verify attribute usage against the substitution constraints. + * + * As a micro-optimization, it seems better to start with max_attr and + * count down rather than starting with min_attr and counting up, on the + * theory that the system attributes are somewhat less likely to be wanted + * and should be tested last. + */ + for (attroff = ref_rel->max_attr - ref_rel->min_attr; + attroff >= 0; + attroff--) + { + if (bms_is_member(attroff, fk_attnums)) + { + /* + * The specific columns involved in the foreign key are allowed to + * bridge multi-hop joins via EquivalenceClasses. However, they + * must not be needed in the final targetlist, which would require + * variable substitution. + */ + if (bms_is_member(0, ref_rel->attr_needed[attroff])) + return false; + + continue; + } + + /* + * The non-key columns must not be used anywhere. See comments above. + */ + if (!bms_is_empty(ref_rel->attr_needed[attroff])) + return false; + } + + /* Compute the relid set for the join we are considering */ + inputrelids = bms_make_singleton(fkinfo->con_relid); + inputrelids = bms_add_member(inputrelids, fkinfo->ref_relid); + + /* + * Similarly check that the referenced rel isn't needed by any + * PlaceHolderVars that will be used above the join. The PHV case is a + * little bit more complicated, because PHVs may have been assigned a + * ph_eval_at location that includes the ref_rel, yet their contained + * expression might not actually reference the ref_rel (it could be just a + * constant, for instance). If such a PHV is due to be evaluated above + * the join then it needn't prevent inner join removal. + */ + foreach_node(PlaceHolderInfo, phinfo, root->placeholder_list) + { + if (bms_overlap(phinfo->ph_lateral, ref_rel->relids)) + return false; /* it references ref_rel laterally */ + if (!bms_overlap(phinfo->ph_eval_at, ref_rel->relids)) + continue; /* it definitely doesn't reference ref_rel */ + if (bms_is_subset(phinfo->ph_needed, inputrelids)) + continue; /* PHV is not used above the join */ + + /* + * We need to be sure there will still be a place to evaluate the PHV + * if we remove the join, ie that ph_eval_at wouldn't become empty. + * We've established above that ph_eval_at overlaps ref_rel->relids, + * so the only way removal empties it is if ref_rel is the sole + * member. + */ + if (bms_membership(phinfo->ph_eval_at) == BMS_SINGLETON) + return false; /* there isn't any other place to eval PHV */ + /* Check contained expression last, since this is a bit expensive */ + if (bms_overlap(pull_varnos(root, (Node *) phinfo->ph_var->phexpr), + ref_rel->relids)) + return false; /* contained expression references ref_rel */ + } + + /* + * If the referencing and referenced relations are separated by an outer + * join boundary, removing the inner join alters the null-padding + * semantics of the query. + * + * Additionally, if the referenced relation's columns are referenced in + * the RHS expressions of any semi-join, we must punt. We do not have a + * way to rewrite those references. + */ + foreach_node(SpecialJoinInfo, sjinfo, root->join_info_list) + { + if ((bms_is_member(fkinfo->con_relid, sjinfo->syn_lefthand) ^ + bms_is_member(fkinfo->ref_relid, sjinfo->syn_lefthand)) || + (bms_is_member(fkinfo->con_relid, sjinfo->syn_righthand) ^ + bms_is_member(fkinfo->ref_relid, sjinfo->syn_righthand))) + return false; + + if (sjinfo->semi_rhs_exprs != NIL) + { + if (bms_is_member(fkinfo->ref_relid, + pull_varnos(root, (Node *) sjinfo->semi_rhs_exprs))) + return false; + } + } + + /* + * If the referenced relation is referenced laterally by any other + * relation, punt. We do not have a way to rewrite those references. + */ + if (root->hasLateralRTEs) + { + Index rti; + + for (rti = 1; rti < root->simple_rel_array_size; rti++) + { + RelOptInfo *otherrel = root->simple_rel_array[rti]; + + if (otherrel == NULL || otherrel->relid == fkinfo->ref_relid) + continue; + + if (otherrel->lateral_vars != NIL) + { + if (bms_is_member(fkinfo->ref_relid, + pull_varnos(root, (Node *) otherrel->lateral_vars))) + return false; + } + } + } + + /* + * We must mathematically prove that every column in the referenced + * relation's foreign key is bound to the referencing relation's foreign + * key via a valid equality operator within an equivalence class. + */ + for (colno = 0; colno < fkinfo->nkeys; colno++) + { + EquivalenceClass *ec; + + ec = match_eclasses_to_foreign_key_col(root, fkinfo, colno, NULL); + + if (ec == NULL) + return false; + } + + /* + * We must also prove the inverse: the referenced relation must not + * participate in any EquivalenceClasses other than the ones that bridge + * it to the referencing relation's foreign key, and within those ECs no + * EquivalenceMember may mix ref_rel with other relations. + * + * We have already verified that the relation participates in 'nkeys' + * valid ECs bridging to the referencing relation. If it appears in more + * multi-rel ECs than that, it means a referenced key column is involved + * in an equality that the planner refused to merge with the foreign key's + * EC. This split occurs during collation mismatches, incompatible + * operator families, or if the key is wrapped in an expression more + * complex than a simple Var (e.g., ref_rel.pk + 1 = c.val). In those + * scenarios, removing the referenced relation would silently destroy the + * join condition of that separate EC, because the referencing relation's + * column is not present in it to take over the transitive equality. + * + * Single-rel ECs (sort/group expressions, or ECs left degenerate by a + * prior FK removal stripping their other side) are skipped: their + * surviving members all reference ref_rel exclusively and will be dropped + * during remove_rel_from_eclass. Skipping them is what lets a chain of + * FK removals succeed once the caller re-runs the scan. + * + * Within the bridging ECs, we also need to reject any EM that mentions + * ref_rel together with other relations (e.g., ref_rel.pk + other_rel.x). + * Such an EM would survive remove_rel_from_eclass with a non-empty + * em_relids, yet its expression still embeds a Var on the now-removed + * ref_rel. + */ + i = -1; + while ((i = bms_next_member(ref_rel->eclass_indexes, i)) >= 0) + { + EquivalenceClass *ec = (EquivalenceClass *) list_nth(root->eq_classes, i); + + if (bms_membership(ec->ec_relids) == BMS_MULTIPLE) + multirel_ec_count++; + + foreach_node(EquivalenceMember, em, ec->ec_members) + { + if (bms_is_member(fkinfo->ref_relid, em->em_relids) && + bms_membership(em->em_relids) == BMS_MULTIPLE) + return false; + } + } + if (multirel_ec_count != fkinfo->nkeys) + return false; + + /* All checks passed */ + return true; + } + + /* + * inject_fk_not_null_quals + * Injects IS NOT NULL clauses into the referencing relation's restriction + * list for any foreign key columns that are not enforced as NOT NULL by the + * schema. + * + * When we remove a referenced relation (the inner join target) based on a + * foreign key, we lose the implicit filtering of NULLs that a standard inner + * join performs. To preserve mathematical equivalence, we must ensure the + * referencing relation does not emit rows with NULL foreign keys. + */ + static void + inject_fk_not_null_quals(PlannerInfo *root, ForeignKeyOptInfo *fkinfo) + { + RelOptInfo *con_rel; + RangeTblEntry *con_rte; + Bitmapset *notnullattnums; + Bitmapset *already_injected = NULL; + int i; + + con_rel = find_base_rel(root, fkinfo->con_relid); + con_rte = root->simple_rte_array[fkinfo->con_relid]; + Assert(con_rte->rtekind == RTE_RELATION); + Assert(!con_rte->inh); + + /* + * Get the column not-null constraint information for the referencing + * relation. + */ + notnullattnums = find_relation_notnullatts(root, con_rte->relid); + + /* + * Collect attnos already covered by an IS NOT NULL clause on con_rel in + * baserestrictinfo, so we don't append a redundant qual. Such clauses + * may come from a prior FK removal for another FK on the same con_rel, a + * user-written IS NOT NULL clause, or other planner transformations that + * inject NullTest restrictions. + */ + foreach_node(RestrictInfo, r, con_rel->baserestrictinfo) + { + NullTest *ntest; + Var *var; + + if (!IsA(r->clause, NullTest)) + continue; + ntest = (NullTest *) r->clause; + if (ntest->nulltesttype != IS_NOT_NULL || + ntest->argisrow || + !IsA(ntest->arg, Var)) + continue; + var = (Var *) ntest->arg; + Assert(var->varno == fkinfo->con_relid); + if (var->varattno > 0) + already_injected = bms_add_member(already_injected, var->varattno); + } + + for (i = 0; i < fkinfo->nkeys; i++) + { + AttrNumber con_attno = fkinfo->conkey[i]; + Var *var; + NullTest *ntest; + RestrictInfo *rinfo; + Oid vartype; + int32 vartypmod; + Oid varcollid; + + /* System columns are implicitly NOT NULL */ + if (con_attno < 0) + continue; + + /* Schema already guarantees the column is NOT NULL */ + if (bms_is_member(con_attno, notnullattnums)) + continue; + + /* Already covered by an existing IS NOT NULL on con_rel */ + if (bms_is_member(con_attno, already_injected)) + continue; + + get_atttypetypmodcoll(con_rte->relid, + con_attno, + &vartype, + &vartypmod, + &varcollid); + + var = makeVar(fkinfo->con_relid, + con_attno, + vartype, + vartypmod, + varcollid, + 0); + + ntest = makeNode(NullTest); + ntest->arg = (Expr *) var; + ntest->nulltesttype = IS_NOT_NULL; + ntest->argisrow = false; + ntest->location = -1; + + rinfo = make_restrictinfo(root, + (Expr *) ntest, + true, + false, + false, + false, + root->qual_security_level, + bms_make_singleton(fkinfo->con_relid), + NULL, + NULL); + + con_rel->baserestrictinfo = lappend(con_rel->baserestrictinfo, rinfo); + already_injected = bms_add_member(already_injected, con_attno); + } + + bms_free(already_injected); + } + + /* + * remove_referenced_rel_from_query + * Remove the referenced rel of a foreign key and references to it from + * the planner's data structures, having determined that there is no + * need to include it in the query. + * + * We are not terribly thorough here. We only bother to update parts of + * the planner's data structures that will actually be consulted later. + */ + static void + remove_referenced_rel_from_query(PlannerInfo *root, ForeignKeyOptInfo *fkinfo) + { + int relid = fkinfo->ref_relid; + RelOptInfo *ref_rel = find_base_rel(root, relid); + Relids joinrelids; + + /* Compute the relid set for the join we are considering */ + joinrelids = bms_make_singleton(fkinfo->con_relid); + joinrelids = bms_add_member(joinrelids, relid); + + remove_rel_from_query(root, relid, -1, NULL, joinrelids); + + bms_free(joinrelids); + + /* + * Any join clause that survived in ref_rel->joininfo doesn't reference + * ref_rel, but its relid sets may still mention ref_rel because it was + * distributed there based on required_relids. Strip ref_rel from each + * such clause's relid sets so that surviving rels see a consistent state. + */ + foreach_node(RestrictInfo, rinfo, ref_rel->joininfo) + { + Assert(!bms_is_member(ref_rel->relid, rinfo->clause_relids)); + + remove_rel_from_restrictinfo(rinfo, relid, 0); + + Assert(bms_membership(rinfo->required_relids) == BMS_MULTIPLE); + } + + /* + * There may be references to the rel in root->fkey_list, but if so, + * match_foreign_keys_to_quals() will get rid of them. + */ + + /* + * Now remove the rel from the baserel array to prevent it from being + * referenced again. + */ + root->simple_rel_array[relid] = NULL; + root->simple_rte_array[relid] = NULL; + + /* And nuke the RelOptInfo, just in case there's another access path */ + pfree(ref_rel); + + /* + * Now repeat construction of attr_needed bits coming from all other + * sources. + */ + rebuild_placeholder_attr_needed(root); + rebuild_joinclause_attr_needed(root); + rebuild_eclass_attr_needed(root); + rebuild_lateral_attr_needed(root); + } diff --cc src/include/optimizer/planmain.h index c23ab568b98,b6b5b930831..00000000000 --- a/src/include/optimizer/planmain.h +++ b/src/include/optimizer/planmain.h @@@ -111,7 -116,12 +112,16 @@@ extern bool query_is_distinct_for(Quer extern bool innerrel_is_unique(PlannerInfo *root, Relids joinrelids, Relids outerrelids, RelOptInfo *innerrel, JoinType jointype, List *restrictlist, bool force_cache); ++<<<<<<< ours +extern bool remove_useless_self_joins(PlannerInfo *root, List *joinlist); ++======= + extern bool innerrel_is_unique_ext(PlannerInfo *root, Relids joinrelids, + Relids outerrelids, RelOptInfo *innerrel, + JoinType jointype, List *restrictlist, + bool force_cache, List **extra_clauses); + extern List *remove_useless_self_joins(PlannerInfo *root, List *joinlist); + extern List *remove_useless_inner_joins(PlannerInfo *root, List *joinlist); ++>>>>>>> theirs /* * prototypes for plan/setrefs.c