pg.ddx.io  pgsql-hackers@postgresql.org mailing list archive  
help / color / mirror / Atom feed
remove_useless_joins vs. bug #19560
74+ messages / 9 participants
[nested] [flat]

Commits from this thread:
  2026-10-06 6b858a36dd 8bcb6f901e 3bfc7c8491 00d1b4598a 533915857a  Don't reprocess PHV copies within outer aggregates' arguments
  2026-09-29 37c2bc950c 78d07020bd dca6a9e320  Prevent self-join elimination when RTEs' checkAsUser fields differ.
  2026-09-19 a8bb1a7779 c04649d1d3 051db7737c bd003dca09 9df23331f0  Fix join removal when Vars reference the removed join via its alias
  2026-09-19 bee81f7864 22a8f53397 83bd1c1bad 51f9e30f38 8ea97ee348  Fix preprocessing of PHV copies pushed down into subqueries
  2026-09-14 e28cf96e93 2d48d0f153 37b6e2657c ccb7d9dba1 54ac06f31b  Fix stale copies of PHVs in subqueries
  2026-09-02 197a41aa6e fc8ed63624  Remove quals made redundant by reducing outer joins to antijoins
* remove_useless_joins vs. bug #19560
@ 2026-07-20 18:52 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-22 07:44 ` Re: remove_useless_joins vs. bug #19560 Tender Wang <tndrwang@gmail.com>
  2026-07-24 13:38 ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  0 siblings, 2 replies; 74+ messages in thread

From: Tom Lane @ 2026-07-20 18:52 UTC (permalink / raw)
  To: pgsql-hackers@lists.postgresql.org

I've traced through bug #19560 [1], and determined that what is
happening is this:

1. After flattening the CTE and recognizing that the join to it
can be discarded, we are left with the outer join between the
two real tables, plus a WHERE clause that looks like
"Var = PlaceHolderVar", where the PHV is marked as needing to
be evaluated above the outer join.  So far so good.

2. Within deconstruct_jointree, we break the WHERE clause down
into an EquivalenceClass.

3. remove_useless_joins detects that the outer join's RHS is
unique and we don't need any values from the RHS above the join,
so we can remove that join too.  It runs around and does a
not-great job of removing references to the removed RTE.

4. The EquivalenceClass now represents a base restriction clause,
since the only rel it still references is the one surviving relation
(the "items" table).

5. But we've already generated base restriction clauses, and
remove_useless_joins does nothing to reconsider that.  So the
WHERE clause effectively disappears into the ether: it will
never get propagated into the generated plan.

I'm more than slightly astonished that nobody has reported this
before, because it seems like a failure mode that could be reached
fairly easily.  I think it wasn't reachable before v16, because
before we had "nullingrels" we had to avoid treating clauses like
this one as EquivalenceClasses.  But that seems like plenty of time
for someone to notice they were getting wrong answers.

Anyway, what to do?  I imagine we could write some code in
analyzejoins.c to consider whether ECs give rise to base restriction
clauses that they didn't before.  But that seems ugly and fragile.
More generally, there is nothing that is not ugly and fragile about
analyzejoins.c's relation removal logic, and the recent addition of
self-join elimination made that situation even worse.  I think we
have a permanent maintenance gotcha there.

I have a modest proposal to make instead: let's nuke all that logic
from orbit.  Revise analyzejoins.c so that it does join removals
working strictly on the jointree representation, which is simpler
and far more stable than any of the planner's derived data.  Then,
if we successfully removed any joins, throw away all the derived
data and loop back around within query_planner() to redo
deconstruct_jointree and all the rest of it.

I'm not sure offhand what the implications would be for planning
speed.  It's possible that this'd actually be faster, considering
what a mess the relation-removal logic is.  But in any case, we
have a bug-prone maintenance nightmare there, and it will get
worse not better as people add more stuff to the planner.  I think
the current approach is unsustainable.

I don't, at present, have a feeling for whether this approach would
lead to a back-patchable fix for the immediate bug.  Maybe we'd take
the risk of a back-patch even if it's bigger than the average
back-patched change.  I find it hard to believe that there are not
other bugs lurking in there, given that remove_leftjoinrel_from_query
intentionally only bothers to "update parts of the planner's data
structures that will actually be consulted later" but it has no good
way to be sure what those are, nor are there any forcing functions to
keep it in sync with what the rest of the code thinks.  The SJE code
seems as bad or worse.

Thoughts?

			regards, tom lane

[1] https://www.postgresql.org/message-id/19560-54cd7ede78d5e355%40postgresql.org






^ permalink  raw  reply  [nested|flat] 74+ messages in thread

* Re: remove_useless_joins vs. bug #19560
  2026-07-20 18:52 remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
@ 2026-07-22 07:44 ` Tender Wang <tndrwang@gmail.com>
  1 sibling, 0 replies; 74+ messages in thread

From: Tender Wang @ 2026-07-22 07:44 UTC (permalink / raw)
  To: Tom Lane <tgl@sss.pgh.pa.us>; +Cc: pgsql-hackers@lists.postgresql.org

Tom Lane <tgl@sss.pgh.pa.us> 于2026年7月21日周二 02:52写道:
>
> Anyway, what to do?  I imagine we could write some code in
> analyzejoins.c to consider whether ECs give rise to base restriction
> clauses that they didn't before.  But that seems ugly and fragile.
> More generally, there is nothing that is not ugly and fragile about
> analyzejoins.c's relation removal logic, and the recent addition of
> self-join elimination made that situation even worse.  I think we
> have a permanent maintenance gotcha there.

Yes,  recently, there have been a few bug fixes on HEAD related to
outer-join removal.
And there is still a bug that is not finished for self-join
elimination, for example: [1]
In the future, more kinds of join removal will be added. We should
think about maintenance now.

>
> I have a modest proposal to make instead: let's nuke all that logic
> from orbit.  Revise analyzejoins.c so that it does join removals
> working strictly on the jointree representation, which is simpler
> and far more stable than any of the planner's derived data.  Then,
> if we successfully removed any joins, throw away all the derived
> data and loop back around within query_planner() to redo
> deconstruct_jointree and all the rest of it.

Current join removals based on the planner's derived data are not complete.
What I mean by complete is: for example,  foo left join (bar t1 inner
join bar t2)
If "bar t1 inner join bar t2", this inner join can be removed according to SJE.
But we have no chance to perform left-join removals. We first do
left-join removals in current logic,
But the right side is not a single rel, so remove_useless_joins()
returns directly.

Can working strictly on the jointree representation handle the above case?

>
> I'm not sure offhand what the implications would be for planning
> speed.  It's possible that this'd actually be faster, considering
> what a mess the relation-removal logic is.  But in any case, we
> have a bug-prone maintenance nightmare there, and it will get
> worse not better as people add more stuff to the planner.  I think
> the current approach is unsustainable.

Agree
In the future, inner join removal may be added, and
remove_rel_from_query() will consider 3 types of join removals at that
time.
I don't think it is easy to maintain.


[1] https://www.postgresql.org/message-id/CAHewXN%3D7kDJjUcgEm%2B6qhaKOXuqzvhRqAAKdafNCRgn0yH7BGg%40mail...

-- 
Thanks,
Tender Wang






^ permalink  raw  reply  [nested|flat] 74+ messages in thread

* Re: remove_useless_joins vs. bug #19560
  2026-07-20 18:52 remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
@ 2026-07-24 13:38 ` Richard Guo <guofenglinux@gmail.com>
  2026-07-25 16:46   ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  1 sibling, 1 reply; 74+ messages in thread

From: Richard Guo @ 2026-07-24 13:38 UTC (permalink / raw)
  To: Tom Lane <tgl@sss.pgh.pa.us>; +Cc: pgsql-hackers@lists.postgresql.org

On Tue, Jul 21, 2026 at 3:52 AM Tom Lane <tgl@sss.pgh.pa.us> wrote:
> Anyway, what to do?  I imagine we could write some code in
> analyzejoins.c to consider whether ECs give rise to base restriction
> clauses that they didn't before.  But that seems ugly and fragile.
> More generally, there is nothing that is not ugly and fragile about
> analyzejoins.c's relation removal logic, and the recent addition of
> self-join elimination made that situation even worse.  I think we
> have a permanent maintenance gotcha there.

I feel the same way about this.

> I have a modest proposal to make instead: let's nuke all that logic
> from orbit.  Revise analyzejoins.c so that it does join removals
> working strictly on the jointree representation, which is simpler
> and far more stable than any of the planner's derived data.  Then,
> if we successfully removed any joins, throw away all the derived
> data and loop back around within query_planner() to redo
> deconstruct_jointree and all the rest of it.

I prototyped this proposal to see how it would look in code, mainly
copying how remove_useless_result_rtes does the removal from the join
tree.  See attached PoC.  Please note that this is far from
review-ready, and it only covers outer-join removal, skipping
self-join elimination for now, and it lacks badly proper comments and
test cases.

But it does fix the reported bug.  It causes one plan change in the
existing tests.  I haven't looked into it, but it doesn't seem like a
blocker.

Overall, the code looks much neater and easier to maintain.  I think
we should go with this proposal.  (I haven't benchmarked planning
performance yet, though.)

- Richard

Attachments:

v1-0001-wip-refactor-join-removal.patch (application/octet-stream, 37.6K) download From 3d7400c22c51389124846e63346c59c685852fa8 Mon Sep 17 00:00:00 2001 From: Richard Guo <guofenglinux@gmail.com> Date: Fri, 24 Jul 2026 22:07:07 +0900 Subject: [PATCH v1] wip: refactor join removal --- src/backend/optimizer/plan/analyzejoins.c | 661 ++-------------------- src/backend/optimizer/plan/planmain.c | 82 ++- src/backend/optimizer/prep/prepjointree.c | 78 +++ src/include/optimizer/planmain.h | 2 +- src/include/optimizer/prep.h | 2 + 5 files changed, 220 insertions(+), 605 deletions(-) diff --git a/src/backend/optimizer/plan/analyzejoins.c b/src/backend/optimizer/plan/analyzejoins.c index 881950e5264..9404dfacd29 100644 --- a/src/backend/optimizer/plan/analyzejoins.c +++ b/src/backend/optimizer/plan/analyzejoins.c @@ -30,6 +30,7 @@ #include "optimizer/paths.h" #include "optimizer/placeholder.h" #include "optimizer/planmain.h" +#include "optimizer/prep.h" #include "optimizer/restrictinfo.h" #include "parser/parse_agg.h" #include "rewrite/rewriteManip.h" @@ -55,19 +56,7 @@ bool enable_self_join_elimination; /* local functions */ static bool join_is_removable(PlannerInfo *root, SpecialJoinInfo *sjinfo); -static void remove_leftjoinrel_from_query(PlannerInfo *root, int relid, - SpecialJoinInfo *sjinfo); -static void remove_rel_from_query(PlannerInfo *root, int relid, - int subst, SpecialJoinInfo *sjinfo, - Relids joinrelids); -static void remove_rel_from_restrictinfo(RestrictInfo *rinfo, - int relid, int ojrelid); -static void remove_rel_from_eclass(PlannerInfo *root, EquivalenceClass *ec, - int relid, int ojrelid); -static void remove_rel_from_restrictinfo_phvs(RestrictInfo *rinfo, - int relid, int ojrelid); -static Node *remove_rel_from_phvs(Node *node, int relid, int ojrelid); -static Node *remove_rel_from_phvs_mutator(Node *node, Relids removable); +static void remove_rel_from_query(PlannerInfo *root, int relid, int subst); static List *remove_rel_from_joinlist(List *joinlist, int relid, int *nremoved); static bool rel_supports_distinctness(PlannerInfo *root, RelOptInfo *rel); static bool rel_is_distinct_for(PlannerInfo *root, RelOptInfo *rel, @@ -88,13 +77,14 @@ static bool replace_relid_callback(Node *node, /* * remove_useless_joins * Check for relations that don't actually need to be joined at all, - * and remove them from the query. + * and remove the first such join we find from the query jointree. * - * We are passed the current joinlist and return the updated list. Other - * data structures that have to be updated are accessible via "root". + * Returns true if a join was removed. Removal works on the jointree + * representation, and the caller is responsible for discarding and rebuilding + * all derived planner state before calling us again. */ -List * -remove_useless_joins(PlannerInfo *root, List *joinlist) +bool +remove_useless_joins(PlannerInfo *root) { ListCell *lc; @@ -102,12 +92,10 @@ remove_useless_joins(PlannerInfo *root, List *joinlist) * We are only interested in relations that are left-joined to, so we can * scan the join_info_list to find them easily. */ -restart: foreach(lc, root->join_info_list) { SpecialJoinInfo *sjinfo = (SpecialJoinInfo *) lfirst(lc); int innerrelid; - int nremoved; /* Skip if not removable */ if (!join_is_removable(root, sjinfo)) @@ -115,36 +103,20 @@ restart: /* * Currently, join_is_removable can only succeed when the sjinfo's - * righthand is a single baserel. Remove that rel from the query and - * joinlist. + * righthand is a single baserel. Remove that join out of the + * jointree; the caller will rebuild everything else. */ innerrelid = bms_singleton_member(sjinfo->min_righthand); - remove_leftjoinrel_from_query(root, innerrelid, sjinfo); + remove_leftjoin_from_jointree(root, innerrelid, sjinfo->ojrelid); - /* We verify that exactly one reference gets removed from joinlist */ - nremoved = 0; - joinlist = remove_rel_from_joinlist(joinlist, innerrelid, &nremoved); - if (nremoved != 1) - elog(ERROR, "failed to find relation %d in joinlist", innerrelid); - - /* - * We can delete this SpecialJoinInfo from the list too, since it's no - * longer of interest. (Since we'll restart the foreach loop - * immediately, we don't bother with foreach_delete_current.) - */ - root->join_info_list = list_delete_cell(root->join_info_list, lc); + pfree(root->simple_rel_array[innerrelid]); + root->simple_rel_array[innerrelid] = NULL; - /* - * Restart the scan. This is necessary to ensure we find all - * removable joins independently of ordering of the join_info_list - * (note that removal of attr_needed bits may make a join appear - * removable that did not before). - */ - goto restart; + return true; } - return joinlist; + return false; } /* @@ -319,151 +291,17 @@ join_is_removable(PlannerInfo *root, SpecialJoinInfo *sjinfo) } /* - * 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. - * - * 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. - * - * This function serves as the common infrastructure for left-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). + * Remove the target relid and references to it from the planner's data + * structures, having determined that there is no need to include it in the + * query. References to the removed relid are replaced with subst. */ static void -remove_rel_from_query(PlannerInfo *root, int relid, - int subst, SpecialJoinInfo *sjinfo, - Relids joinrelids) +remove_rel_from_query(PlannerInfo *root, int relid, int subst) { - 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); - Bitmapset *seen_serials = NULL; - Assert(is_outer_join || is_self_join); - Assert(!is_outer_join || ojrelid > 0); - Assert(!is_outer_join || joinrelids != NULL); + Assert(subst > 0); /* * Update all_baserels and related relid sets. @@ -471,20 +309,11 @@ remove_rel_from_query(PlannerInfo *root, int relid, 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) - { - root->outer_join_rels = bms_del_member(root->outer_join_rels, ojrelid); - root->all_query_rels = bms_del_member(root->all_query_rels, ojrelid); - } - /* * 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. + * relid sets of special joins: those sets have to be adjusted. */ foreach(l, root->join_info_list) { @@ -494,7 +323,6 @@ remove_rel_from_query(PlannerInfo *root, int relid, * 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); @@ -507,125 +335,56 @@ remove_rel_from_query(PlannerInfo *root, int relid, 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 - { - /* - * For self-join removal, replace relid references in - * semi_rhs_exprs. - */ - ChangeVarNodesExtended((Node *) sjinf->semi_rhs_exprs, relid, subst, - 0, replace_relid_callback); - } + /* Replace relid references in semi_rhs_exprs */ + ChangeVarNodesExtended((Node *) sjinf->semi_rhs_exprs, relid, subst, + 0, replace_relid_callback); } /* - * Likewise remove references from PlaceHolderVar data structures, - * removing any no-longer-needed placeholders entirely. We only remove - * PHVs for left-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 is no corresponding test in - * join_is_removable because it doesn't need to distinguish those cases. + * Likewise remove references from PlaceHolderVar data structures. With + * self-join elimination, PHVs get moved to the remaining relation, where + * they might still be needed, so we don't remove any of them. */ foreach(l, root->placeholder_list) { PlaceHolderInfo *phinfo = (PlaceHolderInfo *) lfirst(l); + PlaceHolderVar *phv = phinfo->ph_var; - Assert(!is_outer_join || !bms_is_member(relid, phinfo->ph_lateral)); + phinfo->ph_eval_at = adjust_relid_set(phinfo->ph_eval_at, relid, subst); + Assert(!bms_is_empty(phinfo->ph_eval_at)); /* checked previously */ - if (is_outer_join && - bms_is_subset(phinfo->ph_needed, joinrelids) && - bms_is_member(relid, phinfo->ph_eval_at) && - !bms_is_member(ojrelid, phinfo->ph_eval_at)) - { - root->placeholder_list = foreach_delete_current(root->placeholder_list, - l); - root->placeholder_array[phinfo->phid] = NULL; - } + /* 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 - { - 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 */ + phinfo->ph_needed = NULL; - /* 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); + Assert(!bms_is_empty(phv->phrels)); - 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 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.) - */ - 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); + /* + * Update Var nodes within the PHV's expression to reference the + * replacement relid, and adjust ph_lateral for the relid + * substitution. + */ + 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 */ - } + /* + * 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 */ - } + 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. + * The EquivalenceClasses have already been updated by the caller + * (update_eclasses), so we don't need to touch them here. */ - if (is_outer_join) - { - foreach(l, root->eq_classes) - { - EquivalenceClass *ec = (EquivalenceClass *) lfirst(l); - - remove_rel_from_eclass(root, ec, relid, ojrelid); - } - } /* * Finally, we must prepare for the caller to recompute per-Var @@ -642,14 +401,8 @@ remove_rel_from_query(PlannerInfo *root, int relid, * 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 removal, we strip the removed rel and join from any - * PlaceHolderVar embedded in the surviving rels' restriction clauses and - * join clauses; we needn't bother with the rel being removed, nor when - * the query has no PlaceHolderVars. + * We must also replace references to the removed relid with subst within + * the lateral_vars lists. */ for (rti = 1; rti < root->simple_rel_array_size; rti++) { @@ -672,307 +425,9 @@ remove_rel_from_query(PlannerInfo *root, int relid, otherrel->attr_needed[attroff] = NULL; } - if (is_self_join) - ChangeVarNodesExtended((Node *) otherrel->lateral_vars, relid, - subst, 0, replace_relid_callback); - - if (is_outer_join && rti != relid && root->glob->lastPHId != 0) - { - foreach_node(RestrictInfo, rinfo, otherrel->baserestrictinfo) - remove_rel_from_restrictinfo_phvs(rinfo, relid, ojrelid); - - /* - * Join clauses need the same treatment, but there's no value in - * processing any join clause more than once. So it's slightly - * annoying that we have to find them via the per-base-relation - * joininfo lists. Avoid duplicate processing by tracking the - * rinfo_serial numbers of join clauses we've already seen. (This - * doesn't work for is_clone clauses, so we must waste effort on - * them.) - */ - foreach_node(RestrictInfo, rinfo, otherrel->joininfo) - { - if (!rinfo->is_clone) /* else serial number is not unique */ - { - if (bms_is_member(rinfo->rinfo_serial, seen_serials)) - continue; /* saw it already */ - seen_serials = bms_add_member(seen_serials, - rinfo->rinfo_serial); - } - remove_rel_from_restrictinfo_phvs(rinfo, relid, ojrelid); - } - } - } -} - -/* - * Remove any references to relid or ojrelid from the RestrictInfo. - * - * 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); - 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); - 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); - 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); - 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); - 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); - 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. - * - * 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. - */ -static void -remove_rel_from_eclass(PlannerInfo *root, EquivalenceClass *ec, - int relid, int ojrelid) -{ - 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) && - !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); - 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) || - 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); - 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 relid or ojrelid from the PlaceHolderVars embedded - * in a RestrictInfo's clause. - * - * If it's an OR clause, we must also fix up the orclause, which is a parallel - * representation built from its own sub-RestrictInfos. We recurse into the - * sub-clauses for that, mirroring remove_rel_from_restrictinfo. - */ -static void -remove_rel_from_restrictinfo_phvs(RestrictInfo *rinfo, int relid, int ojrelid) -{ - rinfo->clause = (Expr *) - remove_rel_from_phvs((Node *) rinfo->clause, relid, 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_phvs(rinfo2, relid, ojrelid); - } - } - else - { - RestrictInfo *rinfo2 = castNode(RestrictInfo, orarg); - - remove_rel_from_restrictinfo_phvs(rinfo2, relid, ojrelid); - } - } - } -} - -/* - * 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); -} - -static Node * -remove_rel_from_phvs_mutator(Node *node, Relids removable) -{ - if (node == NULL) - return NULL; - if (IsA(node, PlaceHolderVar)) - { - 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); - - /* - * ... 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. - */ - newphrels = bms_difference(phv->phrels, removable); - if (!bms_is_empty(newphrels)) - { - phv->phrels = newphrels; - phv->phnullingrels = bms_difference(phv->phnullingrels, - removable); - } - - return (Node *) phv; + ChangeVarNodesExtended((Node *) otherrel->lateral_vars, relid, + subst, 0, replace_relid_callback); } - return expression_tree_mutator(node, - remove_rel_from_phvs_mutator, - removable); } /* @@ -2172,7 +1627,7 @@ remove_self_join_rel(PlannerInfo *root, PlanRowMark *kmark, PlanRowMark *rmark, 0, replace_relid_callback); /* Replace links in the planner info */ - remove_rel_from_query(root, toRemove->relid, toKeep->relid, NULL, NULL); + remove_rel_from_query(root, toRemove->relid, toKeep->relid); /* Replace varno in the fully-processed targetlist */ ChangeVarNodesExtended((Node *) root->processed_tlist, toRemove->relid, diff --git a/src/backend/optimizer/plan/planmain.c b/src/backend/optimizer/plan/planmain.c index 02495e22e24..ff15dfab96d 100644 --- a/src/backend/optimizer/plan/planmain.c +++ b/src/backend/optimizer/plan/planmain.c @@ -20,6 +20,8 @@ */ #include "postgres.h" +#include <limits.h> + #include "optimizer/appendinfo.h" #include "optimizer/clauses.h" #include "optimizer/optimizer.h" @@ -28,6 +30,10 @@ #include "optimizer/paths.h" #include "optimizer/placeholder.h" #include "optimizer/planmain.h" +#include "optimizer/tlist.h" + + +static void reset_query_planner(PlannerInfo *root); /* @@ -175,6 +181,12 @@ query_planner(PlannerInfo *root, /* Remove any redundant GROUP BY columns */ remove_useless_groupby_columns(root); + /* + * If we successfully removed any joins, throw away all the derived data + * and loop back around. + */ +restart: + /* * Examine the targetlist and join tree, adding entries to baserel * targetlists for all referenced Vars, and generating PlaceHolderInfo @@ -228,7 +240,11 @@ query_planner(PlannerInfo *root, * jointree preprocessing, but the necessary information isn't available * until we've built baserel data structures and classified qual clauses. */ - joinlist = remove_useless_joins(root, joinlist); + if (remove_useless_joins(root)) + { + reset_query_planner(root); + goto restart; + } /* * Also, reduce any semijoins with unique inner rels to plain inner joins. @@ -303,3 +319,67 @@ query_planner(PlannerInfo *root, return final_rel; } + +static void +reset_query_planner(PlannerInfo *root) +{ + int i; + + /* Relids sets rebuilt by deconstruct_jointree() */ + root->all_baserels = NULL; + root->outer_join_rels = NULL; + root->all_query_rels = NULL; + + /* join-order and equivalence-class */ + root->join_domains = list_make1(makeNode(JoinDomain)); + root->eq_classes = NIL; + root->ec_merging_done = false; + root->canon_pathkeys = NIL; + root->left_join_clauses = NIL; + root->right_join_clauses = NIL; + root->full_join_clauses = NIL; + root->join_info_list = NIL; + + /* RestrictInfo serial numbers */ + root->last_rinfo_serial = 0; + + /* PlaceHolderInfos */ + root->placeholder_list = NIL; + root->placeholder_array = NULL; + root->placeholder_array_size = 0; + root->placeholdersFrozen = false; + + root->hasPseudoConstantQuals = false; + + /* pathkeys and processed clause lists recomputed by the qp_callback */ + root->query_pathkeys = NIL; + root->group_pathkeys = NIL; + root->num_groupby_pathkeys = 0; + root->window_pathkeys = NIL; + root->distinct_pathkeys = NIL; + root->sort_pathkeys = NIL; + root->setop_pathkeys = NIL; + root->processed_distinctClause = NIL; + + for (i = 1; i < root->simple_rel_array_size; i++) + { + RelOptInfo *rel = root->simple_rel_array[i]; + int attroff; + + if (rel == NULL) + continue; + + rel->reltarget = create_empty_pathtarget(); + for (attroff = rel->max_attr - rel->min_attr; attroff >= 0; attroff--) + rel->attr_needed[attroff] = NULL; + rel->lateral_vars = NIL; + rel->nulling_relids = NULL; + rel->baserestrictinfo = NIL; + rel->baserestrict_min_security = UINT_MAX; + rel->joininfo = NIL; + rel->has_eclass_joins = false; + rel->eclass_indexes = NULL; + rel->unique_for_rels = NIL; + rel->non_unique_for_rels = NIL; + } +} diff --git a/src/backend/optimizer/prep/prepjointree.c b/src/backend/optimizer/prep/prepjointree.c index 72d39ba30fd..7fd77964034 100644 --- a/src/backend/optimizer/prep/prepjointree.c +++ b/src/backend/optimizer/prep/prepjointree.c @@ -171,6 +171,8 @@ static Node *remove_useless_results_recurse(PlannerInfo *root, Node *jtnode, Relids *dropped_outer_joins); static int get_result_relid(PlannerInfo *root, Node *jtnode); static void remove_result_refs(PlannerInfo *root, int varno, Node *newjtloc); +static Node *remove_leftjoin_recurse(PlannerInfo *root, Node *jtnode, + int relid, int ojrelid); static bool find_dependent_phvs(PlannerInfo *root, int varno, Relids baserels); static bool find_dependent_phvs_in_jointree(PlannerInfo *root, Node *node, int varno, @@ -4300,6 +4302,82 @@ remove_result_refs(PlannerInfo *root, int varno, Node *newjtloc) */ } +/* + * remove_leftjoin_from_jointree + * Remove a provably-useless left join out of the query jointree. + */ +void +remove_leftjoin_from_jointree(PlannerInfo *root, int relid, int ojrelid) +{ + root->parse->jointree = (FromExpr *) + remove_leftjoin_recurse(root, (Node *) root->parse->jointree, + relid, ojrelid); + Assert(IsA(root->parse->jointree, FromExpr)); + + remove_nulling_relids((Node *) root->parse, + bms_make_singleton(ojrelid), NULL); + remove_nulling_relids((Node *) root->append_rel_list, + bms_make_singleton(ojrelid), NULL); +} + +/* + * Recursive guts of remove_leftjoin_from_jointree: find the JoinExpr whose + * rtindex is ojrelid and return its left input in place of the join. + */ +static Node * +remove_leftjoin_recurse(PlannerInfo *root, Node *jtnode, + int relid, int ojrelid) +{ + if (jtnode == NULL) + return NULL; + + if (IsA(jtnode, RangeTblRef)) + { + /* nothing to do */ + } + else if (IsA(jtnode, FromExpr)) + { + FromExpr *f = (FromExpr *) jtnode; + ListCell *l; + + foreach(l, f->fromlist) + lfirst(l) = remove_leftjoin_recurse(root, (Node *) lfirst(l), + relid, ojrelid); + } + else if (IsA(jtnode, JoinExpr)) + { + JoinExpr *j = (JoinExpr *) jtnode; + + j->larg = remove_leftjoin_recurse(root, j->larg, relid, ojrelid); + j->rarg = remove_leftjoin_recurse(root, j->rarg, relid, ojrelid); + + if (j->rtindex == ojrelid) + { + Assert(j->jointype == JOIN_LEFT); + + /* Fix up PlaceHolderVars as needed */ + if (root->glob->lastPHId != 0) + { + Relids subrelids; + + subrelids = get_relids_in_jointree(j->larg, true, false); + Assert(!bms_is_empty(subrelids)); + substitute_phv_relids((Node *) root->parse, relid, subrelids); + substitute_phv_relids((Node *) root->parse, ojrelid, subrelids); + fix_append_rel_relids(root, relid, subrelids); + fix_append_rel_relids(root, ojrelid, subrelids); + } + + /* Replace the join with its left input */ + return j->larg; + } + } + else + elog(ERROR, "unrecognized node type: %d", (int) nodeTag(jtnode)); + + return jtnode; +} + /* * find_dependent_phvs - are there any PlaceHolderVars whose base relids are diff --git a/src/include/optimizer/planmain.h b/src/include/optimizer/planmain.h index 71c043a25e8..bce4db8faed 100644 --- a/src/include/optimizer/planmain.h +++ b/src/include/optimizer/planmain.h @@ -108,7 +108,7 @@ extern void match_foreign_keys_to_quals(PlannerInfo *root); /* * prototypes for plan/analyzejoins.c */ -extern List *remove_useless_joins(PlannerInfo *root, List *joinlist); +extern bool remove_useless_joins(PlannerInfo *root); extern void reduce_unique_semijoins(PlannerInfo *root); extern bool query_supports_distinctness(Query *query); extern bool query_is_distinct_for(Query *query, List *distinct_cols); diff --git a/src/include/optimizer/prep.h b/src/include/optimizer/prep.h index 00bc567da76..1dc75ce332e 100644 --- a/src/include/optimizer/prep.h +++ b/src/include/optimizer/prep.h @@ -30,6 +30,8 @@ extern void pull_up_subqueries(PlannerInfo *root); extern void flatten_simple_union_all(PlannerInfo *root); extern void reduce_outer_joins(PlannerInfo *root); extern void remove_useless_result_rtes(PlannerInfo *root); +extern void remove_leftjoin_from_jointree(PlannerInfo *root, int relid, + int ojrelid); extern Relids get_relids_in_jointree(Node *jtnode, bool include_outer_joins, bool include_inner_joins); extern Relids get_relids_for_join(Query *query, int joinrelid); -- 2.39.5 (Apple Git-154)
^ permalink raw reply [nested|flat] 74+ messages in thread

* Re: remove_useless_joins vs. bug #19560
  2026-07-20 18:52 remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-24 13:38 ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
@ 2026-07-25 16:46   ` Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-25 20:07     ` Re: remove_useless_joins vs. bug #19560 Thom Brown <thom@linux.com>
  0 siblings, 1 reply; 74+ messages in thread

From: Tom Lane @ 2026-07-25 16:46 UTC (permalink / raw)
  To: Richard Guo <guofenglinux@gmail.com>; +Cc: pgsql-hackers@lists.postgresql.org

Richard Guo <guofenglinux@gmail.com> writes:
> On Tue, Jul 21, 2026 at 3:52 AM Tom Lane <tgl@sss.pgh.pa.us> wrote:
>> I have a modest proposal to make instead: let's nuke all that logic
>> from orbit.  Revise analyzejoins.c so that it does join removals
>> working strictly on the jointree representation, which is simpler
>> and far more stable than any of the planner's derived data.  Then,
>> if we successfully removed any joins, throw away all the derived
>> data and loop back around within query_planner() to redo
>> deconstruct_jointree and all the rest of it.

> I prototyped this proposal to see how it would look in code, mainly
> copying how remove_useless_result_rtes does the removal from the join
> tree.  See attached PoC.  Please note that this is far from
> review-ready, and it only covers outer-join removal, skipping
> self-join elimination for now, and it lacks badly proper comments and
> test cases.

I spent some time hacking on this with the aid of Claude Code, and
arrived at what seems a complete patch.  It's a net deletion of
over 900 lines of code, and the newly-added code is mostly very
straightforward recursions over the jointree.

I had Claude do some performance testing, and the only case that got
noticeably slower was removal of multiple self-joins (about 10%
planning time slowdown for removal of 8 self-joins).  I'm not super
concerned about that; it doesn't seem like such cases would be common.

What I'm pretty unclear on is whether we want to risk back-patching
this.  It's a big change, and I can't honestly promise that it doesn't
bring some new bugs.  Still, it fixes one known bug and very likely
some not-yet-known ones.  Perhaps a reasonable choice would be to
back-patch to v18 where self-join elimination came in, because I still
have very little faith in that code.

			regards, tom lane

Attachments: download all (3 files, .tar.gz)

v2-0001-Postpone-initialization-of-all_result_relids-leaf.patch (text/x-diff, 4.7K) download From 3c3015f5c51d8501ac9f3bb79c4d83901519da04 Mon Sep 17 00:00:00 2001 From: Tom Lane <tgl@sss.pgh.pa.us> Date: Sat, 25 Jul 2026 10:46:29 -0400 Subject: [PATCH v2 1/3] Postpone initialization of all_result_relids/leaf_result_relids. Nothing actually pays attention to these PlannerInfo fields before add_other_rels_to_query(), since they're not really useful until that function has finished filling them in. By delaying their setup until just before we call that function, we can remove them from the set of things that join removal has to worry about. (It was already not doing anything with them, but now we do not need an argument why that's okay.) This is just some minor refactoring before the main patch to deal with bug #19560. Bug: #19560 Reported-by: Orestis Markou <orestis@orestis.gr> Author: Tom Lane <tgl@sss.pgh.pa.us> Discussion: https://postgr.es/m/1186816.1784573544@sss.pgh.pa.us --- src/backend/optimizer/plan/analyzejoins.c | 11 ----------- src/backend/optimizer/plan/planmain.c | 17 +++++++++++++++++ src/backend/optimizer/plan/planner.c | 18 ++---------------- 3 files changed, 19 insertions(+), 27 deletions(-) diff --git a/src/backend/optimizer/plan/analyzejoins.c b/src/backend/optimizer/plan/analyzejoins.c index 881950e5264..e1af49d3dea 100644 --- a/src/backend/optimizer/plan/analyzejoins.c +++ b/src/backend/optimizer/plan/analyzejoins.c @@ -2178,17 +2178,6 @@ remove_self_join_rel(PlannerInfo *root, PlanRowMark *kmark, PlanRowMark *rmark, 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. diff --git a/src/backend/optimizer/plan/planmain.c b/src/backend/optimizer/plan/planmain.c index 02495e22e24..c123a397c1a 100644 --- a/src/backend/optimizer/plan/planmain.c +++ b/src/backend/optimizer/plan/planmain.c @@ -28,6 +28,7 @@ #include "optimizer/paths.h" #include "optimizer/placeholder.h" #include "optimizer/planmain.h" +#include "parser/parsetree.h" /* @@ -274,6 +275,22 @@ query_planner(PlannerInfo *root, */ setup_eager_aggregation(root); + /* + * If there's a result relation, initialize all_result_relids to include + * it; and if we've verified that it is non-inheriting, mark it as a leaf + * target. add_other_rels_to_query() will expand these sets if the result + * relation has children. + */ + if (parse->resultRelation) + { + RangeTblEntry *rte = rt_fetch(parse->resultRelation, parse->rtable); + + root->all_result_relids = bms_make_singleton(parse->resultRelation); + if (!rte->inh) + root->leaf_result_relids = + bms_make_singleton(parse->resultRelation); + } + /* * Now expand appendrels by adding "otherrels" for their children. We * delay this to the end so that we have as much information as possible diff --git a/src/backend/optimizer/plan/planner.c b/src/backend/optimizer/plan/planner.c index 3225185d16f..16ad18babaa 100644 --- a/src/backend/optimizer/plan/planner.c +++ b/src/backend/optimizer/plan/planner.c @@ -803,9 +803,8 @@ subquery_planner(PlannerGlobal *glob, Query *parse, char *plan_name, root->eq_classes = NIL; root->ec_merging_done = false; root->last_rinfo_serial = 0; - root->all_result_relids = - parse->resultRelation ? bms_make_singleton(parse->resultRelation) : NULL; - root->leaf_result_relids = NULL; /* we'll find out leaf-ness later */ + root->all_result_relids = NULL; + root->leaf_result_relids = NULL; root->append_rel_list = NIL; root->row_identity_vars = NIL; root->rowMarks = NIL; @@ -976,19 +975,6 @@ subquery_planner(PlannerGlobal *glob, Query *parse, char *plan_name, list_length(rte->securityQuals)); } - /* - * If we have now verified that the query target relation is - * non-inheriting, mark it as a leaf target. - */ - if (parse->resultRelation) - { - RangeTblEntry *rte = rt_fetch(parse->resultRelation, parse->rtable); - - if (!rte->inh) - root->leaf_result_relids = - bms_make_singleton(parse->resultRelation); - } - /* * This would be a convenient time to check access permissions for all * relations mentioned in the query, since it would be better to fail now, -- 2.52.0
v2-0002-Perform-join-removal-by-editing-the-query-s-joint.patch (text/x-diff, 58.2K) download From e06e5d1fa86c66133036e5ea59e0483d5b51624f Mon Sep 17 00:00:00 2001 From: Tom Lane <tgl@sss.pgh.pa.us> Date: Sat, 25 Jul 2026 11:34:55 -0400 Subject: [PATCH v2 2/3] Perform join removal by editing the query's jointree. analyzejoins.c decided which joins could be dropped by consulting the planner's derived data structures, but then implemented the removal by updating those structures in-place. That is a lot of fiddly work, and nothing keeps it in step with the rest of the planner: remove_leftjoinrel_from_query only bothered to update "parts of the planner's data structures that will actually be consulted later", with no good way to know what those are. Bug #19560 is one consequence. Removing a join there leaves an EquivalenceClass that now gives rise to a base restriction clause, but base restriction clauses have already been generated and nothing reconsiders them, so the WHERE condition disappears from the plan and we return wrong answers. The self-join elimination code has the same design and the same type of hazard. Instead, do the removals by editing root->parse->jointree, which is a far simpler and more stable representation than the derived data, and then have query_planner() discard everything it computed from the jointree and derive it over again. reduce_unique_semijoins() gets the same treatment: rather than deleting the semijoin's SpecialJoinInfo and relying on the jointree not being consulted again, it now changes the JoinExpr's jointype to JOIN_INNER. Some plans change in the join regression test. Qual evaluation order shifts in a few cases, because the conditions now reach later planning in jointree order rather than in whatever order the removal code re-distributed them. A few plans improve, since the rebuilt relation targetlists no longer carry columns that only a removed join needed. We also detect a constant-false filter condition whose test used to carry a FIXME label. One plan gets marginally worse, because the old code recomputed attr_needed from equivalence classes after a join removal; that is more accurate than what deconstruct_jointree() derives from the original clauses, but we no longer do that. Making that recomputation happen anyway could be worth doing, but it should be considered independently and perhaps implemented differently. This leaves a good deal of dead code behind, which the next commit removes; the separation is made to make each diff a little more readable. As of this patch there are -Wunused-function warnings about several no-longer-used functions in analyzejoins.c. Bug: #19560 Reported-by: Orestis Markou <orestis@orestis.gr> Author: Tom Lane <tgl@sss.pgh.pa.us> Discussion: https://postgr.es/m/1186816.1784573544@sss.pgh.pa.us --- src/backend/optimizer/plan/analyzejoins.c | 833 +++++++++++++++------- src/backend/optimizer/plan/initsplan.c | 6 +- src/backend/optimizer/plan/planmain.c | 67 +- src/include/optimizer/planmain.h | 6 +- src/test/regress/expected/join.out | 101 ++- src/test/regress/sql/join.sql | 40 +- 6 files changed, 755 insertions(+), 298 deletions(-) diff --git a/src/backend/optimizer/plan/analyzejoins.c b/src/backend/optimizer/plan/analyzejoins.c index e1af49d3dea..ef355ec1fe1 100644 --- a/src/backend/optimizer/plan/analyzejoins.c +++ b/src/backend/optimizer/plan/analyzejoins.c @@ -7,9 +7,14 @@ * certain optimizations cannot be performed at that stage for lack of * detailed information about the query. The routines here are invoked * after initsplan.c has done its work, and can do additional join removal - * and simplification steps based on the information extracted. The penalty - * is that we have to work harder to clean up after ourselves when we modify - * the query, since the derived data structures have to be updated too. + * and simplification steps based on the information extracted. + * + * Although the decisions about what can be removed are made using the + * planner's derived data structures, the removals themselves are implemented + * by editing the query's jointree, which is a far simpler and more stable + * representation. We make no attempt to update the derived data structures + * to match; instead, query_planner() throws them all away and recomputes them + * whenever we report having removed something. * * Portions Copyright (c) 1996-2026, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California @@ -23,6 +28,7 @@ #include "postgres.h" #include "catalog/pg_class.h" +#include "nodes/makefuncs.h" #include "nodes/nodeFuncs.h" #include "optimizer/joininfo.h" #include "optimizer/optimizer.h" @@ -30,6 +36,7 @@ #include "optimizer/paths.h" #include "optimizer/placeholder.h" #include "optimizer/planmain.h" +#include "optimizer/prep.h" #include "optimizer/restrictinfo.h" #include "parser/parse_agg.h" #include "rewrite/rewriteManip.h" @@ -69,6 +76,11 @@ static void remove_rel_from_restrictinfo_phvs(RestrictInfo *rinfo, static Node *remove_rel_from_phvs(Node *node, int relid, int ojrelid); static Node *remove_rel_from_phvs_mutator(Node *node, Relids removable); static List *remove_rel_from_joinlist(List *joinlist, int relid, int *nremoved); +static Node *remove_join_from_jointree(Node *jtnode, int ojrelid, + int *nremoved); +static void remove_rels_from_query_tree(PlannerInfo *root, + Relids removed_relids); +static bool reduce_semijoin_in_jointree(Node *jtnode, Relids syn_righthand); static bool rel_supports_distinctness(PlannerInfo *root, RelOptInfo *rel); static bool rel_is_distinct_for(PlannerInfo *root, RelOptInfo *rel, List *clause_list, List **extra_clauses); @@ -80,6 +92,13 @@ static bool is_innerrel_unique_for(PlannerInfo *root, 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); +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); static bool replace_relid_callback(Node *node, ChangeVarNodes_context *context); @@ -88,21 +107,22 @@ static bool replace_relid_callback(Node *node, /* * remove_useless_joins * Check for relations that don't actually need to be joined at all, - * and remove them from the query. + * and remove them from the query's jointree. * - * We are passed the current joinlist and return the updated list. Other - * data structures that have to be updated are accessible via "root". + * Returns true if we removed anything. In that case the caller must discard + * everything it has derived from the jointree and compute it over again, + * since we don't try to update any of that here. */ -List * -remove_useless_joins(PlannerInfo *root, List *joinlist) +bool +remove_useless_joins(PlannerInfo *root) { + Relids removed_relids = NULL; ListCell *lc; /* * We are only interested in relations that are left-joined to, so we can * scan the join_info_list to find them easily. */ -restart: foreach(lc, root->join_info_list) { SpecialJoinInfo *sjinfo = (SpecialJoinInfo *) lfirst(lc); @@ -114,37 +134,59 @@ restart: continue; /* - * Currently, join_is_removable can only succeed when the sjinfo's - * righthand is a single baserel. Remove that rel from the query and - * joinlist. + * join_is_removable insists that the join's syntactic righthand side + * be a single baserel, so we can implement the removal by dropping + * the JoinExpr and everything below its righthand side. */ - innerrelid = bms_singleton_member(sjinfo->min_righthand); + innerrelid = bms_singleton_member(sjinfo->syn_righthand); - remove_leftjoinrel_from_query(root, innerrelid, sjinfo); + /* + * The removed rel had better not be one that the rest of the planner + * expects to find. It can't be, really: a result relation or a + * row-marked relation has junk columns in the query targetlist, and + * join_is_removable would have seen those as uses of the rel from + * "relation 0". But let's check. + */ + Assert(innerrelid != root->parse->resultRelation); +#ifdef USE_ASSERT_CHECKING + foreach_node(PlanRowMark, rc, root->rowMarks) + Assert(rc->rti != innerrelid && rc->prti != innerrelid); +#endif - /* We verify that exactly one reference gets removed from joinlist */ + /* We verify that exactly one JoinExpr gets removed */ nremoved = 0; - joinlist = remove_rel_from_joinlist(joinlist, innerrelid, &nremoved); + root->parse->jointree = (FromExpr *) + remove_join_from_jointree((Node *) root->parse->jointree, + sjinfo->ojrelid, &nremoved); if (nremoved != 1) - elog(ERROR, "failed to find relation %d in joinlist", innerrelid); + elog(ERROR, "failed to find join %d in jointree", sjinfo->ojrelid); - /* - * We can delete this SpecialJoinInfo from the list too, since it's no - * longer of interest. (Since we'll restart the foreach loop - * immediately, we don't bother with foreach_delete_current.) - */ - root->join_info_list = list_delete_cell(root->join_info_list, lc); + /* Track all the relids we've removed, for use below */ + removed_relids = bms_add_member(removed_relids, innerrelid); + removed_relids = bms_add_member(removed_relids, sjinfo->ojrelid); /* - * Restart the scan. This is necessary to ensure we find all - * removable joins independently of ordering of the join_info_list - * (note that removal of attr_needed bits may make a join appear - * removable that did not before). + * It's okay to keep scanning join_info_list for more removable joins, + * even though the data that join_is_removable consults is now + * slightly out of date. Removing a join can only delete attr_needed + * bits and join clauses, and any attr_needed bit or join clause that + * mentions the removed rel above its own join level would have + * prevented that rel from being removable. So what remains to be + * examined is unchanged by what we just did. + * + * The converse doesn't hold: dropping a join can make some other join + * removable that didn't look so before. That's why our caller loops + * until we report finding nothing more to remove. */ - goto restart; } - return joinlist; + if (bms_is_empty(removed_relids)) + return false; + + /* Clean up the traces that the removed rels have left elsewhere */ + remove_rels_from_query_tree(root, removed_relids); + + return true; } /* @@ -176,8 +218,15 @@ join_is_removable(PlannerInfo *root, SpecialJoinInfo *sjinfo) if (sjinfo->jointype != JOIN_LEFT) return false; - if (!bms_get_singleton_member(sjinfo->min_righthand, &innerrelid)) + /* + * We test the syntactic righthand side, not min_righthand, because the + * removal is done by deleting the whole righthand subtree of the join. + * (min_righthand can be a singleton when syn_righthand is not, but in + * such a case the attr_needed tests below would reject the join anyway.) + */ + if (!bms_get_singleton_member(sjinfo->syn_righthand, &innerrelid)) return false; + Assert(bms_equal(sjinfo->min_righthand, sjinfo->syn_righthand)); /* * Never try to eliminate a left join to the query result rel. Although @@ -1025,6 +1074,91 @@ remove_rel_from_joinlist(List *joinlist, int relid, int *nremoved) } +/* + * remove_join_from_jointree + * Delete the JoinExpr with the given RT index, along with everything + * below its righthand side, from the query's jointree. + * + * 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). + */ +static Node * +remove_join_from_jointree(Node *jtnode, int ojrelid, int *nremoved) +{ + if (jtnode == NULL) + return NULL; + if (IsA(jtnode, RangeTblRef)) + { + /* nothing to do here */ + } + else if (IsA(jtnode, FromExpr)) + { + FromExpr *f = (FromExpr *) jtnode; + ListCell *l; + + foreach(l, f->fromlist) + lfirst(l) = remove_join_from_jointree((Node *) lfirst(l), + ojrelid, nremoved); + } + else if (IsA(jtnode, JoinExpr)) + { + JoinExpr *j = (JoinExpr *) jtnode; + + if (j->rtindex == 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)); + + return jtnode; +} + +/* + * remove_rels_from_query_tree + * Delete all remaining references to the given relids from the query. + * + * 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 the relids can + * still appear in the nullingrels sets of surviving Vars and PlaceHolderVars, + * and in the phrels sets of PlaceHolderVars. ChangeVarNodes knows how to + * strip a relid out of all of those. + */ +static void +remove_rels_from_query_tree(PlannerInfo *root, Relids removed_relids) +{ + int relid = -1; + + while ((relid = bms_next_member(removed_relids, relid)) >= 0) + { + /* Pass -1 for new_index to get the removal behavior */ + ChangeVarNodes((Node *) root->parse, relid, -1, 0); + + /* + * 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.) + */ + ChangeVarNodes((Node *) root->processed_tlist, relid, -1, 0); + + /* There could be references in the append_rel_list, too */ + if (root->append_rel_list != NIL) + ChangeVarNodes((Node *) root->append_rel_list, relid, -1, 0); + } +} + /* * reduce_unique_semijoins * Check for semijoins that can be simplified to plain inner joins @@ -1033,14 +1167,13 @@ remove_rel_from_joinlist(List *joinlist, int relid, int *nremoved) * Ideally this would happen during reduce_outer_joins, but we don't have * enough information at that point. * - * To perform the strength reduction when applicable, we need only delete - * the semijoin's SpecialJoinInfo from root->join_info_list. (We don't - * bother fixing the join type attributed to it in the query jointree, - * since that won't be consulted again.) + * Like the join removal cases, we do this on the query's jointree, so + * returning true means the caller must recompute the derived data. */ -void +bool reduce_unique_semijoins(PlannerInfo *root) { + bool changed = false; ListCell *lc; /* @@ -1097,9 +1230,65 @@ reduce_unique_semijoins(PlannerInfo *root) JOIN_SEMI, restrictlist, true)) continue; - /* OK, remove the SpecialJoinInfo from the list. */ - root->join_info_list = foreach_delete_current(root->join_info_list, lc); + /* OK, reduce the join to a plain inner join in the jointree. */ + if (!reduce_semijoin_in_jointree((Node *) root->parse->jointree, + sjinfo->syn_righthand)) + elog(ERROR, "failed to find semijoin in jointree"); + changed = true; + } + + return changed; +} + +/* + * reduce_semijoin_in_jointree + * Find the JoinExpr for the semijoin with the given syntactic righthand + * side, and turn it into an inner join. + * + * Semijoins have no RT index of their own, so we have to identify the one + * we want by the set of relids on its righthand side. + */ +static bool +reduce_semijoin_in_jointree(Node *jtnode, Relids syn_righthand) +{ + if (jtnode == NULL) + return false; + if (IsA(jtnode, RangeTblRef)) + { + /* nothing to do here */ + } + else if (IsA(jtnode, FromExpr)) + { + FromExpr *f = (FromExpr *) jtnode; + ListCell *l; + + foreach(l, f->fromlist) + { + if (reduce_semijoin_in_jointree((Node *) lfirst(l), syn_righthand)) + return true; + } } + else if (IsA(jtnode, JoinExpr)) + { + JoinExpr *j = (JoinExpr *) jtnode; + + if (j->jointype == JOIN_SEMI && + bms_equal(get_relids_in_jointree(j->rarg, true, false), + syn_righthand)) + { + j->jointype = JOIN_INNER; + return true; + } + if (reduce_semijoin_in_jointree(j->larg, syn_righthand)) + return true; + if (reduce_semijoin_in_jointree(j->rarg, syn_righthand)) + return true; + } + else + elog(ERROR, "unrecognized jointree node type: %d", + (int) nodeTag(jtnode)); + + return false; } @@ -2014,130 +2203,64 @@ replace_relid_callback(Node *node, ChangeVarNodes_context *context) } /* - * Remove a relation after we have proven that it participates only in an - * unneeded unique self-join. - * - * Replace any links in planner info structures. - * - * 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 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. + * Remove the toRemove relation after we have proven that it participates only + * in an unneeded unique self-join with toKeep. + * + * The removal is done by deleting the relation's RangeTblRef from the + * jointree and then pointing everything that referenced it at the relation we + * are keeping. All the conditions that were attached to the removed relation + * thereby become conditions on the remaining one, which is what we want: + * we've proven that the two relations select the same rows. + * + * kmark and rmark are the PlanRowMarks (if any) for the kept and removed + * relations. We could re-locate those, but the caller already found them. */ static void -remove_self_join_rel(PlannerInfo *root, PlanRowMark *kmark, PlanRowMark *rmark, +remove_self_join_rel(PlannerInfo *root, RelOptInfo *toKeep, RelOptInfo *toRemove, - List *restrictlist) + PlanRowMark *kmark, PlanRowMark *rmark) { - List *joininfos; - ListCell *lc; - int i; - List *jinfo_candidates = NIL; - List *binfo_candidates = NIL; + Node *orphan_quals = NULL; + int nremoved = 0; 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); - } + /* We verify that exactly one reference gets removed from the jointree */ + root->parse->jointree = (FromExpr *) + remove_rel_from_jointree((Node *) root->parse->jointree, + toRemove->relid, + &orphan_quals, &nremoved); + if (nremoved != 1) + elog(ERROR, "failed to find relation %d in jointree", toRemove->relid); + /* The topmost FromExpr can't have gone away, so nothing can be orphaned */ + Assert(root->parse->jointree != NULL); + Assert(orphan_quals == NULL); /* - * 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. + * Replace all references to the removed relation. Note that this must + * happen after the jointree surgery, else we'd not be able to tell the + * two relations' RangeTblRefs apart. */ - 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); - } + ChangeVarNodes((Node *) root->parse, toRemove->relid, toKeep->relid, 0); /* - * Transfer the targetlist and attr_needed flags. + * 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 the second visit to a + * shared node finds nothing to change.) */ + ChangeVarNodes((Node *) root->processed_tlist, toRemove->relid, + toKeep->relid, 0); - 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); - } + /* There could be references in the append_rel_list, too */ + if (root->append_rel_list != NIL) + ChangeVarNodes((Node *) root->append_rel_list, toRemove->relid, + toKeep->relid, 0); - 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]); - } + /* Clean up the quals that the substitution has messed with */ + fixup_selfjoin_jointree(root, (Node *) root->parse->jointree, + toKeep->relid); /* * If the removed relation has a row mark, transfer it to the remaining @@ -2157,52 +2280,270 @@ remove_self_join_rel(PlannerInfo *root, PlanRowMark *kmark, PlanRowMark *rmark, } else { - /* Shouldn't have inheritance children here. */ + /* Shouldn't have inheritance children yet. */ Assert(rmark->rti == rmark->prti); rmark->rti = rmark->prti = toKeep->relid; } } +} - /* - * 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); +/* + * remove_rel_from_jointree + * Delete the RangeTblRef for the given relation from the query's + * jointree. + * + * This is used for self-join elimination, where the removed relation's + * qual conditions must all be preserved (they will be transposed onto the + * remaining relation afterwards). Hence, if dropping the RangeTblRef leaves + * a JoinExpr or FromExpr with nothing under it, we can't simply drop that + * node; we hand its quals back to the caller in *orphan_quals, to be merged + * into the nearest enclosing node that still has some content. That's a + * valid transformation only for inner joins, but a jointree node can't become + * empty at an outer join here: remove_self_joins_one_group() insists that the + * two relations be on the same side of every outer join, so the relation we + * are keeping would have to be in the emptied subtree too. + * + * *nremoved is incremented by the number of RangeTblRefs removed (there + * should be exactly one, but the caller checks that). + */ +static Node * +remove_rel_from_jointree(Node *jtnode, int relid, + Node **orphan_quals, int *nremoved) +{ + if (jtnode == NULL) + return NULL; + if (IsA(jtnode, RangeTblRef)) + { + RangeTblRef *rtr = (RangeTblRef *) jtnode; - /* Replace links in the planner info */ - remove_rel_from_query(root, toRemove->relid, toKeep->relid, NULL, NULL); + if (rtr->rtindex == relid) + { + (*nremoved)++; + return NULL; + } + } + else if (IsA(jtnode, FromExpr)) + { + FromExpr *f = (FromExpr *) jtnode; + List *newfromlist = NIL; + Node *sub_orphans = NULL; + ListCell *l; - /* Replace varno in the fully-processed targetlist */ - ChangeVarNodesExtended((Node *) root->processed_tlist, toRemove->relid, - toKeep->relid, 0, replace_relid_callback); + foreach(l, f->fromlist) + { + Node *newchild; - /* - * There may be references to the rel in root->fkey_list, but if so, - * match_foreign_keys_to_quals() will get rid of them. - */ + newchild = remove_rel_from_jointree((Node *) lfirst(l), relid, + &sub_orphans, nremoved); + if (newchild != NULL) + newfromlist = lappend(newfromlist, newchild); + } + f->fromlist = newfromlist; + f->quals = merge_quals(sub_orphans, f->quals); + if (newfromlist == NIL) + { + /* Nothing left here, so pass our quals up to the parent */ + *orphan_quals = merge_quals(f->quals, *orphan_quals); + return NULL; + } + } + else if (IsA(jtnode, JoinExpr)) + { + JoinExpr *j = (JoinExpr *) jtnode; + Node *sub_orphans = NULL; + + j->larg = remove_rel_from_jointree(j->larg, relid, + &sub_orphans, nremoved); + j->rarg = remove_rel_from_jointree(j->rarg, relid, + &sub_orphans, nremoved); + if (j->larg == NULL || j->rarg == NULL) + { + Node *surviving = (j->larg != NULL) ? j->larg : j->rarg; + Node *quals = merge_quals(sub_orphans, j->quals); - /* - * 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; + /* As explained above, this can only happen for an inner join */ + Assert(j->jointype == JOIN_INNER); + /* We can't have removed both children */ + Assert(surviving != NULL); + + /* + * Replace the join by a FromExpr, so that the surviving side's + * rows are still filtered by the join's conditions. + */ + return (Node *) makeFromExpr(list_make1(surviving), quals); + } + /* A subtree that survives never hands any quals back to us */ + Assert(sub_orphans == NULL); + } + else + elog(ERROR, "unrecognized jointree node type: %d", + (int) nodeTag(jtnode)); + + return jtnode; +} + +/* + * merge_quals + * Combine two jointree qual conditions. + * + * quals1 should be the quals from the lower of the two jointree levels, + * so that those quals get applied first. + * + * Jointree quals have been through preprocess_expression() by now, so each + * one is either NULL or an implicitly-ANDed List. + */ +static Node * +merge_quals(Node *quals1, Node *quals2) +{ + if (quals1 == NULL) + return quals2; + if (quals2 == NULL) + return quals1; + return (Node *) list_concat(castNode(List, quals1), + castNode(List, quals2)); +} + +/* + * fixup_selfjoin_jointree + * Clean up the query's jointree quals after self-join elimination has + * merged one relation into another. (relid is the kept relation.) + * + * See fixup_selfjoin_quals() for what needs fixing. + */ +static void +fixup_selfjoin_jointree(PlannerInfo *root, Node *jtnode, int relid) +{ + if (jtnode == NULL) + return; + if (IsA(jtnode, RangeTblRef)) + { + /* nothing to do here */ + } + else if (IsA(jtnode, FromExpr)) + { + FromExpr *f = (FromExpr *) jtnode; + ListCell *l; + + foreach(l, f->fromlist) + fixup_selfjoin_jointree(root, (Node *) lfirst(l), relid); + f->quals = (Node *) fixup_selfjoin_quals(root, + castNode(List, f->quals), + relid); + } + else if (IsA(jtnode, JoinExpr)) + { + JoinExpr *j = (JoinExpr *) jtnode; + + fixup_selfjoin_jointree(root, j->larg, relid); + fixup_selfjoin_jointree(root, j->rarg, relid); + j->quals = (Node *) fixup_selfjoin_quals(root, + castNode(List, j->quals), + relid); + } + else + elog(ERROR, "unrecognized jointree node type: %d", + (int) nodeTag(jtnode)); +} + +/* + * fixup_selfjoin_quals + * Clean up one qual list after self-join elimination. + * + * 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). + * + * 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. + * + * 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 List * +fixup_selfjoin_quals(PlannerInfo *root, List *quals, int relid) +{ + List *result = NIL; + ListCell *l; - /* And nuke the RelOptInfo, just in case there's another access path. */ - pfree(toRemove); + foreach(l, quals) + { + Node *qual = (Node *) lfirst(l); + if (bms_is_member(relid, pull_varnos(root, qual))) + { + 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); + } + + return result; +} + +/* + * 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; /* - * 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; } /* @@ -2227,7 +2568,12 @@ split_selfjoin_quals(PlannerInfo *root, List *joinquals, List **selfjoinquals, Node *leftexpr; Node *rightexpr; - /* In general, clause looks like F(arg1) = G(arg2) */ + /* + * Since the given joinquals all came from + * generate_join_implied_equalities, they ought to look like equality + * operators on single-relation expressions. But let's check that. + * Anything that doesn't look like that can be dumped into ojoinquals. + */ if (!rinfo->mergeopfamilies || bms_num_members(rinfo->clause_relids) != 2 || bms_membership(rinfo->left_relids) != BMS_SINGLETON || @@ -2340,15 +2686,16 @@ match_unique_clauses(PlannerInfo *root, RelOptInfo *outer, List *uclauses, } /* - * Find and remove unique self-joins in a group of base relations that have + * Find and remove one unique self-join in a group of base relations that have * the same Oid. * - * Returns a set of relids that were removed. + * Returns true if we removed a relation. We stop at the first removal, + * because it invalidates all the derived information that the tests here + * depend on; our caller will come back for more once that's been rebuilt. */ -static Relids +static bool remove_self_joins_one_group(PlannerInfo *root, Relids relids) { - Relids result = NULL; int k; /* Index of kept relation */ int r = -1; /* Index of removed relation */ @@ -2356,8 +2703,8 @@ remove_self_joins_one_group(PlannerInfo *root, Relids relids) { RelOptInfo *rrel = root->simple_rel_array[r]; + /* k iterates over the relids after r */ k = r; - while ((k = bms_next_member(relids, k)) > 0) { Relids joinrelids = NULL; @@ -2377,8 +2724,8 @@ remove_self_joins_one_group(PlannerInfo *root, Relids relids) /* * It is impossible to eliminate the join of two relations if they - * belong to different rules of order. Otherwise, the planner - * can't find any variants of the correct query plan. + * are not on the same side of every outer join. Otherwise, the + * planner can't find any variants of the correct query plan. */ foreach(lc, root->join_info_list) { @@ -2492,29 +2839,26 @@ remove_self_joins_one_group(PlannerInfo *root, Relids relids) if (!match_unique_clauses(root, rrel, uclauses, krel->relid)) continue; - /* - * Remove rrel RelOptInfo from the planner structures and the - * corresponding row mark. - */ - remove_self_join_rel(root, kmark, rmark, krel, rrel, restrictlist); - - result = bms_add_member(result, r); + /* OK, remove rrel from the query, and report that we did so */ + remove_self_join_rel(root, krel, rrel, kmark, rmark); - /* We have removed the outer relation, try the next one. */ - break; + return true; } } - return result; + return false; } /* - * Gather indexes of base relations from the joinlist and try to eliminate self - * joins. + * Gather indexes of base relations from the joinlist and try to eliminate one + * self join. + * + * Returns true if we removed a relation. */ -static Relids -remove_self_joins_recurse(PlannerInfo *root, List *joinlist, Relids toRemove) +static bool +remove_self_joins_recurse(PlannerInfo *root, List *joinlist) { + bool removed = false; ListCell *jl; Relids relids = NULL; SelfJoinCandidate *candidates = NULL; @@ -2536,7 +2880,7 @@ remove_self_joins_recurse(PlannerInfo *root, List *joinlist, Relids toRemove) * We only consider ordinary relations as candidates to be * removed, and these relations should not have TABLESAMPLE * clauses specified. Removing a relation with TABLESAMPLE clause - * could potentially change the syntax of the query. Because of + * could potentially change the semantics of the query. Because of * UPDATE/DELETE EPQ mechanism, currently Query->resultRelation or * Query->mergeTargetRelation associated rel cannot be eliminated. */ @@ -2552,9 +2896,9 @@ remove_self_joins_recurse(PlannerInfo *root, List *joinlist, Relids toRemove) } else if (IsA(jlnode, List)) { - /* Recursively go inside the sub-joinlist */ - toRemove = remove_self_joins_recurse(root, (List *) jlnode, - toRemove); + /* Recursively consider SJE within the sub-joinlist */ + if (remove_self_joins_recurse(root, (List *) jlnode)) + return true; } else elog(ERROR, "unrecognized joinlist node type: %d", @@ -2565,7 +2909,7 @@ remove_self_joins_recurse(PlannerInfo *root, List *joinlist, Relids toRemove) /* Need at least two relations for the join */ if (numRels < 2) - return toRemove; + return false; /* * In order to find relations with the same oid we first build an array of @@ -2586,8 +2930,7 @@ remove_self_joins_recurse(PlannerInfo *root, List *joinlist, Relids toRemove) /* * Iteratively form a group of relation indexes with the same oid and - * launch the routine that detects self-joins in this group and removes - * excessive range table entries. + * launch the routine that detects a self-join in this group. * * At the end of the iteration, exclude the group from the overall relids * list. So each next iteration of the cycle will involve less and less @@ -2598,11 +2941,10 @@ remove_self_joins_recurse(PlannerInfo *root, List *joinlist, Relids toRemove) { if (j == numRels || candidates[j].reloid != candidates[i].reloid) { - if (j - i >= 2) + if (j - i >= 2 && !removed) { /* Create a group of relation indexes with the same oid */ Relids group = NULL; - Relids removed; while (i < j) { @@ -2612,34 +2954,29 @@ remove_self_joins_recurse(PlannerInfo *root, List *joinlist, Relids toRemove) relids = bms_del_members(relids, group); /* - * Try to remove self-joins from a group of identical entries. - * Make the next attempt iteratively - if something is deleted - * from a group, changes in clauses and equivalence classes - * can give us a chance to find more candidates. + * Try to remove a self-join from a group of identical + * entries. We stop as soon as we succeed, since the + * information we based the decision on is then out of date; + * our caller will start over from scratch. */ - do - { - Assert(!bms_overlap(group, toRemove)); - removed = remove_self_joins_one_group(root, group); - toRemove = bms_add_members(toRemove, removed); - group = bms_del_members(group, removed); - } while (!bms_is_empty(removed) && - bms_membership(group) == BMS_MULTIPLE); - bms_free(removed); + removed = remove_self_joins_one_group(root, group); bms_free(group); } else { - /* Single relation, just remove it from the set */ - relids = bms_del_member(relids, candidates[i].relid); - i = j; + /* Nothing to do with this group, just drop it from the set */ + while (i < j) + { + relids = bms_del_member(relids, candidates[i].relid); + i++; + } } } } Assert(bms_is_empty(relids)); - return toRemove; + return removed; } /* @@ -2681,45 +3018,25 @@ self_join_candidates_cmp(const void *a, const void *b) * 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; we use it to identify + * groups of relations that could be joined to each other. * - * '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. + * We remove at most one self-join per call, and return true if we did so. + * The caller must then recompute everything that was derived from the + * jointree before calling here again. */ -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 one pair of relations participating in a self-join. */ + return remove_self_joins_recurse(root, joinlist); } diff --git a/src/backend/optimizer/plan/initsplan.c b/src/backend/optimizer/plan/initsplan.c index b38422c47a4..7b6d7249c66 100644 --- a/src/backend/optimizer/plan/initsplan.c +++ b/src/backend/optimizer/plan/initsplan.c @@ -4044,9 +4044,9 @@ match_foreign_keys_to_quals(PlannerInfo *root) /* * 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 don't use - * find_base_rel() here. We can ignore such FKs. + * isn't referenced by the jointree (typically because it's been + * removed by join removal), so that it won't have a RelOptInfo. Hence + * don't use find_base_rel() here. We can ignore such FKs. */ if (fkinfo->con_relid >= root->simple_rel_array_size || fkinfo->ref_relid >= root->simple_rel_array_size) diff --git a/src/backend/optimizer/plan/planmain.c b/src/backend/optimizer/plan/planmain.c index c123a397c1a..298affe6bca 100644 --- a/src/backend/optimizer/plan/planmain.c +++ b/src/backend/optimizer/plan/planmain.c @@ -55,33 +55,71 @@ RelOptInfo * query_planner(PlannerInfo *root, query_pathkeys_callback qp_callback, void *qp_extra) { - Query *parse = root->parse; + Query *parse; List *joinlist; RelOptInfo *final_rel; /* - * Init planner lists to empty. + * The join simplification steps below work by modifying parse->jointree, + * and they make no attempt to update the information we derive from it. + * So whenever one of them succeeds, we must throw away all that derived + * information and recompute it from scratch, which we do by looping back + * to "restart". We cannot loop indefinitely, because each successful + * simplification either deletes a base relation from the jointree or + * turns a semijoin into an inner join, and neither of those can be undone + * by a later pass. * - * NOTE: append_rel_list was set up by subquery_planner, so do not touch - * here. + * These initial Asserts check that the state at entry is not too complex + * for the code below to restore. There mustn't be any EquivalenceClasses + * yet, and we should have only the top-level JoinDomain. */ + Assert(root->eq_classes == NIL); + Assert(list_length(root->join_domains) == 1); + +restart: + parse = root->parse; + + /* + * Initialize information derived from the jointree to empty. + * + * It's critical that this reset every field that the steps below will + * fill in, since we may be going around this loop more than once. + * + * NOTE: append_rel_list was created earlier, so do not clear it here; + * rowMarks ditto. Join simplification must update those if necessary. + */ + root->all_baserels = NULL; + root->outer_join_rels = NULL; + root->all_query_rels = NULL; root->join_rel_list = NIL; root->join_rel_hash = NULL; root->join_rel_level = NULL; root->join_cur_level = 0; + root->eq_classes = NIL; + root->ec_merging_done = false; root->canon_pathkeys = NIL; root->left_join_clauses = NIL; root->right_join_clauses = NIL; root->full_join_clauses = NIL; root->join_info_list = NIL; + root->last_rinfo_serial = 0; root->placeholder_list = NIL; root->placeholder_array = NULL; root->placeholder_array_size = 0; + root->placeholdersFrozen = false; root->agg_clause_list = NIL; root->group_expr_list = NIL; root->tlist_vars = NIL; root->fkey_list = NIL; root->initial_rels = NIL; + root->hasPseudoConstantQuals = false; + + /* + * We don't want to delete the top-level join domain, but get rid of other + * ones so as to reset the list to initial state. deconstruct_jointree + * will take care of (re)computing the top level's jd_relids. + */ + root->join_domains = list_truncate(root->join_domains, 1); /* * Set up arrays for accessing base relations and AppendRelInfos. @@ -228,19 +266,30 @@ query_planner(PlannerInfo *root, * Remove any useless outer joins. Ideally this would be done during * jointree preprocessing, but the necessary information isn't available * until we've built baserel data structures and classified qual clauses. + * If we remove a join, loop back to the top and redo what we did so far. */ - joinlist = remove_useless_joins(root, joinlist); + if (remove_useless_joins(root)) + goto restart; /* * Also, reduce any semijoins with unique inner rels to plain inner joins. - * Likewise, this can't be done until now for lack of needed info. + * Likewise, this can't be done until now for lack of needed info, and we + * must loop around if we find any simplifications. + */ + if (reduce_unique_semijoins(root)) + goto restart; + + /* + * Remove self joins on a unique column. Again, this couldn't be done any + * earlier, and we must loop around if we find anything to remove. */ - reduce_unique_semijoins(root); + if (remove_useless_self_joins(root, joinlist)) + goto restart; /* - * Remove self joins on a unique column. + * No more join simplifications apply, so we're done looping. Code below + * this point does not need to be able to restart. */ - joinlist = remove_useless_self_joins(root, joinlist); /* * Now distribute "placeholders" to base rels as needed. This has to be diff --git a/src/include/optimizer/planmain.h b/src/include/optimizer/planmain.h index 71c043a25e8..85301d912f0 100644 --- a/src/include/optimizer/planmain.h +++ b/src/include/optimizer/planmain.h @@ -108,8 +108,8 @@ extern void match_foreign_keys_to_quals(PlannerInfo *root); /* * prototypes for plan/analyzejoins.c */ -extern List *remove_useless_joins(PlannerInfo *root, List *joinlist); -extern void reduce_unique_semijoins(PlannerInfo *root); +extern bool remove_useless_joins(PlannerInfo *root); +extern bool reduce_unique_semijoins(PlannerInfo *root); extern bool query_supports_distinctness(Query *query); extern bool query_is_distinct_for(Query *query, List *distinct_cols); extern bool innerrel_is_unique(PlannerInfo *root, @@ -119,7 +119,7 @@ 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 bool remove_useless_self_joins(PlannerInfo *root, List *joinlist); /* * prototypes for plan/setrefs.c diff --git a/src/test/regress/expected/join.out b/src/test/regress/expected/join.out index 19e2cca548b..254b203aeba 100644 --- a/src/test/regress/expected/join.out +++ b/src/test/regress/expected/join.out @@ -6890,6 +6890,38 @@ where t1.a = s.c; ---------- (0 rows) +rollback; +-- join removal bug #19560: removing a join can leave an EquivalenceClass that +-- now yields a base restriction clause, so we must redo equivalence +-- processing from scratch +begin; +create temp table items (id text, owner text); +create temp table follows (item_id text, user_id text, + unique (user_id, item_id)); +insert into items values ('item1', 'alice'); +explain (costs off) +with viewer as (select 'bob' as id) +select count(*) from items + left join follows on follows.item_id = items.id and follows.user_id = 'bob' + left join viewer on true +where items.owner = viewer.id; + QUERY PLAN +--------------------------------------- + Aggregate + -> Seq Scan on items + Filter: (owner = 'bob'::text) +(3 rows) + +with viewer as (select 'bob' as id) +select count(*) from items + left join follows on follows.item_id = items.id and follows.user_id = 'bob' + left join viewer on true +where items.owner = viewer.id; + count +------- + 0 +(1 row) + rollback; -- check handling of semijoins after join removal: we must suppress -- unique-ification of known-constant values @@ -6915,17 +6947,17 @@ where exists (select 1 from t t4 Output: t1.a Index Cond: (t1.a = 1) -> HashAggregate - Output: t5.a + Output: t4.a, t5.a Group Key: t5.a -> Hash Join - Output: t5.a + Output: t4.a, t5.a Hash Cond: (t6.b = t4.b) -> Seq Scan on pg_temp.t t6 Output: t6.a, t6.b -> Hash - Output: t4.b, t5.b, t5.a + Output: t4.b, t4.a, t5.b, t5.a -> Hash Join - Output: t4.b, t5.b, t5.a + Output: t4.b, t4.a, t5.b, t5.a Inner Unique: true Hash Cond: (t5.b = t4.b) -> Seq Scan on pg_temp.t t5 @@ -7357,7 +7389,7 @@ on q1.ax = q2.a; Nested Loop Left Join Join Filter: (t2.a = t4.a) -> Seq Scan on sj t2 - Filter: ((b IS NULL) AND (a IS NOT NULL) AND ((c * c) = (c + 2))) + Filter: ((a IS NOT NULL) AND (b IS NULL) AND ((c * c) = (c + 2))) -> Seq Scan on sj t4 Filter: (c IS NOT NULL) (6 rows) @@ -7440,9 +7472,9 @@ select t1.a from sj t1 where t1.b in ( -> Seq Scan on public.sj t1 Output: t1.a, t1.b, t1.c -> Materialize - Output: t3.c, t3.b + Output: t3.b -> Seq Scan on public.sj t3 - Output: t3.c, t3.b + Output: t3.b Filter: (t3.c IS NOT NULL) (10 rows) @@ -7776,15 +7808,15 @@ explain (costs off) select * from sj p join sj q on p.a = q.a -> Seq Scan on sj r (6 rows) --- FIXME this constant false filter doesn't look good. Should we merge --- equivalence classes? +-- Check that we detect constant-false condition after merging ECs. explain (costs off) select * from sj p, sj q where p.a = q.a and p.b = 1 and q.b = 2; - QUERY PLAN ------------------------------------------------------ - Seq Scan on sj q - Filter: ((a IS NOT NULL) AND (b = 2) AND (b = 1)) -(2 rows) + QUERY PLAN +-------------------------- + Result + Replaces: Scan on q + One-Time Filter: false +(3 rows) -- Check that attr_needed is updated correctly after self-join removal. In this -- test, the join of j1 with j2 is removed. k1.b is required at either j1 or j2. @@ -7920,11 +7952,9 @@ where s1.x = 1; -> Seq Scan on public.emp1 t1 Output: t1.id, t1.code -> Materialize - Output: t3.id -> Seq Scan on public.emp1 t3 - Output: t3.id Filter: (1 = 1) -(9 rows) +(7 rows) -- Check that PHVs do not impose any constraints on removing self joins explain (verbose, costs off) @@ -7974,14 +8004,14 @@ SELECT 1 FROM tbl_phv t1 LEFT JOIN (SELECT y FROM tbl_phv tr) t4 ON t4.y = t3.y ON true WHERE t3.extra IS NOT NULL AND t3.x = t1.x % 2; - QUERY PLAN ---------------------------------------------------------- + QUERY PLAN +-------------------------------------------------------------- Nested Loop Output: 1 -> Seq Scan on public.tbl_phv t1 Output: t1.x, t1.y - -> Index Scan using tbl_phv_idx on public.tbl_phv tr - Output: tr.x, tr.y + -> Index Only Scan using tbl_phv_idx on public.tbl_phv tr + Output: tr.x Index Cond: (tr.x = (t1.x % 2)) Filter: (1 IS NOT NULL) (8 rows) @@ -8162,7 +8192,7 @@ where t1.b = t2.b and t2.a = 3 and t1.a = 3 --------------------------------------------------------------------------------------------- Seq Scan on public.sl t2 Output: t2.a, t2.b, t2.c, t2.a, t2.b, t2.c - Filter: ((t2.c IS NOT NULL) AND (t2.b IS NOT NULL) AND (t2.a IS NOT NULL) AND (t2.a = 3)) + Filter: ((t2.b IS NOT NULL) AND (t2.c IS NOT NULL) AND (t2.a IS NOT NULL) AND (t2.a = 3)) (3 rows) -- Join qual isn't mergejoinable, but inner is unique. @@ -8204,10 +8234,35 @@ SELECT 1 AS c1 FROM sl sl1 LEFT JOIN (sl AS sl2 NATURAL JOIN sl AS sl3) -> Nested Loop Left Join Join Filter: sl3.bool_col -> Seq Scan on sl sl3 - Filter: (bool_col AND (a IS NOT NULL) AND (b IS NOT NULL) AND (c IS NOT NULL) AND (bool_col IS NOT NULL)) + Filter: ((a IS NOT NULL) AND (b IS NOT NULL) AND (c IS NOT NULL) AND (bool_col IS NOT NULL) AND bool_col) -> Seq Scan on sl sl4 (7 rows) +-- Check that quals of a jointree node that becomes empty when the self-join +-- is removed are not lost, and that they don't migrate above an outer join +EXPLAIN (COSTS OFF) +SELECT s.a FROM (SELECT * FROM sl WHERE c IS NOT NULL) s, sl t +WHERE t.a = s.a AND t.b = s.b; + QUERY PLAN +--------------------------------------------------------------------- + Seq Scan on sl + Filter: ((c IS NOT NULL) AND (a IS NOT NULL) AND (b IS NOT NULL)) +(2 rows) + +EXPLAIN (COSTS OFF) +SELECT t1.a, ss.a FROM sl t1 + LEFT JOIN (SELECT s.a FROM (SELECT * FROM sl WHERE c IS NOT NULL) s + JOIN sl t ON t.a = s.a AND t.b = s.b) ss + ON ss.a = t1.a; + QUERY PLAN +--------------------------------------------------------------------------- + Nested Loop Left Join + Join Filter: (sl.a = t1.a) + -> Seq Scan on sl t1 + -> Seq Scan on sl + Filter: ((c IS NOT NULL) AND (a IS NOT NULL) AND (b IS NOT NULL)) +(5 rows) + -- Check optimization disabling if it will violate special join conditions. -- Two identical joined relations satisfies self join removal conditions but -- stay in different special join infos. diff --git a/src/test/regress/sql/join.sql b/src/test/regress/sql/join.sql index 85aed7bf704..afa96daecb5 100644 --- a/src/test/regress/sql/join.sql +++ b/src/test/regress/sql/join.sql @@ -2601,6 +2601,31 @@ where t1.a = s.c; rollback; +-- join removal bug #19560: removing a join can leave an EquivalenceClass that +-- now yields a base restriction clause, so we must redo equivalence +-- processing from scratch +begin; + +create temp table items (id text, owner text); +create temp table follows (item_id text, user_id text, + unique (user_id, item_id)); +insert into items values ('item1', 'alice'); + +explain (costs off) +with viewer as (select 'bob' as id) +select count(*) from items + left join follows on follows.item_id = items.id and follows.user_id = 'bob' + left join viewer on true +where items.owner = viewer.id; + +with viewer as (select 'bob' as id) +select count(*) from items + left join follows on follows.item_id = items.id and follows.user_id = 'bob' + left join viewer on true +where items.owner = viewer.id; + +rollback; + -- check handling of semijoins after join removal: we must suppress -- unique-ification of known-constant values begin; @@ -3015,8 +3040,7 @@ select 1 from (select y.* from sj x, sj y where x.a = y.a) q, explain (costs off) select * from sj p join sj q on p.a = q.a left join sj r on p.a + q.a = r.a; --- FIXME this constant false filter doesn't look good. Should we merge --- equivalence classes? +-- Check that we detect constant-false condition after merging ECs. explain (costs off) select * from sj p, sj q where p.a = q.a and p.b = 1 and q.b = 2; @@ -3214,6 +3238,18 @@ EXPLAIN (COSTS OFF) SELECT 1 AS c1 FROM sl sl1 LEFT JOIN (sl AS sl2 NATURAL JOIN sl AS sl3) ON sl2.bool_col LEFT JOIN sl AS sl4 ON sl2.bool_col; +-- Check that quals of a jointree node that becomes empty when the self-join +-- is removed are not lost, and that they don't migrate above an outer join +EXPLAIN (COSTS OFF) +SELECT s.a FROM (SELECT * FROM sl WHERE c IS NOT NULL) s, sl t +WHERE t.a = s.a AND t.b = s.b; + +EXPLAIN (COSTS OFF) +SELECT t1.a, ss.a FROM sl t1 + LEFT JOIN (SELECT s.a FROM (SELECT * FROM sl WHERE c IS NOT NULL) s + JOIN sl t ON t.a = s.a AND t.b = s.b) ss + ON ss.a = t1.a; + -- Check optimization disabling if it will violate special join conditions. -- Two identical joined relations satisfies self join removal conditions but -- stay in different special join infos. -- 2.52.0
v2-0003-Remove-dead-code-that-s-no-longer-needed-for-join.patch (text/x-diff, 64.1K) download From a3d6ff0731aea4461b641486f645095efedfa91e Mon Sep 17 00:00:00 2001 From: Tom Lane <tgl@sss.pgh.pa.us> Date: Sat, 25 Jul 2026 12:32:46 -0400 Subject: [PATCH v2 3/3] Remove dead code that's no longer needed for join removal. This is mostly a straightforward exercise in deleting unreferenced functions, but a couple of points are worth noting. While replace_relid_callback() was still reached in the previous patch, it did nothing since we no longer invoked it on any trees containing RangeTblRef or RestrictInfo nodes. So we can delete it and make the two remaining users use ChangeVarNodes instead of ChangeVarNodesExtended. Then, ChangeVarNodesExtended is unused and we can remove that too, along with the exposed definition of ChangeVarNodes_context (basically reverting that area of the code to what it was in v17). ec_clear_derived_clauses, innerrel_is_unique_ext, adjust_relid_set are now static since they're no longer called from outside their modules. Bug: #19560 Reported-by: Orestis Markou <orestis@orestis.gr> Author: Tom Lane <tgl@sss.pgh.pa.us> Discussion: https://postgr.es/m/1186816.1784573544@sss.pgh.pa.us --- src/backend/optimizer/path/equivclass.c | 51 +- src/backend/optimizer/plan/analyzejoins.c | 1037 +-------------------- src/backend/optimizer/plan/initsplan.c | 179 +--- src/backend/optimizer/util/joininfo.c | 36 - src/backend/optimizer/util/placeholder.c | 27 - src/backend/rewrite/rewriteManip.c | 65 +- src/include/optimizer/joininfo.h | 3 - src/include/optimizer/paths.h | 2 - src/include/optimizer/placeholder.h | 1 - src/include/optimizer/planmain.h | 8 - src/include/rewrite/rewriteManip.h | 19 - src/tools/pgindent/typedefs.list | 1 - 12 files changed, 30 insertions(+), 1399 deletions(-) diff --git a/src/backend/optimizer/path/equivclass.c b/src/backend/optimizer/path/equivclass.c index e3697df51a2..66fe1c24a58 100644 --- a/src/backend/optimizer/path/equivclass.c +++ b/src/backend/optimizer/path/equivclass.c @@ -89,6 +89,7 @@ static void ec_build_derives_hash(PlannerInfo *root, EquivalenceClass *ec); static void ec_add_derived_clauses(EquivalenceClass *ec, List *clauses); static void ec_add_derived_clause(EquivalenceClass *ec, RestrictInfo *clause); static void ec_add_clause_to_derives_hash(EquivalenceClass *ec, RestrictInfo *rinfo); +static void ec_clear_derived_clauses(EquivalenceClass *ec); static RestrictInfo *ec_search_clause_for_ems(PlannerInfo *root, EquivalenceClass *ec, EquivalenceMember *leftem, EquivalenceMember *rightem, @@ -1452,8 +1453,7 @@ generate_base_implied_equalities_no_const(PlannerInfo *root, * For the moment we force all the Vars to be available at all join nodes * for this eclass. Perhaps this could be improved by doing some * pre-analysis of which members we prefer to join, but it's no worse than - * what happened in the pre-8.3 code. (Note: rebuild_eclass_attr_needed - * needs to match this code.) + * what happened in the pre-8.3 code. */ foreach(lc, ec->ec_members) { @@ -2560,51 +2560,6 @@ reconsider_full_join_clause(PlannerInfo *root, OuterJoinClauseInfo *ojcinfo) return false; /* failed to make any deduction */ } -/* - * rebuild_eclass_attr_needed - * Put back attr_needed bits for Vars/PHVs needed for join eclasses. - * - * This is used to rebuild attr_needed/ph_needed sets after removal of a - * useless outer join. It should match what - * generate_base_implied_equalities_no_const did, except that we call - * add_vars_to_attr_needed not add_vars_to_targetlist. - */ -void -rebuild_eclass_attr_needed(PlannerInfo *root) -{ - ListCell *lc; - - foreach(lc, root->eq_classes) - { - EquivalenceClass *ec = (EquivalenceClass *) lfirst(lc); - - /* - * 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); - - /* Need do anything only for a multi-member, no-const EC. */ - if (list_length(ec->ec_members) > 1 && !ec->ec_has_const) - { - ListCell *lc2; - - foreach(lc2, ec->ec_members) - { - EquivalenceMember *cur_em = (EquivalenceMember *) lfirst(lc2); - List *vars = pull_var_clause((Node *) cur_em->em_expr, - PVC_RECURSE_AGGREGATES | - PVC_RECURSE_WINDOWFUNCS | - PVC_INCLUDE_PLACEHOLDERS); - - add_vars_to_attr_needed(root, vars, ec->ec_relids); - list_free(vars); - } - } - } -} - /* * find_join_domain * Find the highest JoinDomain enclosed within the given relid set. @@ -3826,7 +3781,7 @@ ec_add_clause_to_derives_hash(EquivalenceClass *ec, RestrictInfo *rinfo) * when thousands of partitions are involved, so we free it as well -- even * though we do not typically free lists. */ -void +static void ec_clear_derived_clauses(EquivalenceClass *ec) { list_free(ec->ec_derives_list); diff --git a/src/backend/optimizer/plan/analyzejoins.c b/src/backend/optimizer/plan/analyzejoins.c index ef355ec1fe1..a038b898bdb 100644 --- a/src/backend/optimizer/plan/analyzejoins.c +++ b/src/backend/optimizer/plan/analyzejoins.c @@ -30,11 +30,9 @@ #include "catalog/pg_class.h" #include "nodes/makefuncs.h" #include "nodes/nodeFuncs.h" -#include "optimizer/joininfo.h" #include "optimizer/optimizer.h" #include "optimizer/pathnode.h" #include "optimizer/paths.h" -#include "optimizer/placeholder.h" #include "optimizer/planmain.h" #include "optimizer/prep.h" #include "optimizer/restrictinfo.h" @@ -62,20 +60,6 @@ bool enable_self_join_elimination; /* local functions */ static bool join_is_removable(PlannerInfo *root, SpecialJoinInfo *sjinfo); -static void remove_leftjoinrel_from_query(PlannerInfo *root, int relid, - SpecialJoinInfo *sjinfo); -static void remove_rel_from_query(PlannerInfo *root, int relid, - int subst, SpecialJoinInfo *sjinfo, - Relids joinrelids); -static void remove_rel_from_restrictinfo(RestrictInfo *rinfo, - int relid, int ojrelid); -static void remove_rel_from_eclass(PlannerInfo *root, EquivalenceClass *ec, - int relid, int ojrelid); -static void remove_rel_from_restrictinfo_phvs(RestrictInfo *rinfo, - int relid, int ojrelid); -static Node *remove_rel_from_phvs(Node *node, int relid, int ojrelid); -static Node *remove_rel_from_phvs_mutator(Node *node, Relids removable); -static List *remove_rel_from_joinlist(List *joinlist, int relid, int *nremoved); static Node *remove_join_from_jointree(Node *jtnode, int ojrelid, int *nremoved); static void remove_rels_from_query_tree(PlannerInfo *root, @@ -85,6 +69,14 @@ static bool rel_supports_distinctness(PlannerInfo *root, RelOptInfo *rel); static bool rel_is_distinct_for(PlannerInfo *root, RelOptInfo *rel, List *clause_list, List **extra_clauses); static DistinctColInfo *distinct_col_search(int colno, List *distinct_cols); +static bool innerrel_is_unique_ext(PlannerInfo *root, + Relids joinrelids, + Relids outerrelids, + RelOptInfo *innerrel, + JoinType jointype, + List *restrictlist, + bool force_cache, + List **extra_clauses); static bool is_innerrel_unique_for(PlannerInfo *root, Relids joinrelids, Relids outerrelids, @@ -100,8 +92,6 @@ static void fixup_selfjoin_jointree(PlannerInfo *root, Node *jtnode, 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); -static bool replace_relid_callback(Node *node, - ChangeVarNodes_context *context); /* @@ -367,713 +357,6 @@ join_is_removable(PlannerInfo *root, SpecialJoinInfo *sjinfo) return false; } -/* - * 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. - * - * 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. - * - * This function serves as the common infrastructure for left-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). - */ -static void -remove_rel_from_query(PlannerInfo *root, int relid, - int subst, SpecialJoinInfo *sjinfo, - Relids joinrelids) -{ - 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); - Bitmapset *seen_serials = NULL; - - Assert(is_outer_join || is_self_join); - Assert(!is_outer_join || ojrelid > 0); - Assert(!is_outer_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) - { - root->outer_join_rels = bms_del_member(root->outer_join_rels, ojrelid); - root->all_query_rels = bms_del_member(root->all_query_rels, ojrelid); - } - - /* - * 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) - { - SpecialJoinInfo *sjinf = (SpecialJoinInfo *) lfirst(l); - - /* - * 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 - { - /* - * For self-join removal, replace relid references in - * semi_rhs_exprs. - */ - ChangeVarNodesExtended((Node *) sjinf->semi_rhs_exprs, relid, subst, - 0, replace_relid_callback); - } - } - - /* - * Likewise remove references from PlaceHolderVar data structures, - * removing any no-longer-needed placeholders entirely. We only remove - * PHVs for left-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 is no corresponding test in - * join_is_removable because it doesn't need to distinguish those cases. - */ - foreach(l, root->placeholder_list) - { - PlaceHolderInfo *phinfo = (PlaceHolderInfo *) lfirst(l); - - Assert(!is_outer_join || !bms_is_member(relid, phinfo->ph_lateral)); - - if (is_outer_join && - bms_is_subset(phinfo->ph_needed, joinrelids) && - bms_is_member(relid, phinfo->ph_eval_at) && - !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 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.) - */ - 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) - { - foreach(l, root->eq_classes) - { - EquivalenceClass *ec = (EquivalenceClass *) lfirst(l); - - remove_rel_from_eclass(root, ec, relid, ojrelid); - } - } - - /* - * 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 removal, we strip the removed rel and join from any - * PlaceHolderVar embedded in the surviving rels' restriction clauses and - * join clauses; 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 && rti != relid && root->glob->lastPHId != 0) - { - foreach_node(RestrictInfo, rinfo, otherrel->baserestrictinfo) - remove_rel_from_restrictinfo_phvs(rinfo, relid, ojrelid); - - /* - * Join clauses need the same treatment, but there's no value in - * processing any join clause more than once. So it's slightly - * annoying that we have to find them via the per-base-relation - * joininfo lists. Avoid duplicate processing by tracking the - * rinfo_serial numbers of join clauses we've already seen. (This - * doesn't work for is_clone clauses, so we must waste effort on - * them.) - */ - foreach_node(RestrictInfo, rinfo, otherrel->joininfo) - { - if (!rinfo->is_clone) /* else serial number is not unique */ - { - if (bms_is_member(rinfo->rinfo_serial, seen_serials)) - continue; /* saw it already */ - seen_serials = bms_add_member(seen_serials, - rinfo->rinfo_serial); - } - remove_rel_from_restrictinfo_phvs(rinfo, relid, ojrelid); - } - } - } -} - -/* - * Remove any references to relid or ojrelid from the RestrictInfo. - * - * 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); - 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); - 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); - 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); - 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); - 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); - 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. - * - * 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. - */ -static void -remove_rel_from_eclass(PlannerInfo *root, EquivalenceClass *ec, - int relid, int ojrelid) -{ - 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) && - !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); - 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) || - 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); - 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 relid or ojrelid from the PlaceHolderVars embedded - * in a RestrictInfo's clause. - * - * If it's an OR clause, we must also fix up the orclause, which is a parallel - * representation built from its own sub-RestrictInfos. We recurse into the - * sub-clauses for that, mirroring remove_rel_from_restrictinfo. - */ -static void -remove_rel_from_restrictinfo_phvs(RestrictInfo *rinfo, int relid, int ojrelid) -{ - rinfo->clause = (Expr *) - remove_rel_from_phvs((Node *) rinfo->clause, relid, 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_phvs(rinfo2, relid, ojrelid); - } - } - else - { - RestrictInfo *rinfo2 = castNode(RestrictInfo, orarg); - - remove_rel_from_restrictinfo_phvs(rinfo2, relid, ojrelid); - } - } - } -} - -/* - * 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); -} - -static Node * -remove_rel_from_phvs_mutator(Node *node, Relids removable) -{ - if (node == NULL) - return NULL; - if (IsA(node, PlaceHolderVar)) - { - 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); - - /* - * ... 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. - */ - newphrels = bms_difference(phv->phrels, removable); - if (!bms_is_empty(newphrels)) - { - phv->phrels = newphrels; - phv->phnullingrels = bms_difference(phv->phnullingrels, - removable); - } - - return (Node *) phv; - } - 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; -} - - /* * remove_join_from_jointree * Delete the JoinExpr with the given RT index, along with everything @@ -1731,7 +1014,7 @@ innerrel_is_unique(PlannerInfo *root, * A non-NULL extra_clauses indicates that we're checking for self-join and * correspondingly dealing with filtered clauses. */ -bool +static bool innerrel_is_unique_ext(PlannerInfo *root, Relids joinrelids, Relids outerrelids, @@ -1910,298 +1193,6 @@ is_innerrel_unique_for(PlannerInfo *root, return rel_is_distinct_for(root, innerrel, clause_list, extra_clauses); } -/* - * Update EC members to point to the remaining relation instead of the removed - * one, removing duplicates. - * - * Restriction clauses for base relations are already distributed to - * the respective baserestrictinfo lists (see - * generate_implied_equalities_for_column). The above code has already processed - * this list and updated these clauses to reference the remaining - * relation, so that we can skip them here based on their relids. - * - * Likewise, we have already processed the join clauses that join the - * removed relation to the remaining one. - * - * Finally, there might be join clauses tying the removed relation to - * some third relation. We can't just delete the source clauses and - * regenerate them from the EC because the corresponding equality - * operators might be missing (see the handling of ec_broken). - * Therefore, we will update the references in the source clauses. - * - * Derived clauses can be generated again, so it is simpler just to - * delete them. - */ -static void -update_eclasses(EquivalenceClass *ec, int from, int to) -{ - List *new_members = NIL; - List *new_sources = NIL; - - /* - * 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); - - foreach_node(EquivalenceMember, em, ec->ec_members) - { - bool is_redundant = false; - - if (!bms_is_member(from, em->em_relids)) - { - new_members = lappend(new_members, em); - continue; - } - - em->em_relids = adjust_relid_set(em->em_relids, from, to); - em->em_jdomain->jd_relids = adjust_relid_set(em->em_jdomain->jd_relids, from, to); - - /* We only process inner joins */ - ChangeVarNodesExtended((Node *) em->em_expr, from, to, 0, - replace_relid_callback); - - foreach_node(EquivalenceMember, other, new_members) - { - if (!equal(em->em_relids, other->em_relids)) - continue; - - if (equal(em->em_expr, other->em_expr)) - { - is_redundant = true; - break; - } - } - - if (!is_redundant) - new_members = lappend(new_members, em); - } - - list_free(ec->ec_members); - ec->ec_members = new_members; - - ec_clear_derived_clauses(ec); - - /* Update EC source expressions */ - foreach_node(RestrictInfo, rinfo, ec->ec_sources) - { - bool is_redundant = false; - - if (!bms_is_member(from, rinfo->required_relids)) - { - new_sources = lappend(new_sources, rinfo); - continue; - } - - ChangeVarNodesExtended((Node *) rinfo, from, to, 0, - replace_relid_callback); - - /* - * After switching the clause to the remaining relation, check it for - * redundancy with existing ones. We don't have to check for - * redundancy with derived clauses, because we've just deleted them. - */ - foreach_node(RestrictInfo, other, new_sources) - { - if (!equal(rinfo->clause_relids, other->clause_relids)) - continue; - - if (equal(rinfo->clause, other->clause)) - { - is_redundant = true; - break; - } - } - - if (!is_redundant) - new_sources = lappend(new_sources, rinfo); - } - - list_free(ec->ec_sources); - ec->ec_sources = new_sources; - ec->ec_relids = adjust_relid_set(ec->ec_relids, from, to); -} - -/* - * "Logically" compares two RestrictInfo's ignoring the 'rinfo_serial' field, - * which makes almost every RestrictInfo unique. This type of comparison is - * useful when removing duplicates while moving RestrictInfo's from removed - * relation to remaining relation during self-join elimination. - * - * XXX: In the future, we might remove the 'rinfo_serial' field completely and - * get rid of this function. - */ -static bool -restrict_infos_logically_equal(RestrictInfo *a, RestrictInfo *b) -{ - int saved_rinfo_serial = a->rinfo_serial; - bool result; - - a->rinfo_serial = b->rinfo_serial; - result = equal(a, b); - a->rinfo_serial = saved_rinfo_serial; - - return result; -} - -/* - * This function adds all non-redundant clauses to the keeping relation - * during self-join elimination. That is a contradictory operation. On the - * one hand, we reduce the length of the `restrict` lists, which can - * impact planning or executing time. Additionally, we improve the - * accuracy of cardinality estimation. On the other hand, it is one more - * place that can make planning time much longer in specific cases. It - * would have been better to avoid calling the equal() function here, but - * it's the only way to detect duplicated inequality expressions. - * - * (*keep_rinfo_list) is given by pointer because it might be altered by - * distribute_restrictinfo_to_rels(). - */ -static void -add_non_redundant_clauses(PlannerInfo *root, - List *rinfo_candidates, - List **keep_rinfo_list, - Index removed_relid) -{ - foreach_node(RestrictInfo, rinfo, rinfo_candidates) - { - bool is_redundant = false; - - Assert(!bms_is_member(removed_relid, rinfo->required_relids)); - - foreach_node(RestrictInfo, src, (*keep_rinfo_list)) - { - if (!bms_equal(src->clause_relids, rinfo->clause_relids)) - /* Can't compare trivially different clauses */ - continue; - - if (src == rinfo || - (rinfo->parent_ec != NULL && - src->parent_ec == rinfo->parent_ec) || - restrict_infos_logically_equal(rinfo, src)) - { - is_redundant = true; - break; - } - } - if (!is_redundant) - distribute_restrictinfo_to_rels(root, rinfo); - } -} - -/* - * A custom callback for ChangeVarNodesExtended() providing Self-join - * elimination (SJE) related functionality - * - * SJE needs to skip the RangeTblRef node type. During SJE's last - * step, remove_rel_from_joinlist() removes remaining RangeTblRefs - * with target relid. If ChangeVarNodes() replaces the target relid - * before, remove_rel_from_joinlist() would fail to identify the nodes - * to delete. - * - * SJE also needs to change the relids within RestrictInfo's. - */ -static bool -replace_relid_callback(Node *node, ChangeVarNodes_context *context) -{ - if (IsA(node, RangeTblRef)) - { - return true; - } - else if (IsA(node, RestrictInfo)) - { - RestrictInfo *rinfo = (RestrictInfo *) node; - int relid = -1; - bool is_req_equal = - (rinfo->required_relids == rinfo->clause_relids); - bool clause_relids_is_multiple = - (bms_membership(rinfo->clause_relids) == BMS_MULTIPLE); - - /* - * Recurse down into clauses if the target relation is present in - * clause_relids or required_relids. We must check required_relids - * because the relation not present in clause_relids might still be - * present somewhere in orclause. - */ - if (bms_is_member(context->rt_index, rinfo->clause_relids) || - bms_is_member(context->rt_index, rinfo->required_relids)) - { - Relids new_clause_relids; - - ChangeVarNodesWalkExpression((Node *) rinfo->clause, context); - ChangeVarNodesWalkExpression((Node *) rinfo->orclause, context); - - new_clause_relids = adjust_relid_set(rinfo->clause_relids, - context->rt_index, - context->new_index); - - /* - * Incrementally adjust num_base_rels based on the change of - * clause_relids, which could contain both base relids and - * outer-join relids. This operation is legal until we remove - * only baserels. - */ - rinfo->num_base_rels -= bms_num_members(rinfo->clause_relids) - - bms_num_members(new_clause_relids); - - rinfo->clause_relids = new_clause_relids; - rinfo->left_relids = - adjust_relid_set(rinfo->left_relids, context->rt_index, context->new_index); - rinfo->right_relids = - adjust_relid_set(rinfo->right_relids, context->rt_index, context->new_index); - } - - if (is_req_equal) - rinfo->required_relids = rinfo->clause_relids; - else - rinfo->required_relids = - adjust_relid_set(rinfo->required_relids, context->rt_index, context->new_index); - - rinfo->outer_relids = - adjust_relid_set(rinfo->outer_relids, context->rt_index, context->new_index); - rinfo->incompatible_relids = - adjust_relid_set(rinfo->incompatible_relids, context->rt_index, context->new_index); - - if (rinfo->mergeopfamilies && - bms_get_singleton_member(rinfo->clause_relids, &relid) && - clause_relids_is_multiple && - relid == context->new_index && IsA(rinfo->clause, OpExpr)) - { - Expr *leftOp; - Expr *rightOp; - - leftOp = (Expr *) get_leftop(rinfo->clause); - rightOp = (Expr *) get_rightop(rinfo->clause); - - /* - * For self-join elimination, changing varnos could transform - * "t1.a = t2.a" into "t1.a = t1.a". That is always true as long - * as "t1.a" is not null. We use equal() to check for such a - * case, and then we replace the qual with a check for not null - * (NullTest). - */ - if (leftOp != NULL && equal(leftOp, rightOp)) - { - NullTest *ntest = makeNode(NullTest); - - ntest->arg = leftOp; - ntest->nulltesttype = IS_NOT_NULL; - ntest->argisrow = false; - ntest->location = -1; - rinfo->clause = (Expr *) ntest; - rinfo->mergeopfamilies = NIL; - rinfo->left_em = NULL; - rinfo->right_em = NULL; - } - Assert(rinfo->orclause == NULL); - } - return true; - } - - return false; -} - /* * Remove the toRemove relation after we have proven that it participates only * in an unneeded unique self-join with toKeep. @@ -2604,10 +1595,9 @@ split_selfjoin_quals(PlannerInfo *root, List *joinquals, List **selfjoinquals, * when we have cast of the same var to different (but compatible) * types. */ - ChangeVarNodesExtended(rightexpr, - bms_singleton_member(rinfo->right_relids), - bms_singleton_member(rinfo->left_relids), 0, - replace_relid_callback); + ChangeVarNodes(rightexpr, + bms_singleton_member(rinfo->right_relids), + bms_singleton_member(rinfo->left_relids), 0); if (equal(leftexpr, rightexpr)) sjoinquals = lappend(sjoinquals, rinfo); @@ -2643,8 +1633,7 @@ match_unique_clauses(PlannerInfo *root, RelOptInfo *outer, List *uclauses, bms_is_empty(rinfo->right_relids)); clause = (Expr *) copyObject(rinfo->clause); - ChangeVarNodesExtended((Node *) clause, relid, outer->relid, 0, - replace_relid_callback); + ChangeVarNodes((Node *) clause, relid, outer->relid, 0); iclause = bms_is_empty(rinfo->left_relids) ? get_rightop(clause) : get_leftop(clause); diff --git a/src/backend/optimizer/plan/initsplan.c b/src/backend/optimizer/plan/initsplan.c index 7b6d7249c66..d8a5c242eef 100644 --- a/src/backend/optimizer/plan/initsplan.c +++ b/src/backend/optimizer/plan/initsplan.c @@ -295,8 +295,6 @@ build_base_rel_tlists(PlannerInfo *root, List *final_tlist) * have a single owning relation; we keep their attr_needed info in * root->placeholder_list instead. Find or create the associated * PlaceHolderInfo entry, and update its ph_needed. - * - * See also add_vars_to_attr_needed. */ void add_vars_to_targetlist(PlannerInfo *root, List *vars, @@ -350,63 +348,6 @@ add_vars_to_targetlist(PlannerInfo *root, List *vars, } } -/* - * add_vars_to_attr_needed - * This does a subset of what add_vars_to_targetlist does: it just - * updates attr_needed for Vars and ph_needed for PlaceHolderVars. - * We assume the Vars are already in their relations' targetlists. - * - * This is used to rebuild attr_needed/ph_needed sets after removal - * of a useless outer join. The removed join clause might have been - * the only upper-level use of some other relation's Var, in which - * case we can reduce that Var's attr_needed and thereby possibly - * open the door to further join removals. But we can't tell that - * without tedious reconstruction of the attr_needed data. - * - * Note that if a Var's attr_needed is successfully reduced to empty, - * it will still be in the relation's targetlist even though we do - * not really need the scan plan node to emit it. The extra plan - * inefficiency seems tiny enough to not be worth spending planner - * cycles to get rid of it. - */ -void -add_vars_to_attr_needed(PlannerInfo *root, List *vars, - Relids where_needed) -{ - ListCell *temp; - - Assert(!bms_is_empty(where_needed)); - - foreach(temp, vars) - { - Node *node = (Node *) lfirst(temp); - - if (IsA(node, Var)) - { - Var *var = (Var *) node; - RelOptInfo *rel = find_base_rel(root, var->varno); - int attno = var->varattno; - - if (bms_is_subset(where_needed, rel->relids)) - continue; - Assert(attno >= rel->min_attr && attno <= rel->max_attr); - attno -= rel->min_attr; - rel->attr_needed[attno] = bms_add_members(rel->attr_needed[attno], - where_needed); - } - else if (IsA(node, PlaceHolderVar)) - { - PlaceHolderVar *phv = (PlaceHolderVar *) node; - PlaceHolderInfo *phinfo = find_placeholder_info(root, phv); - - phinfo->ph_needed = bms_add_members(phinfo->ph_needed, - where_needed); - } - else - elog(ERROR, "unrecognized node type: %d", (int) nodeTag(node)); - } -} - /***************************************************************************** * * GROUP BY @@ -1226,54 +1167,10 @@ extract_lateral_references(PlannerInfo *root, RelOptInfo *brel, Index rtindex) */ add_vars_to_targetlist(root, newvars, where_needed); - /* - * Remember the lateral references for rebuild_lateral_attr_needed and - * create_lateral_join_info. - */ + /* Remember the lateral references for create_lateral_join_info */ brel->lateral_vars = newvars; } -/* - * rebuild_lateral_attr_needed - * Put back attr_needed bits for Vars/PHVs needed for lateral references. - * - * This is used to rebuild attr_needed/ph_needed sets after removal of a - * useless outer join. It should match what find_lateral_references did, - * except that we call add_vars_to_attr_needed not add_vars_to_targetlist. - */ -void -rebuild_lateral_attr_needed(PlannerInfo *root) -{ - Index rti; - - /* We need do nothing if the query contains no LATERAL RTEs */ - if (!root->hasLateralRTEs) - return; - - /* Examine the same baserels that find_lateral_references did */ - for (rti = 1; rti < root->simple_rel_array_size; rti++) - { - RelOptInfo *brel = root->simple_rel_array[rti]; - Relids where_needed; - - if (brel == NULL) - continue; - if (brel->reloptkind != RELOPT_BASEREL) - continue; - - /* - * We don't need to repeat all of extract_lateral_references, since it - * kindly saved the extracted Vars/PHVs in lateral_vars. - */ - if (brel->lateral_vars == NIL) - continue; - - where_needed = bms_make_singleton(rti); - - add_vars_to_attr_needed(root, brel->lateral_vars, where_needed); - } -} - /* * create_lateral_join_info * Fill in the per-base-relation direct_lateral_relids, lateral_relids @@ -3227,9 +3124,6 @@ distribute_qual_to_rels(PlannerInfo *root, Node *clause, * var propagation is ensured by making ojscope include input rels from * both sides of the join. * - * See also rebuild_joinclause_attr_needed, which has to partially repeat - * this work after removal of an outer join. - * * Note: if the clause gets absorbed into an EquivalenceClass then this * may be unnecessary, but for now we have to do it to cover the case * where the EC becomes ec_broken and we end up reinserting the original @@ -3803,11 +3697,6 @@ process_implied_equality(PlannerInfo *root, * some of the Vars could have missed having that done because they only * appeared in single-relation clauses originally. So do it here for * safety. - * - * See also rebuild_joinclause_attr_needed, which has to partially repeat - * this work after removal of an outer join. (Since we will put this - * clause into the joininfo lists, that function needn't do any extra work - * to find it.) */ if (bms_membership(relids) == BMS_MULTIPLE) { @@ -3949,72 +3838,6 @@ get_join_domain_min_rels(PlannerInfo *root, Relids domain_relids) } -/* - * rebuild_joinclause_attr_needed - * Put back attr_needed bits for Vars/PHVs needed for join clauses. - * - * This is used to rebuild attr_needed/ph_needed sets after removal of a - * useless outer join. It should match what distribute_qual_to_rels did, - * except that we call add_vars_to_attr_needed not add_vars_to_targetlist. - */ -void -rebuild_joinclause_attr_needed(PlannerInfo *root) -{ - /* - * We must examine all join clauses, but there's no value in processing - * any join clause more than once. So it's slightly annoying that we have - * to find them via the per-base-relation joininfo lists. Avoid duplicate - * processing by tracking the rinfo_serial numbers of join clauses we've - * already seen. (This doesn't work for is_clone clauses, so we must - * waste effort on them.) - */ - Bitmapset *seen_serials = NULL; - Index rti; - - /* Scan all baserels for join clauses */ - for (rti = 1; rti < root->simple_rel_array_size; rti++) - { - RelOptInfo *brel = root->simple_rel_array[rti]; - ListCell *lc; - - if (brel == NULL) - continue; - if (brel->reloptkind != RELOPT_BASEREL) - continue; - - foreach(lc, brel->joininfo) - { - RestrictInfo *rinfo = (RestrictInfo *) lfirst(lc); - Relids relids = rinfo->required_relids; - - if (!rinfo->is_clone) /* else serial number is not unique */ - { - if (bms_is_member(rinfo->rinfo_serial, seen_serials)) - continue; /* saw it already */ - seen_serials = bms_add_member(seen_serials, - rinfo->rinfo_serial); - } - - if (bms_membership(relids) == BMS_MULTIPLE) - { - List *vars = pull_var_clause((Node *) rinfo->clause, - PVC_RECURSE_AGGREGATES | - PVC_RECURSE_WINDOWFUNCS | - PVC_INCLUDE_PLACEHOLDERS); - Relids where_needed; - - if (rinfo->is_clone) - where_needed = bms_intersect(relids, root->all_baserels); - else - where_needed = relids; - add_vars_to_attr_needed(root, vars, where_needed); - list_free(vars); - } - } - } -} - - /* * match_foreign_keys_to_quals * Match foreign-key constraints to equivalence classes and join quals diff --git a/src/backend/optimizer/util/joininfo.c b/src/backend/optimizer/util/joininfo.c index ef2f054c39e..f75e35f22ae 100644 --- a/src/backend/optimizer/util/joininfo.c +++ b/src/backend/optimizer/util/joininfo.c @@ -145,39 +145,3 @@ add_join_clause_to_rels(PlannerInfo *root, rel->joininfo = lappend(rel->joininfo, restrictinfo); } } - -/* - * remove_join_clause_from_rels - * Delete 'restrictinfo' from all the joininfo lists it is in - * - * This reverses the effect of add_join_clause_to_rels. It's used when we - * discover that a relation need not be joined at all. - * - * 'restrictinfo' describes the join clause - * 'join_relids' is the set of relations participating in the join clause - * (some of these could be outer joins) - */ -void -remove_join_clause_from_rels(PlannerInfo *root, - RestrictInfo *restrictinfo, - Relids join_relids) -{ - int cur_relid; - - cur_relid = -1; - while ((cur_relid = bms_next_member(join_relids, cur_relid)) >= 0) - { - RelOptInfo *rel = find_base_rel_ignore_join(root, cur_relid); - - /* We would only have added the clause to baserels */ - if (rel == NULL) - continue; - - /* - * Remove the restrictinfo from the list. Pointer comparison is - * sufficient. - */ - Assert(list_member_ptr(rel->joininfo, restrictinfo)); - rel->joininfo = list_delete_ptr(rel->joininfo, restrictinfo); - } -} diff --git a/src/backend/optimizer/util/placeholder.c b/src/backend/optimizer/util/placeholder.c index dd9b11885af..07171f84f61 100644 --- a/src/backend/optimizer/util/placeholder.c +++ b/src/backend/optimizer/util/placeholder.c @@ -316,33 +316,6 @@ fix_placeholder_input_needed_levels(PlannerInfo *root) } } -/* - * rebuild_placeholder_attr_needed - * Put back attr_needed bits for Vars/PHVs needed in PlaceHolderVars. - * - * This is used to rebuild attr_needed/ph_needed sets after removal of a - * useless outer join. It should match what - * fix_placeholder_input_needed_levels did, except that we call - * add_vars_to_attr_needed not add_vars_to_targetlist. - */ -void -rebuild_placeholder_attr_needed(PlannerInfo *root) -{ - ListCell *lc; - - foreach(lc, root->placeholder_list) - { - PlaceHolderInfo *phinfo = (PlaceHolderInfo *) lfirst(lc); - List *vars = pull_var_clause((Node *) phinfo->ph_var->phexpr, - PVC_RECURSE_AGGREGATES | - PVC_RECURSE_WINDOWFUNCS | - PVC_INCLUDE_PLACEHOLDERS); - - add_vars_to_attr_needed(root, vars, phinfo->ph_eval_at); - list_free(vars); - } -} - /* * add_placeholders_to_base_rels * Add any required PlaceHolderVars to base rels' targetlists. diff --git a/src/backend/rewrite/rewriteManip.c b/src/backend/rewrite/rewriteManip.c index 9c9d1cad33b..330ec596162 100644 --- a/src/backend/rewrite/rewriteManip.c +++ b/src/backend/rewrite/rewriteManip.c @@ -64,6 +64,7 @@ static bool contain_windowfuncs_walker(Node *node, void *context); static bool locate_windowfunc_walker(Node *node, locate_windowfunc_context *context); static bool checkExprHasSubLink_walker(Node *node, void *context); +static Relids adjust_relid_set(Relids relids, int oldrelid, int newrelid); static Node *add_nulling_relids_mutator(Node *node, add_nulling_relids_context *context); static Node *remove_nulling_relids_mutator(Node *node, @@ -528,23 +529,27 @@ OffsetVarNodes(Node *node, int offset, int sublevels_up) * * Find all Var nodes in the given tree belonging to a specific relation * (identified by sublevels_up and rt_index), and change their varno fields - * to 'new_index'. The varnosyn fields are changed too. Also, adjust other - * nodes that contain rangetable indexes, such as RangeTblRef and JoinExpr. + * to 'new_index' (see adjust_relid_set for the exact change behavior). + * The varnosyn fields are changed too. Also adjust other nodes that + * contain rangetable indexes, such as RangeTblRef and JoinExpr. * * NOTE: although this has the form of a walker, we cheat and modify the * nodes in-place. The given expression tree should have been copied * earlier to ensure that no unwanted side-effects occur! */ +typedef struct +{ + int rt_index; + int new_index; + int sublevels_up; +} ChangeVarNodes_context; + static bool ChangeVarNodes_walker(Node *node, ChangeVarNodes_context *context) { if (node == NULL) return false; - - if (context->callback && context->callback(node, context)) - return false; - if (IsA(node, Var)) { Var *var = (Var *) node; @@ -649,28 +654,14 @@ ChangeVarNodes_walker(Node *node, ChangeVarNodes_context *context) return expression_tree_walker(node, ChangeVarNodes_walker, context); } -/* - * ChangeVarNodesExtended - similar to ChangeVarNodes, but with an additional - * 'callback' param - * - * ChangeVarNodes changes a given node and all of its underlying nodes. This - * version of function additionally takes a callback, which has a chance to - * process a node before ChangeVarNodes_walker. A callback returns a boolean - * value indicating if the given node should be skipped from further processing - * by ChangeVarNodes_walker. The callback is called only for expressions and - * other children nodes of a Query processed by a walker. Initial processing - * of the root Query node doesn't invoke the callback. - */ void -ChangeVarNodesExtended(Node *node, int rt_index, int new_index, - int sublevels_up, ChangeVarNodes_callback callback) +ChangeVarNodes(Node *node, int rt_index, int new_index, int sublevels_up) { ChangeVarNodes_context context; context.rt_index = rt_index; context.new_index = new_index; context.sublevels_up = sublevels_up; - context.callback = callback; /* * Must be prepared to start with a Query or a bare expression tree; if @@ -717,36 +708,6 @@ ChangeVarNodesExtended(Node *node, int rt_index, int new_index, ChangeVarNodes_walker(node, &context); } -void -ChangeVarNodes(Node *node, int rt_index, int new_index, int sublevels_up) -{ - ChangeVarNodesExtended(node, rt_index, new_index, sublevels_up, NULL); -} - -/* - * ChangeVarNodesWalkExpression - process subexpression within a callback - * function passed to ChangeVarNodesExtended. - * - * This is intended to be used by a callback that needs to recursively - * process subexpressions of some node being visited by an outer - * ChangeVarNodesExtended call, instead of relying on ChangeVarNodes_walker's - * default recursion. We invoke ChangeVarNodes_walker directly rather than - * via expression_tree_walker, because expression_tree_walker only visits - * child nodes and would fail to process the passed node itself -- - * for example, a bare Var node would not get its varno adjusted. - * - * Because this calls ChangeVarNodes_walker directly, if the passed node is - * a Query, it will be treated as a sub-Query: sublevels_up is incremented - * before recursing into it, and Query-level fields (resultRelation, - * mergeTargetRelation, rowMarks, etc.) will not be adjusted. Do not apply - * this to a top-level Query node; use ChangeVarNodesExtended for that. - */ -bool -ChangeVarNodesWalkExpression(Node *node, ChangeVarNodes_context *context) -{ - return ChangeVarNodes_walker(node, context); -} - /* * adjust_relid_set - substitute newrelid for oldrelid in a Relid set * @@ -756,7 +717,7 @@ ChangeVarNodesWalkExpression(Node *node, ChangeVarNodes_context *context) * a special varno, this function does nothing. When newrelid is a special * varno, this function behaves as delete. */ -Relids +static Relids adjust_relid_set(Relids relids, int oldrelid, int newrelid) { if (!IS_SPECIAL_VARNO(oldrelid) && bms_is_member(oldrelid, relids)) diff --git a/src/include/optimizer/joininfo.h b/src/include/optimizer/joininfo.h index 117195fbcfa..aa26cc670f9 100644 --- a/src/include/optimizer/joininfo.h +++ b/src/include/optimizer/joininfo.h @@ -23,8 +23,5 @@ extern bool have_relevant_joinclause(PlannerInfo *root, extern void add_join_clause_to_rels(PlannerInfo *root, RestrictInfo *restrictinfo, Relids join_relids); -extern void remove_join_clause_from_rels(PlannerInfo *root, - RestrictInfo *restrictinfo, - Relids join_relids); #endif /* JOININFO_H */ diff --git a/src/include/optimizer/paths.h b/src/include/optimizer/paths.h index 17f2099ec3b..051e38c1189 100644 --- a/src/include/optimizer/paths.h +++ b/src/include/optimizer/paths.h @@ -137,7 +137,6 @@ extern bool process_equivalence(PlannerInfo *root, extern Expr *canonicalize_ec_expression(Expr *expr, Oid req_type, Oid req_collation); extern void reconsider_outer_join_clauses(PlannerInfo *root); -extern void rebuild_eclass_attr_needed(PlannerInfo *root); extern EquivalenceClass *get_eclass_for_sort_expr(PlannerInfo *root, Expr *expr, List *opfamilies, @@ -208,7 +207,6 @@ extern bool eclass_useful_for_merging(PlannerInfo *root, extern bool is_redundant_derived_clause(RestrictInfo *rinfo, List *clauselist); extern bool is_redundant_with_indexclauses(RestrictInfo *rinfo, List *indexclauses); -extern void ec_clear_derived_clauses(EquivalenceClass *ec); /* * pathkeys.c diff --git a/src/include/optimizer/placeholder.h b/src/include/optimizer/placeholder.h index 60798281090..2099075e670 100644 --- a/src/include/optimizer/placeholder.h +++ b/src/include/optimizer/placeholder.h @@ -23,7 +23,6 @@ extern PlaceHolderInfo *find_placeholder_info(PlannerInfo *root, PlaceHolderVar *phv); extern void find_placeholders_in_jointree(PlannerInfo *root); extern void fix_placeholder_input_needed_levels(PlannerInfo *root); -extern void rebuild_placeholder_attr_needed(PlannerInfo *root); extern void add_placeholders_to_base_rels(PlannerInfo *root); extern void add_placeholders_to_joinrel(PlannerInfo *root, RelOptInfo *joinrel, RelOptInfo *outer_rel, RelOptInfo *inner_rel, diff --git a/src/include/optimizer/planmain.h b/src/include/optimizer/planmain.h index 85301d912f0..f7e22f5989d 100644 --- a/src/include/optimizer/planmain.h +++ b/src/include/optimizer/planmain.h @@ -73,12 +73,9 @@ extern void add_other_rels_to_query(PlannerInfo *root); extern void build_base_rel_tlists(PlannerInfo *root, List *final_tlist); extern void add_vars_to_targetlist(PlannerInfo *root, List *vars, Relids where_needed); -extern void add_vars_to_attr_needed(PlannerInfo *root, List *vars, - Relids where_needed); extern void remove_useless_groupby_columns(PlannerInfo *root); extern void setup_eager_aggregation(PlannerInfo *root); extern void find_lateral_references(PlannerInfo *root); -extern void rebuild_lateral_attr_needed(PlannerInfo *root); extern void create_lateral_join_info(PlannerInfo *root); extern List *deconstruct_jointree(PlannerInfo *root); extern bool restriction_is_always_true(PlannerInfo *root, @@ -102,7 +99,6 @@ extern RestrictInfo *build_implied_join_equality(PlannerInfo *root, Expr *item2, Relids qualscope, Index security_level); -extern void rebuild_joinclause_attr_needed(PlannerInfo *root); extern void match_foreign_keys_to_quals(PlannerInfo *root); /* @@ -115,10 +111,6 @@ extern bool query_is_distinct_for(Query *query, List *distinct_cols); extern bool innerrel_is_unique(PlannerInfo *root, Relids joinrelids, Relids outerrelids, RelOptInfo *innerrel, JoinType jointype, List *restrictlist, bool force_cache); -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 bool remove_useless_self_joins(PlannerInfo *root, List *joinlist); /* diff --git a/src/include/rewrite/rewriteManip.h b/src/include/rewrite/rewriteManip.h index 9d234cb8741..2d15d8f8f95 100644 --- a/src/include/rewrite/rewriteManip.h +++ b/src/include/rewrite/rewriteManip.h @@ -41,30 +41,11 @@ typedef enum ReplaceVarsNoMatchOption REPLACEVARS_SUBSTITUTE_NULL, /* replace with a NULL Const */ } ReplaceVarsNoMatchOption; -typedef struct ChangeVarNodes_context ChangeVarNodes_context; - -typedef bool (*ChangeVarNodes_callback) (Node *node, - ChangeVarNodes_context *arg); - -struct ChangeVarNodes_context -{ - int rt_index; - int new_index; - int sublevels_up; - ChangeVarNodes_callback callback; -}; - -pg_nodiscard extern Relids adjust_relid_set(Relids relids, int oldrelid, int newrelid); extern void CombineRangeTables(List **dst_rtable, List **dst_perminfos, List *src_rtable, List *src_perminfos); extern void OffsetVarNodes(Node *node, int offset, int sublevels_up); extern void ChangeVarNodes(Node *node, int rt_index, int new_index, int sublevels_up); -extern void ChangeVarNodesExtended(Node *node, int rt_index, int new_index, - int sublevels_up, - ChangeVarNodes_callback callback); -extern bool ChangeVarNodesWalkExpression(Node *node, - ChangeVarNodes_context *context); extern void IncrementVarSublevelsUp(Node *node, int delta_sublevels_up, int min_sublevels_up); extern void IncrementVarSublevelsUp_rtable(List *rtable, diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list index 56c1f997f88..41ceb9b160d 100644 --- a/src/tools/pgindent/typedefs.list +++ b/src/tools/pgindent/typedefs.list @@ -431,7 +431,6 @@ CatalogId CatalogIdMapEntry CatalogIndexState ChangeContext -ChangeVarNodes_callback ChangeVarNodes_context ChannelName CheckPoint -- 2.52.0
^ permalink raw reply [nested|flat] 74+ messages in thread

* Re: remove_useless_joins vs. bug #19560
  2026-07-20 18:52 remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-24 13:38 ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-07-25 16:46   ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
@ 2026-07-25 20:07     ` Thom Brown <thom@linux.com>
  2026-07-25 21:23       ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  0 siblings, 1 reply; 74+ messages in thread

From: Thom Brown @ 2026-07-25 20:07 UTC (permalink / raw)
  To: Tom Lane <tgl@sss.pgh.pa.us>; +Cc: Richard Guo <guofenglinux@gmail.com>; pgsql-hackers@lists.postgresql.org

On Sat, 25 Jul 2026 at 17:47, Tom Lane <tgl@sss.pgh.pa.us> wrote:
>
> Richard Guo <guofenglinux@gmail.com> writes:
> > On Tue, Jul 21, 2026 at 3:52 AM Tom Lane <tgl@sss.pgh.pa.us> wrote:
> >> I have a modest proposal to make instead: let's nuke all that logic
> >> from orbit.  Revise analyzejoins.c so that it does join removals
> >> working strictly on the jointree representation, which is simpler
> >> and far more stable than any of the planner's derived data.  Then,
> >> if we successfully removed any joins, throw away all the derived
> >> data and loop back around within query_planner() to redo
> >> deconstruct_jointree and all the rest of it.
>
> > I prototyped this proposal to see how it would look in code, mainly
> > copying how remove_useless_result_rtes does the removal from the join
> > tree.  See attached PoC.  Please note that this is far from
> > review-ready, and it only covers outer-join removal, skipping
> > self-join elimination for now, and it lacks badly proper comments and
> > test cases.
>
> I spent some time hacking on this with the aid of Claude Code, and
> arrived at what seems a complete patch.  It's a net deletion of
> over 900 lines of code, and the newly-added code is mostly very
> straightforward recursions over the jointree.
>
> I had Claude do some performance testing, and the only case that got
> noticeably slower was removal of multiple self-joins (about 10%
> planning time slowdown for removal of 8 self-joins).  I'm not super
> concerned about that; it doesn't seem like such cases would be common.
>
> What I'm pretty unclear on is whether we want to risk back-patching
> this.  It's a big change, and I can't honestly promise that it doesn't
> bring some new bugs.  Still, it fixes one known bug and very likely
> some not-yet-known ones.  Perhaps a reasonable choice would be to
> back-patch to v18 where self-join elimination came in, because I still
> have very little faith in that code.

I can't get this to crash in a standard build, but with asserts, I can:

create table a (a int primary key, b int);
create table b (a int, b int);

select a2.a
from b b1
  join a a1 on b1.a = a1.a
  join a a2 on a2.a = a1.a and a2.b = a1.b;

server closed the connection unexpectedly
    This probably means the server terminated abnormally
    before or while processing the request.
The connection to the server was lost. Attempting reset: Failed.
The connection to the server was lost. Attempting reset: Failed.
!?>

I got Claude to verify and review, and it returned:

Verdict on the design: the approach is right, and it does what it
claims. The bug repro is fixed, the code is far more legible than what
it replaces, and the restart loop composes better than the old
one-shot logic (e.g. a LEFT JOIN (b LEFT JOIN c ON b.j=c.j) ON a.i=b.i
now removes both joins — the inner one first, the outer one on the
next pass). But your crash is real, it's in the self-join elimination
part, and it reaches well beyond the shape you found; separately, the
SJE planning-time cost is substantially worse than the email reports.

---
1. BLOCKER — your repro confirmed: SJE leaves quals outside their jointree scope

Reproduced exactly as you wrote it, on empty, never-analyzed tables:

create table a (a int primary key, b int);
create table b (a int, b int);

select a2.a
from b b1
  join a a1 on b1.a = a1.a
  join a a2 on a2.a = a1.a and a2.b = a1.b;

TRAP: failed Assert("root->hasLateralRTEs"), File: "initsplan.c", Line: 2921
LOG:  client backend was terminated by signal 6: Aborted

Your read is right that a standard build doesn't show it. Same source
tree built with cassert=false plans it fine, and the plan is
byte-identical to master's:

 Hash Join
   Hash Cond: (b1.a = a2.a)
   ->  Seq Scan on b b1
   ->  Hash
         ->  Seq Scan on a a2
               Filter: (b IS NOT NULL)

Root cause. remove_self_join_rel() edits the jointree first, then runs
ChangeVarNodes(parse, toRemove, toKeep). Any qual that referenced
toRemove now references toKeep, which may not be within the scope of
the jointree node the qual hangs off. distribute_qual_to_rels() then
falls into the pulled-up-LATERAL postponement branch, and that
branch's entry assertion fires.

In your query specifically: a1 is removed (the lower relid is the one
dropped), which collapses JoinExpr(b b1, a a1, ON b1.a = a1.a) into
makeFromExpr([b1], [a1.a = b1.a]); the substitution then rewrites that
qual to a2.a = b1.a inside a node whose scope is only {b1}.

It's broader than the explicit-self-join shape.
reduce_unique_semijoins() now genuinely rewrites the jointree, so
after a restart SJE can act on an ex-semijoin. That means a plain
EXISTS/IN against a unique key is enough — both of these crash the
same way, and both plan fine on master:

select a1.a from b b1 join a a1 on a1.a = b1.a
  where exists (select 1 from a s where s.a = a1.a);

select a1.a from a a1 join b b1 on a1.a = b1.a
  where a1.a in (select s.a from a s);

set enable_self_join_elimination = off avoids all of them, confirming
the source.

There are two distinct sub-cases, which matters for sizing the fix. I
prototyped a fix for the collapse case only (hoist the quals to the
parent when the surviving subtree doesn'tcontain toKeep); it
eliminated 33 of 46 crashes but not the rest. The remainder are
JoinExprs that don't collapse but whose ON quals referenced toRemove
while toKeep lives elsewhere in the tree. So the fix needs to be
general: relocate every qual to the lowest enclosing node whose relid
set covers its post-substitution varnos. fixup_selfjoin_jointree()
already walksthe whole jointree after the substitution and looks like
the natural home. (Prototype reverted — flagging the shape, not
proposing a patch.)

The remove_self_joins_one_group() same-side-of-every-outer-join
precondition does guarantee no outer join ever has to be crossed when
hoisting, so the relocation is safe. Worth noting the header comment
on remove_rel_from_jointree() establishes that a node can't become
empty at an outer join — true, but not the invariant that actually
matters here.

Severity. As you saw, non-assert builds don't crash: the misplaced
qual is rescued by the postponement machinery and answers stay
correct. I checked that deliberately by taking 22crashing queries and
adding a dummy , LATERAL (SELECT 1) l so hasLateralRTEs is true and
the assertion is bypassed — every result matched master. So the
production symptom is "the planner relies on a mechanism it was never
meant to reach", not wrong answers. But it kills every assert-enabled
build: beta, buildfarm, and anyone's dev tree.

Frequency: 46 crashes across ~2,900 randomly generated join queries
(1.6%); zero on master. Yours is not a corner case.

---
2. SJE planning-time regression is ~2–3×, not ~10%

remove_useless_self_joins() removes at most one join per call and
forces a full re-derivation, so N self-joins cost N+1 passes.
remove_useless_joins(), by contrast, drains all removable outer joins
in a single pass. Median Planning Time from EXPLAIN (SUMMARY ON),
21–25 reps (cassert + -O1 builds, so treat the ratios as indicative
rather than absolute):

┌────────────┬──────────┬──────────┬───────┐
│ self-joins │ patched  │   base   │ ratio │
├────────────┼──────────┼──────────┼───────┤
│ 8          │ 0.196 ms │ 0.113 ms │ 1.7×  │
├────────────┼──────────┼──────────┼───────┤
│ 12         │ 0.369    │ 0.202    │ 1.8×  │
├────────────┼──────────┼──────────┼───────┤
│ 16         │ 0.567    │ 0.251    │ 2.3×  │
├────────────┼──────────┼──────────┼───────┤
│ 20         │ 0.903    │ 0.381    │ 2.4×  │
├────────────┼──────────┼──────────┼───────┤
│ 24         │ 1.375    │ 0.465    │ 3.0×  │
├────────────┼──────────┼──────────┼───────┤
│ 28         │ 1.705    │ 0.621    │ 2.7×  │
└────────────┴──────────┴──────────┴───────┘

Outer-join removal actually got faster (16-way chain: 0.158 vs 0.201
ms), and queries with nothing to remove are unchanged. The cost is
specifically the one-removal-per-restart policyin SJE. Worth
re-checking the methodology behind the "about 10% for 8 self-joins"
figure, and worth considering letting remove_self_joins_one_group()
drain all independent pairs before returning — the same staleness
argument remove_useless_joins() makes should apply.

----------------

Thom





^ permalink  raw  reply  [nested|flat] 74+ messages in thread

* Re: remove_useless_joins vs. bug #19560
  2026-07-20 18:52 remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-24 13:38 ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-07-25 16:46   ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-25 20:07     ` Re: remove_useless_joins vs. bug #19560 Thom Brown <thom@linux.com>
@ 2026-07-25 21:23       ` Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-26 02:15         ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-26 20:34         ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  0 siblings, 2 replies; 74+ messages in thread

From: Tom Lane @ 2026-07-25 21:23 UTC (permalink / raw)
  To: Thom Brown <thom@linux.com>; +Cc: Richard Guo <guofenglinux@gmail.com>; pgsql-hackers@lists.postgresql.org

Thom Brown <thom@linux.com> writes:
> I can't get this to crash in a standard build, but with asserts, I can:

Thanks for the report!  I'd seen the same failed
Assert("root->hasLateralRTEs") in the core tests with an earlier draft
of this patch, but I thought it was resolved.  Obviously not ... I'll
look closer tomorrow.

As for the speed question, I'd not poked at the details of Claude's
claim, but I guess I should have.

			regards, tom lane






^ permalink  raw  reply  [nested|flat] 74+ messages in thread

* Re: remove_useless_joins vs. bug #19560
  2026-07-20 18:52 remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-24 13:38 ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-07-25 16:46   ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-25 20:07     ` Re: remove_useless_joins vs. bug #19560 Thom Brown <thom@linux.com>
  2026-07-25 21:23       ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
@ 2026-07-26 02:15         ` Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-26 04:23           ` Re: remove_useless_joins vs. bug #19560 Jacob Brazeal <jacob.brazeal@gmail.com>
  2026-07-26 09:49           ` Re: remove_useless_joins vs. bug #19560 Thom Brown <thom@linux.com>
  1 sibling, 2 replies; 74+ messages in thread

From: Tom Lane @ 2026-07-26 02:15 UTC (permalink / raw)
  To: Thom Brown <thom@linux.com>; +Cc: Richard Guo <guofenglinux@gmail.com>; pgsql-hackers@lists.postgresql.org

Here's a patchset addressing that.  0001-0003 are the same as before,
and then 0004 fixes this bug and adds tests.

Your Claude session mentioned a different failure scenario, but
gave no examples so I'm not quite sure if this covers it or not.

			regards, tom lane

Attachments: download all (4 files, .tar.gz)

v3-0001-Postpone-initialization-of-all_result_relids-leaf.patch (text/x-diff, 4.7K) download From 3c3015f5c51d8501ac9f3bb79c4d83901519da04 Mon Sep 17 00:00:00 2001 From: Tom Lane <tgl@sss.pgh.pa.us> Date: Sat, 25 Jul 2026 10:46:29 -0400 Subject: [PATCH v3 1/4] Postpone initialization of all_result_relids/leaf_result_relids. Nothing actually pays attention to these PlannerInfo fields before add_other_rels_to_query(), since they're not really useful until that function has finished filling them in. By delaying their setup until just before we call that function, we can remove them from the set of things that join removal has to worry about. (It was already not doing anything with them, but now we do not need an argument why that's okay.) This is just some minor refactoring before the main patch to deal with bug #19560. Bug: #19560 Reported-by: Orestis Markou <orestis@orestis.gr> Author: Tom Lane <tgl@sss.pgh.pa.us> Discussion: https://postgr.es/m/1186816.1784573544@sss.pgh.pa.us --- src/backend/optimizer/plan/analyzejoins.c | 11 ----------- src/backend/optimizer/plan/planmain.c | 17 +++++++++++++++++ src/backend/optimizer/plan/planner.c | 18 ++---------------- 3 files changed, 19 insertions(+), 27 deletions(-) diff --git a/src/backend/optimizer/plan/analyzejoins.c b/src/backend/optimizer/plan/analyzejoins.c index 881950e5264..e1af49d3dea 100644 --- a/src/backend/optimizer/plan/analyzejoins.c +++ b/src/backend/optimizer/plan/analyzejoins.c @@ -2178,17 +2178,6 @@ remove_self_join_rel(PlannerInfo *root, PlanRowMark *kmark, PlanRowMark *rmark, 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. diff --git a/src/backend/optimizer/plan/planmain.c b/src/backend/optimizer/plan/planmain.c index 02495e22e24..c123a397c1a 100644 --- a/src/backend/optimizer/plan/planmain.c +++ b/src/backend/optimizer/plan/planmain.c @@ -28,6 +28,7 @@ #include "optimizer/paths.h" #include "optimizer/placeholder.h" #include "optimizer/planmain.h" +#include "parser/parsetree.h" /* @@ -274,6 +275,22 @@ query_planner(PlannerInfo *root, */ setup_eager_aggregation(root); + /* + * If there's a result relation, initialize all_result_relids to include + * it; and if we've verified that it is non-inheriting, mark it as a leaf + * target. add_other_rels_to_query() will expand these sets if the result + * relation has children. + */ + if (parse->resultRelation) + { + RangeTblEntry *rte = rt_fetch(parse->resultRelation, parse->rtable); + + root->all_result_relids = bms_make_singleton(parse->resultRelation); + if (!rte->inh) + root->leaf_result_relids = + bms_make_singleton(parse->resultRelation); + } + /* * Now expand appendrels by adding "otherrels" for their children. We * delay this to the end so that we have as much information as possible diff --git a/src/backend/optimizer/plan/planner.c b/src/backend/optimizer/plan/planner.c index 3225185d16f..16ad18babaa 100644 --- a/src/backend/optimizer/plan/planner.c +++ b/src/backend/optimizer/plan/planner.c @@ -803,9 +803,8 @@ subquery_planner(PlannerGlobal *glob, Query *parse, char *plan_name, root->eq_classes = NIL; root->ec_merging_done = false; root->last_rinfo_serial = 0; - root->all_result_relids = - parse->resultRelation ? bms_make_singleton(parse->resultRelation) : NULL; - root->leaf_result_relids = NULL; /* we'll find out leaf-ness later */ + root->all_result_relids = NULL; + root->leaf_result_relids = NULL; root->append_rel_list = NIL; root->row_identity_vars = NIL; root->rowMarks = NIL; @@ -976,19 +975,6 @@ subquery_planner(PlannerGlobal *glob, Query *parse, char *plan_name, list_length(rte->securityQuals)); } - /* - * If we have now verified that the query target relation is - * non-inheriting, mark it as a leaf target. - */ - if (parse->resultRelation) - { - RangeTblEntry *rte = rt_fetch(parse->resultRelation, parse->rtable); - - if (!rte->inh) - root->leaf_result_relids = - bms_make_singleton(parse->resultRelation); - } - /* * This would be a convenient time to check access permissions for all * relations mentioned in the query, since it would be better to fail now, -- 2.52.0
v3-0002-Perform-join-removal-by-editing-the-query-s-joint.patch (text/x-diff, 58.2K) download From e06e5d1fa86c66133036e5ea59e0483d5b51624f Mon Sep 17 00:00:00 2001 From: Tom Lane <tgl@sss.pgh.pa.us> Date: Sat, 25 Jul 2026 11:34:55 -0400 Subject: [PATCH v3 2/4] Perform join removal by editing the query's jointree. analyzejoins.c decided which joins could be dropped by consulting the planner's derived data structures, but then implemented the removal by updating those structures in-place. That is a lot of fiddly work, and nothing keeps it in step with the rest of the planner: remove_leftjoinrel_from_query only bothered to update "parts of the planner's data structures that will actually be consulted later", with no good way to know what those are. Bug #19560 is one consequence. Removing a join there leaves an EquivalenceClass that now gives rise to a base restriction clause, but base restriction clauses have already been generated and nothing reconsiders them, so the WHERE condition disappears from the plan and we return wrong answers. The self-join elimination code has the same design and the same type of hazard. Instead, do the removals by editing root->parse->jointree, which is a far simpler and more stable representation than the derived data, and then have query_planner() discard everything it computed from the jointree and derive it over again. reduce_unique_semijoins() gets the same treatment: rather than deleting the semijoin's SpecialJoinInfo and relying on the jointree not being consulted again, it now changes the JoinExpr's jointype to JOIN_INNER. Some plans change in the join regression test. Qual evaluation order shifts in a few cases, because the conditions now reach later planning in jointree order rather than in whatever order the removal code re-distributed them. A few plans improve, since the rebuilt relation targetlists no longer carry columns that only a removed join needed. We also detect a constant-false filter condition whose test used to carry a FIXME label. One plan gets marginally worse, because the old code recomputed attr_needed from equivalence classes after a join removal; that is more accurate than what deconstruct_jointree() derives from the original clauses, but we no longer do that. Making that recomputation happen anyway could be worth doing, but it should be considered independently and perhaps implemented differently. This leaves a good deal of dead code behind, which the next commit removes; the separation is made to make each diff a little more readable. As of this patch there are -Wunused-function warnings about several no-longer-used functions in analyzejoins.c. Bug: #19560 Reported-by: Orestis Markou <orestis@orestis.gr> Author: Tom Lane <tgl@sss.pgh.pa.us> Discussion: https://postgr.es/m/1186816.1784573544@sss.pgh.pa.us --- src/backend/optimizer/plan/analyzejoins.c | 833 +++++++++++++++------- src/backend/optimizer/plan/initsplan.c | 6 +- src/backend/optimizer/plan/planmain.c | 67 +- src/include/optimizer/planmain.h | 6 +- src/test/regress/expected/join.out | 101 ++- src/test/regress/sql/join.sql | 40 +- 6 files changed, 755 insertions(+), 298 deletions(-) diff --git a/src/backend/optimizer/plan/analyzejoins.c b/src/backend/optimizer/plan/analyzejoins.c index e1af49d3dea..ef355ec1fe1 100644 --- a/src/backend/optimizer/plan/analyzejoins.c +++ b/src/backend/optimizer/plan/analyzejoins.c @@ -7,9 +7,14 @@ * certain optimizations cannot be performed at that stage for lack of * detailed information about the query. The routines here are invoked * after initsplan.c has done its work, and can do additional join removal - * and simplification steps based on the information extracted. The penalty - * is that we have to work harder to clean up after ourselves when we modify - * the query, since the derived data structures have to be updated too. + * and simplification steps based on the information extracted. + * + * Although the decisions about what can be removed are made using the + * planner's derived data structures, the removals themselves are implemented + * by editing the query's jointree, which is a far simpler and more stable + * representation. We make no attempt to update the derived data structures + * to match; instead, query_planner() throws them all away and recomputes them + * whenever we report having removed something. * * Portions Copyright (c) 1996-2026, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California @@ -23,6 +28,7 @@ #include "postgres.h" #include "catalog/pg_class.h" +#include "nodes/makefuncs.h" #include "nodes/nodeFuncs.h" #include "optimizer/joininfo.h" #include "optimizer/optimizer.h" @@ -30,6 +36,7 @@ #include "optimizer/paths.h" #include "optimizer/placeholder.h" #include "optimizer/planmain.h" +#include "optimizer/prep.h" #include "optimizer/restrictinfo.h" #include "parser/parse_agg.h" #include "rewrite/rewriteManip.h" @@ -69,6 +76,11 @@ static void remove_rel_from_restrictinfo_phvs(RestrictInfo *rinfo, static Node *remove_rel_from_phvs(Node *node, int relid, int ojrelid); static Node *remove_rel_from_phvs_mutator(Node *node, Relids removable); static List *remove_rel_from_joinlist(List *joinlist, int relid, int *nremoved); +static Node *remove_join_from_jointree(Node *jtnode, int ojrelid, + int *nremoved); +static void remove_rels_from_query_tree(PlannerInfo *root, + Relids removed_relids); +static bool reduce_semijoin_in_jointree(Node *jtnode, Relids syn_righthand); static bool rel_supports_distinctness(PlannerInfo *root, RelOptInfo *rel); static bool rel_is_distinct_for(PlannerInfo *root, RelOptInfo *rel, List *clause_list, List **extra_clauses); @@ -80,6 +92,13 @@ static bool is_innerrel_unique_for(PlannerInfo *root, 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); +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); static bool replace_relid_callback(Node *node, ChangeVarNodes_context *context); @@ -88,21 +107,22 @@ static bool replace_relid_callback(Node *node, /* * remove_useless_joins * Check for relations that don't actually need to be joined at all, - * and remove them from the query. + * and remove them from the query's jointree. * - * We are passed the current joinlist and return the updated list. Other - * data structures that have to be updated are accessible via "root". + * Returns true if we removed anything. In that case the caller must discard + * everything it has derived from the jointree and compute it over again, + * since we don't try to update any of that here. */ -List * -remove_useless_joins(PlannerInfo *root, List *joinlist) +bool +remove_useless_joins(PlannerInfo *root) { + Relids removed_relids = NULL; ListCell *lc; /* * We are only interested in relations that are left-joined to, so we can * scan the join_info_list to find them easily. */ -restart: foreach(lc, root->join_info_list) { SpecialJoinInfo *sjinfo = (SpecialJoinInfo *) lfirst(lc); @@ -114,37 +134,59 @@ restart: continue; /* - * Currently, join_is_removable can only succeed when the sjinfo's - * righthand is a single baserel. Remove that rel from the query and - * joinlist. + * join_is_removable insists that the join's syntactic righthand side + * be a single baserel, so we can implement the removal by dropping + * the JoinExpr and everything below its righthand side. */ - innerrelid = bms_singleton_member(sjinfo->min_righthand); + innerrelid = bms_singleton_member(sjinfo->syn_righthand); - remove_leftjoinrel_from_query(root, innerrelid, sjinfo); + /* + * The removed rel had better not be one that the rest of the planner + * expects to find. It can't be, really: a result relation or a + * row-marked relation has junk columns in the query targetlist, and + * join_is_removable would have seen those as uses of the rel from + * "relation 0". But let's check. + */ + Assert(innerrelid != root->parse->resultRelation); +#ifdef USE_ASSERT_CHECKING + foreach_node(PlanRowMark, rc, root->rowMarks) + Assert(rc->rti != innerrelid && rc->prti != innerrelid); +#endif - /* We verify that exactly one reference gets removed from joinlist */ + /* We verify that exactly one JoinExpr gets removed */ nremoved = 0; - joinlist = remove_rel_from_joinlist(joinlist, innerrelid, &nremoved); + root->parse->jointree = (FromExpr *) + remove_join_from_jointree((Node *) root->parse->jointree, + sjinfo->ojrelid, &nremoved); if (nremoved != 1) - elog(ERROR, "failed to find relation %d in joinlist", innerrelid); + elog(ERROR, "failed to find join %d in jointree", sjinfo->ojrelid); - /* - * We can delete this SpecialJoinInfo from the list too, since it's no - * longer of interest. (Since we'll restart the foreach loop - * immediately, we don't bother with foreach_delete_current.) - */ - root->join_info_list = list_delete_cell(root->join_info_list, lc); + /* Track all the relids we've removed, for use below */ + removed_relids = bms_add_member(removed_relids, innerrelid); + removed_relids = bms_add_member(removed_relids, sjinfo->ojrelid); /* - * Restart the scan. This is necessary to ensure we find all - * removable joins independently of ordering of the join_info_list - * (note that removal of attr_needed bits may make a join appear - * removable that did not before). + * It's okay to keep scanning join_info_list for more removable joins, + * even though the data that join_is_removable consults is now + * slightly out of date. Removing a join can only delete attr_needed + * bits and join clauses, and any attr_needed bit or join clause that + * mentions the removed rel above its own join level would have + * prevented that rel from being removable. So what remains to be + * examined is unchanged by what we just did. + * + * The converse doesn't hold: dropping a join can make some other join + * removable that didn't look so before. That's why our caller loops + * until we report finding nothing more to remove. */ - goto restart; } - return joinlist; + if (bms_is_empty(removed_relids)) + return false; + + /* Clean up the traces that the removed rels have left elsewhere */ + remove_rels_from_query_tree(root, removed_relids); + + return true; } /* @@ -176,8 +218,15 @@ join_is_removable(PlannerInfo *root, SpecialJoinInfo *sjinfo) if (sjinfo->jointype != JOIN_LEFT) return false; - if (!bms_get_singleton_member(sjinfo->min_righthand, &innerrelid)) + /* + * We test the syntactic righthand side, not min_righthand, because the + * removal is done by deleting the whole righthand subtree of the join. + * (min_righthand can be a singleton when syn_righthand is not, but in + * such a case the attr_needed tests below would reject the join anyway.) + */ + if (!bms_get_singleton_member(sjinfo->syn_righthand, &innerrelid)) return false; + Assert(bms_equal(sjinfo->min_righthand, sjinfo->syn_righthand)); /* * Never try to eliminate a left join to the query result rel. Although @@ -1025,6 +1074,91 @@ remove_rel_from_joinlist(List *joinlist, int relid, int *nremoved) } +/* + * remove_join_from_jointree + * Delete the JoinExpr with the given RT index, along with everything + * below its righthand side, from the query's jointree. + * + * 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). + */ +static Node * +remove_join_from_jointree(Node *jtnode, int ojrelid, int *nremoved) +{ + if (jtnode == NULL) + return NULL; + if (IsA(jtnode, RangeTblRef)) + { + /* nothing to do here */ + } + else if (IsA(jtnode, FromExpr)) + { + FromExpr *f = (FromExpr *) jtnode; + ListCell *l; + + foreach(l, f->fromlist) + lfirst(l) = remove_join_from_jointree((Node *) lfirst(l), + ojrelid, nremoved); + } + else if (IsA(jtnode, JoinExpr)) + { + JoinExpr *j = (JoinExpr *) jtnode; + + if (j->rtindex == 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)); + + return jtnode; +} + +/* + * remove_rels_from_query_tree + * Delete all remaining references to the given relids from the query. + * + * 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 the relids can + * still appear in the nullingrels sets of surviving Vars and PlaceHolderVars, + * and in the phrels sets of PlaceHolderVars. ChangeVarNodes knows how to + * strip a relid out of all of those. + */ +static void +remove_rels_from_query_tree(PlannerInfo *root, Relids removed_relids) +{ + int relid = -1; + + while ((relid = bms_next_member(removed_relids, relid)) >= 0) + { + /* Pass -1 for new_index to get the removal behavior */ + ChangeVarNodes((Node *) root->parse, relid, -1, 0); + + /* + * 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.) + */ + ChangeVarNodes((Node *) root->processed_tlist, relid, -1, 0); + + /* There could be references in the append_rel_list, too */ + if (root->append_rel_list != NIL) + ChangeVarNodes((Node *) root->append_rel_list, relid, -1, 0); + } +} + /* * reduce_unique_semijoins * Check for semijoins that can be simplified to plain inner joins @@ -1033,14 +1167,13 @@ remove_rel_from_joinlist(List *joinlist, int relid, int *nremoved) * Ideally this would happen during reduce_outer_joins, but we don't have * enough information at that point. * - * To perform the strength reduction when applicable, we need only delete - * the semijoin's SpecialJoinInfo from root->join_info_list. (We don't - * bother fixing the join type attributed to it in the query jointree, - * since that won't be consulted again.) + * Like the join removal cases, we do this on the query's jointree, so + * returning true means the caller must recompute the derived data. */ -void +bool reduce_unique_semijoins(PlannerInfo *root) { + bool changed = false; ListCell *lc; /* @@ -1097,9 +1230,65 @@ reduce_unique_semijoins(PlannerInfo *root) JOIN_SEMI, restrictlist, true)) continue; - /* OK, remove the SpecialJoinInfo from the list. */ - root->join_info_list = foreach_delete_current(root->join_info_list, lc); + /* OK, reduce the join to a plain inner join in the jointree. */ + if (!reduce_semijoin_in_jointree((Node *) root->parse->jointree, + sjinfo->syn_righthand)) + elog(ERROR, "failed to find semijoin in jointree"); + changed = true; + } + + return changed; +} + +/* + * reduce_semijoin_in_jointree + * Find the JoinExpr for the semijoin with the given syntactic righthand + * side, and turn it into an inner join. + * + * Semijoins have no RT index of their own, so we have to identify the one + * we want by the set of relids on its righthand side. + */ +static bool +reduce_semijoin_in_jointree(Node *jtnode, Relids syn_righthand) +{ + if (jtnode == NULL) + return false; + if (IsA(jtnode, RangeTblRef)) + { + /* nothing to do here */ + } + else if (IsA(jtnode, FromExpr)) + { + FromExpr *f = (FromExpr *) jtnode; + ListCell *l; + + foreach(l, f->fromlist) + { + if (reduce_semijoin_in_jointree((Node *) lfirst(l), syn_righthand)) + return true; + } } + else if (IsA(jtnode, JoinExpr)) + { + JoinExpr *j = (JoinExpr *) jtnode; + + if (j->jointype == JOIN_SEMI && + bms_equal(get_relids_in_jointree(j->rarg, true, false), + syn_righthand)) + { + j->jointype = JOIN_INNER; + return true; + } + if (reduce_semijoin_in_jointree(j->larg, syn_righthand)) + return true; + if (reduce_semijoin_in_jointree(j->rarg, syn_righthand)) + return true; + } + else + elog(ERROR, "unrecognized jointree node type: %d", + (int) nodeTag(jtnode)); + + return false; } @@ -2014,130 +2203,64 @@ replace_relid_callback(Node *node, ChangeVarNodes_context *context) } /* - * Remove a relation after we have proven that it participates only in an - * unneeded unique self-join. - * - * Replace any links in planner info structures. - * - * 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 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. + * Remove the toRemove relation after we have proven that it participates only + * in an unneeded unique self-join with toKeep. + * + * The removal is done by deleting the relation's RangeTblRef from the + * jointree and then pointing everything that referenced it at the relation we + * are keeping. All the conditions that were attached to the removed relation + * thereby become conditions on the remaining one, which is what we want: + * we've proven that the two relations select the same rows. + * + * kmark and rmark are the PlanRowMarks (if any) for the kept and removed + * relations. We could re-locate those, but the caller already found them. */ static void -remove_self_join_rel(PlannerInfo *root, PlanRowMark *kmark, PlanRowMark *rmark, +remove_self_join_rel(PlannerInfo *root, RelOptInfo *toKeep, RelOptInfo *toRemove, - List *restrictlist) + PlanRowMark *kmark, PlanRowMark *rmark) { - List *joininfos; - ListCell *lc; - int i; - List *jinfo_candidates = NIL; - List *binfo_candidates = NIL; + Node *orphan_quals = NULL; + int nremoved = 0; 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); - } + /* We verify that exactly one reference gets removed from the jointree */ + root->parse->jointree = (FromExpr *) + remove_rel_from_jointree((Node *) root->parse->jointree, + toRemove->relid, + &orphan_quals, &nremoved); + if (nremoved != 1) + elog(ERROR, "failed to find relation %d in jointree", toRemove->relid); + /* The topmost FromExpr can't have gone away, so nothing can be orphaned */ + Assert(root->parse->jointree != NULL); + Assert(orphan_quals == NULL); /* - * 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. + * Replace all references to the removed relation. Note that this must + * happen after the jointree surgery, else we'd not be able to tell the + * two relations' RangeTblRefs apart. */ - 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); - } + ChangeVarNodes((Node *) root->parse, toRemove->relid, toKeep->relid, 0); /* - * Transfer the targetlist and attr_needed flags. + * 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 the second visit to a + * shared node finds nothing to change.) */ + ChangeVarNodes((Node *) root->processed_tlist, toRemove->relid, + toKeep->relid, 0); - 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); - } + /* There could be references in the append_rel_list, too */ + if (root->append_rel_list != NIL) + ChangeVarNodes((Node *) root->append_rel_list, toRemove->relid, + toKeep->relid, 0); - 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]); - } + /* Clean up the quals that the substitution has messed with */ + fixup_selfjoin_jointree(root, (Node *) root->parse->jointree, + toKeep->relid); /* * If the removed relation has a row mark, transfer it to the remaining @@ -2157,52 +2280,270 @@ remove_self_join_rel(PlannerInfo *root, PlanRowMark *kmark, PlanRowMark *rmark, } else { - /* Shouldn't have inheritance children here. */ + /* Shouldn't have inheritance children yet. */ Assert(rmark->rti == rmark->prti); rmark->rti = rmark->prti = toKeep->relid; } } +} - /* - * 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); +/* + * remove_rel_from_jointree + * Delete the RangeTblRef for the given relation from the query's + * jointree. + * + * This is used for self-join elimination, where the removed relation's + * qual conditions must all be preserved (they will be transposed onto the + * remaining relation afterwards). Hence, if dropping the RangeTblRef leaves + * a JoinExpr or FromExpr with nothing under it, we can't simply drop that + * node; we hand its quals back to the caller in *orphan_quals, to be merged + * into the nearest enclosing node that still has some content. That's a + * valid transformation only for inner joins, but a jointree node can't become + * empty at an outer join here: remove_self_joins_one_group() insists that the + * two relations be on the same side of every outer join, so the relation we + * are keeping would have to be in the emptied subtree too. + * + * *nremoved is incremented by the number of RangeTblRefs removed (there + * should be exactly one, but the caller checks that). + */ +static Node * +remove_rel_from_jointree(Node *jtnode, int relid, + Node **orphan_quals, int *nremoved) +{ + if (jtnode == NULL) + return NULL; + if (IsA(jtnode, RangeTblRef)) + { + RangeTblRef *rtr = (RangeTblRef *) jtnode; - /* Replace links in the planner info */ - remove_rel_from_query(root, toRemove->relid, toKeep->relid, NULL, NULL); + if (rtr->rtindex == relid) + { + (*nremoved)++; + return NULL; + } + } + else if (IsA(jtnode, FromExpr)) + { + FromExpr *f = (FromExpr *) jtnode; + List *newfromlist = NIL; + Node *sub_orphans = NULL; + ListCell *l; - /* Replace varno in the fully-processed targetlist */ - ChangeVarNodesExtended((Node *) root->processed_tlist, toRemove->relid, - toKeep->relid, 0, replace_relid_callback); + foreach(l, f->fromlist) + { + Node *newchild; - /* - * There may be references to the rel in root->fkey_list, but if so, - * match_foreign_keys_to_quals() will get rid of them. - */ + newchild = remove_rel_from_jointree((Node *) lfirst(l), relid, + &sub_orphans, nremoved); + if (newchild != NULL) + newfromlist = lappend(newfromlist, newchild); + } + f->fromlist = newfromlist; + f->quals = merge_quals(sub_orphans, f->quals); + if (newfromlist == NIL) + { + /* Nothing left here, so pass our quals up to the parent */ + *orphan_quals = merge_quals(f->quals, *orphan_quals); + return NULL; + } + } + else if (IsA(jtnode, JoinExpr)) + { + JoinExpr *j = (JoinExpr *) jtnode; + Node *sub_orphans = NULL; + + j->larg = remove_rel_from_jointree(j->larg, relid, + &sub_orphans, nremoved); + j->rarg = remove_rel_from_jointree(j->rarg, relid, + &sub_orphans, nremoved); + if (j->larg == NULL || j->rarg == NULL) + { + Node *surviving = (j->larg != NULL) ? j->larg : j->rarg; + Node *quals = merge_quals(sub_orphans, j->quals); - /* - * 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; + /* As explained above, this can only happen for an inner join */ + Assert(j->jointype == JOIN_INNER); + /* We can't have removed both children */ + Assert(surviving != NULL); + + /* + * Replace the join by a FromExpr, so that the surviving side's + * rows are still filtered by the join's conditions. + */ + return (Node *) makeFromExpr(list_make1(surviving), quals); + } + /* A subtree that survives never hands any quals back to us */ + Assert(sub_orphans == NULL); + } + else + elog(ERROR, "unrecognized jointree node type: %d", + (int) nodeTag(jtnode)); + + return jtnode; +} + +/* + * merge_quals + * Combine two jointree qual conditions. + * + * quals1 should be the quals from the lower of the two jointree levels, + * so that those quals get applied first. + * + * Jointree quals have been through preprocess_expression() by now, so each + * one is either NULL or an implicitly-ANDed List. + */ +static Node * +merge_quals(Node *quals1, Node *quals2) +{ + if (quals1 == NULL) + return quals2; + if (quals2 == NULL) + return quals1; + return (Node *) list_concat(castNode(List, quals1), + castNode(List, quals2)); +} + +/* + * fixup_selfjoin_jointree + * Clean up the query's jointree quals after self-join elimination has + * merged one relation into another. (relid is the kept relation.) + * + * See fixup_selfjoin_quals() for what needs fixing. + */ +static void +fixup_selfjoin_jointree(PlannerInfo *root, Node *jtnode, int relid) +{ + if (jtnode == NULL) + return; + if (IsA(jtnode, RangeTblRef)) + { + /* nothing to do here */ + } + else if (IsA(jtnode, FromExpr)) + { + FromExpr *f = (FromExpr *) jtnode; + ListCell *l; + + foreach(l, f->fromlist) + fixup_selfjoin_jointree(root, (Node *) lfirst(l), relid); + f->quals = (Node *) fixup_selfjoin_quals(root, + castNode(List, f->quals), + relid); + } + else if (IsA(jtnode, JoinExpr)) + { + JoinExpr *j = (JoinExpr *) jtnode; + + fixup_selfjoin_jointree(root, j->larg, relid); + fixup_selfjoin_jointree(root, j->rarg, relid); + j->quals = (Node *) fixup_selfjoin_quals(root, + castNode(List, j->quals), + relid); + } + else + elog(ERROR, "unrecognized jointree node type: %d", + (int) nodeTag(jtnode)); +} + +/* + * fixup_selfjoin_quals + * Clean up one qual list after self-join elimination. + * + * 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). + * + * 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. + * + * 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 List * +fixup_selfjoin_quals(PlannerInfo *root, List *quals, int relid) +{ + List *result = NIL; + ListCell *l; - /* And nuke the RelOptInfo, just in case there's another access path. */ - pfree(toRemove); + foreach(l, quals) + { + Node *qual = (Node *) lfirst(l); + if (bms_is_member(relid, pull_varnos(root, qual))) + { + 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); + } + + return result; +} + +/* + * 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; /* - * 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; } /* @@ -2227,7 +2568,12 @@ split_selfjoin_quals(PlannerInfo *root, List *joinquals, List **selfjoinquals, Node *leftexpr; Node *rightexpr; - /* In general, clause looks like F(arg1) = G(arg2) */ + /* + * Since the given joinquals all came from + * generate_join_implied_equalities, they ought to look like equality + * operators on single-relation expressions. But let's check that. + * Anything that doesn't look like that can be dumped into ojoinquals. + */ if (!rinfo->mergeopfamilies || bms_num_members(rinfo->clause_relids) != 2 || bms_membership(rinfo->left_relids) != BMS_SINGLETON || @@ -2340,15 +2686,16 @@ match_unique_clauses(PlannerInfo *root, RelOptInfo *outer, List *uclauses, } /* - * Find and remove unique self-joins in a group of base relations that have + * Find and remove one unique self-join in a group of base relations that have * the same Oid. * - * Returns a set of relids that were removed. + * Returns true if we removed a relation. We stop at the first removal, + * because it invalidates all the derived information that the tests here + * depend on; our caller will come back for more once that's been rebuilt. */ -static Relids +static bool remove_self_joins_one_group(PlannerInfo *root, Relids relids) { - Relids result = NULL; int k; /* Index of kept relation */ int r = -1; /* Index of removed relation */ @@ -2356,8 +2703,8 @@ remove_self_joins_one_group(PlannerInfo *root, Relids relids) { RelOptInfo *rrel = root->simple_rel_array[r]; + /* k iterates over the relids after r */ k = r; - while ((k = bms_next_member(relids, k)) > 0) { Relids joinrelids = NULL; @@ -2377,8 +2724,8 @@ remove_self_joins_one_group(PlannerInfo *root, Relids relids) /* * It is impossible to eliminate the join of two relations if they - * belong to different rules of order. Otherwise, the planner - * can't find any variants of the correct query plan. + * are not on the same side of every outer join. Otherwise, the + * planner can't find any variants of the correct query plan. */ foreach(lc, root->join_info_list) { @@ -2492,29 +2839,26 @@ remove_self_joins_one_group(PlannerInfo *root, Relids relids) if (!match_unique_clauses(root, rrel, uclauses, krel->relid)) continue; - /* - * Remove rrel RelOptInfo from the planner structures and the - * corresponding row mark. - */ - remove_self_join_rel(root, kmark, rmark, krel, rrel, restrictlist); - - result = bms_add_member(result, r); + /* OK, remove rrel from the query, and report that we did so */ + remove_self_join_rel(root, krel, rrel, kmark, rmark); - /* We have removed the outer relation, try the next one. */ - break; + return true; } } - return result; + return false; } /* - * Gather indexes of base relations from the joinlist and try to eliminate self - * joins. + * Gather indexes of base relations from the joinlist and try to eliminate one + * self join. + * + * Returns true if we removed a relation. */ -static Relids -remove_self_joins_recurse(PlannerInfo *root, List *joinlist, Relids toRemove) +static bool +remove_self_joins_recurse(PlannerInfo *root, List *joinlist) { + bool removed = false; ListCell *jl; Relids relids = NULL; SelfJoinCandidate *candidates = NULL; @@ -2536,7 +2880,7 @@ remove_self_joins_recurse(PlannerInfo *root, List *joinlist, Relids toRemove) * We only consider ordinary relations as candidates to be * removed, and these relations should not have TABLESAMPLE * clauses specified. Removing a relation with TABLESAMPLE clause - * could potentially change the syntax of the query. Because of + * could potentially change the semantics of the query. Because of * UPDATE/DELETE EPQ mechanism, currently Query->resultRelation or * Query->mergeTargetRelation associated rel cannot be eliminated. */ @@ -2552,9 +2896,9 @@ remove_self_joins_recurse(PlannerInfo *root, List *joinlist, Relids toRemove) } else if (IsA(jlnode, List)) { - /* Recursively go inside the sub-joinlist */ - toRemove = remove_self_joins_recurse(root, (List *) jlnode, - toRemove); + /* Recursively consider SJE within the sub-joinlist */ + if (remove_self_joins_recurse(root, (List *) jlnode)) + return true; } else elog(ERROR, "unrecognized joinlist node type: %d", @@ -2565,7 +2909,7 @@ remove_self_joins_recurse(PlannerInfo *root, List *joinlist, Relids toRemove) /* Need at least two relations for the join */ if (numRels < 2) - return toRemove; + return false; /* * In order to find relations with the same oid we first build an array of @@ -2586,8 +2930,7 @@ remove_self_joins_recurse(PlannerInfo *root, List *joinlist, Relids toRemove) /* * Iteratively form a group of relation indexes with the same oid and - * launch the routine that detects self-joins in this group and removes - * excessive range table entries. + * launch the routine that detects a self-join in this group. * * At the end of the iteration, exclude the group from the overall relids * list. So each next iteration of the cycle will involve less and less @@ -2598,11 +2941,10 @@ remove_self_joins_recurse(PlannerInfo *root, List *joinlist, Relids toRemove) { if (j == numRels || candidates[j].reloid != candidates[i].reloid) { - if (j - i >= 2) + if (j - i >= 2 && !removed) { /* Create a group of relation indexes with the same oid */ Relids group = NULL; - Relids removed; while (i < j) { @@ -2612,34 +2954,29 @@ remove_self_joins_recurse(PlannerInfo *root, List *joinlist, Relids toRemove) relids = bms_del_members(relids, group); /* - * Try to remove self-joins from a group of identical entries. - * Make the next attempt iteratively - if something is deleted - * from a group, changes in clauses and equivalence classes - * can give us a chance to find more candidates. + * Try to remove a self-join from a group of identical + * entries. We stop as soon as we succeed, since the + * information we based the decision on is then out of date; + * our caller will start over from scratch. */ - do - { - Assert(!bms_overlap(group, toRemove)); - removed = remove_self_joins_one_group(root, group); - toRemove = bms_add_members(toRemove, removed); - group = bms_del_members(group, removed); - } while (!bms_is_empty(removed) && - bms_membership(group) == BMS_MULTIPLE); - bms_free(removed); + removed = remove_self_joins_one_group(root, group); bms_free(group); } else { - /* Single relation, just remove it from the set */ - relids = bms_del_member(relids, candidates[i].relid); - i = j; + /* Nothing to do with this group, just drop it from the set */ + while (i < j) + { + relids = bms_del_member(relids, candidates[i].relid); + i++; + } } } } Assert(bms_is_empty(relids)); - return toRemove; + return removed; } /* @@ -2681,45 +3018,25 @@ self_join_candidates_cmp(const void *a, const void *b) * 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; we use it to identify + * groups of relations that could be joined to each other. * - * '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. + * We remove at most one self-join per call, and return true if we did so. + * The caller must then recompute everything that was derived from the + * jointree before calling here again. */ -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 one pair of relations participating in a self-join. */ + return remove_self_joins_recurse(root, joinlist); } diff --git a/src/backend/optimizer/plan/initsplan.c b/src/backend/optimizer/plan/initsplan.c index b38422c47a4..7b6d7249c66 100644 --- a/src/backend/optimizer/plan/initsplan.c +++ b/src/backend/optimizer/plan/initsplan.c @@ -4044,9 +4044,9 @@ match_foreign_keys_to_quals(PlannerInfo *root) /* * 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 don't use - * find_base_rel() here. We can ignore such FKs. + * isn't referenced by the jointree (typically because it's been + * removed by join removal), so that it won't have a RelOptInfo. Hence + * don't use find_base_rel() here. We can ignore such FKs. */ if (fkinfo->con_relid >= root->simple_rel_array_size || fkinfo->ref_relid >= root->simple_rel_array_size) diff --git a/src/backend/optimizer/plan/planmain.c b/src/backend/optimizer/plan/planmain.c index c123a397c1a..298affe6bca 100644 --- a/src/backend/optimizer/plan/planmain.c +++ b/src/backend/optimizer/plan/planmain.c @@ -55,33 +55,71 @@ RelOptInfo * query_planner(PlannerInfo *root, query_pathkeys_callback qp_callback, void *qp_extra) { - Query *parse = root->parse; + Query *parse; List *joinlist; RelOptInfo *final_rel; /* - * Init planner lists to empty. + * The join simplification steps below work by modifying parse->jointree, + * and they make no attempt to update the information we derive from it. + * So whenever one of them succeeds, we must throw away all that derived + * information and recompute it from scratch, which we do by looping back + * to "restart". We cannot loop indefinitely, because each successful + * simplification either deletes a base relation from the jointree or + * turns a semijoin into an inner join, and neither of those can be undone + * by a later pass. * - * NOTE: append_rel_list was set up by subquery_planner, so do not touch - * here. + * These initial Asserts check that the state at entry is not too complex + * for the code below to restore. There mustn't be any EquivalenceClasses + * yet, and we should have only the top-level JoinDomain. */ + Assert(root->eq_classes == NIL); + Assert(list_length(root->join_domains) == 1); + +restart: + parse = root->parse; + + /* + * Initialize information derived from the jointree to empty. + * + * It's critical that this reset every field that the steps below will + * fill in, since we may be going around this loop more than once. + * + * NOTE: append_rel_list was created earlier, so do not clear it here; + * rowMarks ditto. Join simplification must update those if necessary. + */ + root->all_baserels = NULL; + root->outer_join_rels = NULL; + root->all_query_rels = NULL; root->join_rel_list = NIL; root->join_rel_hash = NULL; root->join_rel_level = NULL; root->join_cur_level = 0; + root->eq_classes = NIL; + root->ec_merging_done = false; root->canon_pathkeys = NIL; root->left_join_clauses = NIL; root->right_join_clauses = NIL; root->full_join_clauses = NIL; root->join_info_list = NIL; + root->last_rinfo_serial = 0; root->placeholder_list = NIL; root->placeholder_array = NULL; root->placeholder_array_size = 0; + root->placeholdersFrozen = false; root->agg_clause_list = NIL; root->group_expr_list = NIL; root->tlist_vars = NIL; root->fkey_list = NIL; root->initial_rels = NIL; + root->hasPseudoConstantQuals = false; + + /* + * We don't want to delete the top-level join domain, but get rid of other + * ones so as to reset the list to initial state. deconstruct_jointree + * will take care of (re)computing the top level's jd_relids. + */ + root->join_domains = list_truncate(root->join_domains, 1); /* * Set up arrays for accessing base relations and AppendRelInfos. @@ -228,19 +266,30 @@ query_planner(PlannerInfo *root, * Remove any useless outer joins. Ideally this would be done during * jointree preprocessing, but the necessary information isn't available * until we've built baserel data structures and classified qual clauses. + * If we remove a join, loop back to the top and redo what we did so far. */ - joinlist = remove_useless_joins(root, joinlist); + if (remove_useless_joins(root)) + goto restart; /* * Also, reduce any semijoins with unique inner rels to plain inner joins. - * Likewise, this can't be done until now for lack of needed info. + * Likewise, this can't be done until now for lack of needed info, and we + * must loop around if we find any simplifications. + */ + if (reduce_unique_semijoins(root)) + goto restart; + + /* + * Remove self joins on a unique column. Again, this couldn't be done any + * earlier, and we must loop around if we find anything to remove. */ - reduce_unique_semijoins(root); + if (remove_useless_self_joins(root, joinlist)) + goto restart; /* - * Remove self joins on a unique column. + * No more join simplifications apply, so we're done looping. Code below + * this point does not need to be able to restart. */ - joinlist = remove_useless_self_joins(root, joinlist); /* * Now distribute "placeholders" to base rels as needed. This has to be diff --git a/src/include/optimizer/planmain.h b/src/include/optimizer/planmain.h index 71c043a25e8..85301d912f0 100644 --- a/src/include/optimizer/planmain.h +++ b/src/include/optimizer/planmain.h @@ -108,8 +108,8 @@ extern void match_foreign_keys_to_quals(PlannerInfo *root); /* * prototypes for plan/analyzejoins.c */ -extern List *remove_useless_joins(PlannerInfo *root, List *joinlist); -extern void reduce_unique_semijoins(PlannerInfo *root); +extern bool remove_useless_joins(PlannerInfo *root); +extern bool reduce_unique_semijoins(PlannerInfo *root); extern bool query_supports_distinctness(Query *query); extern bool query_is_distinct_for(Query *query, List *distinct_cols); extern bool innerrel_is_unique(PlannerInfo *root, @@ -119,7 +119,7 @@ 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 bool remove_useless_self_joins(PlannerInfo *root, List *joinlist); /* * prototypes for plan/setrefs.c diff --git a/src/test/regress/expected/join.out b/src/test/regress/expected/join.out index 19e2cca548b..254b203aeba 100644 --- a/src/test/regress/expected/join.out +++ b/src/test/regress/expected/join.out @@ -6890,6 +6890,38 @@ where t1.a = s.c; ---------- (0 rows) +rollback; +-- join removal bug #19560: removing a join can leave an EquivalenceClass that +-- now yields a base restriction clause, so we must redo equivalence +-- processing from scratch +begin; +create temp table items (id text, owner text); +create temp table follows (item_id text, user_id text, + unique (user_id, item_id)); +insert into items values ('item1', 'alice'); +explain (costs off) +with viewer as (select 'bob' as id) +select count(*) from items + left join follows on follows.item_id = items.id and follows.user_id = 'bob' + left join viewer on true +where items.owner = viewer.id; + QUERY PLAN +--------------------------------------- + Aggregate + -> Seq Scan on items + Filter: (owner = 'bob'::text) +(3 rows) + +with viewer as (select 'bob' as id) +select count(*) from items + left join follows on follows.item_id = items.id and follows.user_id = 'bob' + left join viewer on true +where items.owner = viewer.id; + count +------- + 0 +(1 row) + rollback; -- check handling of semijoins after join removal: we must suppress -- unique-ification of known-constant values @@ -6915,17 +6947,17 @@ where exists (select 1 from t t4 Output: t1.a Index Cond: (t1.a = 1) -> HashAggregate - Output: t5.a + Output: t4.a, t5.a Group Key: t5.a -> Hash Join - Output: t5.a + Output: t4.a, t5.a Hash Cond: (t6.b = t4.b) -> Seq Scan on pg_temp.t t6 Output: t6.a, t6.b -> Hash - Output: t4.b, t5.b, t5.a + Output: t4.b, t4.a, t5.b, t5.a -> Hash Join - Output: t4.b, t5.b, t5.a + Output: t4.b, t4.a, t5.b, t5.a Inner Unique: true Hash Cond: (t5.b = t4.b) -> Seq Scan on pg_temp.t t5 @@ -7357,7 +7389,7 @@ on q1.ax = q2.a; Nested Loop Left Join Join Filter: (t2.a = t4.a) -> Seq Scan on sj t2 - Filter: ((b IS NULL) AND (a IS NOT NULL) AND ((c * c) = (c + 2))) + Filter: ((a IS NOT NULL) AND (b IS NULL) AND ((c * c) = (c + 2))) -> Seq Scan on sj t4 Filter: (c IS NOT NULL) (6 rows) @@ -7440,9 +7472,9 @@ select t1.a from sj t1 where t1.b in ( -> Seq Scan on public.sj t1 Output: t1.a, t1.b, t1.c -> Materialize - Output: t3.c, t3.b + Output: t3.b -> Seq Scan on public.sj t3 - Output: t3.c, t3.b + Output: t3.b Filter: (t3.c IS NOT NULL) (10 rows) @@ -7776,15 +7808,15 @@ explain (costs off) select * from sj p join sj q on p.a = q.a -> Seq Scan on sj r (6 rows) --- FIXME this constant false filter doesn't look good. Should we merge --- equivalence classes? +-- Check that we detect constant-false condition after merging ECs. explain (costs off) select * from sj p, sj q where p.a = q.a and p.b = 1 and q.b = 2; - QUERY PLAN ------------------------------------------------------ - Seq Scan on sj q - Filter: ((a IS NOT NULL) AND (b = 2) AND (b = 1)) -(2 rows) + QUERY PLAN +-------------------------- + Result + Replaces: Scan on q + One-Time Filter: false +(3 rows) -- Check that attr_needed is updated correctly after self-join removal. In this -- test, the join of j1 with j2 is removed. k1.b is required at either j1 or j2. @@ -7920,11 +7952,9 @@ where s1.x = 1; -> Seq Scan on public.emp1 t1 Output: t1.id, t1.code -> Materialize - Output: t3.id -> Seq Scan on public.emp1 t3 - Output: t3.id Filter: (1 = 1) -(9 rows) +(7 rows) -- Check that PHVs do not impose any constraints on removing self joins explain (verbose, costs off) @@ -7974,14 +8004,14 @@ SELECT 1 FROM tbl_phv t1 LEFT JOIN (SELECT y FROM tbl_phv tr) t4 ON t4.y = t3.y ON true WHERE t3.extra IS NOT NULL AND t3.x = t1.x % 2; - QUERY PLAN ---------------------------------------------------------- + QUERY PLAN +-------------------------------------------------------------- Nested Loop Output: 1 -> Seq Scan on public.tbl_phv t1 Output: t1.x, t1.y - -> Index Scan using tbl_phv_idx on public.tbl_phv tr - Output: tr.x, tr.y + -> Index Only Scan using tbl_phv_idx on public.tbl_phv tr + Output: tr.x Index Cond: (tr.x = (t1.x % 2)) Filter: (1 IS NOT NULL) (8 rows) @@ -8162,7 +8192,7 @@ where t1.b = t2.b and t2.a = 3 and t1.a = 3 --------------------------------------------------------------------------------------------- Seq Scan on public.sl t2 Output: t2.a, t2.b, t2.c, t2.a, t2.b, t2.c - Filter: ((t2.c IS NOT NULL) AND (t2.b IS NOT NULL) AND (t2.a IS NOT NULL) AND (t2.a = 3)) + Filter: ((t2.b IS NOT NULL) AND (t2.c IS NOT NULL) AND (t2.a IS NOT NULL) AND (t2.a = 3)) (3 rows) -- Join qual isn't mergejoinable, but inner is unique. @@ -8204,10 +8234,35 @@ SELECT 1 AS c1 FROM sl sl1 LEFT JOIN (sl AS sl2 NATURAL JOIN sl AS sl3) -> Nested Loop Left Join Join Filter: sl3.bool_col -> Seq Scan on sl sl3 - Filter: (bool_col AND (a IS NOT NULL) AND (b IS NOT NULL) AND (c IS NOT NULL) AND (bool_col IS NOT NULL)) + Filter: ((a IS NOT NULL) AND (b IS NOT NULL) AND (c IS NOT NULL) AND (bool_col IS NOT NULL) AND bool_col) -> Seq Scan on sl sl4 (7 rows) +-- Check that quals of a jointree node that becomes empty when the self-join +-- is removed are not lost, and that they don't migrate above an outer join +EXPLAIN (COSTS OFF) +SELECT s.a FROM (SELECT * FROM sl WHERE c IS NOT NULL) s, sl t +WHERE t.a = s.a AND t.b = s.b; + QUERY PLAN +--------------------------------------------------------------------- + Seq Scan on sl + Filter: ((c IS NOT NULL) AND (a IS NOT NULL) AND (b IS NOT NULL)) +(2 rows) + +EXPLAIN (COSTS OFF) +SELECT t1.a, ss.a FROM sl t1 + LEFT JOIN (SELECT s.a FROM (SELECT * FROM sl WHERE c IS NOT NULL) s + JOIN sl t ON t.a = s.a AND t.b = s.b) ss + ON ss.a = t1.a; + QUERY PLAN +--------------------------------------------------------------------------- + Nested Loop Left Join + Join Filter: (sl.a = t1.a) + -> Seq Scan on sl t1 + -> Seq Scan on sl + Filter: ((c IS NOT NULL) AND (a IS NOT NULL) AND (b IS NOT NULL)) +(5 rows) + -- Check optimization disabling if it will violate special join conditions. -- Two identical joined relations satisfies self join removal conditions but -- stay in different special join infos. diff --git a/src/test/regress/sql/join.sql b/src/test/regress/sql/join.sql index 85aed7bf704..afa96daecb5 100644 --- a/src/test/regress/sql/join.sql +++ b/src/test/regress/sql/join.sql @@ -2601,6 +2601,31 @@ where t1.a = s.c; rollback; +-- join removal bug #19560: removing a join can leave an EquivalenceClass that +-- now yields a base restriction clause, so we must redo equivalence +-- processing from scratch +begin; + +create temp table items (id text, owner text); +create temp table follows (item_id text, user_id text, + unique (user_id, item_id)); +insert into items values ('item1', 'alice'); + +explain (costs off) +with viewer as (select 'bob' as id) +select count(*) from items + left join follows on follows.item_id = items.id and follows.user_id = 'bob' + left join viewer on true +where items.owner = viewer.id; + +with viewer as (select 'bob' as id) +select count(*) from items + left join follows on follows.item_id = items.id and follows.user_id = 'bob' + left join viewer on true +where items.owner = viewer.id; + +rollback; + -- check handling of semijoins after join removal: we must suppress -- unique-ification of known-constant values begin; @@ -3015,8 +3040,7 @@ select 1 from (select y.* from sj x, sj y where x.a = y.a) q, explain (costs off) select * from sj p join sj q on p.a = q.a left join sj r on p.a + q.a = r.a; --- FIXME this constant false filter doesn't look good. Should we merge --- equivalence classes? +-- Check that we detect constant-false condition after merging ECs. explain (costs off) select * from sj p, sj q where p.a = q.a and p.b = 1 and q.b = 2; @@ -3214,6 +3238,18 @@ EXPLAIN (COSTS OFF) SELECT 1 AS c1 FROM sl sl1 LEFT JOIN (sl AS sl2 NATURAL JOIN sl AS sl3) ON sl2.bool_col LEFT JOIN sl AS sl4 ON sl2.bool_col; +-- Check that quals of a jointree node that becomes empty when the self-join +-- is removed are not lost, and that they don't migrate above an outer join +EXPLAIN (COSTS OFF) +SELECT s.a FROM (SELECT * FROM sl WHERE c IS NOT NULL) s, sl t +WHERE t.a = s.a AND t.b = s.b; + +EXPLAIN (COSTS OFF) +SELECT t1.a, ss.a FROM sl t1 + LEFT JOIN (SELECT s.a FROM (SELECT * FROM sl WHERE c IS NOT NULL) s + JOIN sl t ON t.a = s.a AND t.b = s.b) ss + ON ss.a = t1.a; + -- Check optimization disabling if it will violate special join conditions. -- Two identical joined relations satisfies self join removal conditions but -- stay in different special join infos. -- 2.52.0
v3-0003-Remove-dead-code-that-s-no-longer-needed-for-join.patch (text/x-diff, 64.1K) download From a3d6ff0731aea4461b641486f645095efedfa91e Mon Sep 17 00:00:00 2001 From: Tom Lane <tgl@sss.pgh.pa.us> Date: Sat, 25 Jul 2026 12:32:46 -0400 Subject: [PATCH v3 3/4] Remove dead code that's no longer needed for join removal. This is mostly a straightforward exercise in deleting unreferenced functions, but a couple of points are worth noting. While replace_relid_callback() was still reached in the previous patch, it did nothing since we no longer invoked it on any trees containing RangeTblRef or RestrictInfo nodes. So we can delete it and make the two remaining users use ChangeVarNodes instead of ChangeVarNodesExtended. Then, ChangeVarNodesExtended is unused and we can remove that too, along with the exposed definition of ChangeVarNodes_context (basically reverting that area of the code to what it was in v17). ec_clear_derived_clauses, innerrel_is_unique_ext, adjust_relid_set are now static since they're no longer called from outside their modules. Bug: #19560 Reported-by: Orestis Markou <orestis@orestis.gr> Author: Tom Lane <tgl@sss.pgh.pa.us> Discussion: https://postgr.es/m/1186816.1784573544@sss.pgh.pa.us --- src/backend/optimizer/path/equivclass.c | 51 +- src/backend/optimizer/plan/analyzejoins.c | 1037 +-------------------- src/backend/optimizer/plan/initsplan.c | 179 +--- src/backend/optimizer/util/joininfo.c | 36 - src/backend/optimizer/util/placeholder.c | 27 - src/backend/rewrite/rewriteManip.c | 65 +- src/include/optimizer/joininfo.h | 3 - src/include/optimizer/paths.h | 2 - src/include/optimizer/placeholder.h | 1 - src/include/optimizer/planmain.h | 8 - src/include/rewrite/rewriteManip.h | 19 - src/tools/pgindent/typedefs.list | 1 - 12 files changed, 30 insertions(+), 1399 deletions(-) diff --git a/src/backend/optimizer/path/equivclass.c b/src/backend/optimizer/path/equivclass.c index e3697df51a2..66fe1c24a58 100644 --- a/src/backend/optimizer/path/equivclass.c +++ b/src/backend/optimizer/path/equivclass.c @@ -89,6 +89,7 @@ static void ec_build_derives_hash(PlannerInfo *root, EquivalenceClass *ec); static void ec_add_derived_clauses(EquivalenceClass *ec, List *clauses); static void ec_add_derived_clause(EquivalenceClass *ec, RestrictInfo *clause); static void ec_add_clause_to_derives_hash(EquivalenceClass *ec, RestrictInfo *rinfo); +static void ec_clear_derived_clauses(EquivalenceClass *ec); static RestrictInfo *ec_search_clause_for_ems(PlannerInfo *root, EquivalenceClass *ec, EquivalenceMember *leftem, EquivalenceMember *rightem, @@ -1452,8 +1453,7 @@ generate_base_implied_equalities_no_const(PlannerInfo *root, * For the moment we force all the Vars to be available at all join nodes * for this eclass. Perhaps this could be improved by doing some * pre-analysis of which members we prefer to join, but it's no worse than - * what happened in the pre-8.3 code. (Note: rebuild_eclass_attr_needed - * needs to match this code.) + * what happened in the pre-8.3 code. */ foreach(lc, ec->ec_members) { @@ -2560,51 +2560,6 @@ reconsider_full_join_clause(PlannerInfo *root, OuterJoinClauseInfo *ojcinfo) return false; /* failed to make any deduction */ } -/* - * rebuild_eclass_attr_needed - * Put back attr_needed bits for Vars/PHVs needed for join eclasses. - * - * This is used to rebuild attr_needed/ph_needed sets after removal of a - * useless outer join. It should match what - * generate_base_implied_equalities_no_const did, except that we call - * add_vars_to_attr_needed not add_vars_to_targetlist. - */ -void -rebuild_eclass_attr_needed(PlannerInfo *root) -{ - ListCell *lc; - - foreach(lc, root->eq_classes) - { - EquivalenceClass *ec = (EquivalenceClass *) lfirst(lc); - - /* - * 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); - - /* Need do anything only for a multi-member, no-const EC. */ - if (list_length(ec->ec_members) > 1 && !ec->ec_has_const) - { - ListCell *lc2; - - foreach(lc2, ec->ec_members) - { - EquivalenceMember *cur_em = (EquivalenceMember *) lfirst(lc2); - List *vars = pull_var_clause((Node *) cur_em->em_expr, - PVC_RECURSE_AGGREGATES | - PVC_RECURSE_WINDOWFUNCS | - PVC_INCLUDE_PLACEHOLDERS); - - add_vars_to_attr_needed(root, vars, ec->ec_relids); - list_free(vars); - } - } - } -} - /* * find_join_domain * Find the highest JoinDomain enclosed within the given relid set. @@ -3826,7 +3781,7 @@ ec_add_clause_to_derives_hash(EquivalenceClass *ec, RestrictInfo *rinfo) * when thousands of partitions are involved, so we free it as well -- even * though we do not typically free lists. */ -void +static void ec_clear_derived_clauses(EquivalenceClass *ec) { list_free(ec->ec_derives_list); diff --git a/src/backend/optimizer/plan/analyzejoins.c b/src/backend/optimizer/plan/analyzejoins.c index ef355ec1fe1..a038b898bdb 100644 --- a/src/backend/optimizer/plan/analyzejoins.c +++ b/src/backend/optimizer/plan/analyzejoins.c @@ -30,11 +30,9 @@ #include "catalog/pg_class.h" #include "nodes/makefuncs.h" #include "nodes/nodeFuncs.h" -#include "optimizer/joininfo.h" #include "optimizer/optimizer.h" #include "optimizer/pathnode.h" #include "optimizer/paths.h" -#include "optimizer/placeholder.h" #include "optimizer/planmain.h" #include "optimizer/prep.h" #include "optimizer/restrictinfo.h" @@ -62,20 +60,6 @@ bool enable_self_join_elimination; /* local functions */ static bool join_is_removable(PlannerInfo *root, SpecialJoinInfo *sjinfo); -static void remove_leftjoinrel_from_query(PlannerInfo *root, int relid, - SpecialJoinInfo *sjinfo); -static void remove_rel_from_query(PlannerInfo *root, int relid, - int subst, SpecialJoinInfo *sjinfo, - Relids joinrelids); -static void remove_rel_from_restrictinfo(RestrictInfo *rinfo, - int relid, int ojrelid); -static void remove_rel_from_eclass(PlannerInfo *root, EquivalenceClass *ec, - int relid, int ojrelid); -static void remove_rel_from_restrictinfo_phvs(RestrictInfo *rinfo, - int relid, int ojrelid); -static Node *remove_rel_from_phvs(Node *node, int relid, int ojrelid); -static Node *remove_rel_from_phvs_mutator(Node *node, Relids removable); -static List *remove_rel_from_joinlist(List *joinlist, int relid, int *nremoved); static Node *remove_join_from_jointree(Node *jtnode, int ojrelid, int *nremoved); static void remove_rels_from_query_tree(PlannerInfo *root, @@ -85,6 +69,14 @@ static bool rel_supports_distinctness(PlannerInfo *root, RelOptInfo *rel); static bool rel_is_distinct_for(PlannerInfo *root, RelOptInfo *rel, List *clause_list, List **extra_clauses); static DistinctColInfo *distinct_col_search(int colno, List *distinct_cols); +static bool innerrel_is_unique_ext(PlannerInfo *root, + Relids joinrelids, + Relids outerrelids, + RelOptInfo *innerrel, + JoinType jointype, + List *restrictlist, + bool force_cache, + List **extra_clauses); static bool is_innerrel_unique_for(PlannerInfo *root, Relids joinrelids, Relids outerrelids, @@ -100,8 +92,6 @@ static void fixup_selfjoin_jointree(PlannerInfo *root, Node *jtnode, 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); -static bool replace_relid_callback(Node *node, - ChangeVarNodes_context *context); /* @@ -367,713 +357,6 @@ join_is_removable(PlannerInfo *root, SpecialJoinInfo *sjinfo) return false; } -/* - * 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. - * - * 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. - * - * This function serves as the common infrastructure for left-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). - */ -static void -remove_rel_from_query(PlannerInfo *root, int relid, - int subst, SpecialJoinInfo *sjinfo, - Relids joinrelids) -{ - 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); - Bitmapset *seen_serials = NULL; - - Assert(is_outer_join || is_self_join); - Assert(!is_outer_join || ojrelid > 0); - Assert(!is_outer_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) - { - root->outer_join_rels = bms_del_member(root->outer_join_rels, ojrelid); - root->all_query_rels = bms_del_member(root->all_query_rels, ojrelid); - } - - /* - * 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) - { - SpecialJoinInfo *sjinf = (SpecialJoinInfo *) lfirst(l); - - /* - * 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 - { - /* - * For self-join removal, replace relid references in - * semi_rhs_exprs. - */ - ChangeVarNodesExtended((Node *) sjinf->semi_rhs_exprs, relid, subst, - 0, replace_relid_callback); - } - } - - /* - * Likewise remove references from PlaceHolderVar data structures, - * removing any no-longer-needed placeholders entirely. We only remove - * PHVs for left-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 is no corresponding test in - * join_is_removable because it doesn't need to distinguish those cases. - */ - foreach(l, root->placeholder_list) - { - PlaceHolderInfo *phinfo = (PlaceHolderInfo *) lfirst(l); - - Assert(!is_outer_join || !bms_is_member(relid, phinfo->ph_lateral)); - - if (is_outer_join && - bms_is_subset(phinfo->ph_needed, joinrelids) && - bms_is_member(relid, phinfo->ph_eval_at) && - !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 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.) - */ - 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) - { - foreach(l, root->eq_classes) - { - EquivalenceClass *ec = (EquivalenceClass *) lfirst(l); - - remove_rel_from_eclass(root, ec, relid, ojrelid); - } - } - - /* - * 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 removal, we strip the removed rel and join from any - * PlaceHolderVar embedded in the surviving rels' restriction clauses and - * join clauses; 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 && rti != relid && root->glob->lastPHId != 0) - { - foreach_node(RestrictInfo, rinfo, otherrel->baserestrictinfo) - remove_rel_from_restrictinfo_phvs(rinfo, relid, ojrelid); - - /* - * Join clauses need the same treatment, but there's no value in - * processing any join clause more than once. So it's slightly - * annoying that we have to find them via the per-base-relation - * joininfo lists. Avoid duplicate processing by tracking the - * rinfo_serial numbers of join clauses we've already seen. (This - * doesn't work for is_clone clauses, so we must waste effort on - * them.) - */ - foreach_node(RestrictInfo, rinfo, otherrel->joininfo) - { - if (!rinfo->is_clone) /* else serial number is not unique */ - { - if (bms_is_member(rinfo->rinfo_serial, seen_serials)) - continue; /* saw it already */ - seen_serials = bms_add_member(seen_serials, - rinfo->rinfo_serial); - } - remove_rel_from_restrictinfo_phvs(rinfo, relid, ojrelid); - } - } - } -} - -/* - * Remove any references to relid or ojrelid from the RestrictInfo. - * - * 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); - 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); - 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); - 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); - 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); - 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); - 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. - * - * 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. - */ -static void -remove_rel_from_eclass(PlannerInfo *root, EquivalenceClass *ec, - int relid, int ojrelid) -{ - 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) && - !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); - 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) || - 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); - 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 relid or ojrelid from the PlaceHolderVars embedded - * in a RestrictInfo's clause. - * - * If it's an OR clause, we must also fix up the orclause, which is a parallel - * representation built from its own sub-RestrictInfos. We recurse into the - * sub-clauses for that, mirroring remove_rel_from_restrictinfo. - */ -static void -remove_rel_from_restrictinfo_phvs(RestrictInfo *rinfo, int relid, int ojrelid) -{ - rinfo->clause = (Expr *) - remove_rel_from_phvs((Node *) rinfo->clause, relid, 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_phvs(rinfo2, relid, ojrelid); - } - } - else - { - RestrictInfo *rinfo2 = castNode(RestrictInfo, orarg); - - remove_rel_from_restrictinfo_phvs(rinfo2, relid, ojrelid); - } - } - } -} - -/* - * 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); -} - -static Node * -remove_rel_from_phvs_mutator(Node *node, Relids removable) -{ - if (node == NULL) - return NULL; - if (IsA(node, PlaceHolderVar)) - { - 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); - - /* - * ... 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. - */ - newphrels = bms_difference(phv->phrels, removable); - if (!bms_is_empty(newphrels)) - { - phv->phrels = newphrels; - phv->phnullingrels = bms_difference(phv->phnullingrels, - removable); - } - - return (Node *) phv; - } - 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; -} - - /* * remove_join_from_jointree * Delete the JoinExpr with the given RT index, along with everything @@ -1731,7 +1014,7 @@ innerrel_is_unique(PlannerInfo *root, * A non-NULL extra_clauses indicates that we're checking for self-join and * correspondingly dealing with filtered clauses. */ -bool +static bool innerrel_is_unique_ext(PlannerInfo *root, Relids joinrelids, Relids outerrelids, @@ -1910,298 +1193,6 @@ is_innerrel_unique_for(PlannerInfo *root, return rel_is_distinct_for(root, innerrel, clause_list, extra_clauses); } -/* - * Update EC members to point to the remaining relation instead of the removed - * one, removing duplicates. - * - * Restriction clauses for base relations are already distributed to - * the respective baserestrictinfo lists (see - * generate_implied_equalities_for_column). The above code has already processed - * this list and updated these clauses to reference the remaining - * relation, so that we can skip them here based on their relids. - * - * Likewise, we have already processed the join clauses that join the - * removed relation to the remaining one. - * - * Finally, there might be join clauses tying the removed relation to - * some third relation. We can't just delete the source clauses and - * regenerate them from the EC because the corresponding equality - * operators might be missing (see the handling of ec_broken). - * Therefore, we will update the references in the source clauses. - * - * Derived clauses can be generated again, so it is simpler just to - * delete them. - */ -static void -update_eclasses(EquivalenceClass *ec, int from, int to) -{ - List *new_members = NIL; - List *new_sources = NIL; - - /* - * 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); - - foreach_node(EquivalenceMember, em, ec->ec_members) - { - bool is_redundant = false; - - if (!bms_is_member(from, em->em_relids)) - { - new_members = lappend(new_members, em); - continue; - } - - em->em_relids = adjust_relid_set(em->em_relids, from, to); - em->em_jdomain->jd_relids = adjust_relid_set(em->em_jdomain->jd_relids, from, to); - - /* We only process inner joins */ - ChangeVarNodesExtended((Node *) em->em_expr, from, to, 0, - replace_relid_callback); - - foreach_node(EquivalenceMember, other, new_members) - { - if (!equal(em->em_relids, other->em_relids)) - continue; - - if (equal(em->em_expr, other->em_expr)) - { - is_redundant = true; - break; - } - } - - if (!is_redundant) - new_members = lappend(new_members, em); - } - - list_free(ec->ec_members); - ec->ec_members = new_members; - - ec_clear_derived_clauses(ec); - - /* Update EC source expressions */ - foreach_node(RestrictInfo, rinfo, ec->ec_sources) - { - bool is_redundant = false; - - if (!bms_is_member(from, rinfo->required_relids)) - { - new_sources = lappend(new_sources, rinfo); - continue; - } - - ChangeVarNodesExtended((Node *) rinfo, from, to, 0, - replace_relid_callback); - - /* - * After switching the clause to the remaining relation, check it for - * redundancy with existing ones. We don't have to check for - * redundancy with derived clauses, because we've just deleted them. - */ - foreach_node(RestrictInfo, other, new_sources) - { - if (!equal(rinfo->clause_relids, other->clause_relids)) - continue; - - if (equal(rinfo->clause, other->clause)) - { - is_redundant = true; - break; - } - } - - if (!is_redundant) - new_sources = lappend(new_sources, rinfo); - } - - list_free(ec->ec_sources); - ec->ec_sources = new_sources; - ec->ec_relids = adjust_relid_set(ec->ec_relids, from, to); -} - -/* - * "Logically" compares two RestrictInfo's ignoring the 'rinfo_serial' field, - * which makes almost every RestrictInfo unique. This type of comparison is - * useful when removing duplicates while moving RestrictInfo's from removed - * relation to remaining relation during self-join elimination. - * - * XXX: In the future, we might remove the 'rinfo_serial' field completely and - * get rid of this function. - */ -static bool -restrict_infos_logically_equal(RestrictInfo *a, RestrictInfo *b) -{ - int saved_rinfo_serial = a->rinfo_serial; - bool result; - - a->rinfo_serial = b->rinfo_serial; - result = equal(a, b); - a->rinfo_serial = saved_rinfo_serial; - - return result; -} - -/* - * This function adds all non-redundant clauses to the keeping relation - * during self-join elimination. That is a contradictory operation. On the - * one hand, we reduce the length of the `restrict` lists, which can - * impact planning or executing time. Additionally, we improve the - * accuracy of cardinality estimation. On the other hand, it is one more - * place that can make planning time much longer in specific cases. It - * would have been better to avoid calling the equal() function here, but - * it's the only way to detect duplicated inequality expressions. - * - * (*keep_rinfo_list) is given by pointer because it might be altered by - * distribute_restrictinfo_to_rels(). - */ -static void -add_non_redundant_clauses(PlannerInfo *root, - List *rinfo_candidates, - List **keep_rinfo_list, - Index removed_relid) -{ - foreach_node(RestrictInfo, rinfo, rinfo_candidates) - { - bool is_redundant = false; - - Assert(!bms_is_member(removed_relid, rinfo->required_relids)); - - foreach_node(RestrictInfo, src, (*keep_rinfo_list)) - { - if (!bms_equal(src->clause_relids, rinfo->clause_relids)) - /* Can't compare trivially different clauses */ - continue; - - if (src == rinfo || - (rinfo->parent_ec != NULL && - src->parent_ec == rinfo->parent_ec) || - restrict_infos_logically_equal(rinfo, src)) - { - is_redundant = true; - break; - } - } - if (!is_redundant) - distribute_restrictinfo_to_rels(root, rinfo); - } -} - -/* - * A custom callback for ChangeVarNodesExtended() providing Self-join - * elimination (SJE) related functionality - * - * SJE needs to skip the RangeTblRef node type. During SJE's last - * step, remove_rel_from_joinlist() removes remaining RangeTblRefs - * with target relid. If ChangeVarNodes() replaces the target relid - * before, remove_rel_from_joinlist() would fail to identify the nodes - * to delete. - * - * SJE also needs to change the relids within RestrictInfo's. - */ -static bool -replace_relid_callback(Node *node, ChangeVarNodes_context *context) -{ - if (IsA(node, RangeTblRef)) - { - return true; - } - else if (IsA(node, RestrictInfo)) - { - RestrictInfo *rinfo = (RestrictInfo *) node; - int relid = -1; - bool is_req_equal = - (rinfo->required_relids == rinfo->clause_relids); - bool clause_relids_is_multiple = - (bms_membership(rinfo->clause_relids) == BMS_MULTIPLE); - - /* - * Recurse down into clauses if the target relation is present in - * clause_relids or required_relids. We must check required_relids - * because the relation not present in clause_relids might still be - * present somewhere in orclause. - */ - if (bms_is_member(context->rt_index, rinfo->clause_relids) || - bms_is_member(context->rt_index, rinfo->required_relids)) - { - Relids new_clause_relids; - - ChangeVarNodesWalkExpression((Node *) rinfo->clause, context); - ChangeVarNodesWalkExpression((Node *) rinfo->orclause, context); - - new_clause_relids = adjust_relid_set(rinfo->clause_relids, - context->rt_index, - context->new_index); - - /* - * Incrementally adjust num_base_rels based on the change of - * clause_relids, which could contain both base relids and - * outer-join relids. This operation is legal until we remove - * only baserels. - */ - rinfo->num_base_rels -= bms_num_members(rinfo->clause_relids) - - bms_num_members(new_clause_relids); - - rinfo->clause_relids = new_clause_relids; - rinfo->left_relids = - adjust_relid_set(rinfo->left_relids, context->rt_index, context->new_index); - rinfo->right_relids = - adjust_relid_set(rinfo->right_relids, context->rt_index, context->new_index); - } - - if (is_req_equal) - rinfo->required_relids = rinfo->clause_relids; - else - rinfo->required_relids = - adjust_relid_set(rinfo->required_relids, context->rt_index, context->new_index); - - rinfo->outer_relids = - adjust_relid_set(rinfo->outer_relids, context->rt_index, context->new_index); - rinfo->incompatible_relids = - adjust_relid_set(rinfo->incompatible_relids, context->rt_index, context->new_index); - - if (rinfo->mergeopfamilies && - bms_get_singleton_member(rinfo->clause_relids, &relid) && - clause_relids_is_multiple && - relid == context->new_index && IsA(rinfo->clause, OpExpr)) - { - Expr *leftOp; - Expr *rightOp; - - leftOp = (Expr *) get_leftop(rinfo->clause); - rightOp = (Expr *) get_rightop(rinfo->clause); - - /* - * For self-join elimination, changing varnos could transform - * "t1.a = t2.a" into "t1.a = t1.a". That is always true as long - * as "t1.a" is not null. We use equal() to check for such a - * case, and then we replace the qual with a check for not null - * (NullTest). - */ - if (leftOp != NULL && equal(leftOp, rightOp)) - { - NullTest *ntest = makeNode(NullTest); - - ntest->arg = leftOp; - ntest->nulltesttype = IS_NOT_NULL; - ntest->argisrow = false; - ntest->location = -1; - rinfo->clause = (Expr *) ntest; - rinfo->mergeopfamilies = NIL; - rinfo->left_em = NULL; - rinfo->right_em = NULL; - } - Assert(rinfo->orclause == NULL); - } - return true; - } - - return false; -} - /* * Remove the toRemove relation after we have proven that it participates only * in an unneeded unique self-join with toKeep. @@ -2604,10 +1595,9 @@ split_selfjoin_quals(PlannerInfo *root, List *joinquals, List **selfjoinquals, * when we have cast of the same var to different (but compatible) * types. */ - ChangeVarNodesExtended(rightexpr, - bms_singleton_member(rinfo->right_relids), - bms_singleton_member(rinfo->left_relids), 0, - replace_relid_callback); + ChangeVarNodes(rightexpr, + bms_singleton_member(rinfo->right_relids), + bms_singleton_member(rinfo->left_relids), 0); if (equal(leftexpr, rightexpr)) sjoinquals = lappend(sjoinquals, rinfo); @@ -2643,8 +1633,7 @@ match_unique_clauses(PlannerInfo *root, RelOptInfo *outer, List *uclauses, bms_is_empty(rinfo->right_relids)); clause = (Expr *) copyObject(rinfo->clause); - ChangeVarNodesExtended((Node *) clause, relid, outer->relid, 0, - replace_relid_callback); + ChangeVarNodes((Node *) clause, relid, outer->relid, 0); iclause = bms_is_empty(rinfo->left_relids) ? get_rightop(clause) : get_leftop(clause); diff --git a/src/backend/optimizer/plan/initsplan.c b/src/backend/optimizer/plan/initsplan.c index 7b6d7249c66..d8a5c242eef 100644 --- a/src/backend/optimizer/plan/initsplan.c +++ b/src/backend/optimizer/plan/initsplan.c @@ -295,8 +295,6 @@ build_base_rel_tlists(PlannerInfo *root, List *final_tlist) * have a single owning relation; we keep their attr_needed info in * root->placeholder_list instead. Find or create the associated * PlaceHolderInfo entry, and update its ph_needed. - * - * See also add_vars_to_attr_needed. */ void add_vars_to_targetlist(PlannerInfo *root, List *vars, @@ -350,63 +348,6 @@ add_vars_to_targetlist(PlannerInfo *root, List *vars, } } -/* - * add_vars_to_attr_needed - * This does a subset of what add_vars_to_targetlist does: it just - * updates attr_needed for Vars and ph_needed for PlaceHolderVars. - * We assume the Vars are already in their relations' targetlists. - * - * This is used to rebuild attr_needed/ph_needed sets after removal - * of a useless outer join. The removed join clause might have been - * the only upper-level use of some other relation's Var, in which - * case we can reduce that Var's attr_needed and thereby possibly - * open the door to further join removals. But we can't tell that - * without tedious reconstruction of the attr_needed data. - * - * Note that if a Var's attr_needed is successfully reduced to empty, - * it will still be in the relation's targetlist even though we do - * not really need the scan plan node to emit it. The extra plan - * inefficiency seems tiny enough to not be worth spending planner - * cycles to get rid of it. - */ -void -add_vars_to_attr_needed(PlannerInfo *root, List *vars, - Relids where_needed) -{ - ListCell *temp; - - Assert(!bms_is_empty(where_needed)); - - foreach(temp, vars) - { - Node *node = (Node *) lfirst(temp); - - if (IsA(node, Var)) - { - Var *var = (Var *) node; - RelOptInfo *rel = find_base_rel(root, var->varno); - int attno = var->varattno; - - if (bms_is_subset(where_needed, rel->relids)) - continue; - Assert(attno >= rel->min_attr && attno <= rel->max_attr); - attno -= rel->min_attr; - rel->attr_needed[attno] = bms_add_members(rel->attr_needed[attno], - where_needed); - } - else if (IsA(node, PlaceHolderVar)) - { - PlaceHolderVar *phv = (PlaceHolderVar *) node; - PlaceHolderInfo *phinfo = find_placeholder_info(root, phv); - - phinfo->ph_needed = bms_add_members(phinfo->ph_needed, - where_needed); - } - else - elog(ERROR, "unrecognized node type: %d", (int) nodeTag(node)); - } -} - /***************************************************************************** * * GROUP BY @@ -1226,54 +1167,10 @@ extract_lateral_references(PlannerInfo *root, RelOptInfo *brel, Index rtindex) */ add_vars_to_targetlist(root, newvars, where_needed); - /* - * Remember the lateral references for rebuild_lateral_attr_needed and - * create_lateral_join_info. - */ + /* Remember the lateral references for create_lateral_join_info */ brel->lateral_vars = newvars; } -/* - * rebuild_lateral_attr_needed - * Put back attr_needed bits for Vars/PHVs needed for lateral references. - * - * This is used to rebuild attr_needed/ph_needed sets after removal of a - * useless outer join. It should match what find_lateral_references did, - * except that we call add_vars_to_attr_needed not add_vars_to_targetlist. - */ -void -rebuild_lateral_attr_needed(PlannerInfo *root) -{ - Index rti; - - /* We need do nothing if the query contains no LATERAL RTEs */ - if (!root->hasLateralRTEs) - return; - - /* Examine the same baserels that find_lateral_references did */ - for (rti = 1; rti < root->simple_rel_array_size; rti++) - { - RelOptInfo *brel = root->simple_rel_array[rti]; - Relids where_needed; - - if (brel == NULL) - continue; - if (brel->reloptkind != RELOPT_BASEREL) - continue; - - /* - * We don't need to repeat all of extract_lateral_references, since it - * kindly saved the extracted Vars/PHVs in lateral_vars. - */ - if (brel->lateral_vars == NIL) - continue; - - where_needed = bms_make_singleton(rti); - - add_vars_to_attr_needed(root, brel->lateral_vars, where_needed); - } -} - /* * create_lateral_join_info * Fill in the per-base-relation direct_lateral_relids, lateral_relids @@ -3227,9 +3124,6 @@ distribute_qual_to_rels(PlannerInfo *root, Node *clause, * var propagation is ensured by making ojscope include input rels from * both sides of the join. * - * See also rebuild_joinclause_attr_needed, which has to partially repeat - * this work after removal of an outer join. - * * Note: if the clause gets absorbed into an EquivalenceClass then this * may be unnecessary, but for now we have to do it to cover the case * where the EC becomes ec_broken and we end up reinserting the original @@ -3803,11 +3697,6 @@ process_implied_equality(PlannerInfo *root, * some of the Vars could have missed having that done because they only * appeared in single-relation clauses originally. So do it here for * safety. - * - * See also rebuild_joinclause_attr_needed, which has to partially repeat - * this work after removal of an outer join. (Since we will put this - * clause into the joininfo lists, that function needn't do any extra work - * to find it.) */ if (bms_membership(relids) == BMS_MULTIPLE) { @@ -3949,72 +3838,6 @@ get_join_domain_min_rels(PlannerInfo *root, Relids domain_relids) } -/* - * rebuild_joinclause_attr_needed - * Put back attr_needed bits for Vars/PHVs needed for join clauses. - * - * This is used to rebuild attr_needed/ph_needed sets after removal of a - * useless outer join. It should match what distribute_qual_to_rels did, - * except that we call add_vars_to_attr_needed not add_vars_to_targetlist. - */ -void -rebuild_joinclause_attr_needed(PlannerInfo *root) -{ - /* - * We must examine all join clauses, but there's no value in processing - * any join clause more than once. So it's slightly annoying that we have - * to find them via the per-base-relation joininfo lists. Avoid duplicate - * processing by tracking the rinfo_serial numbers of join clauses we've - * already seen. (This doesn't work for is_clone clauses, so we must - * waste effort on them.) - */ - Bitmapset *seen_serials = NULL; - Index rti; - - /* Scan all baserels for join clauses */ - for (rti = 1; rti < root->simple_rel_array_size; rti++) - { - RelOptInfo *brel = root->simple_rel_array[rti]; - ListCell *lc; - - if (brel == NULL) - continue; - if (brel->reloptkind != RELOPT_BASEREL) - continue; - - foreach(lc, brel->joininfo) - { - RestrictInfo *rinfo = (RestrictInfo *) lfirst(lc); - Relids relids = rinfo->required_relids; - - if (!rinfo->is_clone) /* else serial number is not unique */ - { - if (bms_is_member(rinfo->rinfo_serial, seen_serials)) - continue; /* saw it already */ - seen_serials = bms_add_member(seen_serials, - rinfo->rinfo_serial); - } - - if (bms_membership(relids) == BMS_MULTIPLE) - { - List *vars = pull_var_clause((Node *) rinfo->clause, - PVC_RECURSE_AGGREGATES | - PVC_RECURSE_WINDOWFUNCS | - PVC_INCLUDE_PLACEHOLDERS); - Relids where_needed; - - if (rinfo->is_clone) - where_needed = bms_intersect(relids, root->all_baserels); - else - where_needed = relids; - add_vars_to_attr_needed(root, vars, where_needed); - list_free(vars); - } - } - } -} - - /* * match_foreign_keys_to_quals * Match foreign-key constraints to equivalence classes and join quals diff --git a/src/backend/optimizer/util/joininfo.c b/src/backend/optimizer/util/joininfo.c index ef2f054c39e..f75e35f22ae 100644 --- a/src/backend/optimizer/util/joininfo.c +++ b/src/backend/optimizer/util/joininfo.c @@ -145,39 +145,3 @@ add_join_clause_to_rels(PlannerInfo *root, rel->joininfo = lappend(rel->joininfo, restrictinfo); } } - -/* - * remove_join_clause_from_rels - * Delete 'restrictinfo' from all the joininfo lists it is in - * - * This reverses the effect of add_join_clause_to_rels. It's used when we - * discover that a relation need not be joined at all. - * - * 'restrictinfo' describes the join clause - * 'join_relids' is the set of relations participating in the join clause - * (some of these could be outer joins) - */ -void -remove_join_clause_from_rels(PlannerInfo *root, - RestrictInfo *restrictinfo, - Relids join_relids) -{ - int cur_relid; - - cur_relid = -1; - while ((cur_relid = bms_next_member(join_relids, cur_relid)) >= 0) - { - RelOptInfo *rel = find_base_rel_ignore_join(root, cur_relid); - - /* We would only have added the clause to baserels */ - if (rel == NULL) - continue; - - /* - * Remove the restrictinfo from the list. Pointer comparison is - * sufficient. - */ - Assert(list_member_ptr(rel->joininfo, restrictinfo)); - rel->joininfo = list_delete_ptr(rel->joininfo, restrictinfo); - } -} diff --git a/src/backend/optimizer/util/placeholder.c b/src/backend/optimizer/util/placeholder.c index dd9b11885af..07171f84f61 100644 --- a/src/backend/optimizer/util/placeholder.c +++ b/src/backend/optimizer/util/placeholder.c @@ -316,33 +316,6 @@ fix_placeholder_input_needed_levels(PlannerInfo *root) } } -/* - * rebuild_placeholder_attr_needed - * Put back attr_needed bits for Vars/PHVs needed in PlaceHolderVars. - * - * This is used to rebuild attr_needed/ph_needed sets after removal of a - * useless outer join. It should match what - * fix_placeholder_input_needed_levels did, except that we call - * add_vars_to_attr_needed not add_vars_to_targetlist. - */ -void -rebuild_placeholder_attr_needed(PlannerInfo *root) -{ - ListCell *lc; - - foreach(lc, root->placeholder_list) - { - PlaceHolderInfo *phinfo = (PlaceHolderInfo *) lfirst(lc); - List *vars = pull_var_clause((Node *) phinfo->ph_var->phexpr, - PVC_RECURSE_AGGREGATES | - PVC_RECURSE_WINDOWFUNCS | - PVC_INCLUDE_PLACEHOLDERS); - - add_vars_to_attr_needed(root, vars, phinfo->ph_eval_at); - list_free(vars); - } -} - /* * add_placeholders_to_base_rels * Add any required PlaceHolderVars to base rels' targetlists. diff --git a/src/backend/rewrite/rewriteManip.c b/src/backend/rewrite/rewriteManip.c index 9c9d1cad33b..330ec596162 100644 --- a/src/backend/rewrite/rewriteManip.c +++ b/src/backend/rewrite/rewriteManip.c @@ -64,6 +64,7 @@ static bool contain_windowfuncs_walker(Node *node, void *context); static bool locate_windowfunc_walker(Node *node, locate_windowfunc_context *context); static bool checkExprHasSubLink_walker(Node *node, void *context); +static Relids adjust_relid_set(Relids relids, int oldrelid, int newrelid); static Node *add_nulling_relids_mutator(Node *node, add_nulling_relids_context *context); static Node *remove_nulling_relids_mutator(Node *node, @@ -528,23 +529,27 @@ OffsetVarNodes(Node *node, int offset, int sublevels_up) * * Find all Var nodes in the given tree belonging to a specific relation * (identified by sublevels_up and rt_index), and change their varno fields - * to 'new_index'. The varnosyn fields are changed too. Also, adjust other - * nodes that contain rangetable indexes, such as RangeTblRef and JoinExpr. + * to 'new_index' (see adjust_relid_set for the exact change behavior). + * The varnosyn fields are changed too. Also adjust other nodes that + * contain rangetable indexes, such as RangeTblRef and JoinExpr. * * NOTE: although this has the form of a walker, we cheat and modify the * nodes in-place. The given expression tree should have been copied * earlier to ensure that no unwanted side-effects occur! */ +typedef struct +{ + int rt_index; + int new_index; + int sublevels_up; +} ChangeVarNodes_context; + static bool ChangeVarNodes_walker(Node *node, ChangeVarNodes_context *context) { if (node == NULL) return false; - - if (context->callback && context->callback(node, context)) - return false; - if (IsA(node, Var)) { Var *var = (Var *) node; @@ -649,28 +654,14 @@ ChangeVarNodes_walker(Node *node, ChangeVarNodes_context *context) return expression_tree_walker(node, ChangeVarNodes_walker, context); } -/* - * ChangeVarNodesExtended - similar to ChangeVarNodes, but with an additional - * 'callback' param - * - * ChangeVarNodes changes a given node and all of its underlying nodes. This - * version of function additionally takes a callback, which has a chance to - * process a node before ChangeVarNodes_walker. A callback returns a boolean - * value indicating if the given node should be skipped from further processing - * by ChangeVarNodes_walker. The callback is called only for expressions and - * other children nodes of a Query processed by a walker. Initial processing - * of the root Query node doesn't invoke the callback. - */ void -ChangeVarNodesExtended(Node *node, int rt_index, int new_index, - int sublevels_up, ChangeVarNodes_callback callback) +ChangeVarNodes(Node *node, int rt_index, int new_index, int sublevels_up) { ChangeVarNodes_context context; context.rt_index = rt_index; context.new_index = new_index; context.sublevels_up = sublevels_up; - context.callback = callback; /* * Must be prepared to start with a Query or a bare expression tree; if @@ -717,36 +708,6 @@ ChangeVarNodesExtended(Node *node, int rt_index, int new_index, ChangeVarNodes_walker(node, &context); } -void -ChangeVarNodes(Node *node, int rt_index, int new_index, int sublevels_up) -{ - ChangeVarNodesExtended(node, rt_index, new_index, sublevels_up, NULL); -} - -/* - * ChangeVarNodesWalkExpression - process subexpression within a callback - * function passed to ChangeVarNodesExtended. - * - * This is intended to be used by a callback that needs to recursively - * process subexpressions of some node being visited by an outer - * ChangeVarNodesExtended call, instead of relying on ChangeVarNodes_walker's - * default recursion. We invoke ChangeVarNodes_walker directly rather than - * via expression_tree_walker, because expression_tree_walker only visits - * child nodes and would fail to process the passed node itself -- - * for example, a bare Var node would not get its varno adjusted. - * - * Because this calls ChangeVarNodes_walker directly, if the passed node is - * a Query, it will be treated as a sub-Query: sublevels_up is incremented - * before recursing into it, and Query-level fields (resultRelation, - * mergeTargetRelation, rowMarks, etc.) will not be adjusted. Do not apply - * this to a top-level Query node; use ChangeVarNodesExtended for that. - */ -bool -ChangeVarNodesWalkExpression(Node *node, ChangeVarNodes_context *context) -{ - return ChangeVarNodes_walker(node, context); -} - /* * adjust_relid_set - substitute newrelid for oldrelid in a Relid set * @@ -756,7 +717,7 @@ ChangeVarNodesWalkExpression(Node *node, ChangeVarNodes_context *context) * a special varno, this function does nothing. When newrelid is a special * varno, this function behaves as delete. */ -Relids +static Relids adjust_relid_set(Relids relids, int oldrelid, int newrelid) { if (!IS_SPECIAL_VARNO(oldrelid) && bms_is_member(oldrelid, relids)) diff --git a/src/include/optimizer/joininfo.h b/src/include/optimizer/joininfo.h index 117195fbcfa..aa26cc670f9 100644 --- a/src/include/optimizer/joininfo.h +++ b/src/include/optimizer/joininfo.h @@ -23,8 +23,5 @@ extern bool have_relevant_joinclause(PlannerInfo *root, extern void add_join_clause_to_rels(PlannerInfo *root, RestrictInfo *restrictinfo, Relids join_relids); -extern void remove_join_clause_from_rels(PlannerInfo *root, - RestrictInfo *restrictinfo, - Relids join_relids); #endif /* JOININFO_H */ diff --git a/src/include/optimizer/paths.h b/src/include/optimizer/paths.h index 17f2099ec3b..051e38c1189 100644 --- a/src/include/optimizer/paths.h +++ b/src/include/optimizer/paths.h @@ -137,7 +137,6 @@ extern bool process_equivalence(PlannerInfo *root, extern Expr *canonicalize_ec_expression(Expr *expr, Oid req_type, Oid req_collation); extern void reconsider_outer_join_clauses(PlannerInfo *root); -extern void rebuild_eclass_attr_needed(PlannerInfo *root); extern EquivalenceClass *get_eclass_for_sort_expr(PlannerInfo *root, Expr *expr, List *opfamilies, @@ -208,7 +207,6 @@ extern bool eclass_useful_for_merging(PlannerInfo *root, extern bool is_redundant_derived_clause(RestrictInfo *rinfo, List *clauselist); extern bool is_redundant_with_indexclauses(RestrictInfo *rinfo, List *indexclauses); -extern void ec_clear_derived_clauses(EquivalenceClass *ec); /* * pathkeys.c diff --git a/src/include/optimizer/placeholder.h b/src/include/optimizer/placeholder.h index 60798281090..2099075e670 100644 --- a/src/include/optimizer/placeholder.h +++ b/src/include/optimizer/placeholder.h @@ -23,7 +23,6 @@ extern PlaceHolderInfo *find_placeholder_info(PlannerInfo *root, PlaceHolderVar *phv); extern void find_placeholders_in_jointree(PlannerInfo *root); extern void fix_placeholder_input_needed_levels(PlannerInfo *root); -extern void rebuild_placeholder_attr_needed(PlannerInfo *root); extern void add_placeholders_to_base_rels(PlannerInfo *root); extern void add_placeholders_to_joinrel(PlannerInfo *root, RelOptInfo *joinrel, RelOptInfo *outer_rel, RelOptInfo *inner_rel, diff --git a/src/include/optimizer/planmain.h b/src/include/optimizer/planmain.h index 85301d912f0..f7e22f5989d 100644 --- a/src/include/optimizer/planmain.h +++ b/src/include/optimizer/planmain.h @@ -73,12 +73,9 @@ extern void add_other_rels_to_query(PlannerInfo *root); extern void build_base_rel_tlists(PlannerInfo *root, List *final_tlist); extern void add_vars_to_targetlist(PlannerInfo *root, List *vars, Relids where_needed); -extern void add_vars_to_attr_needed(PlannerInfo *root, List *vars, - Relids where_needed); extern void remove_useless_groupby_columns(PlannerInfo *root); extern void setup_eager_aggregation(PlannerInfo *root); extern void find_lateral_references(PlannerInfo *root); -extern void rebuild_lateral_attr_needed(PlannerInfo *root); extern void create_lateral_join_info(PlannerInfo *root); extern List *deconstruct_jointree(PlannerInfo *root); extern bool restriction_is_always_true(PlannerInfo *root, @@ -102,7 +99,6 @@ extern RestrictInfo *build_implied_join_equality(PlannerInfo *root, Expr *item2, Relids qualscope, Index security_level); -extern void rebuild_joinclause_attr_needed(PlannerInfo *root); extern void match_foreign_keys_to_quals(PlannerInfo *root); /* @@ -115,10 +111,6 @@ extern bool query_is_distinct_for(Query *query, List *distinct_cols); extern bool innerrel_is_unique(PlannerInfo *root, Relids joinrelids, Relids outerrelids, RelOptInfo *innerrel, JoinType jointype, List *restrictlist, bool force_cache); -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 bool remove_useless_self_joins(PlannerInfo *root, List *joinlist); /* diff --git a/src/include/rewrite/rewriteManip.h b/src/include/rewrite/rewriteManip.h index 9d234cb8741..2d15d8f8f95 100644 --- a/src/include/rewrite/rewriteManip.h +++ b/src/include/rewrite/rewriteManip.h @@ -41,30 +41,11 @@ typedef enum ReplaceVarsNoMatchOption REPLACEVARS_SUBSTITUTE_NULL, /* replace with a NULL Const */ } ReplaceVarsNoMatchOption; -typedef struct ChangeVarNodes_context ChangeVarNodes_context; - -typedef bool (*ChangeVarNodes_callback) (Node *node, - ChangeVarNodes_context *arg); - -struct ChangeVarNodes_context -{ - int rt_index; - int new_index; - int sublevels_up; - ChangeVarNodes_callback callback; -}; - -pg_nodiscard extern Relids adjust_relid_set(Relids relids, int oldrelid, int newrelid); extern void CombineRangeTables(List **dst_rtable, List **dst_perminfos, List *src_rtable, List *src_perminfos); extern void OffsetVarNodes(Node *node, int offset, int sublevels_up); extern void ChangeVarNodes(Node *node, int rt_index, int new_index, int sublevels_up); -extern void ChangeVarNodesExtended(Node *node, int rt_index, int new_index, - int sublevels_up, - ChangeVarNodes_callback callback); -extern bool ChangeVarNodesWalkExpression(Node *node, - ChangeVarNodes_context *context); extern void IncrementVarSublevelsUp(Node *node, int delta_sublevels_up, int min_sublevels_up); extern void IncrementVarSublevelsUp_rtable(List *rtable, diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list index 56c1f997f88..41ceb9b160d 100644 --- a/src/tools/pgindent/typedefs.list +++ b/src/tools/pgindent/typedefs.list @@ -431,7 +431,6 @@ CatalogId CatalogIdMapEntry CatalogIndexState ChangeContext -ChangeVarNodes_callback ChangeVarNodes_context ChannelName CheckPoint -- 2.52.0
v3-0004-Ensure-we-hoist-modified-quals-to-the-right-join-.patch (text/x-diff, 9.4K) download From 9b0d2965770f6375c1d503b1bda044a3b68835f0 Mon Sep 17 00:00:00 2001 From: Tom Lane <tgl@sss.pgh.pa.us> Date: Sat, 25 Jul 2026 22:10:11 -0400 Subject: [PATCH v3 4/4] Ensure we hoist modified quals to the right join level after SJE. The v2 patchset in this series failed to consider whether a modified qual was actually appropriate for its original position in the join tree. It might not be, in which case we'd better move it up. Reported-by: Thom Brown <thom@linux.com> Author: Tom Lane <tgl@sss.pgh.pa.us> Discussion: https://postgr.es/m/1186816.1784573544@sss.pgh.pa.us --- src/backend/optimizer/plan/analyzejoins.c | 100 +++++++++++++++++++--- src/test/regress/expected/join.out | 37 ++++++++ src/test/regress/sql/join.sql | 12 +++ 3 files changed, 139 insertions(+), 10 deletions(-) diff --git a/src/backend/optimizer/plan/analyzejoins.c b/src/backend/optimizer/plan/analyzejoins.c index a038b898bdb..e2dcc6a7cf5 100644 --- a/src/backend/optimizer/plan/analyzejoins.c +++ b/src/backend/optimizer/plan/analyzejoins.c @@ -87,8 +87,8 @@ static bool is_innerrel_unique_for(PlannerInfo *root, 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); +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); @@ -1201,7 +1201,9 @@ is_innerrel_unique_for(PlannerInfo *root, * jointree and then pointing everything that referenced it at the relation we * are keeping. All the conditions that were attached to the removed relation * thereby become conditions on the remaining one, which is what we want: - * we've proven that the two relations select the same rows. + * we've proven that the two relations select the same rows. Note that + * this change requires us to hoist those conditions up to someplace + * syntactically enclosing toKeep. * * kmark and rmark are the PlanRowMarks (if any) for the kept and removed * relations. We could re-locate those, but the caller already found them. @@ -1213,6 +1215,8 @@ remove_self_join_rel(PlannerInfo *root, { Node *orphan_quals = NULL; int nremoved = 0; + Node *hoist_quals = NULL; + bool found_relid = false; Assert(toKeep->relid > 0); Assert(toRemove->relid > 0); @@ -1251,7 +1255,11 @@ remove_self_join_rel(PlannerInfo *root, /* Clean up the quals that the substitution has messed with */ fixup_selfjoin_jointree(root, (Node *) root->parse->jointree, - toKeep->relid); + toKeep->relid, + &hoist_quals, &found_relid); + /* We shouldn't have any leftover quals, and we must have found toKeep */ + Assert(hoist_quals == NULL); + Assert(found_relid); /* * If the removed relation has a row mark, transfer it to the remaining @@ -1400,24 +1408,68 @@ merge_quals(Node *quals1, Node *quals2) * Clean up the query's jointree quals after self-join elimination has * merged one relation into another. (relid is the kept relation.) * - * See fixup_selfjoin_quals() for what needs fixing. + * See fixup_selfjoin_quals() for what needs fixing locally to each qual list. + * In addition, we need to check quals to see if they refer to relid, and if + * so make sure they get hoisted to someplace syntactically above relid. + * Do that using a "hoist_quals" in/out parameter similar to "orphan_quals" + * in remove_rel_from_jointree. (We can't readily merge these concerns into + * a single pass, since remove_rel_from_jointree must run before we relabel + * the removed rel's Vars.) In addition, *found_relid is set true if + * the subtree rooted at jtnode is found to contain relid, so that we can + * tell when to stop hoisting quals. + * If a qual gets hoisted up, we apply fixup_selfjoin_quals() to it only + * after it reaches its final level. */ static void -fixup_selfjoin_jointree(PlannerInfo *root, Node *jtnode, int relid) +fixup_selfjoin_jointree(PlannerInfo *root, Node *jtnode, int relid, + Node **hoist_quals, bool *found_relid) { if (jtnode == NULL) return; if (IsA(jtnode, RangeTblRef)) { - /* nothing to do here */ + RangeTblRef *rtr = (RangeTblRef *) jtnode; + + if (rtr->rtindex == relid) + { + Assert(!*found_relid); + *found_relid = true; + } } else if (IsA(jtnode, FromExpr)) { FromExpr *f = (FromExpr *) jtnode; + Node *sub_hoist_quals = NULL; + bool sub_found_relid = false; ListCell *l; foreach(l, f->fromlist) - fixup_selfjoin_jointree(root, (Node *) lfirst(l), relid); + fixup_selfjoin_jointree(root, (Node *) lfirst(l), relid, + &sub_hoist_quals, &sub_found_relid); + if (sub_found_relid) + { + /* This FromExpr covers relid, so OK to stop hoisting quals here */ + f->quals = merge_quals(sub_hoist_quals, f->quals); + Assert(!*found_relid); + *found_relid = true; + } + else + { + /* We might need to hoist some of our own quals too */ + List *hoistable = NIL; + List *keepable = NIL; + + foreach_ptr(Node, qual, castNode(List, f->quals)) + { + if (bms_is_member(relid, pull_varnos(root, qual))) + hoistable = lappend(hoistable, qual); + else + keepable = lappend(keepable, qual); + } + f->quals = (Node *) keepable; + sub_hoist_quals = merge_quals(sub_hoist_quals, (Node *) hoistable); + *hoist_quals = merge_quals(sub_hoist_quals, *hoist_quals); + } f->quals = (Node *) fixup_selfjoin_quals(root, castNode(List, f->quals), relid); @@ -1425,9 +1477,37 @@ fixup_selfjoin_jointree(PlannerInfo *root, Node *jtnode, int relid) else if (IsA(jtnode, JoinExpr)) { JoinExpr *j = (JoinExpr *) jtnode; + Node *sub_hoist_quals = NULL; + bool sub_found_relid = false; + + fixup_selfjoin_jointree(root, j->larg, relid, + &sub_hoist_quals, &sub_found_relid); + fixup_selfjoin_jointree(root, j->rarg, relid, + &sub_hoist_quals, &sub_found_relid); + if (sub_found_relid) + { + /* This JoinExpr covers relid, so OK to stop hoisting quals here */ + j->quals = merge_quals(sub_hoist_quals, j->quals); + Assert(!*found_relid); + *found_relid = true; + } + else + { + /* We might need to hoist some of our own quals too */ + List *hoistable = NIL; + List *keepable = NIL; - fixup_selfjoin_jointree(root, j->larg, relid); - fixup_selfjoin_jointree(root, j->rarg, relid); + foreach_ptr(Node, qual, castNode(List, j->quals)) + { + if (bms_is_member(relid, pull_varnos(root, qual))) + hoistable = lappend(hoistable, qual); + else + keepable = lappend(keepable, qual); + } + j->quals = (Node *) keepable; + sub_hoist_quals = merge_quals(sub_hoist_quals, (Node *) hoistable); + *hoist_quals = merge_quals(sub_hoist_quals, *hoist_quals); + } j->quals = (Node *) fixup_selfjoin_quals(root, castNode(List, j->quals), relid); diff --git a/src/test/regress/expected/join.out b/src/test/regress/expected/join.out index 254b203aeba..e383dfc072b 100644 --- a/src/test/regress/expected/join.out +++ b/src/test/regress/expected/join.out @@ -7478,6 +7478,43 @@ select t1.a from sj t1 where t1.b in ( Filter: (t3.c IS NOT NULL) (10 rows) +-- Check that quals get hoisted to the appropriate join level after SJE removal +explain (verbose, costs off) +select a2.a +from sj b1 + join sj a1 on b1.b = a1.a + join sj a2 on a2.a = a1.a and a2.b = a1.b; + QUERY PLAN +------------------------------------------------------------- + Nested Loop + Output: a2.a + Join Filter: (b1.b = a2.a) + -> Seq Scan on public.sj a2 + Output: a2.a, a2.b, a2.c + Filter: ((a2.a IS NOT NULL) AND (a2.b IS NOT NULL)) + -> Seq Scan on public.sj b1 + Output: b1.a, b1.b, b1.c +(8 rows) + +-- Same, when a semijoin removal happens first +explain (verbose, costs off) +select a1.a from sj b1 join sj a1 on a1.a = b1.b + where exists (select 1 from sj s where s.a = a1.a); + QUERY PLAN +----------------------------------------- + Nested Loop + Output: s.a + Inner Unique: true + Join Filter: (b1.b = s.a) + -> Seq Scan on public.sj b1 + Output: b1.a, b1.b, b1.c + -> Materialize + Output: s.a + -> Seq Scan on public.sj s + Output: s.a + Filter: (s.a IS NOT NULL) +(11 rows) + -- -- SJE corner case: uniqueness of an inner is [partially] derived from -- baserestrictinfo clauses. diff --git a/src/test/regress/sql/join.sql b/src/test/regress/sql/join.sql index afa96daecb5..6b93e95eb13 100644 --- a/src/test/regress/sql/join.sql +++ b/src/test/regress/sql/join.sql @@ -2892,6 +2892,18 @@ explain (verbose, costs off) select t1.a from sj t1 where t1.b in ( select t2.b from sj t2 join sj t3 on t2.c=t3.c); +-- Check that quals get hoisted to the appropriate join level after SJE removal +explain (verbose, costs off) +select a2.a +from sj b1 + join sj a1 on b1.b = a1.a + join sj a2 on a2.a = a1.a and a2.b = a1.b; + +-- Same, when a semijoin removal happens first +explain (verbose, costs off) +select a1.a from sj b1 join sj a1 on a1.a = b1.b + where exists (select 1 from sj s where s.a = a1.a); + -- -- SJE corner case: uniqueness of an inner is [partially] derived from -- baserestrictinfo clauses. -- 2.52.0
^ permalink raw reply [nested|flat] 74+ messages in thread

* Re: remove_useless_joins vs. bug #19560
  2026-07-20 18:52 remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-24 13:38 ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-07-25 16:46   ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-25 20:07     ` Re: remove_useless_joins vs. bug #19560 Thom Brown <thom@linux.com>
  2026-07-25 21:23       ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-26 02:15         ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
@ 2026-07-26 04:23           ` Jacob Brazeal <jacob.brazeal@gmail.com>
  2026-07-26 04:27             ` Re: remove_useless_joins vs. bug #19560 Jacob Brazeal <jacob.brazeal@gmail.com>
  1 sibling, 1 reply; 74+ messages in thread

From: Jacob Brazeal @ 2026-07-26 04:23 UTC (permalink / raw)
  To: Tom Lane <tgl@sss.pgh.pa.us>; +Cc: Thom Brown <thom@linux.com>; Richard Guo <guofenglinux@gmail.com>; pgsql-hackers@lists.postgresql.org

These patches fix all my known failure cases (attached.) In addition, as a
plus, a small set of queries that previously didn't compile are now
accepted, for example:

SELECT coalesce(u1.id + 1, 1) AS o0
FROM (u AS u1 FULL JOIN (u AS u2 JOIN u AS u3 ON u2.id = u3.id)
              ON u2.id = u2.id)
GROUP BY 1;

... previously gave ERROR:  FULL JOIN is only supported with merge-joinable
or hash-joinable join conditions

now returns 10 rows (`2 … 11`), which I believe is correct.

```
 HashAggregate
   Group Key: COALESCE((u1.id + 1), 1)
   ->  Merge Full Join
         ->  Seq Scan on u u1
         ->  Materialize
               ->  Seq Scan on u u3
```

So that's nice.

On Sat, Jul 25, 2026 at 7:15 PM Tom Lane <tgl@sss.pgh.pa.us> wrote:

> Here's a patchset addressing that.  0001-0003 are the same as before,
> and then 0004 fixes this bug and adds tests.
>
> Your Claude session mentioned a different failure scenario, but
> gave no examples so I'm not quite sure if this covers it or not.
>
>                         regards, tom lane
>
>

Attachments:

  finding-81-queries.sql (application/sql, 9.8K) download

^ permalink  raw  reply  [nested|flat] 74+ messages in thread

* Re: remove_useless_joins vs. bug #19560
  2026-07-20 18:52 remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-24 13:38 ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-07-25 16:46   ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-25 20:07     ` Re: remove_useless_joins vs. bug #19560 Thom Brown <thom@linux.com>
  2026-07-25 21:23       ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-26 02:15         ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-26 04:23           ` Re: remove_useless_joins vs. bug #19560 Jacob Brazeal <jacob.brazeal@gmail.com>
@ 2026-07-26 04:27             ` Jacob Brazeal <jacob.brazeal@gmail.com>
  0 siblings, 0 replies; 74+ messages in thread

From: Jacob Brazeal @ 2026-07-26 04:27 UTC (permalink / raw)
  To: Tom Lane <tgl@sss.pgh.pa.us>; +Cc: Thom Brown <thom@linux.com>; Richard Guo <guofenglinux@gmail.com>; pgsql-hackers@lists.postgresql.org

...For completeness the definition of u here is like so:

CREATE TABLE u (id int PRIMARY KEY, a int);
INSERT INTO u (id, a) VALUES
  (1, 1),
  (2, 2),
  (3, 3),
  (4, 0),
  (5, 1),
  (6, 2),
  (7, 3),
  (8, 0),
  (9, 1),
  (10, 2);

^ permalink  raw  reply  [nested|flat] 74+ messages in thread

* Re: remove_useless_joins vs. bug #19560
  2026-07-20 18:52 remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-24 13:38 ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-07-25 16:46   ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-25 20:07     ` Re: remove_useless_joins vs. bug #19560 Thom Brown <thom@linux.com>
  2026-07-25 21:23       ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-26 02:15         ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
@ 2026-07-26 09:49           ` Thom Brown <thom@linux.com>
  2026-07-26 17:33             ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  1 sibling, 1 reply; 74+ messages in thread

From: Thom Brown @ 2026-07-26 09:49 UTC (permalink / raw)
  To: Tom Lane <tgl@sss.pgh.pa.us>; +Cc: Richard Guo <guofenglinux@gmail.com>; pgsql-hackers@lists.postgresql.org

On Sun, 26 Jul 2026 at 03:15, Tom Lane <tgl@sss.pgh.pa.us> wrote:
>
> Here's a patchset addressing that.  0001-0003 are the same as before,
> and then 0004 fixes this bug and adds tests.
>
> Your Claude session mentioned a different failure scenario, but
> gave no examples so I'm not quite sure if this covers it or not.

Thanks. I've re-tested against these and I'm no longer able to crash it.

The different failure scenario was brought up when Claude also tested
the latest patches:

<claude>

My evidence for a second case was that I'd prototyped a fix covering
only the collapsed-node path and it killed 33 of 46 fuzz crashes,
leaving 13. I described the surviving class but never reduced one,
which wasn't much use to anyone. It is:

a JoinExpr that does not collapse, but whose ON qual referenced the
removed relation, while the kept relation lives outside that JoinExpr.

create table a (a int primary key, b int);
create table b (a int, b int);
create table c (a int, b int);

select a2.a
from ((b b1 join a a1 on true) join c c1 on c1.a = a1.a)
  join a a2 on a2.a = a1.a and a2.b = a1.b;

On v2 this trips the same Assert("root->hasLateralRTEs"). Here a1 is
removed and a2 kept. The inner b1 join a1 on true collapses to b1 —
that's the case your v2 code already reasoned about. But the middle
JoinExpr keeps both children (b1 and c1), so nothing collapses there;
its ON qual is simply rewritten from c1.a = a1.a to c1.a = a2.a, and
a2 isn't in that JoinExpr's scope. A fix that only inspects nodes
which lost a child can't see it.

v3 handles it, because you keyed the hoist off "mentions relid" rather
than off collapse:

 Nested Loop
   ->  Seq Scan on b b1
   ->  Materialize
         ->  Hash Join
               Inner Unique: true
               Hash Cond: (c1.a = a2.a)
               ->  Seq Scan on c c1
               ->  Hash
                     ->  Seq Scan on a a2
                           Filter: (a2.b IS NOT NULL)

Your two new regression tests both exercise the collapse path (the
second via semijoin reduction). Something like the above would be
worth adding as a third, since it's the case a narrower fix would have
missed — it needs a second non-self-joined table, so it doesn't drop
straight into the sj-only section.

</claude>

And it still reports the same previous planner regression, although
thinks it may be considered acceptable. It also mentioned adding
jointype assertions because the hoisting code doesn't have any.

But all good as far as I can see.

Thom






^ permalink  raw  reply  [nested|flat] 74+ messages in thread

* Re: remove_useless_joins vs. bug #19560
  2026-07-20 18:52 remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-24 13:38 ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-07-25 16:46   ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-25 20:07     ` Re: remove_useless_joins vs. bug #19560 Thom Brown <thom@linux.com>
  2026-07-25 21:23       ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-26 02:15         ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-26 09:49           ` Re: remove_useless_joins vs. bug #19560 Thom Brown <thom@linux.com>
@ 2026-07-26 17:33             ` Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-26 17:35               ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  0 siblings, 1 reply; 74+ messages in thread

From: Tom Lane @ 2026-07-26 17:33 UTC (permalink / raw)
  To: Thom Brown <thom@linux.com>; +Cc: Richard Guo <guofenglinux@gmail.com>; pgsql-hackers@lists.postgresql.org

Thom Brown <thom@linux.com> writes:
> Thanks. I've re-tested against these and I'm no longer able to crash it.

Thanks for testing!

> And it still reports the same previous planner regression, although
> thinks it may be considered acceptable. It also mentioned adding
> jointype assertions because the hoisting code doesn't have any.

Yeah, it occurred to me right after sending out the v3 patchset that
fixup_selfjoin_jointree should have an Assert that it doesn't hoist
anything above an outer join.  Revised 0004 attached has that, and
adds a test case based on this example.  0001-0003 still the same.

As for the performance issue, I attach an 0005 that changes the
self-join logic to perform as many removals as it can.  I don't
have a huge amount of faith in that, but I can't immediately see
any reason why it's not okay.  It seems almost certainly okay to
perform SJE within groups of rels with different common OIDs, and
even within a single group, an earlier removal doesn't look like
it'd trash anything we are looking at.  But it'd be worth running
a fuzzer to see if any cases turn up where the patchset fails or
gives different answers with/without 0005.

			regards, tom lane

#text/x-diff; name="v4-0001-Postpone-initialization-of-all_result_relids-leaf.patch" [v4-0001-Postpone-initialization-of-all_result_relids-leaf.patch] /home/tgl/pgsql/v4-0001-Postpone-initialization-of-all_result_relids-leaf.patch
#text/x-diff; name="v4-0002-Perform-join-removal-by-editing-the-query-s-joint.patch" [v4-0002-Perform-join-removal-by-editing-the-query-s-joint.patch] /home/tgl/pgsql/v4-0002-Perform-join-removal-by-editing-the-query-s-joint.patch
#text/x-diff; name="v4-0003-Remove-dead-code-that-s-no-longer-needed-for-join.patch" [v4-0003-Remove-dead-code-that-s-no-longer-needed-for-join.patch] /home/tgl/pgsql/v4-0003-Remove-dead-code-that-s-no-longer-needed-for-join.patch
#text/x-diff; name="v4-0004-Ensure-we-hoist-modified-quals-to-the-right-join-.patch" [v4-0004-Ensure-we-hoist-modified-quals-to-the-right-join-.patch] /home/tgl/pgsql/v4-0004-Ensure-we-hoist-modified-quals-to-the-right-join-.patch
#text/x-diff; name="v4-0005-Allow-remove_useless_self_joins-to-remove-multipl.patch" [v4-0005-Allow-remove_useless_self_joins-to-remove-multipl.patch] /home/tgl/pgsql/v4-0005-Allow-remove_useless_self_joins-to-remove-multipl.patch





^ permalink  raw  reply  [nested|flat] 74+ messages in thread

* Re: remove_useless_joins vs. bug #19560
  2026-07-20 18:52 remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-24 13:38 ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-07-25 16:46   ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-25 20:07     ` Re: remove_useless_joins vs. bug #19560 Thom Brown <thom@linux.com>
  2026-07-25 21:23       ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-26 02:15         ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-26 09:49           ` Re: remove_useless_joins vs. bug #19560 Thom Brown <thom@linux.com>
  2026-07-26 17:33             ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
@ 2026-07-26 17:35               ` Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-27 07:07                 ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  0 siblings, 1 reply; 74+ messages in thread

From: Tom Lane @ 2026-07-26 17:35 UTC (permalink / raw)
  To: Thom Brown <thom@linux.com>; +Cc: Richard Guo <guofenglinux@gmail.com>; pgsql-hackers@lists.postgresql.org

Drat, failed to hit control-C control-E.  Now with patches attached,
for sure.

			regards, tom lane

Attachments: download all (5 files, .tar.gz)

v4-0001-Postpone-initialization-of-all_result_relids-leaf.patch (text/x-diff, 4.7K) download From 8a4367368998eb8044cb2ca33ba1d03ab1bb9424 Mon Sep 17 00:00:00 2001 From: Tom Lane <tgl@sss.pgh.pa.us> Date: Sun, 26 Jul 2026 11:43:46 -0400 Subject: [PATCH v4 1/5] Postpone initialization of all_result_relids/leaf_result_relids. Nothing actually pays attention to these PlannerInfo fields before add_other_rels_to_query(), since they're not really useful until that function has finished filling them in. By delaying their setup until just before we call that function, we can remove them from the set of things that join removal has to worry about. (It was already not doing anything with them, but now we do not need an argument why that's okay.) This is just some minor refactoring before the main patch to deal with bug #19560. Bug: #19560 Reported-by: Orestis Markou <orestis@orestis.gr> Author: Tom Lane <tgl@sss.pgh.pa.us> Discussion: https://postgr.es/m/1186816.1784573544@sss.pgh.pa.us --- src/backend/optimizer/plan/analyzejoins.c | 11 ----------- src/backend/optimizer/plan/planmain.c | 17 +++++++++++++++++ src/backend/optimizer/plan/planner.c | 18 ++---------------- 3 files changed, 19 insertions(+), 27 deletions(-) diff --git a/src/backend/optimizer/plan/analyzejoins.c b/src/backend/optimizer/plan/analyzejoins.c index 881950e5264..e1af49d3dea 100644 --- a/src/backend/optimizer/plan/analyzejoins.c +++ b/src/backend/optimizer/plan/analyzejoins.c @@ -2178,17 +2178,6 @@ remove_self_join_rel(PlannerInfo *root, PlanRowMark *kmark, PlanRowMark *rmark, 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. diff --git a/src/backend/optimizer/plan/planmain.c b/src/backend/optimizer/plan/planmain.c index 02495e22e24..c123a397c1a 100644 --- a/src/backend/optimizer/plan/planmain.c +++ b/src/backend/optimizer/plan/planmain.c @@ -28,6 +28,7 @@ #include "optimizer/paths.h" #include "optimizer/placeholder.h" #include "optimizer/planmain.h" +#include "parser/parsetree.h" /* @@ -274,6 +275,22 @@ query_planner(PlannerInfo *root, */ setup_eager_aggregation(root); + /* + * If there's a result relation, initialize all_result_relids to include + * it; and if we've verified that it is non-inheriting, mark it as a leaf + * target. add_other_rels_to_query() will expand these sets if the result + * relation has children. + */ + if (parse->resultRelation) + { + RangeTblEntry *rte = rt_fetch(parse->resultRelation, parse->rtable); + + root->all_result_relids = bms_make_singleton(parse->resultRelation); + if (!rte->inh) + root->leaf_result_relids = + bms_make_singleton(parse->resultRelation); + } + /* * Now expand appendrels by adding "otherrels" for their children. We * delay this to the end so that we have as much information as possible diff --git a/src/backend/optimizer/plan/planner.c b/src/backend/optimizer/plan/planner.c index 3225185d16f..16ad18babaa 100644 --- a/src/backend/optimizer/plan/planner.c +++ b/src/backend/optimizer/plan/planner.c @@ -803,9 +803,8 @@ subquery_planner(PlannerGlobal *glob, Query *parse, char *plan_name, root->eq_classes = NIL; root->ec_merging_done = false; root->last_rinfo_serial = 0; - root->all_result_relids = - parse->resultRelation ? bms_make_singleton(parse->resultRelation) : NULL; - root->leaf_result_relids = NULL; /* we'll find out leaf-ness later */ + root->all_result_relids = NULL; + root->leaf_result_relids = NULL; root->append_rel_list = NIL; root->row_identity_vars = NIL; root->rowMarks = NIL; @@ -976,19 +975,6 @@ subquery_planner(PlannerGlobal *glob, Query *parse, char *plan_name, list_length(rte->securityQuals)); } - /* - * If we have now verified that the query target relation is - * non-inheriting, mark it as a leaf target. - */ - if (parse->resultRelation) - { - RangeTblEntry *rte = rt_fetch(parse->resultRelation, parse->rtable); - - if (!rte->inh) - root->leaf_result_relids = - bms_make_singleton(parse->resultRelation); - } - /* * This would be a convenient time to check access permissions for all * relations mentioned in the query, since it would be better to fail now, -- 2.52.0
v4-0002-Perform-join-removal-by-editing-the-query-s-joint.patch (text/x-diff, 58.2K) download From 40b404d0d6560769f767969c276449bee73f917d Mon Sep 17 00:00:00 2001 From: Tom Lane <tgl@sss.pgh.pa.us> Date: Sun, 26 Jul 2026 11:44:03 -0400 Subject: [PATCH v4 2/5] Perform join removal by editing the query's jointree. analyzejoins.c decided which joins could be dropped by consulting the planner's derived data structures, but then implemented the removal by updating those structures in-place. That is a lot of fiddly work, and nothing keeps it in step with the rest of the planner: remove_leftjoinrel_from_query only bothered to update "parts of the planner's data structures that will actually be consulted later", with no good way to know what those are. Bug #19560 is one consequence. Removing a join there leaves an EquivalenceClass that now gives rise to a base restriction clause, but base restriction clauses have already been generated and nothing reconsiders them, so the WHERE condition disappears from the plan and we return wrong answers. The self-join elimination code has the same design and the same type of hazard. Instead, do the removals by editing root->parse->jointree, which is a far simpler and more stable representation than the derived data, and then have query_planner() discard everything it computed from the jointree and derive it over again. reduce_unique_semijoins() gets the same treatment: rather than deleting the semijoin's SpecialJoinInfo and relying on the jointree not being consulted again, it now changes the JoinExpr's jointype to JOIN_INNER. Some plans change in the join regression test. Qual evaluation order shifts in a few cases, because the conditions now reach later planning in jointree order rather than in whatever order the removal code re-distributed them. A few plans improve, since the rebuilt relation targetlists no longer carry columns that only a removed join needed. We also detect a constant-false filter condition whose test used to carry a FIXME label. One plan gets marginally worse, because the old code recomputed attr_needed from equivalence classes after a join removal; that is more accurate than what deconstruct_jointree() derives from the original clauses, but we no longer do that. Making that recomputation happen anyway could be worth doing, but it should be considered independently and perhaps implemented differently. This leaves a good deal of dead code behind, which the next commit removes; the separation is made to make each diff a little more readable. As of this patch there are -Wunused-function warnings about several no-longer-used functions in analyzejoins.c. Bug: #19560 Reported-by: Orestis Markou <orestis@orestis.gr> Author: Tom Lane <tgl@sss.pgh.pa.us> Discussion: https://postgr.es/m/1186816.1784573544@sss.pgh.pa.us --- src/backend/optimizer/plan/analyzejoins.c | 833 +++++++++++++++------- src/backend/optimizer/plan/initsplan.c | 6 +- src/backend/optimizer/plan/planmain.c | 67 +- src/include/optimizer/planmain.h | 6 +- src/test/regress/expected/join.out | 101 ++- src/test/regress/sql/join.sql | 40 +- 6 files changed, 755 insertions(+), 298 deletions(-) diff --git a/src/backend/optimizer/plan/analyzejoins.c b/src/backend/optimizer/plan/analyzejoins.c index e1af49d3dea..ef355ec1fe1 100644 --- a/src/backend/optimizer/plan/analyzejoins.c +++ b/src/backend/optimizer/plan/analyzejoins.c @@ -7,9 +7,14 @@ * certain optimizations cannot be performed at that stage for lack of * detailed information about the query. The routines here are invoked * after initsplan.c has done its work, and can do additional join removal - * and simplification steps based on the information extracted. The penalty - * is that we have to work harder to clean up after ourselves when we modify - * the query, since the derived data structures have to be updated too. + * and simplification steps based on the information extracted. + * + * Although the decisions about what can be removed are made using the + * planner's derived data structures, the removals themselves are implemented + * by editing the query's jointree, which is a far simpler and more stable + * representation. We make no attempt to update the derived data structures + * to match; instead, query_planner() throws them all away and recomputes them + * whenever we report having removed something. * * Portions Copyright (c) 1996-2026, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California @@ -23,6 +28,7 @@ #include "postgres.h" #include "catalog/pg_class.h" +#include "nodes/makefuncs.h" #include "nodes/nodeFuncs.h" #include "optimizer/joininfo.h" #include "optimizer/optimizer.h" @@ -30,6 +36,7 @@ #include "optimizer/paths.h" #include "optimizer/placeholder.h" #include "optimizer/planmain.h" +#include "optimizer/prep.h" #include "optimizer/restrictinfo.h" #include "parser/parse_agg.h" #include "rewrite/rewriteManip.h" @@ -69,6 +76,11 @@ static void remove_rel_from_restrictinfo_phvs(RestrictInfo *rinfo, static Node *remove_rel_from_phvs(Node *node, int relid, int ojrelid); static Node *remove_rel_from_phvs_mutator(Node *node, Relids removable); static List *remove_rel_from_joinlist(List *joinlist, int relid, int *nremoved); +static Node *remove_join_from_jointree(Node *jtnode, int ojrelid, + int *nremoved); +static void remove_rels_from_query_tree(PlannerInfo *root, + Relids removed_relids); +static bool reduce_semijoin_in_jointree(Node *jtnode, Relids syn_righthand); static bool rel_supports_distinctness(PlannerInfo *root, RelOptInfo *rel); static bool rel_is_distinct_for(PlannerInfo *root, RelOptInfo *rel, List *clause_list, List **extra_clauses); @@ -80,6 +92,13 @@ static bool is_innerrel_unique_for(PlannerInfo *root, 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); +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); static bool replace_relid_callback(Node *node, ChangeVarNodes_context *context); @@ -88,21 +107,22 @@ static bool replace_relid_callback(Node *node, /* * remove_useless_joins * Check for relations that don't actually need to be joined at all, - * and remove them from the query. + * and remove them from the query's jointree. * - * We are passed the current joinlist and return the updated list. Other - * data structures that have to be updated are accessible via "root". + * Returns true if we removed anything. In that case the caller must discard + * everything it has derived from the jointree and compute it over again, + * since we don't try to update any of that here. */ -List * -remove_useless_joins(PlannerInfo *root, List *joinlist) +bool +remove_useless_joins(PlannerInfo *root) { + Relids removed_relids = NULL; ListCell *lc; /* * We are only interested in relations that are left-joined to, so we can * scan the join_info_list to find them easily. */ -restart: foreach(lc, root->join_info_list) { SpecialJoinInfo *sjinfo = (SpecialJoinInfo *) lfirst(lc); @@ -114,37 +134,59 @@ restart: continue; /* - * Currently, join_is_removable can only succeed when the sjinfo's - * righthand is a single baserel. Remove that rel from the query and - * joinlist. + * join_is_removable insists that the join's syntactic righthand side + * be a single baserel, so we can implement the removal by dropping + * the JoinExpr and everything below its righthand side. */ - innerrelid = bms_singleton_member(sjinfo->min_righthand); + innerrelid = bms_singleton_member(sjinfo->syn_righthand); - remove_leftjoinrel_from_query(root, innerrelid, sjinfo); + /* + * The removed rel had better not be one that the rest of the planner + * expects to find. It can't be, really: a result relation or a + * row-marked relation has junk columns in the query targetlist, and + * join_is_removable would have seen those as uses of the rel from + * "relation 0". But let's check. + */ + Assert(innerrelid != root->parse->resultRelation); +#ifdef USE_ASSERT_CHECKING + foreach_node(PlanRowMark, rc, root->rowMarks) + Assert(rc->rti != innerrelid && rc->prti != innerrelid); +#endif - /* We verify that exactly one reference gets removed from joinlist */ + /* We verify that exactly one JoinExpr gets removed */ nremoved = 0; - joinlist = remove_rel_from_joinlist(joinlist, innerrelid, &nremoved); + root->parse->jointree = (FromExpr *) + remove_join_from_jointree((Node *) root->parse->jointree, + sjinfo->ojrelid, &nremoved); if (nremoved != 1) - elog(ERROR, "failed to find relation %d in joinlist", innerrelid); + elog(ERROR, "failed to find join %d in jointree", sjinfo->ojrelid); - /* - * We can delete this SpecialJoinInfo from the list too, since it's no - * longer of interest. (Since we'll restart the foreach loop - * immediately, we don't bother with foreach_delete_current.) - */ - root->join_info_list = list_delete_cell(root->join_info_list, lc); + /* Track all the relids we've removed, for use below */ + removed_relids = bms_add_member(removed_relids, innerrelid); + removed_relids = bms_add_member(removed_relids, sjinfo->ojrelid); /* - * Restart the scan. This is necessary to ensure we find all - * removable joins independently of ordering of the join_info_list - * (note that removal of attr_needed bits may make a join appear - * removable that did not before). + * It's okay to keep scanning join_info_list for more removable joins, + * even though the data that join_is_removable consults is now + * slightly out of date. Removing a join can only delete attr_needed + * bits and join clauses, and any attr_needed bit or join clause that + * mentions the removed rel above its own join level would have + * prevented that rel from being removable. So what remains to be + * examined is unchanged by what we just did. + * + * The converse doesn't hold: dropping a join can make some other join + * removable that didn't look so before. That's why our caller loops + * until we report finding nothing more to remove. */ - goto restart; } - return joinlist; + if (bms_is_empty(removed_relids)) + return false; + + /* Clean up the traces that the removed rels have left elsewhere */ + remove_rels_from_query_tree(root, removed_relids); + + return true; } /* @@ -176,8 +218,15 @@ join_is_removable(PlannerInfo *root, SpecialJoinInfo *sjinfo) if (sjinfo->jointype != JOIN_LEFT) return false; - if (!bms_get_singleton_member(sjinfo->min_righthand, &innerrelid)) + /* + * We test the syntactic righthand side, not min_righthand, because the + * removal is done by deleting the whole righthand subtree of the join. + * (min_righthand can be a singleton when syn_righthand is not, but in + * such a case the attr_needed tests below would reject the join anyway.) + */ + if (!bms_get_singleton_member(sjinfo->syn_righthand, &innerrelid)) return false; + Assert(bms_equal(sjinfo->min_righthand, sjinfo->syn_righthand)); /* * Never try to eliminate a left join to the query result rel. Although @@ -1025,6 +1074,91 @@ remove_rel_from_joinlist(List *joinlist, int relid, int *nremoved) } +/* + * remove_join_from_jointree + * Delete the JoinExpr with the given RT index, along with everything + * below its righthand side, from the query's jointree. + * + * 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). + */ +static Node * +remove_join_from_jointree(Node *jtnode, int ojrelid, int *nremoved) +{ + if (jtnode == NULL) + return NULL; + if (IsA(jtnode, RangeTblRef)) + { + /* nothing to do here */ + } + else if (IsA(jtnode, FromExpr)) + { + FromExpr *f = (FromExpr *) jtnode; + ListCell *l; + + foreach(l, f->fromlist) + lfirst(l) = remove_join_from_jointree((Node *) lfirst(l), + ojrelid, nremoved); + } + else if (IsA(jtnode, JoinExpr)) + { + JoinExpr *j = (JoinExpr *) jtnode; + + if (j->rtindex == 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)); + + return jtnode; +} + +/* + * remove_rels_from_query_tree + * Delete all remaining references to the given relids from the query. + * + * 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 the relids can + * still appear in the nullingrels sets of surviving Vars and PlaceHolderVars, + * and in the phrels sets of PlaceHolderVars. ChangeVarNodes knows how to + * strip a relid out of all of those. + */ +static void +remove_rels_from_query_tree(PlannerInfo *root, Relids removed_relids) +{ + int relid = -1; + + while ((relid = bms_next_member(removed_relids, relid)) >= 0) + { + /* Pass -1 for new_index to get the removal behavior */ + ChangeVarNodes((Node *) root->parse, relid, -1, 0); + + /* + * 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.) + */ + ChangeVarNodes((Node *) root->processed_tlist, relid, -1, 0); + + /* There could be references in the append_rel_list, too */ + if (root->append_rel_list != NIL) + ChangeVarNodes((Node *) root->append_rel_list, relid, -1, 0); + } +} + /* * reduce_unique_semijoins * Check for semijoins that can be simplified to plain inner joins @@ -1033,14 +1167,13 @@ remove_rel_from_joinlist(List *joinlist, int relid, int *nremoved) * Ideally this would happen during reduce_outer_joins, but we don't have * enough information at that point. * - * To perform the strength reduction when applicable, we need only delete - * the semijoin's SpecialJoinInfo from root->join_info_list. (We don't - * bother fixing the join type attributed to it in the query jointree, - * since that won't be consulted again.) + * Like the join removal cases, we do this on the query's jointree, so + * returning true means the caller must recompute the derived data. */ -void +bool reduce_unique_semijoins(PlannerInfo *root) { + bool changed = false; ListCell *lc; /* @@ -1097,9 +1230,65 @@ reduce_unique_semijoins(PlannerInfo *root) JOIN_SEMI, restrictlist, true)) continue; - /* OK, remove the SpecialJoinInfo from the list. */ - root->join_info_list = foreach_delete_current(root->join_info_list, lc); + /* OK, reduce the join to a plain inner join in the jointree. */ + if (!reduce_semijoin_in_jointree((Node *) root->parse->jointree, + sjinfo->syn_righthand)) + elog(ERROR, "failed to find semijoin in jointree"); + changed = true; + } + + return changed; +} + +/* + * reduce_semijoin_in_jointree + * Find the JoinExpr for the semijoin with the given syntactic righthand + * side, and turn it into an inner join. + * + * Semijoins have no RT index of their own, so we have to identify the one + * we want by the set of relids on its righthand side. + */ +static bool +reduce_semijoin_in_jointree(Node *jtnode, Relids syn_righthand) +{ + if (jtnode == NULL) + return false; + if (IsA(jtnode, RangeTblRef)) + { + /* nothing to do here */ + } + else if (IsA(jtnode, FromExpr)) + { + FromExpr *f = (FromExpr *) jtnode; + ListCell *l; + + foreach(l, f->fromlist) + { + if (reduce_semijoin_in_jointree((Node *) lfirst(l), syn_righthand)) + return true; + } } + else if (IsA(jtnode, JoinExpr)) + { + JoinExpr *j = (JoinExpr *) jtnode; + + if (j->jointype == JOIN_SEMI && + bms_equal(get_relids_in_jointree(j->rarg, true, false), + syn_righthand)) + { + j->jointype = JOIN_INNER; + return true; + } + if (reduce_semijoin_in_jointree(j->larg, syn_righthand)) + return true; + if (reduce_semijoin_in_jointree(j->rarg, syn_righthand)) + return true; + } + else + elog(ERROR, "unrecognized jointree node type: %d", + (int) nodeTag(jtnode)); + + return false; } @@ -2014,130 +2203,64 @@ replace_relid_callback(Node *node, ChangeVarNodes_context *context) } /* - * Remove a relation after we have proven that it participates only in an - * unneeded unique self-join. - * - * Replace any links in planner info structures. - * - * 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 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. + * Remove the toRemove relation after we have proven that it participates only + * in an unneeded unique self-join with toKeep. + * + * The removal is done by deleting the relation's RangeTblRef from the + * jointree and then pointing everything that referenced it at the relation we + * are keeping. All the conditions that were attached to the removed relation + * thereby become conditions on the remaining one, which is what we want: + * we've proven that the two relations select the same rows. + * + * kmark and rmark are the PlanRowMarks (if any) for the kept and removed + * relations. We could re-locate those, but the caller already found them. */ static void -remove_self_join_rel(PlannerInfo *root, PlanRowMark *kmark, PlanRowMark *rmark, +remove_self_join_rel(PlannerInfo *root, RelOptInfo *toKeep, RelOptInfo *toRemove, - List *restrictlist) + PlanRowMark *kmark, PlanRowMark *rmark) { - List *joininfos; - ListCell *lc; - int i; - List *jinfo_candidates = NIL; - List *binfo_candidates = NIL; + Node *orphan_quals = NULL; + int nremoved = 0; 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); - } + /* We verify that exactly one reference gets removed from the jointree */ + root->parse->jointree = (FromExpr *) + remove_rel_from_jointree((Node *) root->parse->jointree, + toRemove->relid, + &orphan_quals, &nremoved); + if (nremoved != 1) + elog(ERROR, "failed to find relation %d in jointree", toRemove->relid); + /* The topmost FromExpr can't have gone away, so nothing can be orphaned */ + Assert(root->parse->jointree != NULL); + Assert(orphan_quals == NULL); /* - * 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. + * Replace all references to the removed relation. Note that this must + * happen after the jointree surgery, else we'd not be able to tell the + * two relations' RangeTblRefs apart. */ - 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); - } + ChangeVarNodes((Node *) root->parse, toRemove->relid, toKeep->relid, 0); /* - * Transfer the targetlist and attr_needed flags. + * 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 the second visit to a + * shared node finds nothing to change.) */ + ChangeVarNodes((Node *) root->processed_tlist, toRemove->relid, + toKeep->relid, 0); - 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); - } + /* There could be references in the append_rel_list, too */ + if (root->append_rel_list != NIL) + ChangeVarNodes((Node *) root->append_rel_list, toRemove->relid, + toKeep->relid, 0); - 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]); - } + /* Clean up the quals that the substitution has messed with */ + fixup_selfjoin_jointree(root, (Node *) root->parse->jointree, + toKeep->relid); /* * If the removed relation has a row mark, transfer it to the remaining @@ -2157,52 +2280,270 @@ remove_self_join_rel(PlannerInfo *root, PlanRowMark *kmark, PlanRowMark *rmark, } else { - /* Shouldn't have inheritance children here. */ + /* Shouldn't have inheritance children yet. */ Assert(rmark->rti == rmark->prti); rmark->rti = rmark->prti = toKeep->relid; } } +} - /* - * 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); +/* + * remove_rel_from_jointree + * Delete the RangeTblRef for the given relation from the query's + * jointree. + * + * This is used for self-join elimination, where the removed relation's + * qual conditions must all be preserved (they will be transposed onto the + * remaining relation afterwards). Hence, if dropping the RangeTblRef leaves + * a JoinExpr or FromExpr with nothing under it, we can't simply drop that + * node; we hand its quals back to the caller in *orphan_quals, to be merged + * into the nearest enclosing node that still has some content. That's a + * valid transformation only for inner joins, but a jointree node can't become + * empty at an outer join here: remove_self_joins_one_group() insists that the + * two relations be on the same side of every outer join, so the relation we + * are keeping would have to be in the emptied subtree too. + * + * *nremoved is incremented by the number of RangeTblRefs removed (there + * should be exactly one, but the caller checks that). + */ +static Node * +remove_rel_from_jointree(Node *jtnode, int relid, + Node **orphan_quals, int *nremoved) +{ + if (jtnode == NULL) + return NULL; + if (IsA(jtnode, RangeTblRef)) + { + RangeTblRef *rtr = (RangeTblRef *) jtnode; - /* Replace links in the planner info */ - remove_rel_from_query(root, toRemove->relid, toKeep->relid, NULL, NULL); + if (rtr->rtindex == relid) + { + (*nremoved)++; + return NULL; + } + } + else if (IsA(jtnode, FromExpr)) + { + FromExpr *f = (FromExpr *) jtnode; + List *newfromlist = NIL; + Node *sub_orphans = NULL; + ListCell *l; - /* Replace varno in the fully-processed targetlist */ - ChangeVarNodesExtended((Node *) root->processed_tlist, toRemove->relid, - toKeep->relid, 0, replace_relid_callback); + foreach(l, f->fromlist) + { + Node *newchild; - /* - * There may be references to the rel in root->fkey_list, but if so, - * match_foreign_keys_to_quals() will get rid of them. - */ + newchild = remove_rel_from_jointree((Node *) lfirst(l), relid, + &sub_orphans, nremoved); + if (newchild != NULL) + newfromlist = lappend(newfromlist, newchild); + } + f->fromlist = newfromlist; + f->quals = merge_quals(sub_orphans, f->quals); + if (newfromlist == NIL) + { + /* Nothing left here, so pass our quals up to the parent */ + *orphan_quals = merge_quals(f->quals, *orphan_quals); + return NULL; + } + } + else if (IsA(jtnode, JoinExpr)) + { + JoinExpr *j = (JoinExpr *) jtnode; + Node *sub_orphans = NULL; + + j->larg = remove_rel_from_jointree(j->larg, relid, + &sub_orphans, nremoved); + j->rarg = remove_rel_from_jointree(j->rarg, relid, + &sub_orphans, nremoved); + if (j->larg == NULL || j->rarg == NULL) + { + Node *surviving = (j->larg != NULL) ? j->larg : j->rarg; + Node *quals = merge_quals(sub_orphans, j->quals); - /* - * 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; + /* As explained above, this can only happen for an inner join */ + Assert(j->jointype == JOIN_INNER); + /* We can't have removed both children */ + Assert(surviving != NULL); + + /* + * Replace the join by a FromExpr, so that the surviving side's + * rows are still filtered by the join's conditions. + */ + return (Node *) makeFromExpr(list_make1(surviving), quals); + } + /* A subtree that survives never hands any quals back to us */ + Assert(sub_orphans == NULL); + } + else + elog(ERROR, "unrecognized jointree node type: %d", + (int) nodeTag(jtnode)); + + return jtnode; +} + +/* + * merge_quals + * Combine two jointree qual conditions. + * + * quals1 should be the quals from the lower of the two jointree levels, + * so that those quals get applied first. + * + * Jointree quals have been through preprocess_expression() by now, so each + * one is either NULL or an implicitly-ANDed List. + */ +static Node * +merge_quals(Node *quals1, Node *quals2) +{ + if (quals1 == NULL) + return quals2; + if (quals2 == NULL) + return quals1; + return (Node *) list_concat(castNode(List, quals1), + castNode(List, quals2)); +} + +/* + * fixup_selfjoin_jointree + * Clean up the query's jointree quals after self-join elimination has + * merged one relation into another. (relid is the kept relation.) + * + * See fixup_selfjoin_quals() for what needs fixing. + */ +static void +fixup_selfjoin_jointree(PlannerInfo *root, Node *jtnode, int relid) +{ + if (jtnode == NULL) + return; + if (IsA(jtnode, RangeTblRef)) + { + /* nothing to do here */ + } + else if (IsA(jtnode, FromExpr)) + { + FromExpr *f = (FromExpr *) jtnode; + ListCell *l; + + foreach(l, f->fromlist) + fixup_selfjoin_jointree(root, (Node *) lfirst(l), relid); + f->quals = (Node *) fixup_selfjoin_quals(root, + castNode(List, f->quals), + relid); + } + else if (IsA(jtnode, JoinExpr)) + { + JoinExpr *j = (JoinExpr *) jtnode; + + fixup_selfjoin_jointree(root, j->larg, relid); + fixup_selfjoin_jointree(root, j->rarg, relid); + j->quals = (Node *) fixup_selfjoin_quals(root, + castNode(List, j->quals), + relid); + } + else + elog(ERROR, "unrecognized jointree node type: %d", + (int) nodeTag(jtnode)); +} + +/* + * fixup_selfjoin_quals + * Clean up one qual list after self-join elimination. + * + * 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). + * + * 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. + * + * 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 List * +fixup_selfjoin_quals(PlannerInfo *root, List *quals, int relid) +{ + List *result = NIL; + ListCell *l; - /* And nuke the RelOptInfo, just in case there's another access path. */ - pfree(toRemove); + foreach(l, quals) + { + Node *qual = (Node *) lfirst(l); + if (bms_is_member(relid, pull_varnos(root, qual))) + { + 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); + } + + return result; +} + +/* + * 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; /* - * 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; } /* @@ -2227,7 +2568,12 @@ split_selfjoin_quals(PlannerInfo *root, List *joinquals, List **selfjoinquals, Node *leftexpr; Node *rightexpr; - /* In general, clause looks like F(arg1) = G(arg2) */ + /* + * Since the given joinquals all came from + * generate_join_implied_equalities, they ought to look like equality + * operators on single-relation expressions. But let's check that. + * Anything that doesn't look like that can be dumped into ojoinquals. + */ if (!rinfo->mergeopfamilies || bms_num_members(rinfo->clause_relids) != 2 || bms_membership(rinfo->left_relids) != BMS_SINGLETON || @@ -2340,15 +2686,16 @@ match_unique_clauses(PlannerInfo *root, RelOptInfo *outer, List *uclauses, } /* - * Find and remove unique self-joins in a group of base relations that have + * Find and remove one unique self-join in a group of base relations that have * the same Oid. * - * Returns a set of relids that were removed. + * Returns true if we removed a relation. We stop at the first removal, + * because it invalidates all the derived information that the tests here + * depend on; our caller will come back for more once that's been rebuilt. */ -static Relids +static bool remove_self_joins_one_group(PlannerInfo *root, Relids relids) { - Relids result = NULL; int k; /* Index of kept relation */ int r = -1; /* Index of removed relation */ @@ -2356,8 +2703,8 @@ remove_self_joins_one_group(PlannerInfo *root, Relids relids) { RelOptInfo *rrel = root->simple_rel_array[r]; + /* k iterates over the relids after r */ k = r; - while ((k = bms_next_member(relids, k)) > 0) { Relids joinrelids = NULL; @@ -2377,8 +2724,8 @@ remove_self_joins_one_group(PlannerInfo *root, Relids relids) /* * It is impossible to eliminate the join of two relations if they - * belong to different rules of order. Otherwise, the planner - * can't find any variants of the correct query plan. + * are not on the same side of every outer join. Otherwise, the + * planner can't find any variants of the correct query plan. */ foreach(lc, root->join_info_list) { @@ -2492,29 +2839,26 @@ remove_self_joins_one_group(PlannerInfo *root, Relids relids) if (!match_unique_clauses(root, rrel, uclauses, krel->relid)) continue; - /* - * Remove rrel RelOptInfo from the planner structures and the - * corresponding row mark. - */ - remove_self_join_rel(root, kmark, rmark, krel, rrel, restrictlist); - - result = bms_add_member(result, r); + /* OK, remove rrel from the query, and report that we did so */ + remove_self_join_rel(root, krel, rrel, kmark, rmark); - /* We have removed the outer relation, try the next one. */ - break; + return true; } } - return result; + return false; } /* - * Gather indexes of base relations from the joinlist and try to eliminate self - * joins. + * Gather indexes of base relations from the joinlist and try to eliminate one + * self join. + * + * Returns true if we removed a relation. */ -static Relids -remove_self_joins_recurse(PlannerInfo *root, List *joinlist, Relids toRemove) +static bool +remove_self_joins_recurse(PlannerInfo *root, List *joinlist) { + bool removed = false; ListCell *jl; Relids relids = NULL; SelfJoinCandidate *candidates = NULL; @@ -2536,7 +2880,7 @@ remove_self_joins_recurse(PlannerInfo *root, List *joinlist, Relids toRemove) * We only consider ordinary relations as candidates to be * removed, and these relations should not have TABLESAMPLE * clauses specified. Removing a relation with TABLESAMPLE clause - * could potentially change the syntax of the query. Because of + * could potentially change the semantics of the query. Because of * UPDATE/DELETE EPQ mechanism, currently Query->resultRelation or * Query->mergeTargetRelation associated rel cannot be eliminated. */ @@ -2552,9 +2896,9 @@ remove_self_joins_recurse(PlannerInfo *root, List *joinlist, Relids toRemove) } else if (IsA(jlnode, List)) { - /* Recursively go inside the sub-joinlist */ - toRemove = remove_self_joins_recurse(root, (List *) jlnode, - toRemove); + /* Recursively consider SJE within the sub-joinlist */ + if (remove_self_joins_recurse(root, (List *) jlnode)) + return true; } else elog(ERROR, "unrecognized joinlist node type: %d", @@ -2565,7 +2909,7 @@ remove_self_joins_recurse(PlannerInfo *root, List *joinlist, Relids toRemove) /* Need at least two relations for the join */ if (numRels < 2) - return toRemove; + return false; /* * In order to find relations with the same oid we first build an array of @@ -2586,8 +2930,7 @@ remove_self_joins_recurse(PlannerInfo *root, List *joinlist, Relids toRemove) /* * Iteratively form a group of relation indexes with the same oid and - * launch the routine that detects self-joins in this group and removes - * excessive range table entries. + * launch the routine that detects a self-join in this group. * * At the end of the iteration, exclude the group from the overall relids * list. So each next iteration of the cycle will involve less and less @@ -2598,11 +2941,10 @@ remove_self_joins_recurse(PlannerInfo *root, List *joinlist, Relids toRemove) { if (j == numRels || candidates[j].reloid != candidates[i].reloid) { - if (j - i >= 2) + if (j - i >= 2 && !removed) { /* Create a group of relation indexes with the same oid */ Relids group = NULL; - Relids removed; while (i < j) { @@ -2612,34 +2954,29 @@ remove_self_joins_recurse(PlannerInfo *root, List *joinlist, Relids toRemove) relids = bms_del_members(relids, group); /* - * Try to remove self-joins from a group of identical entries. - * Make the next attempt iteratively - if something is deleted - * from a group, changes in clauses and equivalence classes - * can give us a chance to find more candidates. + * Try to remove a self-join from a group of identical + * entries. We stop as soon as we succeed, since the + * information we based the decision on is then out of date; + * our caller will start over from scratch. */ - do - { - Assert(!bms_overlap(group, toRemove)); - removed = remove_self_joins_one_group(root, group); - toRemove = bms_add_members(toRemove, removed); - group = bms_del_members(group, removed); - } while (!bms_is_empty(removed) && - bms_membership(group) == BMS_MULTIPLE); - bms_free(removed); + removed = remove_self_joins_one_group(root, group); bms_free(group); } else { - /* Single relation, just remove it from the set */ - relids = bms_del_member(relids, candidates[i].relid); - i = j; + /* Nothing to do with this group, just drop it from the set */ + while (i < j) + { + relids = bms_del_member(relids, candidates[i].relid); + i++; + } } } } Assert(bms_is_empty(relids)); - return toRemove; + return removed; } /* @@ -2681,45 +3018,25 @@ self_join_candidates_cmp(const void *a, const void *b) * 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; we use it to identify + * groups of relations that could be joined to each other. * - * '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. + * We remove at most one self-join per call, and return true if we did so. + * The caller must then recompute everything that was derived from the + * jointree before calling here again. */ -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 one pair of relations participating in a self-join. */ + return remove_self_joins_recurse(root, joinlist); } diff --git a/src/backend/optimizer/plan/initsplan.c b/src/backend/optimizer/plan/initsplan.c index b38422c47a4..7b6d7249c66 100644 --- a/src/backend/optimizer/plan/initsplan.c +++ b/src/backend/optimizer/plan/initsplan.c @@ -4044,9 +4044,9 @@ match_foreign_keys_to_quals(PlannerInfo *root) /* * 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 don't use - * find_base_rel() here. We can ignore such FKs. + * isn't referenced by the jointree (typically because it's been + * removed by join removal), so that it won't have a RelOptInfo. Hence + * don't use find_base_rel() here. We can ignore such FKs. */ if (fkinfo->con_relid >= root->simple_rel_array_size || fkinfo->ref_relid >= root->simple_rel_array_size) diff --git a/src/backend/optimizer/plan/planmain.c b/src/backend/optimizer/plan/planmain.c index c123a397c1a..298affe6bca 100644 --- a/src/backend/optimizer/plan/planmain.c +++ b/src/backend/optimizer/plan/planmain.c @@ -55,33 +55,71 @@ RelOptInfo * query_planner(PlannerInfo *root, query_pathkeys_callback qp_callback, void *qp_extra) { - Query *parse = root->parse; + Query *parse; List *joinlist; RelOptInfo *final_rel; /* - * Init planner lists to empty. + * The join simplification steps below work by modifying parse->jointree, + * and they make no attempt to update the information we derive from it. + * So whenever one of them succeeds, we must throw away all that derived + * information and recompute it from scratch, which we do by looping back + * to "restart". We cannot loop indefinitely, because each successful + * simplification either deletes a base relation from the jointree or + * turns a semijoin into an inner join, and neither of those can be undone + * by a later pass. * - * NOTE: append_rel_list was set up by subquery_planner, so do not touch - * here. + * These initial Asserts check that the state at entry is not too complex + * for the code below to restore. There mustn't be any EquivalenceClasses + * yet, and we should have only the top-level JoinDomain. */ + Assert(root->eq_classes == NIL); + Assert(list_length(root->join_domains) == 1); + +restart: + parse = root->parse; + + /* + * Initialize information derived from the jointree to empty. + * + * It's critical that this reset every field that the steps below will + * fill in, since we may be going around this loop more than once. + * + * NOTE: append_rel_list was created earlier, so do not clear it here; + * rowMarks ditto. Join simplification must update those if necessary. + */ + root->all_baserels = NULL; + root->outer_join_rels = NULL; + root->all_query_rels = NULL; root->join_rel_list = NIL; root->join_rel_hash = NULL; root->join_rel_level = NULL; root->join_cur_level = 0; + root->eq_classes = NIL; + root->ec_merging_done = false; root->canon_pathkeys = NIL; root->left_join_clauses = NIL; root->right_join_clauses = NIL; root->full_join_clauses = NIL; root->join_info_list = NIL; + root->last_rinfo_serial = 0; root->placeholder_list = NIL; root->placeholder_array = NULL; root->placeholder_array_size = 0; + root->placeholdersFrozen = false; root->agg_clause_list = NIL; root->group_expr_list = NIL; root->tlist_vars = NIL; root->fkey_list = NIL; root->initial_rels = NIL; + root->hasPseudoConstantQuals = false; + + /* + * We don't want to delete the top-level join domain, but get rid of other + * ones so as to reset the list to initial state. deconstruct_jointree + * will take care of (re)computing the top level's jd_relids. + */ + root->join_domains = list_truncate(root->join_domains, 1); /* * Set up arrays for accessing base relations and AppendRelInfos. @@ -228,19 +266,30 @@ query_planner(PlannerInfo *root, * Remove any useless outer joins. Ideally this would be done during * jointree preprocessing, but the necessary information isn't available * until we've built baserel data structures and classified qual clauses. + * If we remove a join, loop back to the top and redo what we did so far. */ - joinlist = remove_useless_joins(root, joinlist); + if (remove_useless_joins(root)) + goto restart; /* * Also, reduce any semijoins with unique inner rels to plain inner joins. - * Likewise, this can't be done until now for lack of needed info. + * Likewise, this can't be done until now for lack of needed info, and we + * must loop around if we find any simplifications. + */ + if (reduce_unique_semijoins(root)) + goto restart; + + /* + * Remove self joins on a unique column. Again, this couldn't be done any + * earlier, and we must loop around if we find anything to remove. */ - reduce_unique_semijoins(root); + if (remove_useless_self_joins(root, joinlist)) + goto restart; /* - * Remove self joins on a unique column. + * No more join simplifications apply, so we're done looping. Code below + * this point does not need to be able to restart. */ - joinlist = remove_useless_self_joins(root, joinlist); /* * Now distribute "placeholders" to base rels as needed. This has to be diff --git a/src/include/optimizer/planmain.h b/src/include/optimizer/planmain.h index 71c043a25e8..85301d912f0 100644 --- a/src/include/optimizer/planmain.h +++ b/src/include/optimizer/planmain.h @@ -108,8 +108,8 @@ extern void match_foreign_keys_to_quals(PlannerInfo *root); /* * prototypes for plan/analyzejoins.c */ -extern List *remove_useless_joins(PlannerInfo *root, List *joinlist); -extern void reduce_unique_semijoins(PlannerInfo *root); +extern bool remove_useless_joins(PlannerInfo *root); +extern bool reduce_unique_semijoins(PlannerInfo *root); extern bool query_supports_distinctness(Query *query); extern bool query_is_distinct_for(Query *query, List *distinct_cols); extern bool innerrel_is_unique(PlannerInfo *root, @@ -119,7 +119,7 @@ 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 bool remove_useless_self_joins(PlannerInfo *root, List *joinlist); /* * prototypes for plan/setrefs.c diff --git a/src/test/regress/expected/join.out b/src/test/regress/expected/join.out index 19e2cca548b..254b203aeba 100644 --- a/src/test/regress/expected/join.out +++ b/src/test/regress/expected/join.out @@ -6890,6 +6890,38 @@ where t1.a = s.c; ---------- (0 rows) +rollback; +-- join removal bug #19560: removing a join can leave an EquivalenceClass that +-- now yields a base restriction clause, so we must redo equivalence +-- processing from scratch +begin; +create temp table items (id text, owner text); +create temp table follows (item_id text, user_id text, + unique (user_id, item_id)); +insert into items values ('item1', 'alice'); +explain (costs off) +with viewer as (select 'bob' as id) +select count(*) from items + left join follows on follows.item_id = items.id and follows.user_id = 'bob' + left join viewer on true +where items.owner = viewer.id; + QUERY PLAN +--------------------------------------- + Aggregate + -> Seq Scan on items + Filter: (owner = 'bob'::text) +(3 rows) + +with viewer as (select 'bob' as id) +select count(*) from items + left join follows on follows.item_id = items.id and follows.user_id = 'bob' + left join viewer on true +where items.owner = viewer.id; + count +------- + 0 +(1 row) + rollback; -- check handling of semijoins after join removal: we must suppress -- unique-ification of known-constant values @@ -6915,17 +6947,17 @@ where exists (select 1 from t t4 Output: t1.a Index Cond: (t1.a = 1) -> HashAggregate - Output: t5.a + Output: t4.a, t5.a Group Key: t5.a -> Hash Join - Output: t5.a + Output: t4.a, t5.a Hash Cond: (t6.b = t4.b) -> Seq Scan on pg_temp.t t6 Output: t6.a, t6.b -> Hash - Output: t4.b, t5.b, t5.a + Output: t4.b, t4.a, t5.b, t5.a -> Hash Join - Output: t4.b, t5.b, t5.a + Output: t4.b, t4.a, t5.b, t5.a Inner Unique: true Hash Cond: (t5.b = t4.b) -> Seq Scan on pg_temp.t t5 @@ -7357,7 +7389,7 @@ on q1.ax = q2.a; Nested Loop Left Join Join Filter: (t2.a = t4.a) -> Seq Scan on sj t2 - Filter: ((b IS NULL) AND (a IS NOT NULL) AND ((c * c) = (c + 2))) + Filter: ((a IS NOT NULL) AND (b IS NULL) AND ((c * c) = (c + 2))) -> Seq Scan on sj t4 Filter: (c IS NOT NULL) (6 rows) @@ -7440,9 +7472,9 @@ select t1.a from sj t1 where t1.b in ( -> Seq Scan on public.sj t1 Output: t1.a, t1.b, t1.c -> Materialize - Output: t3.c, t3.b + Output: t3.b -> Seq Scan on public.sj t3 - Output: t3.c, t3.b + Output: t3.b Filter: (t3.c IS NOT NULL) (10 rows) @@ -7776,15 +7808,15 @@ explain (costs off) select * from sj p join sj q on p.a = q.a -> Seq Scan on sj r (6 rows) --- FIXME this constant false filter doesn't look good. Should we merge --- equivalence classes? +-- Check that we detect constant-false condition after merging ECs. explain (costs off) select * from sj p, sj q where p.a = q.a and p.b = 1 and q.b = 2; - QUERY PLAN ------------------------------------------------------ - Seq Scan on sj q - Filter: ((a IS NOT NULL) AND (b = 2) AND (b = 1)) -(2 rows) + QUERY PLAN +-------------------------- + Result + Replaces: Scan on q + One-Time Filter: false +(3 rows) -- Check that attr_needed is updated correctly after self-join removal. In this -- test, the join of j1 with j2 is removed. k1.b is required at either j1 or j2. @@ -7920,11 +7952,9 @@ where s1.x = 1; -> Seq Scan on public.emp1 t1 Output: t1.id, t1.code -> Materialize - Output: t3.id -> Seq Scan on public.emp1 t3 - Output: t3.id Filter: (1 = 1) -(9 rows) +(7 rows) -- Check that PHVs do not impose any constraints on removing self joins explain (verbose, costs off) @@ -7974,14 +8004,14 @@ SELECT 1 FROM tbl_phv t1 LEFT JOIN (SELECT y FROM tbl_phv tr) t4 ON t4.y = t3.y ON true WHERE t3.extra IS NOT NULL AND t3.x = t1.x % 2; - QUERY PLAN ---------------------------------------------------------- + QUERY PLAN +-------------------------------------------------------------- Nested Loop Output: 1 -> Seq Scan on public.tbl_phv t1 Output: t1.x, t1.y - -> Index Scan using tbl_phv_idx on public.tbl_phv tr - Output: tr.x, tr.y + -> Index Only Scan using tbl_phv_idx on public.tbl_phv tr + Output: tr.x Index Cond: (tr.x = (t1.x % 2)) Filter: (1 IS NOT NULL) (8 rows) @@ -8162,7 +8192,7 @@ where t1.b = t2.b and t2.a = 3 and t1.a = 3 --------------------------------------------------------------------------------------------- Seq Scan on public.sl t2 Output: t2.a, t2.b, t2.c, t2.a, t2.b, t2.c - Filter: ((t2.c IS NOT NULL) AND (t2.b IS NOT NULL) AND (t2.a IS NOT NULL) AND (t2.a = 3)) + Filter: ((t2.b IS NOT NULL) AND (t2.c IS NOT NULL) AND (t2.a IS NOT NULL) AND (t2.a = 3)) (3 rows) -- Join qual isn't mergejoinable, but inner is unique. @@ -8204,10 +8234,35 @@ SELECT 1 AS c1 FROM sl sl1 LEFT JOIN (sl AS sl2 NATURAL JOIN sl AS sl3) -> Nested Loop Left Join Join Filter: sl3.bool_col -> Seq Scan on sl sl3 - Filter: (bool_col AND (a IS NOT NULL) AND (b IS NOT NULL) AND (c IS NOT NULL) AND (bool_col IS NOT NULL)) + Filter: ((a IS NOT NULL) AND (b IS NOT NULL) AND (c IS NOT NULL) AND (bool_col IS NOT NULL) AND bool_col) -> Seq Scan on sl sl4 (7 rows) +-- Check that quals of a jointree node that becomes empty when the self-join +-- is removed are not lost, and that they don't migrate above an outer join +EXPLAIN (COSTS OFF) +SELECT s.a FROM (SELECT * FROM sl WHERE c IS NOT NULL) s, sl t +WHERE t.a = s.a AND t.b = s.b; + QUERY PLAN +--------------------------------------------------------------------- + Seq Scan on sl + Filter: ((c IS NOT NULL) AND (a IS NOT NULL) AND (b IS NOT NULL)) +(2 rows) + +EXPLAIN (COSTS OFF) +SELECT t1.a, ss.a FROM sl t1 + LEFT JOIN (SELECT s.a FROM (SELECT * FROM sl WHERE c IS NOT NULL) s + JOIN sl t ON t.a = s.a AND t.b = s.b) ss + ON ss.a = t1.a; + QUERY PLAN +--------------------------------------------------------------------------- + Nested Loop Left Join + Join Filter: (sl.a = t1.a) + -> Seq Scan on sl t1 + -> Seq Scan on sl + Filter: ((c IS NOT NULL) AND (a IS NOT NULL) AND (b IS NOT NULL)) +(5 rows) + -- Check optimization disabling if it will violate special join conditions. -- Two identical joined relations satisfies self join removal conditions but -- stay in different special join infos. diff --git a/src/test/regress/sql/join.sql b/src/test/regress/sql/join.sql index 85aed7bf704..afa96daecb5 100644 --- a/src/test/regress/sql/join.sql +++ b/src/test/regress/sql/join.sql @@ -2601,6 +2601,31 @@ where t1.a = s.c; rollback; +-- join removal bug #19560: removing a join can leave an EquivalenceClass that +-- now yields a base restriction clause, so we must redo equivalence +-- processing from scratch +begin; + +create temp table items (id text, owner text); +create temp table follows (item_id text, user_id text, + unique (user_id, item_id)); +insert into items values ('item1', 'alice'); + +explain (costs off) +with viewer as (select 'bob' as id) +select count(*) from items + left join follows on follows.item_id = items.id and follows.user_id = 'bob' + left join viewer on true +where items.owner = viewer.id; + +with viewer as (select 'bob' as id) +select count(*) from items + left join follows on follows.item_id = items.id and follows.user_id = 'bob' + left join viewer on true +where items.owner = viewer.id; + +rollback; + -- check handling of semijoins after join removal: we must suppress -- unique-ification of known-constant values begin; @@ -3015,8 +3040,7 @@ select 1 from (select y.* from sj x, sj y where x.a = y.a) q, explain (costs off) select * from sj p join sj q on p.a = q.a left join sj r on p.a + q.a = r.a; --- FIXME this constant false filter doesn't look good. Should we merge --- equivalence classes? +-- Check that we detect constant-false condition after merging ECs. explain (costs off) select * from sj p, sj q where p.a = q.a and p.b = 1 and q.b = 2; @@ -3214,6 +3238,18 @@ EXPLAIN (COSTS OFF) SELECT 1 AS c1 FROM sl sl1 LEFT JOIN (sl AS sl2 NATURAL JOIN sl AS sl3) ON sl2.bool_col LEFT JOIN sl AS sl4 ON sl2.bool_col; +-- Check that quals of a jointree node that becomes empty when the self-join +-- is removed are not lost, and that they don't migrate above an outer join +EXPLAIN (COSTS OFF) +SELECT s.a FROM (SELECT * FROM sl WHERE c IS NOT NULL) s, sl t +WHERE t.a = s.a AND t.b = s.b; + +EXPLAIN (COSTS OFF) +SELECT t1.a, ss.a FROM sl t1 + LEFT JOIN (SELECT s.a FROM (SELECT * FROM sl WHERE c IS NOT NULL) s + JOIN sl t ON t.a = s.a AND t.b = s.b) ss + ON ss.a = t1.a; + -- Check optimization disabling if it will violate special join conditions. -- Two identical joined relations satisfies self join removal conditions but -- stay in different special join infos. -- 2.52.0
v4-0003-Remove-dead-code-that-s-no-longer-needed-for-join.patch (text/x-diff, 64.1K) download From e2c82f735404c2b83ada0966da335f06f49fb7c5 Mon Sep 17 00:00:00 2001 From: Tom Lane <tgl@sss.pgh.pa.us> Date: Sun, 26 Jul 2026 11:44:15 -0400 Subject: [PATCH v4 3/5] Remove dead code that's no longer needed for join removal. This is mostly a straightforward exercise in deleting unreferenced functions, but a couple of points are worth noting. While replace_relid_callback() was still reached in the previous patch, it did nothing since we no longer invoked it on any trees containing RangeTblRef or RestrictInfo nodes. So we can delete it and make the two remaining users use ChangeVarNodes instead of ChangeVarNodesExtended. Then, ChangeVarNodesExtended is unused and we can remove that too, along with the exposed definition of ChangeVarNodes_context (basically reverting that area of the code to what it was in v17). ec_clear_derived_clauses, innerrel_is_unique_ext, adjust_relid_set are now static since they're no longer called from outside their modules. Bug: #19560 Reported-by: Orestis Markou <orestis@orestis.gr> Author: Tom Lane <tgl@sss.pgh.pa.us> Discussion: https://postgr.es/m/1186816.1784573544@sss.pgh.pa.us --- src/backend/optimizer/path/equivclass.c | 51 +- src/backend/optimizer/plan/analyzejoins.c | 1037 +-------------------- src/backend/optimizer/plan/initsplan.c | 179 +--- src/backend/optimizer/util/joininfo.c | 36 - src/backend/optimizer/util/placeholder.c | 27 - src/backend/rewrite/rewriteManip.c | 65 +- src/include/optimizer/joininfo.h | 3 - src/include/optimizer/paths.h | 2 - src/include/optimizer/placeholder.h | 1 - src/include/optimizer/planmain.h | 8 - src/include/rewrite/rewriteManip.h | 19 - src/tools/pgindent/typedefs.list | 1 - 12 files changed, 30 insertions(+), 1399 deletions(-) diff --git a/src/backend/optimizer/path/equivclass.c b/src/backend/optimizer/path/equivclass.c index e3697df51a2..66fe1c24a58 100644 --- a/src/backend/optimizer/path/equivclass.c +++ b/src/backend/optimizer/path/equivclass.c @@ -89,6 +89,7 @@ static void ec_build_derives_hash(PlannerInfo *root, EquivalenceClass *ec); static void ec_add_derived_clauses(EquivalenceClass *ec, List *clauses); static void ec_add_derived_clause(EquivalenceClass *ec, RestrictInfo *clause); static void ec_add_clause_to_derives_hash(EquivalenceClass *ec, RestrictInfo *rinfo); +static void ec_clear_derived_clauses(EquivalenceClass *ec); static RestrictInfo *ec_search_clause_for_ems(PlannerInfo *root, EquivalenceClass *ec, EquivalenceMember *leftem, EquivalenceMember *rightem, @@ -1452,8 +1453,7 @@ generate_base_implied_equalities_no_const(PlannerInfo *root, * For the moment we force all the Vars to be available at all join nodes * for this eclass. Perhaps this could be improved by doing some * pre-analysis of which members we prefer to join, but it's no worse than - * what happened in the pre-8.3 code. (Note: rebuild_eclass_attr_needed - * needs to match this code.) + * what happened in the pre-8.3 code. */ foreach(lc, ec->ec_members) { @@ -2560,51 +2560,6 @@ reconsider_full_join_clause(PlannerInfo *root, OuterJoinClauseInfo *ojcinfo) return false; /* failed to make any deduction */ } -/* - * rebuild_eclass_attr_needed - * Put back attr_needed bits for Vars/PHVs needed for join eclasses. - * - * This is used to rebuild attr_needed/ph_needed sets after removal of a - * useless outer join. It should match what - * generate_base_implied_equalities_no_const did, except that we call - * add_vars_to_attr_needed not add_vars_to_targetlist. - */ -void -rebuild_eclass_attr_needed(PlannerInfo *root) -{ - ListCell *lc; - - foreach(lc, root->eq_classes) - { - EquivalenceClass *ec = (EquivalenceClass *) lfirst(lc); - - /* - * 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); - - /* Need do anything only for a multi-member, no-const EC. */ - if (list_length(ec->ec_members) > 1 && !ec->ec_has_const) - { - ListCell *lc2; - - foreach(lc2, ec->ec_members) - { - EquivalenceMember *cur_em = (EquivalenceMember *) lfirst(lc2); - List *vars = pull_var_clause((Node *) cur_em->em_expr, - PVC_RECURSE_AGGREGATES | - PVC_RECURSE_WINDOWFUNCS | - PVC_INCLUDE_PLACEHOLDERS); - - add_vars_to_attr_needed(root, vars, ec->ec_relids); - list_free(vars); - } - } - } -} - /* * find_join_domain * Find the highest JoinDomain enclosed within the given relid set. @@ -3826,7 +3781,7 @@ ec_add_clause_to_derives_hash(EquivalenceClass *ec, RestrictInfo *rinfo) * when thousands of partitions are involved, so we free it as well -- even * though we do not typically free lists. */ -void +static void ec_clear_derived_clauses(EquivalenceClass *ec) { list_free(ec->ec_derives_list); diff --git a/src/backend/optimizer/plan/analyzejoins.c b/src/backend/optimizer/plan/analyzejoins.c index ef355ec1fe1..a038b898bdb 100644 --- a/src/backend/optimizer/plan/analyzejoins.c +++ b/src/backend/optimizer/plan/analyzejoins.c @@ -30,11 +30,9 @@ #include "catalog/pg_class.h" #include "nodes/makefuncs.h" #include "nodes/nodeFuncs.h" -#include "optimizer/joininfo.h" #include "optimizer/optimizer.h" #include "optimizer/pathnode.h" #include "optimizer/paths.h" -#include "optimizer/placeholder.h" #include "optimizer/planmain.h" #include "optimizer/prep.h" #include "optimizer/restrictinfo.h" @@ -62,20 +60,6 @@ bool enable_self_join_elimination; /* local functions */ static bool join_is_removable(PlannerInfo *root, SpecialJoinInfo *sjinfo); -static void remove_leftjoinrel_from_query(PlannerInfo *root, int relid, - SpecialJoinInfo *sjinfo); -static void remove_rel_from_query(PlannerInfo *root, int relid, - int subst, SpecialJoinInfo *sjinfo, - Relids joinrelids); -static void remove_rel_from_restrictinfo(RestrictInfo *rinfo, - int relid, int ojrelid); -static void remove_rel_from_eclass(PlannerInfo *root, EquivalenceClass *ec, - int relid, int ojrelid); -static void remove_rel_from_restrictinfo_phvs(RestrictInfo *rinfo, - int relid, int ojrelid); -static Node *remove_rel_from_phvs(Node *node, int relid, int ojrelid); -static Node *remove_rel_from_phvs_mutator(Node *node, Relids removable); -static List *remove_rel_from_joinlist(List *joinlist, int relid, int *nremoved); static Node *remove_join_from_jointree(Node *jtnode, int ojrelid, int *nremoved); static void remove_rels_from_query_tree(PlannerInfo *root, @@ -85,6 +69,14 @@ static bool rel_supports_distinctness(PlannerInfo *root, RelOptInfo *rel); static bool rel_is_distinct_for(PlannerInfo *root, RelOptInfo *rel, List *clause_list, List **extra_clauses); static DistinctColInfo *distinct_col_search(int colno, List *distinct_cols); +static bool innerrel_is_unique_ext(PlannerInfo *root, + Relids joinrelids, + Relids outerrelids, + RelOptInfo *innerrel, + JoinType jointype, + List *restrictlist, + bool force_cache, + List **extra_clauses); static bool is_innerrel_unique_for(PlannerInfo *root, Relids joinrelids, Relids outerrelids, @@ -100,8 +92,6 @@ static void fixup_selfjoin_jointree(PlannerInfo *root, Node *jtnode, 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); -static bool replace_relid_callback(Node *node, - ChangeVarNodes_context *context); /* @@ -367,713 +357,6 @@ join_is_removable(PlannerInfo *root, SpecialJoinInfo *sjinfo) return false; } -/* - * 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. - * - * 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. - * - * This function serves as the common infrastructure for left-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). - */ -static void -remove_rel_from_query(PlannerInfo *root, int relid, - int subst, SpecialJoinInfo *sjinfo, - Relids joinrelids) -{ - 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); - Bitmapset *seen_serials = NULL; - - Assert(is_outer_join || is_self_join); - Assert(!is_outer_join || ojrelid > 0); - Assert(!is_outer_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) - { - root->outer_join_rels = bms_del_member(root->outer_join_rels, ojrelid); - root->all_query_rels = bms_del_member(root->all_query_rels, ojrelid); - } - - /* - * 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) - { - SpecialJoinInfo *sjinf = (SpecialJoinInfo *) lfirst(l); - - /* - * 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 - { - /* - * For self-join removal, replace relid references in - * semi_rhs_exprs. - */ - ChangeVarNodesExtended((Node *) sjinf->semi_rhs_exprs, relid, subst, - 0, replace_relid_callback); - } - } - - /* - * Likewise remove references from PlaceHolderVar data structures, - * removing any no-longer-needed placeholders entirely. We only remove - * PHVs for left-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 is no corresponding test in - * join_is_removable because it doesn't need to distinguish those cases. - */ - foreach(l, root->placeholder_list) - { - PlaceHolderInfo *phinfo = (PlaceHolderInfo *) lfirst(l); - - Assert(!is_outer_join || !bms_is_member(relid, phinfo->ph_lateral)); - - if (is_outer_join && - bms_is_subset(phinfo->ph_needed, joinrelids) && - bms_is_member(relid, phinfo->ph_eval_at) && - !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 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.) - */ - 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) - { - foreach(l, root->eq_classes) - { - EquivalenceClass *ec = (EquivalenceClass *) lfirst(l); - - remove_rel_from_eclass(root, ec, relid, ojrelid); - } - } - - /* - * 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 removal, we strip the removed rel and join from any - * PlaceHolderVar embedded in the surviving rels' restriction clauses and - * join clauses; 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 && rti != relid && root->glob->lastPHId != 0) - { - foreach_node(RestrictInfo, rinfo, otherrel->baserestrictinfo) - remove_rel_from_restrictinfo_phvs(rinfo, relid, ojrelid); - - /* - * Join clauses need the same treatment, but there's no value in - * processing any join clause more than once. So it's slightly - * annoying that we have to find them via the per-base-relation - * joininfo lists. Avoid duplicate processing by tracking the - * rinfo_serial numbers of join clauses we've already seen. (This - * doesn't work for is_clone clauses, so we must waste effort on - * them.) - */ - foreach_node(RestrictInfo, rinfo, otherrel->joininfo) - { - if (!rinfo->is_clone) /* else serial number is not unique */ - { - if (bms_is_member(rinfo->rinfo_serial, seen_serials)) - continue; /* saw it already */ - seen_serials = bms_add_member(seen_serials, - rinfo->rinfo_serial); - } - remove_rel_from_restrictinfo_phvs(rinfo, relid, ojrelid); - } - } - } -} - -/* - * Remove any references to relid or ojrelid from the RestrictInfo. - * - * 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); - 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); - 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); - 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); - 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); - 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); - 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. - * - * 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. - */ -static void -remove_rel_from_eclass(PlannerInfo *root, EquivalenceClass *ec, - int relid, int ojrelid) -{ - 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) && - !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); - 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) || - 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); - 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 relid or ojrelid from the PlaceHolderVars embedded - * in a RestrictInfo's clause. - * - * If it's an OR clause, we must also fix up the orclause, which is a parallel - * representation built from its own sub-RestrictInfos. We recurse into the - * sub-clauses for that, mirroring remove_rel_from_restrictinfo. - */ -static void -remove_rel_from_restrictinfo_phvs(RestrictInfo *rinfo, int relid, int ojrelid) -{ - rinfo->clause = (Expr *) - remove_rel_from_phvs((Node *) rinfo->clause, relid, 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_phvs(rinfo2, relid, ojrelid); - } - } - else - { - RestrictInfo *rinfo2 = castNode(RestrictInfo, orarg); - - remove_rel_from_restrictinfo_phvs(rinfo2, relid, ojrelid); - } - } - } -} - -/* - * 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); -} - -static Node * -remove_rel_from_phvs_mutator(Node *node, Relids removable) -{ - if (node == NULL) - return NULL; - if (IsA(node, PlaceHolderVar)) - { - 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); - - /* - * ... 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. - */ - newphrels = bms_difference(phv->phrels, removable); - if (!bms_is_empty(newphrels)) - { - phv->phrels = newphrels; - phv->phnullingrels = bms_difference(phv->phnullingrels, - removable); - } - - return (Node *) phv; - } - 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; -} - - /* * remove_join_from_jointree * Delete the JoinExpr with the given RT index, along with everything @@ -1731,7 +1014,7 @@ innerrel_is_unique(PlannerInfo *root, * A non-NULL extra_clauses indicates that we're checking for self-join and * correspondingly dealing with filtered clauses. */ -bool +static bool innerrel_is_unique_ext(PlannerInfo *root, Relids joinrelids, Relids outerrelids, @@ -1910,298 +1193,6 @@ is_innerrel_unique_for(PlannerInfo *root, return rel_is_distinct_for(root, innerrel, clause_list, extra_clauses); } -/* - * Update EC members to point to the remaining relation instead of the removed - * one, removing duplicates. - * - * Restriction clauses for base relations are already distributed to - * the respective baserestrictinfo lists (see - * generate_implied_equalities_for_column). The above code has already processed - * this list and updated these clauses to reference the remaining - * relation, so that we can skip them here based on their relids. - * - * Likewise, we have already processed the join clauses that join the - * removed relation to the remaining one. - * - * Finally, there might be join clauses tying the removed relation to - * some third relation. We can't just delete the source clauses and - * regenerate them from the EC because the corresponding equality - * operators might be missing (see the handling of ec_broken). - * Therefore, we will update the references in the source clauses. - * - * Derived clauses can be generated again, so it is simpler just to - * delete them. - */ -static void -update_eclasses(EquivalenceClass *ec, int from, int to) -{ - List *new_members = NIL; - List *new_sources = NIL; - - /* - * 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); - - foreach_node(EquivalenceMember, em, ec->ec_members) - { - bool is_redundant = false; - - if (!bms_is_member(from, em->em_relids)) - { - new_members = lappend(new_members, em); - continue; - } - - em->em_relids = adjust_relid_set(em->em_relids, from, to); - em->em_jdomain->jd_relids = adjust_relid_set(em->em_jdomain->jd_relids, from, to); - - /* We only process inner joins */ - ChangeVarNodesExtended((Node *) em->em_expr, from, to, 0, - replace_relid_callback); - - foreach_node(EquivalenceMember, other, new_members) - { - if (!equal(em->em_relids, other->em_relids)) - continue; - - if (equal(em->em_expr, other->em_expr)) - { - is_redundant = true; - break; - } - } - - if (!is_redundant) - new_members = lappend(new_members, em); - } - - list_free(ec->ec_members); - ec->ec_members = new_members; - - ec_clear_derived_clauses(ec); - - /* Update EC source expressions */ - foreach_node(RestrictInfo, rinfo, ec->ec_sources) - { - bool is_redundant = false; - - if (!bms_is_member(from, rinfo->required_relids)) - { - new_sources = lappend(new_sources, rinfo); - continue; - } - - ChangeVarNodesExtended((Node *) rinfo, from, to, 0, - replace_relid_callback); - - /* - * After switching the clause to the remaining relation, check it for - * redundancy with existing ones. We don't have to check for - * redundancy with derived clauses, because we've just deleted them. - */ - foreach_node(RestrictInfo, other, new_sources) - { - if (!equal(rinfo->clause_relids, other->clause_relids)) - continue; - - if (equal(rinfo->clause, other->clause)) - { - is_redundant = true; - break; - } - } - - if (!is_redundant) - new_sources = lappend(new_sources, rinfo); - } - - list_free(ec->ec_sources); - ec->ec_sources = new_sources; - ec->ec_relids = adjust_relid_set(ec->ec_relids, from, to); -} - -/* - * "Logically" compares two RestrictInfo's ignoring the 'rinfo_serial' field, - * which makes almost every RestrictInfo unique. This type of comparison is - * useful when removing duplicates while moving RestrictInfo's from removed - * relation to remaining relation during self-join elimination. - * - * XXX: In the future, we might remove the 'rinfo_serial' field completely and - * get rid of this function. - */ -static bool -restrict_infos_logically_equal(RestrictInfo *a, RestrictInfo *b) -{ - int saved_rinfo_serial = a->rinfo_serial; - bool result; - - a->rinfo_serial = b->rinfo_serial; - result = equal(a, b); - a->rinfo_serial = saved_rinfo_serial; - - return result; -} - -/* - * This function adds all non-redundant clauses to the keeping relation - * during self-join elimination. That is a contradictory operation. On the - * one hand, we reduce the length of the `restrict` lists, which can - * impact planning or executing time. Additionally, we improve the - * accuracy of cardinality estimation. On the other hand, it is one more - * place that can make planning time much longer in specific cases. It - * would have been better to avoid calling the equal() function here, but - * it's the only way to detect duplicated inequality expressions. - * - * (*keep_rinfo_list) is given by pointer because it might be altered by - * distribute_restrictinfo_to_rels(). - */ -static void -add_non_redundant_clauses(PlannerInfo *root, - List *rinfo_candidates, - List **keep_rinfo_list, - Index removed_relid) -{ - foreach_node(RestrictInfo, rinfo, rinfo_candidates) - { - bool is_redundant = false; - - Assert(!bms_is_member(removed_relid, rinfo->required_relids)); - - foreach_node(RestrictInfo, src, (*keep_rinfo_list)) - { - if (!bms_equal(src->clause_relids, rinfo->clause_relids)) - /* Can't compare trivially different clauses */ - continue; - - if (src == rinfo || - (rinfo->parent_ec != NULL && - src->parent_ec == rinfo->parent_ec) || - restrict_infos_logically_equal(rinfo, src)) - { - is_redundant = true; - break; - } - } - if (!is_redundant) - distribute_restrictinfo_to_rels(root, rinfo); - } -} - -/* - * A custom callback for ChangeVarNodesExtended() providing Self-join - * elimination (SJE) related functionality - * - * SJE needs to skip the RangeTblRef node type. During SJE's last - * step, remove_rel_from_joinlist() removes remaining RangeTblRefs - * with target relid. If ChangeVarNodes() replaces the target relid - * before, remove_rel_from_joinlist() would fail to identify the nodes - * to delete. - * - * SJE also needs to change the relids within RestrictInfo's. - */ -static bool -replace_relid_callback(Node *node, ChangeVarNodes_context *context) -{ - if (IsA(node, RangeTblRef)) - { - return true; - } - else if (IsA(node, RestrictInfo)) - { - RestrictInfo *rinfo = (RestrictInfo *) node; - int relid = -1; - bool is_req_equal = - (rinfo->required_relids == rinfo->clause_relids); - bool clause_relids_is_multiple = - (bms_membership(rinfo->clause_relids) == BMS_MULTIPLE); - - /* - * Recurse down into clauses if the target relation is present in - * clause_relids or required_relids. We must check required_relids - * because the relation not present in clause_relids might still be - * present somewhere in orclause. - */ - if (bms_is_member(context->rt_index, rinfo->clause_relids) || - bms_is_member(context->rt_index, rinfo->required_relids)) - { - Relids new_clause_relids; - - ChangeVarNodesWalkExpression((Node *) rinfo->clause, context); - ChangeVarNodesWalkExpression((Node *) rinfo->orclause, context); - - new_clause_relids = adjust_relid_set(rinfo->clause_relids, - context->rt_index, - context->new_index); - - /* - * Incrementally adjust num_base_rels based on the change of - * clause_relids, which could contain both base relids and - * outer-join relids. This operation is legal until we remove - * only baserels. - */ - rinfo->num_base_rels -= bms_num_members(rinfo->clause_relids) - - bms_num_members(new_clause_relids); - - rinfo->clause_relids = new_clause_relids; - rinfo->left_relids = - adjust_relid_set(rinfo->left_relids, context->rt_index, context->new_index); - rinfo->right_relids = - adjust_relid_set(rinfo->right_relids, context->rt_index, context->new_index); - } - - if (is_req_equal) - rinfo->required_relids = rinfo->clause_relids; - else - rinfo->required_relids = - adjust_relid_set(rinfo->required_relids, context->rt_index, context->new_index); - - rinfo->outer_relids = - adjust_relid_set(rinfo->outer_relids, context->rt_index, context->new_index); - rinfo->incompatible_relids = - adjust_relid_set(rinfo->incompatible_relids, context->rt_index, context->new_index); - - if (rinfo->mergeopfamilies && - bms_get_singleton_member(rinfo->clause_relids, &relid) && - clause_relids_is_multiple && - relid == context->new_index && IsA(rinfo->clause, OpExpr)) - { - Expr *leftOp; - Expr *rightOp; - - leftOp = (Expr *) get_leftop(rinfo->clause); - rightOp = (Expr *) get_rightop(rinfo->clause); - - /* - * For self-join elimination, changing varnos could transform - * "t1.a = t2.a" into "t1.a = t1.a". That is always true as long - * as "t1.a" is not null. We use equal() to check for such a - * case, and then we replace the qual with a check for not null - * (NullTest). - */ - if (leftOp != NULL && equal(leftOp, rightOp)) - { - NullTest *ntest = makeNode(NullTest); - - ntest->arg = leftOp; - ntest->nulltesttype = IS_NOT_NULL; - ntest->argisrow = false; - ntest->location = -1; - rinfo->clause = (Expr *) ntest; - rinfo->mergeopfamilies = NIL; - rinfo->left_em = NULL; - rinfo->right_em = NULL; - } - Assert(rinfo->orclause == NULL); - } - return true; - } - - return false; -} - /* * Remove the toRemove relation after we have proven that it participates only * in an unneeded unique self-join with toKeep. @@ -2604,10 +1595,9 @@ split_selfjoin_quals(PlannerInfo *root, List *joinquals, List **selfjoinquals, * when we have cast of the same var to different (but compatible) * types. */ - ChangeVarNodesExtended(rightexpr, - bms_singleton_member(rinfo->right_relids), - bms_singleton_member(rinfo->left_relids), 0, - replace_relid_callback); + ChangeVarNodes(rightexpr, + bms_singleton_member(rinfo->right_relids), + bms_singleton_member(rinfo->left_relids), 0); if (equal(leftexpr, rightexpr)) sjoinquals = lappend(sjoinquals, rinfo); @@ -2643,8 +1633,7 @@ match_unique_clauses(PlannerInfo *root, RelOptInfo *outer, List *uclauses, bms_is_empty(rinfo->right_relids)); clause = (Expr *) copyObject(rinfo->clause); - ChangeVarNodesExtended((Node *) clause, relid, outer->relid, 0, - replace_relid_callback); + ChangeVarNodes((Node *) clause, relid, outer->relid, 0); iclause = bms_is_empty(rinfo->left_relids) ? get_rightop(clause) : get_leftop(clause); diff --git a/src/backend/optimizer/plan/initsplan.c b/src/backend/optimizer/plan/initsplan.c index 7b6d7249c66..d8a5c242eef 100644 --- a/src/backend/optimizer/plan/initsplan.c +++ b/src/backend/optimizer/plan/initsplan.c @@ -295,8 +295,6 @@ build_base_rel_tlists(PlannerInfo *root, List *final_tlist) * have a single owning relation; we keep their attr_needed info in * root->placeholder_list instead. Find or create the associated * PlaceHolderInfo entry, and update its ph_needed. - * - * See also add_vars_to_attr_needed. */ void add_vars_to_targetlist(PlannerInfo *root, List *vars, @@ -350,63 +348,6 @@ add_vars_to_targetlist(PlannerInfo *root, List *vars, } } -/* - * add_vars_to_attr_needed - * This does a subset of what add_vars_to_targetlist does: it just - * updates attr_needed for Vars and ph_needed for PlaceHolderVars. - * We assume the Vars are already in their relations' targetlists. - * - * This is used to rebuild attr_needed/ph_needed sets after removal - * of a useless outer join. The removed join clause might have been - * the only upper-level use of some other relation's Var, in which - * case we can reduce that Var's attr_needed and thereby possibly - * open the door to further join removals. But we can't tell that - * without tedious reconstruction of the attr_needed data. - * - * Note that if a Var's attr_needed is successfully reduced to empty, - * it will still be in the relation's targetlist even though we do - * not really need the scan plan node to emit it. The extra plan - * inefficiency seems tiny enough to not be worth spending planner - * cycles to get rid of it. - */ -void -add_vars_to_attr_needed(PlannerInfo *root, List *vars, - Relids where_needed) -{ - ListCell *temp; - - Assert(!bms_is_empty(where_needed)); - - foreach(temp, vars) - { - Node *node = (Node *) lfirst(temp); - - if (IsA(node, Var)) - { - Var *var = (Var *) node; - RelOptInfo *rel = find_base_rel(root, var->varno); - int attno = var->varattno; - - if (bms_is_subset(where_needed, rel->relids)) - continue; - Assert(attno >= rel->min_attr && attno <= rel->max_attr); - attno -= rel->min_attr; - rel->attr_needed[attno] = bms_add_members(rel->attr_needed[attno], - where_needed); - } - else if (IsA(node, PlaceHolderVar)) - { - PlaceHolderVar *phv = (PlaceHolderVar *) node; - PlaceHolderInfo *phinfo = find_placeholder_info(root, phv); - - phinfo->ph_needed = bms_add_members(phinfo->ph_needed, - where_needed); - } - else - elog(ERROR, "unrecognized node type: %d", (int) nodeTag(node)); - } -} - /***************************************************************************** * * GROUP BY @@ -1226,54 +1167,10 @@ extract_lateral_references(PlannerInfo *root, RelOptInfo *brel, Index rtindex) */ add_vars_to_targetlist(root, newvars, where_needed); - /* - * Remember the lateral references for rebuild_lateral_attr_needed and - * create_lateral_join_info. - */ + /* Remember the lateral references for create_lateral_join_info */ brel->lateral_vars = newvars; } -/* - * rebuild_lateral_attr_needed - * Put back attr_needed bits for Vars/PHVs needed for lateral references. - * - * This is used to rebuild attr_needed/ph_needed sets after removal of a - * useless outer join. It should match what find_lateral_references did, - * except that we call add_vars_to_attr_needed not add_vars_to_targetlist. - */ -void -rebuild_lateral_attr_needed(PlannerInfo *root) -{ - Index rti; - - /* We need do nothing if the query contains no LATERAL RTEs */ - if (!root->hasLateralRTEs) - return; - - /* Examine the same baserels that find_lateral_references did */ - for (rti = 1; rti < root->simple_rel_array_size; rti++) - { - RelOptInfo *brel = root->simple_rel_array[rti]; - Relids where_needed; - - if (brel == NULL) - continue; - if (brel->reloptkind != RELOPT_BASEREL) - continue; - - /* - * We don't need to repeat all of extract_lateral_references, since it - * kindly saved the extracted Vars/PHVs in lateral_vars. - */ - if (brel->lateral_vars == NIL) - continue; - - where_needed = bms_make_singleton(rti); - - add_vars_to_attr_needed(root, brel->lateral_vars, where_needed); - } -} - /* * create_lateral_join_info * Fill in the per-base-relation direct_lateral_relids, lateral_relids @@ -3227,9 +3124,6 @@ distribute_qual_to_rels(PlannerInfo *root, Node *clause, * var propagation is ensured by making ojscope include input rels from * both sides of the join. * - * See also rebuild_joinclause_attr_needed, which has to partially repeat - * this work after removal of an outer join. - * * Note: if the clause gets absorbed into an EquivalenceClass then this * may be unnecessary, but for now we have to do it to cover the case * where the EC becomes ec_broken and we end up reinserting the original @@ -3803,11 +3697,6 @@ process_implied_equality(PlannerInfo *root, * some of the Vars could have missed having that done because they only * appeared in single-relation clauses originally. So do it here for * safety. - * - * See also rebuild_joinclause_attr_needed, which has to partially repeat - * this work after removal of an outer join. (Since we will put this - * clause into the joininfo lists, that function needn't do any extra work - * to find it.) */ if (bms_membership(relids) == BMS_MULTIPLE) { @@ -3949,72 +3838,6 @@ get_join_domain_min_rels(PlannerInfo *root, Relids domain_relids) } -/* - * rebuild_joinclause_attr_needed - * Put back attr_needed bits for Vars/PHVs needed for join clauses. - * - * This is used to rebuild attr_needed/ph_needed sets after removal of a - * useless outer join. It should match what distribute_qual_to_rels did, - * except that we call add_vars_to_attr_needed not add_vars_to_targetlist. - */ -void -rebuild_joinclause_attr_needed(PlannerInfo *root) -{ - /* - * We must examine all join clauses, but there's no value in processing - * any join clause more than once. So it's slightly annoying that we have - * to find them via the per-base-relation joininfo lists. Avoid duplicate - * processing by tracking the rinfo_serial numbers of join clauses we've - * already seen. (This doesn't work for is_clone clauses, so we must - * waste effort on them.) - */ - Bitmapset *seen_serials = NULL; - Index rti; - - /* Scan all baserels for join clauses */ - for (rti = 1; rti < root->simple_rel_array_size; rti++) - { - RelOptInfo *brel = root->simple_rel_array[rti]; - ListCell *lc; - - if (brel == NULL) - continue; - if (brel->reloptkind != RELOPT_BASEREL) - continue; - - foreach(lc, brel->joininfo) - { - RestrictInfo *rinfo = (RestrictInfo *) lfirst(lc); - Relids relids = rinfo->required_relids; - - if (!rinfo->is_clone) /* else serial number is not unique */ - { - if (bms_is_member(rinfo->rinfo_serial, seen_serials)) - continue; /* saw it already */ - seen_serials = bms_add_member(seen_serials, - rinfo->rinfo_serial); - } - - if (bms_membership(relids) == BMS_MULTIPLE) - { - List *vars = pull_var_clause((Node *) rinfo->clause, - PVC_RECURSE_AGGREGATES | - PVC_RECURSE_WINDOWFUNCS | - PVC_INCLUDE_PLACEHOLDERS); - Relids where_needed; - - if (rinfo->is_clone) - where_needed = bms_intersect(relids, root->all_baserels); - else - where_needed = relids; - add_vars_to_attr_needed(root, vars, where_needed); - list_free(vars); - } - } - } -} - - /* * match_foreign_keys_to_quals * Match foreign-key constraints to equivalence classes and join quals diff --git a/src/backend/optimizer/util/joininfo.c b/src/backend/optimizer/util/joininfo.c index ef2f054c39e..f75e35f22ae 100644 --- a/src/backend/optimizer/util/joininfo.c +++ b/src/backend/optimizer/util/joininfo.c @@ -145,39 +145,3 @@ add_join_clause_to_rels(PlannerInfo *root, rel->joininfo = lappend(rel->joininfo, restrictinfo); } } - -/* - * remove_join_clause_from_rels - * Delete 'restrictinfo' from all the joininfo lists it is in - * - * This reverses the effect of add_join_clause_to_rels. It's used when we - * discover that a relation need not be joined at all. - * - * 'restrictinfo' describes the join clause - * 'join_relids' is the set of relations participating in the join clause - * (some of these could be outer joins) - */ -void -remove_join_clause_from_rels(PlannerInfo *root, - RestrictInfo *restrictinfo, - Relids join_relids) -{ - int cur_relid; - - cur_relid = -1; - while ((cur_relid = bms_next_member(join_relids, cur_relid)) >= 0) - { - RelOptInfo *rel = find_base_rel_ignore_join(root, cur_relid); - - /* We would only have added the clause to baserels */ - if (rel == NULL) - continue; - - /* - * Remove the restrictinfo from the list. Pointer comparison is - * sufficient. - */ - Assert(list_member_ptr(rel->joininfo, restrictinfo)); - rel->joininfo = list_delete_ptr(rel->joininfo, restrictinfo); - } -} diff --git a/src/backend/optimizer/util/placeholder.c b/src/backend/optimizer/util/placeholder.c index dd9b11885af..07171f84f61 100644 --- a/src/backend/optimizer/util/placeholder.c +++ b/src/backend/optimizer/util/placeholder.c @@ -316,33 +316,6 @@ fix_placeholder_input_needed_levels(PlannerInfo *root) } } -/* - * rebuild_placeholder_attr_needed - * Put back attr_needed bits for Vars/PHVs needed in PlaceHolderVars. - * - * This is used to rebuild attr_needed/ph_needed sets after removal of a - * useless outer join. It should match what - * fix_placeholder_input_needed_levels did, except that we call - * add_vars_to_attr_needed not add_vars_to_targetlist. - */ -void -rebuild_placeholder_attr_needed(PlannerInfo *root) -{ - ListCell *lc; - - foreach(lc, root->placeholder_list) - { - PlaceHolderInfo *phinfo = (PlaceHolderInfo *) lfirst(lc); - List *vars = pull_var_clause((Node *) phinfo->ph_var->phexpr, - PVC_RECURSE_AGGREGATES | - PVC_RECURSE_WINDOWFUNCS | - PVC_INCLUDE_PLACEHOLDERS); - - add_vars_to_attr_needed(root, vars, phinfo->ph_eval_at); - list_free(vars); - } -} - /* * add_placeholders_to_base_rels * Add any required PlaceHolderVars to base rels' targetlists. diff --git a/src/backend/rewrite/rewriteManip.c b/src/backend/rewrite/rewriteManip.c index 9c9d1cad33b..330ec596162 100644 --- a/src/backend/rewrite/rewriteManip.c +++ b/src/backend/rewrite/rewriteManip.c @@ -64,6 +64,7 @@ static bool contain_windowfuncs_walker(Node *node, void *context); static bool locate_windowfunc_walker(Node *node, locate_windowfunc_context *context); static bool checkExprHasSubLink_walker(Node *node, void *context); +static Relids adjust_relid_set(Relids relids, int oldrelid, int newrelid); static Node *add_nulling_relids_mutator(Node *node, add_nulling_relids_context *context); static Node *remove_nulling_relids_mutator(Node *node, @@ -528,23 +529,27 @@ OffsetVarNodes(Node *node, int offset, int sublevels_up) * * Find all Var nodes in the given tree belonging to a specific relation * (identified by sublevels_up and rt_index), and change their varno fields - * to 'new_index'. The varnosyn fields are changed too. Also, adjust other - * nodes that contain rangetable indexes, such as RangeTblRef and JoinExpr. + * to 'new_index' (see adjust_relid_set for the exact change behavior). + * The varnosyn fields are changed too. Also adjust other nodes that + * contain rangetable indexes, such as RangeTblRef and JoinExpr. * * NOTE: although this has the form of a walker, we cheat and modify the * nodes in-place. The given expression tree should have been copied * earlier to ensure that no unwanted side-effects occur! */ +typedef struct +{ + int rt_index; + int new_index; + int sublevels_up; +} ChangeVarNodes_context; + static bool ChangeVarNodes_walker(Node *node, ChangeVarNodes_context *context) { if (node == NULL) return false; - - if (context->callback && context->callback(node, context)) - return false; - if (IsA(node, Var)) { Var *var = (Var *) node; @@ -649,28 +654,14 @@ ChangeVarNodes_walker(Node *node, ChangeVarNodes_context *context) return expression_tree_walker(node, ChangeVarNodes_walker, context); } -/* - * ChangeVarNodesExtended - similar to ChangeVarNodes, but with an additional - * 'callback' param - * - * ChangeVarNodes changes a given node and all of its underlying nodes. This - * version of function additionally takes a callback, which has a chance to - * process a node before ChangeVarNodes_walker. A callback returns a boolean - * value indicating if the given node should be skipped from further processing - * by ChangeVarNodes_walker. The callback is called only for expressions and - * other children nodes of a Query processed by a walker. Initial processing - * of the root Query node doesn't invoke the callback. - */ void -ChangeVarNodesExtended(Node *node, int rt_index, int new_index, - int sublevels_up, ChangeVarNodes_callback callback) +ChangeVarNodes(Node *node, int rt_index, int new_index, int sublevels_up) { ChangeVarNodes_context context; context.rt_index = rt_index; context.new_index = new_index; context.sublevels_up = sublevels_up; - context.callback = callback; /* * Must be prepared to start with a Query or a bare expression tree; if @@ -717,36 +708,6 @@ ChangeVarNodesExtended(Node *node, int rt_index, int new_index, ChangeVarNodes_walker(node, &context); } -void -ChangeVarNodes(Node *node, int rt_index, int new_index, int sublevels_up) -{ - ChangeVarNodesExtended(node, rt_index, new_index, sublevels_up, NULL); -} - -/* - * ChangeVarNodesWalkExpression - process subexpression within a callback - * function passed to ChangeVarNodesExtended. - * - * This is intended to be used by a callback that needs to recursively - * process subexpressions of some node being visited by an outer - * ChangeVarNodesExtended call, instead of relying on ChangeVarNodes_walker's - * default recursion. We invoke ChangeVarNodes_walker directly rather than - * via expression_tree_walker, because expression_tree_walker only visits - * child nodes and would fail to process the passed node itself -- - * for example, a bare Var node would not get its varno adjusted. - * - * Because this calls ChangeVarNodes_walker directly, if the passed node is - * a Query, it will be treated as a sub-Query: sublevels_up is incremented - * before recursing into it, and Query-level fields (resultRelation, - * mergeTargetRelation, rowMarks, etc.) will not be adjusted. Do not apply - * this to a top-level Query node; use ChangeVarNodesExtended for that. - */ -bool -ChangeVarNodesWalkExpression(Node *node, ChangeVarNodes_context *context) -{ - return ChangeVarNodes_walker(node, context); -} - /* * adjust_relid_set - substitute newrelid for oldrelid in a Relid set * @@ -756,7 +717,7 @@ ChangeVarNodesWalkExpression(Node *node, ChangeVarNodes_context *context) * a special varno, this function does nothing. When newrelid is a special * varno, this function behaves as delete. */ -Relids +static Relids adjust_relid_set(Relids relids, int oldrelid, int newrelid) { if (!IS_SPECIAL_VARNO(oldrelid) && bms_is_member(oldrelid, relids)) diff --git a/src/include/optimizer/joininfo.h b/src/include/optimizer/joininfo.h index 117195fbcfa..aa26cc670f9 100644 --- a/src/include/optimizer/joininfo.h +++ b/src/include/optimizer/joininfo.h @@ -23,8 +23,5 @@ extern bool have_relevant_joinclause(PlannerInfo *root, extern void add_join_clause_to_rels(PlannerInfo *root, RestrictInfo *restrictinfo, Relids join_relids); -extern void remove_join_clause_from_rels(PlannerInfo *root, - RestrictInfo *restrictinfo, - Relids join_relids); #endif /* JOININFO_H */ diff --git a/src/include/optimizer/paths.h b/src/include/optimizer/paths.h index 17f2099ec3b..051e38c1189 100644 --- a/src/include/optimizer/paths.h +++ b/src/include/optimizer/paths.h @@ -137,7 +137,6 @@ extern bool process_equivalence(PlannerInfo *root, extern Expr *canonicalize_ec_expression(Expr *expr, Oid req_type, Oid req_collation); extern void reconsider_outer_join_clauses(PlannerInfo *root); -extern void rebuild_eclass_attr_needed(PlannerInfo *root); extern EquivalenceClass *get_eclass_for_sort_expr(PlannerInfo *root, Expr *expr, List *opfamilies, @@ -208,7 +207,6 @@ extern bool eclass_useful_for_merging(PlannerInfo *root, extern bool is_redundant_derived_clause(RestrictInfo *rinfo, List *clauselist); extern bool is_redundant_with_indexclauses(RestrictInfo *rinfo, List *indexclauses); -extern void ec_clear_derived_clauses(EquivalenceClass *ec); /* * pathkeys.c diff --git a/src/include/optimizer/placeholder.h b/src/include/optimizer/placeholder.h index 60798281090..2099075e670 100644 --- a/src/include/optimizer/placeholder.h +++ b/src/include/optimizer/placeholder.h @@ -23,7 +23,6 @@ extern PlaceHolderInfo *find_placeholder_info(PlannerInfo *root, PlaceHolderVar *phv); extern void find_placeholders_in_jointree(PlannerInfo *root); extern void fix_placeholder_input_needed_levels(PlannerInfo *root); -extern void rebuild_placeholder_attr_needed(PlannerInfo *root); extern void add_placeholders_to_base_rels(PlannerInfo *root); extern void add_placeholders_to_joinrel(PlannerInfo *root, RelOptInfo *joinrel, RelOptInfo *outer_rel, RelOptInfo *inner_rel, diff --git a/src/include/optimizer/planmain.h b/src/include/optimizer/planmain.h index 85301d912f0..f7e22f5989d 100644 --- a/src/include/optimizer/planmain.h +++ b/src/include/optimizer/planmain.h @@ -73,12 +73,9 @@ extern void add_other_rels_to_query(PlannerInfo *root); extern void build_base_rel_tlists(PlannerInfo *root, List *final_tlist); extern void add_vars_to_targetlist(PlannerInfo *root, List *vars, Relids where_needed); -extern void add_vars_to_attr_needed(PlannerInfo *root, List *vars, - Relids where_needed); extern void remove_useless_groupby_columns(PlannerInfo *root); extern void setup_eager_aggregation(PlannerInfo *root); extern void find_lateral_references(PlannerInfo *root); -extern void rebuild_lateral_attr_needed(PlannerInfo *root); extern void create_lateral_join_info(PlannerInfo *root); extern List *deconstruct_jointree(PlannerInfo *root); extern bool restriction_is_always_true(PlannerInfo *root, @@ -102,7 +99,6 @@ extern RestrictInfo *build_implied_join_equality(PlannerInfo *root, Expr *item2, Relids qualscope, Index security_level); -extern void rebuild_joinclause_attr_needed(PlannerInfo *root); extern void match_foreign_keys_to_quals(PlannerInfo *root); /* @@ -115,10 +111,6 @@ extern bool query_is_distinct_for(Query *query, List *distinct_cols); extern bool innerrel_is_unique(PlannerInfo *root, Relids joinrelids, Relids outerrelids, RelOptInfo *innerrel, JoinType jointype, List *restrictlist, bool force_cache); -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 bool remove_useless_self_joins(PlannerInfo *root, List *joinlist); /* diff --git a/src/include/rewrite/rewriteManip.h b/src/include/rewrite/rewriteManip.h index 9d234cb8741..2d15d8f8f95 100644 --- a/src/include/rewrite/rewriteManip.h +++ b/src/include/rewrite/rewriteManip.h @@ -41,30 +41,11 @@ typedef enum ReplaceVarsNoMatchOption REPLACEVARS_SUBSTITUTE_NULL, /* replace with a NULL Const */ } ReplaceVarsNoMatchOption; -typedef struct ChangeVarNodes_context ChangeVarNodes_context; - -typedef bool (*ChangeVarNodes_callback) (Node *node, - ChangeVarNodes_context *arg); - -struct ChangeVarNodes_context -{ - int rt_index; - int new_index; - int sublevels_up; - ChangeVarNodes_callback callback; -}; - -pg_nodiscard extern Relids adjust_relid_set(Relids relids, int oldrelid, int newrelid); extern void CombineRangeTables(List **dst_rtable, List **dst_perminfos, List *src_rtable, List *src_perminfos); extern void OffsetVarNodes(Node *node, int offset, int sublevels_up); extern void ChangeVarNodes(Node *node, int rt_index, int new_index, int sublevels_up); -extern void ChangeVarNodesExtended(Node *node, int rt_index, int new_index, - int sublevels_up, - ChangeVarNodes_callback callback); -extern bool ChangeVarNodesWalkExpression(Node *node, - ChangeVarNodes_context *context); extern void IncrementVarSublevelsUp(Node *node, int delta_sublevels_up, int min_sublevels_up); extern void IncrementVarSublevelsUp_rtable(List *rtable, diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list index 56c1f997f88..41ceb9b160d 100644 --- a/src/tools/pgindent/typedefs.list +++ b/src/tools/pgindent/typedefs.list @@ -431,7 +431,6 @@ CatalogId CatalogIdMapEntry CatalogIndexState ChangeContext -ChangeVarNodes_callback ChangeVarNodes_context ChannelName CheckPoint -- 2.52.0
v4-0004-Ensure-we-hoist-modified-quals-to-the-right-join-.patch (text/x-diff, 10.6K) download From 4e0512741c757b29af1e4b69579aea1dcc9ffba0 Mon Sep 17 00:00:00 2001 From: Tom Lane <tgl@sss.pgh.pa.us> Date: Sun, 26 Jul 2026 12:38:13 -0400 Subject: [PATCH v4 4/5] Ensure we hoist modified quals to the right join level after SJE. The v2 patchset in this series failed to consider whether a modified qual was actually appropriate for its original position in the join tree. It might not be, in which case we'd better move it up. Reported-by: Thom Brown <thom@linux.com> Author: Tom Lane <tgl@sss.pgh.pa.us> Discussion: https://postgr.es/m/1186816.1784573544@sss.pgh.pa.us --- src/backend/optimizer/plan/analyzejoins.c | 103 +++++++++++++++++++--- src/test/regress/expected/join.out | 58 ++++++++++++ src/test/regress/sql/join.sql | 18 ++++ 3 files changed, 169 insertions(+), 10 deletions(-) diff --git a/src/backend/optimizer/plan/analyzejoins.c b/src/backend/optimizer/plan/analyzejoins.c index a038b898bdb..8fe382c4287 100644 --- a/src/backend/optimizer/plan/analyzejoins.c +++ b/src/backend/optimizer/plan/analyzejoins.c @@ -87,8 +87,8 @@ static bool is_innerrel_unique_for(PlannerInfo *root, 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); +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); @@ -1201,7 +1201,9 @@ is_innerrel_unique_for(PlannerInfo *root, * jointree and then pointing everything that referenced it at the relation we * are keeping. All the conditions that were attached to the removed relation * thereby become conditions on the remaining one, which is what we want: - * we've proven that the two relations select the same rows. + * we've proven that the two relations select the same rows. Note that + * this change requires us to hoist those conditions up to someplace + * syntactically enclosing toKeep. * * kmark and rmark are the PlanRowMarks (if any) for the kept and removed * relations. We could re-locate those, but the caller already found them. @@ -1213,6 +1215,8 @@ remove_self_join_rel(PlannerInfo *root, { Node *orphan_quals = NULL; int nremoved = 0; + Node *hoist_quals = NULL; + bool found_relid = false; Assert(toKeep->relid > 0); Assert(toRemove->relid > 0); @@ -1251,7 +1255,11 @@ remove_self_join_rel(PlannerInfo *root, /* Clean up the quals that the substitution has messed with */ fixup_selfjoin_jointree(root, (Node *) root->parse->jointree, - toKeep->relid); + toKeep->relid, + &hoist_quals, &found_relid); + /* We shouldn't have any leftover quals, and we must have found toKeep */ + Assert(hoist_quals == NULL); + Assert(found_relid); /* * If the removed relation has a row mark, transfer it to the remaining @@ -1400,24 +1408,69 @@ merge_quals(Node *quals1, Node *quals2) * Clean up the query's jointree quals after self-join elimination has * merged one relation into another. (relid is the kept relation.) * - * See fixup_selfjoin_quals() for what needs fixing. + * See fixup_selfjoin_quals() for what needs fixing locally to each qual list. + * In addition, we need to check quals to see if they refer to relid, and if + * so make sure they get hoisted to someplace syntactically above relid. + * Do that using a "hoist_quals" in/out parameter similar to "orphan_quals" + * in remove_rel_from_jointree. (We can't readily merge these concerns into + * a single pass, since remove_rel_from_jointree must run before we relabel + * the removed rel's Vars.) In addition, *found_relid is set true if + * the subtree rooted at jtnode is found to contain relid's RangeTblRef, + * so that we can tell when to stop hoisting quals. + * If a qual gets hoisted up, we apply fixup_selfjoin_quals() to it only + * after it reaches its final level. This rule improves the odds of + * detecting duplicate quals. */ static void -fixup_selfjoin_jointree(PlannerInfo *root, Node *jtnode, int relid) +fixup_selfjoin_jointree(PlannerInfo *root, Node *jtnode, int relid, + Node **hoist_quals, bool *found_relid) { if (jtnode == NULL) return; if (IsA(jtnode, RangeTblRef)) { - /* nothing to do here */ + RangeTblRef *rtr = (RangeTblRef *) jtnode; + + if (rtr->rtindex == relid) + { + Assert(!*found_relid); + *found_relid = true; + } } else if (IsA(jtnode, FromExpr)) { FromExpr *f = (FromExpr *) jtnode; + Node *sub_hoist_quals = NULL; + bool sub_found_relid = false; ListCell *l; foreach(l, f->fromlist) - fixup_selfjoin_jointree(root, (Node *) lfirst(l), relid); + fixup_selfjoin_jointree(root, (Node *) lfirst(l), relid, + &sub_hoist_quals, &sub_found_relid); + if (sub_found_relid) + { + /* This FromExpr covers relid, so OK to stop hoisting quals here */ + f->quals = merge_quals(sub_hoist_quals, f->quals); + Assert(!*found_relid); + *found_relid = true; + } + else + { + /* We might need to hoist some of our own quals too */ + List *hoistable = NIL; + List *keepable = NIL; + + foreach_ptr(Node, qual, castNode(List, f->quals)) + { + if (bms_is_member(relid, pull_varnos(root, qual))) + hoistable = lappend(hoistable, qual); + else + keepable = lappend(keepable, qual); + } + f->quals = (Node *) keepable; + sub_hoist_quals = merge_quals(sub_hoist_quals, (Node *) hoistable); + *hoist_quals = merge_quals(sub_hoist_quals, *hoist_quals); + } f->quals = (Node *) fixup_selfjoin_quals(root, castNode(List, f->quals), relid); @@ -1425,9 +1478,39 @@ fixup_selfjoin_jointree(PlannerInfo *root, Node *jtnode, int relid) else if (IsA(jtnode, JoinExpr)) { JoinExpr *j = (JoinExpr *) jtnode; + Node *sub_hoist_quals = NULL; + bool sub_found_relid = false; + + fixup_selfjoin_jointree(root, j->larg, relid, + &sub_hoist_quals, &sub_found_relid); + fixup_selfjoin_jointree(root, j->rarg, relid, + &sub_hoist_quals, &sub_found_relid); + if (sub_found_relid) + { + /* This JoinExpr covers relid, so OK to stop hoisting quals here */ + j->quals = merge_quals(sub_hoist_quals, j->quals); + Assert(!*found_relid); + *found_relid = true; + } + else + { + /* We might need to hoist some of our own quals too */ + List *hoistable = NIL; + List *keepable = NIL; - fixup_selfjoin_jointree(root, j->larg, relid); - fixup_selfjoin_jointree(root, j->rarg, relid); + foreach_ptr(Node, qual, castNode(List, j->quals)) + { + if (bms_is_member(relid, pull_varnos(root, qual))) + hoistable = lappend(hoistable, qual); + else + keepable = lappend(keepable, qual); + } + j->quals = (Node *) keepable; + sub_hoist_quals = merge_quals(sub_hoist_quals, (Node *) hoistable); + /* We should never need to hoist quals above an outer join */ + Assert(sub_hoist_quals == NULL || j->jointype == JOIN_INNER); + *hoist_quals = merge_quals(sub_hoist_quals, *hoist_quals); + } j->quals = (Node *) fixup_selfjoin_quals(root, castNode(List, j->quals), relid); diff --git a/src/test/regress/expected/join.out b/src/test/regress/expected/join.out index 254b203aeba..57edb38a237 100644 --- a/src/test/regress/expected/join.out +++ b/src/test/regress/expected/join.out @@ -7478,6 +7478,64 @@ select t1.a from sj t1 where t1.b in ( Filter: (t3.c IS NOT NULL) (10 rows) +-- Check that quals get hoisted to the appropriate join level after SJE removal +explain (verbose, costs off) +select a2.a +from sj b1 + join sj a1 on b1.b = a1.a + join sj a2 on a2.a = a1.a and a2.b = a1.b; + QUERY PLAN +------------------------------------------------------------- + Nested Loop + Output: a2.a + Join Filter: (b1.b = a2.a) + -> Seq Scan on public.sj a2 + Output: a2.a, a2.b, a2.c + Filter: ((a2.a IS NOT NULL) AND (a2.b IS NOT NULL)) + -> Seq Scan on public.sj b1 + Output: b1.a, b1.b, b1.c +(8 rows) + +-- Same, when a semijoin removal happens first +explain (verbose, costs off) +select a1.a from sj b1 join sj a1 on a1.a = b1.b + where exists (select 1 from sj s where s.a = a1.a); + QUERY PLAN +----------------------------------------- + Nested Loop + Output: s.a + Inner Unique: true + Join Filter: (b1.b = s.a) + -> Seq Scan on public.sj b1 + Output: b1.a, b1.b, b1.c + -> Materialize + Output: s.a + -> Seq Scan on public.sj s + Output: s.a + Filter: (s.a IS NOT NULL) +(11 rows) + +-- A different case, where modified qual is on a lower join level +explain (verbose, costs off) +select a2.a +from ((sj b1 join sj a1 on true) join sj c1 on c1.b = a1.a) + join sj a2 on a2.a = a1.a and a2.b = a1.b; + QUERY PLAN +------------------------------------------------------------------- + Nested Loop + Output: a2.a + -> Nested Loop + Output: a2.a + Join Filter: (c1.b = a2.a) + -> Seq Scan on public.sj a2 + Output: a2.a, a2.b, a2.c + Filter: ((a2.a IS NOT NULL) AND (a2.b IS NOT NULL)) + -> Seq Scan on public.sj c1 + Output: c1.a, c1.b, c1.c + -> Seq Scan on public.sj b1 + Output: b1.a, b1.b, b1.c +(12 rows) + -- -- SJE corner case: uniqueness of an inner is [partially] derived from -- baserestrictinfo clauses. diff --git a/src/test/regress/sql/join.sql b/src/test/regress/sql/join.sql index afa96daecb5..f2291c67190 100644 --- a/src/test/regress/sql/join.sql +++ b/src/test/regress/sql/join.sql @@ -2892,6 +2892,24 @@ explain (verbose, costs off) select t1.a from sj t1 where t1.b in ( select t2.b from sj t2 join sj t3 on t2.c=t3.c); +-- Check that quals get hoisted to the appropriate join level after SJE removal +explain (verbose, costs off) +select a2.a +from sj b1 + join sj a1 on b1.b = a1.a + join sj a2 on a2.a = a1.a and a2.b = a1.b; + +-- Same, when a semijoin removal happens first +explain (verbose, costs off) +select a1.a from sj b1 join sj a1 on a1.a = b1.b + where exists (select 1 from sj s where s.a = a1.a); + +-- A different case, where modified qual is on a lower join level +explain (verbose, costs off) +select a2.a +from ((sj b1 join sj a1 on true) join sj c1 on c1.b = a1.a) + join sj a2 on a2.a = a1.a and a2.b = a1.b; + -- -- SJE corner case: uniqueness of an inner is [partially] derived from -- baserestrictinfo clauses. -- 2.52.0
v4-0005-Allow-remove_useless_self_joins-to-remove-multipl.patch (text/x-diff, 6.1K) download From fcda43ef0004aa401ddd8d0e56cf99cb3034779c Mon Sep 17 00:00:00 2001 From: Tom Lane <tgl@sss.pgh.pa.us> Date: Sun, 26 Jul 2026 13:21:05 -0400 Subject: [PATCH v4 5/5] Allow remove_useless_self_joins to remove multiple joins per call. There doesn't seem to be any reason for the restriction to one removal per call, and enforcing it makes cases with many removable self-joins noticeably slower. Reported-by: Thom Brown <thom@linux.com> Author: Tom Lane <tgl@sss.pgh.pa.us> Discussion: https://postgr.es/m/1186816.1784573544@sss.pgh.pa.us --- src/backend/optimizer/plan/analyzejoins.c | 62 ++++++++++++----------- 1 file changed, 32 insertions(+), 30 deletions(-) diff --git a/src/backend/optimizer/plan/analyzejoins.c b/src/backend/optimizer/plan/analyzejoins.c index 8fe382c4287..fc8331f5961 100644 --- a/src/backend/optimizer/plan/analyzejoins.c +++ b/src/backend/optimizer/plan/analyzejoins.c @@ -1758,16 +1758,15 @@ match_unique_clauses(PlannerInfo *root, RelOptInfo *outer, List *uclauses, } /* - * Find and remove one unique self-join in a group of base relations that have + * Find and remove unique self-joins in a group of base relations that have * the same Oid. * - * Returns true if we removed a relation. We stop at the first removal, - * because it invalidates all the derived information that the tests here - * depend on; our caller will come back for more once that's been rebuilt. + * Return true if we removed any joins. */ static bool remove_self_joins_one_group(PlannerInfo *root, Relids relids) { + bool removed = false; int k; /* Index of kept relation */ int r = -1; /* Index of removed relation */ @@ -1911,21 +1910,27 @@ remove_self_joins_one_group(PlannerInfo *root, Relids relids) if (!match_unique_clauses(root, rrel, uclauses, krel->relid)) continue; - /* OK, remove rrel from the query, and report that we did so */ + /* OK, remove rrel from the query */ remove_self_join_rel(root, krel, rrel, kmark, rmark); + removed = true; - return true; + /* + * Since relation r is now gone, we mustn't keep looking for + * matches to it. But there seems no reason why we can't continue + * scanning the relids for additional join pairs. + */ + break; } } - return false; + return removed; } /* - * Gather indexes of base relations from the joinlist and try to eliminate one - * self join. + * Gather indexes of base relations from the joinlist and try to eliminate + * self-joins. * - * Returns true if we removed a relation. + * Returns true if we removed any joins. */ static bool remove_self_joins_recurse(PlannerInfo *root, List *joinlist) @@ -1933,7 +1938,7 @@ remove_self_joins_recurse(PlannerInfo *root, List *joinlist) bool removed = false; ListCell *jl; Relids relids = NULL; - SelfJoinCandidate *candidates = NULL; + SelfJoinCandidate *candidates; int i; int j; int numRels; @@ -1969,8 +1974,7 @@ remove_self_joins_recurse(PlannerInfo *root, List *joinlist) else if (IsA(jlnode, List)) { /* Recursively consider SJE within the sub-joinlist */ - if (remove_self_joins_recurse(root, (List *) jlnode)) - return true; + removed |= remove_self_joins_recurse(root, (List *) jlnode); } else elog(ERROR, "unrecognized joinlist node type: %d", @@ -1979,9 +1983,9 @@ remove_self_joins_recurse(PlannerInfo *root, List *joinlist) numRels = bms_num_members(relids); - /* Need at least two relations for the join */ + /* No hope if not at least two relations */ if (numRels < 2) - return false; + return removed; /* * In order to find relations with the same oid we first build an array of @@ -2002,18 +2006,17 @@ remove_self_joins_recurse(PlannerInfo *root, List *joinlist) /* * Iteratively form a group of relation indexes with the same oid and - * launch the routine that detects a self-join in this group. + * launch the routine that detects self-joins in this group. * - * At the end of the iteration, exclude the group from the overall relids - * list. So each next iteration of the cycle will involve less and less - * value of relids. + * We remove considered relations from relids as we scan, so that that set + * should be empty at the end. */ i = 0; - for (j = 1; j < numRels + 1; j++) + for (j = 1; j <= numRels; j++) { if (j == numRels || candidates[j].reloid != candidates[i].reloid) { - if (j - i >= 2 && !removed) + if (j - i >= 2) { /* Create a group of relation indexes with the same oid */ Relids group = NULL; @@ -2026,12 +2029,10 @@ remove_self_joins_recurse(PlannerInfo *root, List *joinlist) relids = bms_del_members(relids, group); /* - * Try to remove a self-join from a group of identical - * entries. We stop as soon as we succeed, since the - * information we based the decision on is then out of date; - * our caller will start over from scratch. + * Try to remove self-joins from the group of identical + * entries. */ - removed = remove_self_joins_one_group(root, group); + removed |= remove_self_joins_one_group(root, group); bms_free(group); } else @@ -2097,9 +2098,10 @@ self_join_candidates_cmp(const void *a, const void *b) * '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 remove at most one self-join per call, and return true if we did so. - * The caller must then recompute everything that was derived from the - * jointree before calling here again. + * 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. */ bool remove_useless_self_joins(PlannerInfo *root, List *joinlist) @@ -2109,6 +2111,6 @@ remove_useless_self_joins(PlannerInfo *root, List *joinlist) (list_length(joinlist) == 1 && !IsA(linitial(joinlist), List))) return false; - /* Try to merge one pair of relations participating in a self-join. */ + /* Try to merge pairs of self-joined relations. */ return remove_self_joins_recurse(root, joinlist); } -- 2.52.0
^ permalink raw reply [nested|flat] 74+ messages in thread

* Re: remove_useless_joins vs. bug #19560
  2026-07-20 18:52 remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-24 13:38 ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-07-25 16:46   ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-25 20:07     ` Re: remove_useless_joins vs. bug #19560 Thom Brown <thom@linux.com>
  2026-07-25 21:23       ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-26 02:15         ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-26 09:49           ` Re: remove_useless_joins vs. bug #19560 Thom Brown <thom@linux.com>
  2026-07-26 17:33             ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-26 17:35               ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
@ 2026-07-27 07:07                 ` Richard Guo <guofenglinux@gmail.com>
  2026-07-27 16:33                   ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  0 siblings, 1 reply; 74+ messages in thread

From: Richard Guo @ 2026-07-27 07:07 UTC (permalink / raw)
  To: Tom Lane <tgl@sss.pgh.pa.us>; +Cc: Thom Brown <thom@linux.com>; pgsql-hackers@lists.postgresql.org

On Mon, Jul 27, 2026 at 2:35 AM Tom Lane <tgl@sss.pgh.pa.us> wrote:
> Drat, failed to hit control-C control-E.  Now with patches attached,
> for sure.

Thanks for the patchset.  Nice cleanup:

    911 insertions(+), 1670 deletions(-)

I noticed that the call to remove_rels_from_query_tree() at the end of
remove_useless_joins() performs a full traversal over the query tree
to delete the removed relids.  I wonder if this is a bit too
brute-force, as AFAICS only PHVs can still contain references to the
removed relids.  If there were any other remaining references,
join_is_removable() wouldn't have considered the join removable in the
first place.

If that's correct, perhaps we can simplify
remove_rels_from_query_tree() to something lighter, similar to
remove_result_refs().


Also, the issue with duplicate clauses after self-join elimination
reported in bug #19435 is still present in v4.  It would be great if
we could address that in passing as well.

Here is a simplified repro:

create table t (a int unique, b int);

explain (costs off)
select * from t t1 left join
  (t t2 join t t3 on t2.a = t3.a) on t3.a is not null;
                         QUERY PLAN
-------------------------------------------------------------
 Nested Loop Left Join
   ->  Seq Scan on t t1
   ->  Materialize
         ->  Seq Scan on t t3
               Filter: ((a IS NOT NULL) AND (a IS NOT NULL))
(5 rows)

- Richard






^ permalink  raw  reply  [nested|flat] 74+ messages in thread

* Re: remove_useless_joins vs. bug #19560
  2026-07-20 18:52 remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-24 13:38 ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-07-25 16:46   ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-25 20:07     ` Re: remove_useless_joins vs. bug #19560 Thom Brown <thom@linux.com>
  2026-07-25 21:23       ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-26 02:15         ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-26 09:49           ` Re: remove_useless_joins vs. bug #19560 Thom Brown <thom@linux.com>
  2026-07-26 17:33             ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-26 17:35               ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-27 07:07                 ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
@ 2026-07-27 16:33                   ` Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-27 18:21                     ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  0 siblings, 1 reply; 74+ messages in thread

From: Tom Lane @ 2026-07-27 16:33 UTC (permalink / raw)
  To: Richard Guo <guofenglinux@gmail.com>; +Cc: Thom Brown <thom@linux.com>; pgsql-hackers@lists.postgresql.org

Richard Guo <guofenglinux@gmail.com> writes:
> Thanks for the patchset.  Nice cleanup:

Thanks for looking at it!

> I noticed that the call to remove_rels_from_query_tree() at the end of
> remove_useless_joins() performs a full traversal over the query tree
> to delete the removed relids.  I wonder if this is a bit too
> brute-force, as AFAICS only PHVs can still contain references to the
> removed relids.  If there were any other remaining references,
> join_is_removable() wouldn't have considered the join removable in the
> first place.

Yeah, I think this is probably true.  The Claude-written comment
claims that the removed OJ's relid could appear in surviving Vars'
nullingrels, but I don't see how that could be: such Vars would
have to refer to the removed baserel, and then they should have
prevented the join removal.

> If that's correct, perhaps we can simplify
> remove_rels_from_query_tree() to something lighter, similar to
> remove_result_refs().

Meh.  I don't think there's a lot to be gained there: we still
have to walk the whole tree, and I'm not excited about duplicating
tree-walking code.  We could maybe use substitute_phv_relids from
prepjointree.c, but I see that has Assert(!IsA(node, AppendRelInfo));
which we'd have to drop.  I doubt there'd be any measurable
improvement over the ChangeVarNodes coding, anyway.

> Also, the issue with duplicate clauses after self-join elimination
> reported in bug #19435 is still present in v4.  It would be great if
> we could address that in passing as well.

I'm not excited about that either.  AFAICS, with the #19435 query:

SELECT  1 AS c1
FROM (
    pg_table_a AS tom0
    RIGHT JOIN (
        (pg_table_a AS tom1 NATURAL JOIN pg_table_a AS tom2)
        RIGHT JOIN pg_table_a AS tom3
        ON tom1.col_bool IS NOT NULL
    )
    ON tom1.col_bool
);

The NATURAL JOIN produces quals

    tom1.id = tom2.id AND tom1.col_bool = tom2.col_bool

SJE correctly replaces those with

    tom2.id IS NOT NULL AND tom2.col_bool IS NOT NULL

We do, later on, detect that the id clause is unnecessary because of
the id column's NOT NULL constraint.  But we don't notice that the
generated col_bool clause is redundant with the user-written
"tom1.col_bool IS NOT NULL" clause appearing in a higher join level.
I don't think it's incumbent on us to fix redundantly-written
user queries, and even if we took that on, the SJE code would not
be the place for it.  You can get similar redundancies without
any SJE happening, eg

regression=# explain (costs off)
select * from pg_table_a as tom1 left join
 (select * from pg_table_a as tom2 where tom2.col_bool is not null) tom3
 on tom3.col_bool is not null;
                                QUERY PLAN                                 
---------------------------------------------------------------------------
 Nested Loop Left Join
   ->  Seq Scan on pg_table_a tom1
   ->  Materialize
         ->  Seq Scan on pg_table_a tom2
               Filter: ((col_bool IS NOT NULL) AND (col_bool IS NOT NULL))
(5 rows)

> Here is a simplified repro:
> create table t (a int unique, b int);
> explain (costs off)
> select * from t t1 left join
>   (t t2 join t t3 on t2.a = t3.a) on t3.a is not null;

On what grounds are these not just stupidly-written queries?
We shouldn't fail of course (which was the actual complaint in
#19435), but I'm not excited about removing the user's redundancy.

If somebody held a gun to my head and said "fix that", I'd probably
teach distribute_quals_to_rels to de-duplicate quals as they go into
baserestrictinfo and joinrestrictinfo lists.  But I'm quite certain
that the planner cycles spent on that would be a net loss for most
people.

			regards, tom lane






^ permalink  raw  reply  [nested|flat] 74+ messages in thread

* Re: remove_useless_joins vs. bug #19560
  2026-07-20 18:52 remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-24 13:38 ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-07-25 16:46   ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-25 20:07     ` Re: remove_useless_joins vs. bug #19560 Thom Brown <thom@linux.com>
  2026-07-25 21:23       ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-26 02:15         ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-26 09:49           ` Re: remove_useless_joins vs. bug #19560 Thom Brown <thom@linux.com>
  2026-07-26 17:33             ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-26 17:35               ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-27 07:07                 ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-07-27 16:33                   ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
@ 2026-07-27 18:21                     ` Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-28 08:58                       ` Re: remove_useless_joins vs. bug #19560 Tender Wang <tndrwang@gmail.com>
  2026-07-29 06:21                       ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  0 siblings, 2 replies; 74+ messages in thread

From: Tom Lane @ 2026-07-27 18:21 UTC (permalink / raw)
  To: Richard Guo <guofenglinux@gmail.com>; +Cc: Thom Brown <thom@linux.com>; Jacob Brazeal <jacob.brazeal@gmail.com>; pgsql-hackers@lists.postgresql.org

I spent some time looking into what would be involved in back-patching
this.  Quite aside from risks of new bugs, there's an API/ABI break
involved for released branches (I don't think we are worried about
that yet for v19, though).  One thing we can do to reduce the API risk
is to not delete the no-longer-used extern functions that the master
patch removes, such as add_vars_to_attr_needed.  I kind of doubt that
anyone is using those in extensions, but leaving them as dead code
seems like cheap insurance.  However, there's an irreducible minimum
API change in remove_useless_joins, reduce_unique_semijoins, and
remove_useless_self_joins: those don't return what they did before,
and even more importantly their side effects are much different from
before.  I don't see any evidence in Debian Code Search that anyone is
calling those, so I'm not inclined to go to lengths like (say) keeping
the whole of the existing analyzejoins.c code around as dead code.
Even if we wanted to consider that, the bugs that we're trying to get
rid of would still bite any hypothetical extension that was messing
with these functions.  So I think it's reasonable to trust that nobody
is calling anything lower-level than query_planner().

Having said that, I think that it'd be a good idea to rename
remove_useless_joins to remove_useless_outer_joins.  The existing
name is already confusing now that we have remove_useless_self_joins
too.  The ABI angle is that if we do that, then any extension that's
trying to call remove_useless_joins will fail with an
easily-understood error at library load time, rather than crashing
or misbehaving in some arcane way because the function didn't do what
it expected.  We could extend this to renaming all three functions,
but I think renaming remove_useless_joins is sufficient --- I really
don't see any use case for calling the other two and not that one.

So attached are a set of patches along that line.  v5-0001 is the
master patchset squashed to one patch; it differs from the v4 series
in having the remove_useless_joins rename and some minor additional
comment-smithing.  The others are draft patches for v16-v19.  The
v19 patch is only trivially different from master.  v18 and earlier
don't remove any of the dead code outside analyzejoins.c.  v16/v17
are a good deal smaller because there's no SJE code to fix.

I think it's still open to debate how far back we want to go.
In principle we could make these changes in v14/v15, but with no known
bugs manifesting in those branches, the risk/reward ratio seems poor,
so I didn't make patches for those.  I think we definitely want to do
this in v18, since aside from #19560 that branch has the SJE bug that
Jacob B. reported at [1] (which is a distinct problem, per Alexander's
analysis).  v16 and v17 seem like a gray area, but we do know that
they have #19560.  Even if we limit our ambition in those branches
to fixing that problem, I don't see a simple localized fix for it.

Thoughts?

			regards, tom lane

[1] https://www.postgresql.org/message-id/flat/CA%2BCOZaBVFHS-eXL7a53iZfNJyv5LqD5t1eSbYDavYxLSyfkL6A%40m...

Attachments:

  v5-join-removal-per-branch-patches.tar.gz (application/gzip, 119.0K) download

^ permalink  raw  reply  [nested|flat] 74+ messages in thread

* Re: remove_useless_joins vs. bug #19560
  2026-07-20 18:52 remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-24 13:38 ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-07-25 16:46   ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-25 20:07     ` Re: remove_useless_joins vs. bug #19560 Thom Brown <thom@linux.com>
  2026-07-25 21:23       ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-26 02:15         ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-26 09:49           ` Re: remove_useless_joins vs. bug #19560 Thom Brown <thom@linux.com>
  2026-07-26 17:33             ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-26 17:35               ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-27 07:07                 ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-07-27 16:33                   ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-27 18:21                     ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
@ 2026-07-28 08:58                       ` Tender Wang <tndrwang@gmail.com>
  2026-07-28 12:24                         ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  1 sibling, 1 reply; 74+ messages in thread

From: Tender Wang @ 2026-07-28 08:58 UTC (permalink / raw)
  To: Tom Lane <tgl@sss.pgh.pa.us>; +Cc: Richard Guo <guofenglinux@gmail.com>; Thom Brown <thom@linux.com>; Jacob Brazeal <jacob.brazeal@gmail.com>; pgsql-hackers@lists.postgresql.org

Tom Lane <tgl@sss.pgh.pa.us> 于2026年7月28日周二 02:21写道:
>
> I think it's still open to debate how far back we want to go.
> In principle we could make these changes in v14/v15, but with no known
> bugs manifesting in those branches, the risk/reward ratio seems poor,
> so I didn't make patches for those.  I think we definitely want to do
> this in v18, since aside from #19560 that branch has the SJE bug that
> Jacob B. reported at [1] (which is a distinct problem, per Alexander's
> analysis).  v16 and v17 seem like a gray area, but we do know that
> they have #19560.  Even if we limit our ambition in those branches
> to fixing that problem, I don't see a simple localized fix for it.
>
> Thoughts?
>

My question is unrelated to back-patching, so apologies if this is not
the right thread.

When I first saw your proposal to rewrite analyzejoins.c, I wondered
whether it might also address the remaining SJE issue discussed in
[1].

However, after applying v5 on top of HEAD, the issue still seems to be
present. In particular, the resulting plan retains a redundant filter
after SJE:

CREATE TABLE pg_table_a (
    id INTEGER PRIMARY KEY,
    col_bool BOOLEAN
);

INSERT INTO pg_table_a (id, col_bool)
VALUES (5, TRUE);

EXPLAIN
SELECT 1 AS c1
FROM (
    pg_table_a AS tom0
    RIGHT JOIN (
        (pg_table_a AS tom1 NATURAL JOIN pg_table_a AS tom2)
        RIGHT JOIN pg_table_a AS tom3
        ON tom1.col_bool IS NOT NULL
    )
    ON tom1.col_bool
);

The relevant part of the plan is:

Seq Scan on pg_table_a tom2
  Filter: ((col_bool IS NOT NULL) AND (col_bool IS NOT NULL))

That duplicate filter appears to be left behind after the join
involving tom1 is removed.

I think this issue is still worth fixing. The discussion in [1] has
been inactive for about two months, so I wanted to ask whether you
intend to address it as part of the analyzejoins.c rewrite, or whether
it would be better for me to resume work on [1] once the rewrite has
been committed.

[1] https://www.postgresql.org/message-id/CAHewXN%3D7kDJjUcgEm%2B6qhaKOXuqzvhRqAAKdafNCRgn0yH7BGg%40mail...



-- 
Thanks,
Tender Wang






^ permalink  raw  reply  [nested|flat] 74+ messages in thread

* Re: remove_useless_joins vs. bug #19560
  2026-07-20 18:52 remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-24 13:38 ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-07-25 16:46   ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-25 20:07     ` Re: remove_useless_joins vs. bug #19560 Thom Brown <thom@linux.com>
  2026-07-25 21:23       ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-26 02:15         ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-26 09:49           ` Re: remove_useless_joins vs. bug #19560 Thom Brown <thom@linux.com>
  2026-07-26 17:33             ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-26 17:35               ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-27 07:07                 ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-07-27 16:33                   ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-27 18:21                     ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-28 08:58                       ` Re: remove_useless_joins vs. bug #19560 Tender Wang <tndrwang@gmail.com>
@ 2026-07-28 12:24                         ` Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-28 13:03                           ` Re: remove_useless_joins vs. bug #19560 Tender Wang <tndrwang@gmail.com>
  0 siblings, 1 reply; 74+ messages in thread

From: Tom Lane @ 2026-07-28 12:24 UTC (permalink / raw)
  To: Tender Wang <tndrwang@gmail.com>; +Cc: Richard Guo <guofenglinux@gmail.com>; Thom Brown <thom@linux.com>; Jacob Brazeal <jacob.brazeal@gmail.com>; pgsql-hackers@lists.postgresql.org

Tender Wang <tndrwang@gmail.com> writes:
> I think this issue is still worth fixing. The discussion in [1] has
> been inactive for about two months, so I wanted to ask whether you
> intend to address it as part of the analyzejoins.c rewrite, or whether
> it would be better for me to resume work on [1] once the rewrite has
> been committed.

I disagree.  That's not a bug -- okay, it's a missed optimization for
a small class of poorly-written queries -- and it's not specific to
SJE either.  I think far too much development effort has been spent
on the point already.  See my upthread reply to Richard [1].

(BTW, sitting here in the light of morning, a totally different
approach occurs to me.  The reason that the user-written IS NOT NULL
is useless is that it's testing the result of a joined column,
where the join operator is strict and the join isn't null-extending.
I wonder if we could detect that and then throw away the upper IS NOT
NULL, independently of any join-elimination strategy.  I think there
is precedent for this idea in the SQL standard's idea of known
dependencies within queries.  It might still not be worth the planner
cycles, but ...)

			regards, tom lane

[1] https://www.postgresql.org/message-id/3968565.1785170019%40sss.pgh.pa.us






^ permalink  raw  reply  [nested|flat] 74+ messages in thread

* Re: remove_useless_joins vs. bug #19560
  2026-07-20 18:52 remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-24 13:38 ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-07-25 16:46   ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-25 20:07     ` Re: remove_useless_joins vs. bug #19560 Thom Brown <thom@linux.com>
  2026-07-25 21:23       ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-26 02:15         ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-26 09:49           ` Re: remove_useless_joins vs. bug #19560 Thom Brown <thom@linux.com>
  2026-07-26 17:33             ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-26 17:35               ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-27 07:07                 ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-07-27 16:33                   ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-27 18:21                     ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-28 08:58                       ` Re: remove_useless_joins vs. bug #19560 Tender Wang <tndrwang@gmail.com>
  2026-07-28 12:24                         ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
@ 2026-07-28 13:03                           ` Tender Wang <tndrwang@gmail.com>
  0 siblings, 0 replies; 74+ messages in thread

From: Tender Wang @ 2026-07-28 13:03 UTC (permalink / raw)
  To: Tom Lane <tgl@sss.pgh.pa.us>; +Cc: Richard Guo <guofenglinux@gmail.com>; Thom Brown <thom@linux.com>; Jacob Brazeal <jacob.brazeal@gmail.com>; pgsql-hackers@lists.postgresql.org

Hi Tom,

Tom Lane <tgl@sss.pgh.pa.us> 于2026年7月28日周二 20:24写道:
>
> Tender Wang <tndrwang@gmail.com> writes:
> > I think this issue is still worth fixing. The discussion in [1] has
> > been inactive for about two months, so I wanted to ask whether you
> > intend to address it as part of the analyzejoins.c rewrite, or whether
> > it would be better for me to resume work on [1] once the rewrite has
> > been committed.
>
> I disagree.  That's not a bug -- okay, it's a missed optimization for
> a small class of poorly-written queries -- and it's not specific to
> SJE either.  I think far too much development effort has been spent
> on the point already.  See my upthread reply to Richard [1].
>

Thanks for the explanation.

I'm not sure why I couldn't see your reply to Richard in my Gmail
inbox, although I can see it on the pgsql-hackers archive.

Anyway, thanks for the clarification, and sorry for raising a point
that had already been discussed.


-- 
Thanks,
Tender Wang






^ permalink  raw  reply  [nested|flat] 74+ messages in thread

* Re: remove_useless_joins vs. bug #19560
  2026-07-20 18:52 remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-24 13:38 ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-07-25 16:46   ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-25 20:07     ` Re: remove_useless_joins vs. bug #19560 Thom Brown <thom@linux.com>
  2026-07-25 21:23       ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-26 02:15         ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-26 09:49           ` Re: remove_useless_joins vs. bug #19560 Thom Brown <thom@linux.com>
  2026-07-26 17:33             ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-26 17:35               ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-27 07:07                 ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-07-27 16:33                   ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-27 18:21                     ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
@ 2026-07-29 06:21                       ` Richard Guo <guofenglinux@gmail.com>
  2026-08-16 23:58                         ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-26 07:33                         ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  1 sibling, 2 replies; 74+ messages in thread

From: Richard Guo @ 2026-07-29 06:21 UTC (permalink / raw)
  To: Tom Lane <tgl@sss.pgh.pa.us>; +Cc: Thom Brown <thom@linux.com>; Jacob Brazeal <jacob.brazeal@gmail.com>; pgsql-hackers@lists.postgresql.org

On Tue, Jul 28, 2026 at 3:21 AM Tom Lane <tgl@sss.pgh.pa.us> wrote:
> So attached are a set of patches along that line.  v5-0001 is the
> master patchset squashed to one patch; it differs from the v4 series
> in having the remove_useless_joins rename and some minor additional
> comment-smithing.

I reviewed v5-0001, and here are some comments.

1. The initialization of all_result_relids/leaf_result_relids is moved
to below the trivial-jointree early return.  So for a query like
"INSERT INTO t VALUES()", both sets now stay NULL where they used to
be {resultRelation}.

I'm not sure if this can cause any issues, but at least it contradicts
the comment in pathnodes.h:

  * all_result_relids is empty for SELECT, otherwise it contains at least
  * parse->resultRelation.

2. Regarding remove_rels_from_query_tree(): I complained about this
function in my previous email, but it does not get changed.

First, I think we can at least add a check on root->glob->lastPHId and
do the ChangeVarNodes walks only if there are any PHVs in the query.
I believe only PHVs can still contain references to the removed relids
here.

Second, as you mentioned, the comment claims that "the relids can
still appear in the nullingrels sets of surviving Vars", but that is
not true.  We should not keep such comment as it is very misleading.

Third, this function works only if "There should be no ordinary Vars
of a removed relation left".  I agree it holds today.  But if it ever
does break, ChangeVarNodes sets var->varno = -1, which is INNER_VAR,
and AppendRelInfo->parent_relid/child_relid would go to -1 too.  This
would produce garbage rather than an error, which makes me nervous.
I hope we can use a walker that mutates on PHVs only.

3. In reduce_unique_semijoins(), analyzejoins.c:480 tests
min_righthand for singleton-ness, but analyzejoins.c:517 uses
syn_righthand to find the JoinExpr and flips the whole node to
JOIN_INNER.  If there is a case where min_righthand is singleton but
syn_righthand is not and the innerrel is unique, we will be in
trouble.

4. The commit message claims that "it doesn't seem to result in any
significant planning-time penalty".  I'm somewhat skeptical of that.

- Richard






^ permalink  raw  reply  [nested|flat] 74+ messages in thread

* Re: remove_useless_joins vs. bug #19560
  2026-07-20 18:52 remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-24 13:38 ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-07-25 16:46   ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-25 20:07     ` Re: remove_useless_joins vs. bug #19560 Thom Brown <thom@linux.com>
  2026-07-25 21:23       ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-26 02:15         ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-26 09:49           ` Re: remove_useless_joins vs. bug #19560 Thom Brown <thom@linux.com>
  2026-07-26 17:33             ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-26 17:35               ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-27 07:07                 ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-07-27 16:33                   ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-27 18:21                     ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-29 06:21                       ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
@ 2026-08-16 23:58                         ` Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-26 05:26                           ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  1 sibling, 1 reply; 74+ messages in thread

From: Tom Lane @ 2026-08-16 23:58 UTC (permalink / raw)
  To: Richard Guo <guofenglinux@gmail.com>; +Cc: Thom Brown <thom@linux.com>; Jacob Brazeal <jacob.brazeal@gmail.com>; pgsql-hackers@lists.postgresql.org

I'm getting back to this task, after much too long in security-fix
land.  I had the idea that we could resolve the disagreement about
whether to use ChangeVarNodes by inserting Asserts in it to catch
any places where it'd attempt to store an invalid value into a
Var's varno (or other fields that hold a relid).  However, when
I tried that, it blew up!  Some investigation showed that it
descends into the subquery fields of subquery RTEs even when those
RTEs are no longer relevant to the query, and there it can find
Var references that trip the assertions.  The sequence is basically
that we pull up a lateral-referencing subquery into the main query,
and after flattening and maybe some preliminary join simplification,
the query no longer references some RTE so we decide we can remove
that.  But ChangeVarNodes will descend into the original subquery RTE,
find the since-elided lateral reference, and boom.

So this is a pretty disturbing discovery: it means that as things
stand, we can't put any sanity checks into ChangeVarNodes, and aside
from that we might be doing quite a bit of useless work mutating
no-longer-interesting subqueries.  Switching to code based on
remove_result_refs() doesn't help since that also scans the whole
query tree.  (That function doesn't have an issue itself, since
at the time it runs we don't have any invalidated subqueries.)

One idea for fixing this is to null out the subquery field of a
subquery RTE as soon as we've pulled it up, but there is probably
code that will crash on a null subquery pointer.  I'm also thinking
about invoking ChangeVarNodes on only portions of the query tree,
not including the rangetable, but that seems messy and not very
maintainable.  Any thoughts?

			regards, tom lane






^ permalink  raw  reply  [nested|flat] 74+ messages in thread

* Re: remove_useless_joins vs. bug #19560
  2026-07-20 18:52 remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-24 13:38 ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-07-25 16:46   ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-25 20:07     ` Re: remove_useless_joins vs. bug #19560 Thom Brown <thom@linux.com>
  2026-07-25 21:23       ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-26 02:15         ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-26 09:49           ` Re: remove_useless_joins vs. bug #19560 Thom Brown <thom@linux.com>
  2026-07-26 17:33             ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-26 17:35               ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-27 07:07                 ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-07-27 16:33                   ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-27 18:21                     ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-29 06:21                       ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-16 23:58                         ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
@ 2026-08-26 05:26                           ` Richard Guo <guofenglinux@gmail.com>
  2026-08-26 17:25                             ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  0 siblings, 1 reply; 74+ messages in thread

From: Richard Guo @ 2026-08-26 05:26 UTC (permalink / raw)
  To: Tom Lane <tgl@sss.pgh.pa.us>; +Cc: Thom Brown <thom@linux.com>; Jacob Brazeal <jacob.brazeal@gmail.com>; pgsql-hackers@lists.postgresql.org

On Mon, Aug 17, 2026 at 8:58 AM Tom Lane <tgl@sss.pgh.pa.us> wrote:
> One idea for fixing this is to null out the subquery field of a
> subquery RTE as soon as we've pulled it up, but there is probably
> code that will crash on a null subquery pointer.

It seems to me that the subquery in question isn't a pulled-up one.
pull_up_simple_subquery() already sets rte->subquery to NULL at line
prepjointree.c:1725.

What is in question is the subquery of a rel removed by join removal
itself.  Its RTE stays in the rangetable with the query tree intact,
and that tree can contain lateral references to rels that are still
around.  Those references are what prevented the referenced rel from
being removed; once the referencing subquery is gone, the next pass
removes the referenced rel, and remove_rels_from_query_tree() then
walks into the dead subquery and finds the stale Var.  To be concrete,
consider:

  select d.* from d
    left join a on d.a = a.id
    left join lateral (select count(*) from c where c.id = a.b_id) s
      on true;

I think we can just null out the subquery field of a subquery RTE that
gets removed.  We've been doing that for pulled-up subqueries for many
years, so it should be safe.  I mean something like below.

@@ -155,6 +154,10 @@ remove_useless_outer_joins(PlannerInfo *root)
        removed_relids = bms_add_member(removed_relids, innerrelid);
        removed_relids = bms_add_member(removed_relids, sjinfo->ojrelid);

+       /* As in pull_up_simple_subquery, discard a no-longer-needed subquery */
+       if (root->simple_rte_array[innerrelid]->rtekind == RTE_SUBQUERY)
+           root->simple_rte_array[innerrelid]->subquery = NULL;
+

While at it, I still don't think we need ChangeVarNodes() here, since
only PHV phrels can still mention a removed relid.  I think we can
leverage substitute_phv_relids() to do the job, and thus we don't need
duplicate tree-walking code.  The Assert(!IsA(node, AppendRelInfo))
you mentioned is not a problem.  We can handle that by a three-line
loop:

+       foreach_node(AppendRelInfo, appinfo, root->append_rel_list)
+       {
+           Assert(appinfo->parent_relid != relid);
+           Assert(appinfo->child_relid != relid);
+           substitute_phv_relids((Node *) appinfo->translated_vars,
+                                 relid, NULL);
+       }

I agree that there may not be any speed gain, since the walk is the
same.  I think the point is that join removal no longer writes -1 into
varno fields.

Attached is a draft patch showing what I mean.

- Richard

Attachments:

nocfbot.Some-updates-to-v5.patch (application/octet-stream, 8.4K) download From 28df8bae223f7614fd4bb41623bcca4a4d2c731a Mon Sep 17 00:00:00 2001 From: Richard Guo <guofenglinux@gmail.com> Date: Wed, 26 Aug 2026 11:42:50 +0900 Subject: [PATCH v1] Some updates to v5 --- src/backend/optimizer/plan/analyzejoins.c | 50 +++++++++++++---------- src/backend/optimizer/prep/prepjointree.c | 7 ++-- src/include/optimizer/prep.h | 1 + src/test/regress/expected/join.out | 11 +++++ src/test/regress/sql/join.sql | 7 ++++ 5 files changed, 51 insertions(+), 25 deletions(-) diff --git a/src/backend/optimizer/plan/analyzejoins.c b/src/backend/optimizer/plan/analyzejoins.c index 7c77118c76a..a8cb8aaca37 100644 --- a/src/backend/optimizer/plan/analyzejoins.c +++ b/src/backend/optimizer/plan/analyzejoins.c @@ -62,8 +62,7 @@ bool enable_self_join_elimination; static bool join_is_removable(PlannerInfo *root, SpecialJoinInfo *sjinfo); static Node *remove_join_from_jointree(Node *jtnode, int ojrelid, int *nremoved); -static void remove_rels_from_query_tree(PlannerInfo *root, - Relids removed_relids); +static void remove_rels_from_phvs(PlannerInfo *root, Relids removed_relids); static bool reduce_semijoin_in_jointree(Node *jtnode, Relids syn_righthand); static bool rel_supports_distinctness(PlannerInfo *root, RelOptInfo *rel); static bool rel_is_distinct_for(PlannerInfo *root, RelOptInfo *rel, @@ -155,6 +154,10 @@ remove_useless_outer_joins(PlannerInfo *root) removed_relids = bms_add_member(removed_relids, innerrelid); removed_relids = bms_add_member(removed_relids, sjinfo->ojrelid); + /* As in pull_up_simple_subquery, discard a no-longer-needed subquery */ + if (root->simple_rte_array[innerrelid]->rtekind == RTE_SUBQUERY) + root->simple_rte_array[innerrelid]->subquery = NULL; + /* * It's okay to keep scanning join_info_list for more removable joins, * even though the data that join_is_removable consults is now @@ -173,8 +176,8 @@ remove_useless_outer_joins(PlannerInfo *root) if (bms_is_empty(removed_relids)) return false; - /* Clean up the traces that the removed rels have left elsewhere */ - remove_rels_from_query_tree(root, removed_relids); + /* PlaceHolderVars may still mention the removed relids in their phrels */ + remove_rels_from_phvs(root, removed_relids); return true; } @@ -408,37 +411,42 @@ remove_join_from_jointree(Node *jtnode, int ojrelid, int *nremoved) } /* - * remove_rels_from_query_tree - * Delete all remaining references to the given relids from the query. + * remove_rels_from_phvs + * Strip the given relids out of all PlaceHolderVars in the query. * - * 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 the relids can - * still appear in the nullingrels sets of surviving Vars and PlaceHolderVars, - * and in the phrels sets of PlaceHolderVars. ChangeVarNodes knows how to - * strip a relid out of all of those. + * join_is_removable ensures that no Var of a removed rel survives, nor any + * Var or PlaceHolderVar nulled by a removed outer join. What can survive is + * a PlaceHolderVar whose phrels includes the removed relids even though its + * expression doesn't reference them, so just strip them from phrels. */ static void -remove_rels_from_query_tree(PlannerInfo *root, Relids removed_relids) +remove_rels_from_phvs(PlannerInfo *root, Relids removed_relids) { int relid = -1; + /* If there are no PHVs anywhere, we needn't work hard */ + if (root->glob->lastPHId == 0) + return; + while ((relid = bms_next_member(removed_relids, relid)) >= 0) { - /* Pass -1 for new_index to get the removal behavior */ - ChangeVarNodes((Node *) root->parse, relid, -1, 0); + /* Pass NULL for subrelids to get the removal behavior */ + substitute_phv_relids((Node *) root->parse, relid, NULL); /* * 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.) + * parse->targetList, so it has to be processed separately. */ - ChangeVarNodes((Node *) root->processed_tlist, relid, -1, 0); + substitute_phv_relids((Node *) root->processed_tlist, relid, NULL); /* There could be references in the append_rel_list, too */ - if (root->append_rel_list != NIL) - ChangeVarNodes((Node *) root->append_rel_list, relid, -1, 0); + foreach_node(AppendRelInfo, appinfo, root->append_rel_list) + { + Assert(appinfo->parent_relid != relid); + Assert(appinfo->child_relid != relid); + substitute_phv_relids((Node *) appinfo->translated_vars, + relid, NULL); + } } } diff --git a/src/backend/optimizer/prep/prepjointree.c b/src/backend/optimizer/prep/prepjointree.c index 5931501e470..05f0d8644ce 100644 --- a/src/backend/optimizer/prep/prepjointree.c +++ b/src/backend/optimizer/prep/prepjointree.c @@ -181,8 +181,6 @@ static bool find_dependent_phvs(PlannerInfo *root, int varno, Relids baserels); static bool find_dependent_phvs_in_jointree(PlannerInfo *root, Node *node, int varno, Relids baserels); -static void substitute_phv_relids(Node *node, - int varno, Relids subrelids); static void fix_append_rel_relids(PlannerInfo *root, int varno, Relids subrelids); static Node *find_jointree_node_for_rel(Node *jtnode, int relid); @@ -4580,10 +4578,11 @@ find_dependent_phvs_in_jointree(PlannerInfo *root, Node *node, int varno, /* * substitute_phv_relids - adjust PlaceHolderVar relid sets after pulling up - * a subquery or removing an RTE_RESULT jointree item + * a subquery or removing a jointree item * * Find any PlaceHolderVar nodes in the given tree that reference the * pulled-up relid, and change them to reference the replacement relid(s). + * If subrelids is empty, the relid is simply deleted. * * NOTE: although this has the form of a walker, we cheat and modify the * nodes in-place. This should be OK since the tree was copied by @@ -4641,7 +4640,7 @@ substitute_phv_relids_walker(Node *node, return expression_tree_walker(node, substitute_phv_relids_walker, context); } -static void +void substitute_phv_relids(Node *node, int varno, Relids subrelids) { substitute_phv_relids_context context; diff --git a/src/include/optimizer/prep.h b/src/include/optimizer/prep.h index 00bc567da76..113c2be3243 100644 --- a/src/include/optimizer/prep.h +++ b/src/include/optimizer/prep.h @@ -30,6 +30,7 @@ extern void pull_up_subqueries(PlannerInfo *root); extern void flatten_simple_union_all(PlannerInfo *root); extern void reduce_outer_joins(PlannerInfo *root); extern void remove_useless_result_rtes(PlannerInfo *root); +extern void substitute_phv_relids(Node *node, int varno, Relids subrelids); extern Relids get_relids_in_jointree(Node *jtnode, bool include_outer_joins, bool include_inner_joins); extern Relids get_relids_for_join(Query *query, int joinrelid); diff --git a/src/test/regress/expected/join.out b/src/test/regress/expected/join.out index db4fcc5a5a0..9f9b28f3334 100644 --- a/src/test/regress/expected/join.out +++ b/src/test/regress/expected/join.out @@ -7361,6 +7361,17 @@ SELECT q.val FROM b LEFT JOIN ( -> Seq Scan on a t1 (7 rows) +-- removing a LATERAL subquery can make the rel it references removable too +explain (costs off) +select d.* from d + left join a on d.a = a.id + left join lateral (select count(*) as cnt from c where c.id = a.b_id) s + on true; + QUERY PLAN +--------------- + Seq Scan on d +(1 row) + CREATE TEMP TABLE parted_b (id int PRIMARY KEY) partition by range(id); CREATE TEMP TABLE parted_b1 partition of parted_b for values from (0) to (10); -- test join removals on a partitioned table diff --git a/src/test/regress/sql/join.sql b/src/test/regress/sql/join.sql index 9533af8656e..a202e66dc52 100644 --- a/src/test/regress/sql/join.sql +++ b/src/test/regress/sql/join.sql @@ -2712,6 +2712,13 @@ SELECT q.val FROM b LEFT JOIN ( ON true ) AS q ON true; +-- removing a LATERAL subquery can make the rel it references removable too +explain (costs off) +select d.* from d + left join a on d.a = a.id + left join lateral (select count(*) as cnt from c where c.id = a.b_id) s + on true; + CREATE TEMP TABLE parted_b (id int PRIMARY KEY) partition by range(id); CREATE TEMP TABLE parted_b1 partition of parted_b for values from (0) to (10); -- 2.37.1 (Apple Git-137.1)
^ permalink raw reply [nested|flat] 74+ messages in thread

* Re: remove_useless_joins vs. bug #19560
  2026-07-20 18:52 remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-24 13:38 ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-07-25 16:46   ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-25 20:07     ` Re: remove_useless_joins vs. bug #19560 Thom Brown <thom@linux.com>
  2026-07-25 21:23       ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-26 02:15         ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-26 09:49           ` Re: remove_useless_joins vs. bug #19560 Thom Brown <thom@linux.com>
  2026-07-26 17:33             ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-26 17:35               ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-27 07:07                 ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-07-27 16:33                   ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-27 18:21                     ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-29 06:21                       ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-16 23:58                         ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-26 05:26                           ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
@ 2026-08-26 17:25                             ` Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-27 01:57                               ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  0 siblings, 1 reply; 74+ messages in thread

From: Tom Lane @ 2026-08-26 17:25 UTC (permalink / raw)
  To: Richard Guo <guofenglinux@gmail.com>; +Cc: Thom Brown <thom@linux.com>; Jacob Brazeal <jacob.brazeal@gmail.com>; pgsql-hackers@lists.postgresql.org

Richard Guo <guofenglinux@gmail.com> writes:
> On Mon, Aug 17, 2026 at 8:58 AM Tom Lane <tgl@sss.pgh.pa.us> wrote:
>> One idea for fixing this is to null out the subquery field of a
>> subquery RTE as soon as we've pulled it up, but there is probably
>> code that will crash on a null subquery pointer.

> It seems to me that the subquery in question isn't a pulled-up one.
> pull_up_simple_subquery() already sets rte->subquery to NULL at line
> prepjointree.c:1725.
> What is in question is the subquery of a rel removed by join removal
> itself.  Its RTE stays in the rangetable with the query tree intact,
> and that tree can contain lateral references to rels that are still
> around.

Hah, thanks for identifying the locus of that issue.

I still don't like replacing this usage of ChangeVarNodes with
substitute_phv_relids though.  While it's a kluge as-presented,
I'm not sure that using substitute_phv_relids that way is much less
of a kluge.  Moreover, if there were any leftover Vars in the tree,
substitute_phv_relids wouldn't notice.  I think noticing that is a
good thing, and the fact that it identified this oversight in
remove_useless_outer_joins seems like evidence in favor of that.

So what I'd prefer to do is as in 0002 attached.  For simplicity of
review, 0001 is the same as the v5 combined patch I presented before.
(But it's rebased onto today's HEAD, which changes only line numbers,
and I tweaked the commit message's claim about planning time per your
other comments.)  0002 changes ChangeVarNodes' API to have a clean
way to represent "we're removing this relid", and adds the fix you
identified with a more extensive comment.

(Maybe it'd make sense to use this version of ChangeVarNodes in
prepjointree too?  I didn't look into that.)

			regards, tom lane

Attachments: download all (2 files, .tar.gz)

v6-0001-Perform-join-removal-by-editing-the-query-s-joint.patch (text/x-diff, 128.8K) download From ac2978656c4af085bbac7cb0f5aca180956a10fa Mon Sep 17 00:00:00 2001 From: Tom Lane <tgl@sss.pgh.pa.us> Date: Wed, 26 Aug 2026 12:31:17 -0400 Subject: [PATCH v6 1/2] Perform join removal by editing the query's jointree. analyzejoins.c decided which joins could be dropped by consulting the planner's derived data structures, but then implemented the removal by updating those structures in-place. That is a lot of fiddly work, and nothing keeps it in step with the rest of the planner: remove_leftjoinrel_from_query only bothered to update "parts of the planner's data structures that will actually be consulted later", with no good way to know what those are. Bug #19560 is one consequence. In that report, removing a join leaves an EquivalenceClass that now gives rise to a base restriction clause, but base restriction clauses have already been generated and nothing reconsiders them, so the WHERE condition disappears from the plan and we return wrong answers. The self-join elimination code has the same design and the same type of hazard. We have seen many related bugs over the years too, so it's time to do something drastic. To fix, do the removals by editing root->parse->jointree (which is a far simpler and more stable representation than the derived data), and then have query_planner() discard everything it computed from the jointree and derive it over again. This requires quite a bit less code, and doesn't require touching analyzejoins.c every time we change the data derived by query_planner(). For typical cases it can actually save a bit of planning time, though in cases where we have to iterate the derivation loop multiple times it does add some time. reduce_unique_semijoins() gets the same treatment: rather than deleting the semijoin's SpecialJoinInfo and relying on the jointree not being consulted again, it now changes the JoinExpr's jointype to JOIN_INNER. Some plans change in the join regression test. Qual evaluation order shifts in a few cases, because the conditions now reach later planning in jointree order rather than in whatever order the removal code re-distributed them. A few plans improve, since the rebuilt relation targetlists no longer carry columns that only a removed join needed. We also detect a constant-false filter condition whose test used to carry a FIXME label. One plan gets marginally worse, because the old code recomputed attr_needed from equivalence classes after a join removal; that is more accurate than what deconstruct_jointree() derives from the original clauses, but we no longer do that. Making that recomputation happen anyway could be worth doing, but it should be considered independently and perhaps implemented differently. Full disclosure: initial drafts of this patch were made with Claude Opus 4.8. Bug: #19560 Reported-by: Orestis Markou <orestis@orestis.gr> Author: Tom Lane <tgl@sss.pgh.pa.us> Reviewed-by: Thom Brown <thom@linux.com> Reviewed-by: Jacob Brazeal <jacob.brazeal@gmail.com> Discussion: https://postgr.es/m/1186816.1784573544@sss.pgh.pa.us Backpatch-through: 16 --- src/backend/optimizer/path/equivclass.c | 51 +- src/backend/optimizer/plan/analyzejoins.c | 1872 +++++++-------------- src/backend/optimizer/plan/initsplan.c | 185 +- src/backend/optimizer/plan/planmain.c | 84 +- src/backend/optimizer/plan/planner.c | 18 +- src/backend/optimizer/util/joininfo.c | 36 - src/backend/optimizer/util/placeholder.c | 27 - src/backend/rewrite/rewriteManip.c | 65 +- src/include/optimizer/joininfo.h | 3 - src/include/optimizer/paths.h | 2 - src/include/optimizer/placeholder.h | 1 - src/include/optimizer/planmain.h | 14 +- src/include/rewrite/rewriteManip.h | 19 - src/test/regress/expected/join.out | 159 +- src/test/regress/sql/join.sql | 58 +- src/tools/pgindent/typedefs.list | 1 - 16 files changed, 922 insertions(+), 1673 deletions(-) diff --git a/src/backend/optimizer/path/equivclass.c b/src/backend/optimizer/path/equivclass.c index 0dcc2ed4266..393a7a69742 100644 --- a/src/backend/optimizer/path/equivclass.c +++ b/src/backend/optimizer/path/equivclass.c @@ -89,6 +89,7 @@ static void ec_build_derives_hash(PlannerInfo *root, EquivalenceClass *ec); static void ec_add_derived_clauses(EquivalenceClass *ec, List *clauses); static void ec_add_derived_clause(EquivalenceClass *ec, RestrictInfo *clause); static void ec_add_clause_to_derives_hash(EquivalenceClass *ec, RestrictInfo *rinfo); +static void ec_clear_derived_clauses(EquivalenceClass *ec); static RestrictInfo *ec_search_clause_for_ems(PlannerInfo *root, EquivalenceClass *ec, EquivalenceMember *leftem, EquivalenceMember *rightem, @@ -1451,8 +1452,7 @@ generate_base_implied_equalities_no_const(PlannerInfo *root, * For the moment we force all the Vars to be available at all join nodes * for this eclass. Perhaps this could be improved by doing some * pre-analysis of which members we prefer to join, but it's no worse than - * what happened in the pre-8.3 code. (Note: rebuild_eclass_attr_needed - * needs to match this code.) + * what happened in the pre-8.3 code. */ foreach(lc, ec->ec_members) { @@ -2559,51 +2559,6 @@ reconsider_full_join_clause(PlannerInfo *root, OuterJoinClauseInfo *ojcinfo) return false; /* failed to make any deduction */ } -/* - * rebuild_eclass_attr_needed - * Put back attr_needed bits for Vars/PHVs needed for join eclasses. - * - * This is used to rebuild attr_needed/ph_needed sets after removal of a - * useless outer join. It should match what - * generate_base_implied_equalities_no_const did, except that we call - * add_vars_to_attr_needed not add_vars_to_targetlist. - */ -void -rebuild_eclass_attr_needed(PlannerInfo *root) -{ - ListCell *lc; - - foreach(lc, root->eq_classes) - { - EquivalenceClass *ec = (EquivalenceClass *) lfirst(lc); - - /* - * 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); - - /* Need do anything only for a multi-member, no-const EC. */ - if (list_length(ec->ec_members) > 1 && !ec->ec_has_const) - { - ListCell *lc2; - - foreach(lc2, ec->ec_members) - { - EquivalenceMember *cur_em = (EquivalenceMember *) lfirst(lc2); - List *vars = pull_var_clause((Node *) cur_em->em_expr, - PVC_RECURSE_AGGREGATES | - PVC_RECURSE_WINDOWFUNCS | - PVC_INCLUDE_PLACEHOLDERS); - - add_vars_to_attr_needed(root, vars, ec->ec_relids); - list_free(vars); - } - } - } -} - /* * find_join_domain * Find the highest JoinDomain enclosed within the given relid set. @@ -3825,7 +3780,7 @@ ec_add_clause_to_derives_hash(EquivalenceClass *ec, RestrictInfo *rinfo) * when thousands of partitions are involved, so we free it as well -- even * though we do not typically free lists. */ -void +static void ec_clear_derived_clauses(EquivalenceClass *ec) { list_free(ec->ec_derives_list); diff --git a/src/backend/optimizer/plan/analyzejoins.c b/src/backend/optimizer/plan/analyzejoins.c index cbd36f85417..7c77118c76a 100644 --- a/src/backend/optimizer/plan/analyzejoins.c +++ b/src/backend/optimizer/plan/analyzejoins.c @@ -7,9 +7,14 @@ * certain optimizations cannot be performed at that stage for lack of * detailed information about the query. The routines here are invoked * after initsplan.c has done its work, and can do additional join removal - * and simplification steps based on the information extracted. The penalty - * is that we have to work harder to clean up after ourselves when we modify - * the query, since the derived data structures have to be updated too. + * and simplification steps based on the information extracted. + * + * Although the decisions about what can be removed are made using the + * planner's derived data structures, the removals themselves are implemented + * by editing the query's jointree, which is a far simpler and more stable + * representation. We make no attempt to update the derived data structures + * to match; instead, query_planner() throws them all away and recomputes them + * whenever we report having removed something. * * Portions Copyright (c) 1996-2026, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California @@ -23,13 +28,13 @@ #include "postgres.h" #include "catalog/pg_class.h" +#include "nodes/makefuncs.h" #include "nodes/nodeFuncs.h" -#include "optimizer/joininfo.h" #include "optimizer/optimizer.h" #include "optimizer/pathnode.h" #include "optimizer/paths.h" -#include "optimizer/placeholder.h" #include "optimizer/planmain.h" +#include "optimizer/prep.h" #include "optimizer/restrictinfo.h" #include "parser/parse_agg.h" #include "rewrite/rewriteManip.h" @@ -55,24 +60,23 @@ bool enable_self_join_elimination; /* local functions */ static bool join_is_removable(PlannerInfo *root, SpecialJoinInfo *sjinfo); -static void remove_leftjoinrel_from_query(PlannerInfo *root, int relid, - SpecialJoinInfo *sjinfo); -static void remove_rel_from_query(PlannerInfo *root, int relid, - int subst, SpecialJoinInfo *sjinfo, - Relids joinrelids); -static void remove_rel_from_restrictinfo(RestrictInfo *rinfo, - int relid, int ojrelid); -static void remove_rel_from_eclass(PlannerInfo *root, EquivalenceClass *ec, - int relid, int ojrelid); -static void remove_rel_from_restrictinfo_phvs(RestrictInfo *rinfo, - int relid, int ojrelid); -static Node *remove_rel_from_phvs(Node *node, int relid, int ojrelid); -static Node *remove_rel_from_phvs_mutator(Node *node, Relids removable); -static List *remove_rel_from_joinlist(List *joinlist, int relid, int *nremoved); +static Node *remove_join_from_jointree(Node *jtnode, int ojrelid, + int *nremoved); +static void remove_rels_from_query_tree(PlannerInfo *root, + Relids removed_relids); +static bool reduce_semijoin_in_jointree(Node *jtnode, Relids syn_righthand); static bool rel_supports_distinctness(PlannerInfo *root, RelOptInfo *rel); static bool rel_is_distinct_for(PlannerInfo *root, RelOptInfo *rel, List *clause_list, List **extra_clauses); static DistinctColInfo *distinct_col_search(int colno, List *distinct_cols); +static bool innerrel_is_unique_ext(PlannerInfo *root, + Relids joinrelids, + Relids outerrelids, + RelOptInfo *innerrel, + JoinType jointype, + List *restrictlist, + bool force_cache, + List **extra_clauses); static bool is_innerrel_unique_for(PlannerInfo *root, Relids joinrelids, Relids outerrelids, @@ -80,29 +84,35 @@ static bool is_innerrel_unique_for(PlannerInfo *root, 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); -static bool replace_relid_callback(Node *node, - ChangeVarNodes_context *context); /* - * remove_useless_joins + * remove_useless_outer_joins * Check for relations that don't actually need to be joined at all, - * and remove them from the query. + * and remove them from the query's jointree. * - * We are passed the current joinlist and return the updated list. Other - * data structures that have to be updated are accessible via "root". + * Returns true if we removed anything. In that case the caller must discard + * everything it has derived from the jointree and compute it over again, + * since we don't try to update any of that here. */ -List * -remove_useless_joins(PlannerInfo *root, List *joinlist) +bool +remove_useless_outer_joins(PlannerInfo *root) { + Relids removed_relids = NULL; ListCell *lc; /* * We are only interested in relations that are left-joined to, so we can * scan the join_info_list to find them easily. */ -restart: foreach(lc, root->join_info_list) { SpecialJoinInfo *sjinfo = (SpecialJoinInfo *) lfirst(lc); @@ -114,37 +124,59 @@ restart: continue; /* - * Currently, join_is_removable can only succeed when the sjinfo's - * righthand is a single baserel. Remove that rel from the query and - * joinlist. + * join_is_removable insists that the join's syntactic righthand side + * be a single baserel, so we can implement the removal by dropping + * the JoinExpr and everything below its righthand side. */ - innerrelid = bms_singleton_member(sjinfo->min_righthand); + innerrelid = bms_singleton_member(sjinfo->syn_righthand); - remove_leftjoinrel_from_query(root, innerrelid, sjinfo); + /* + * The removed rel had better not be one that the rest of the planner + * expects to find. It can't be, really: a result relation or a + * row-marked relation has junk columns in the query targetlist, and + * join_is_removable would have seen those as uses of the rel from + * "relation 0". But let's check. + */ + Assert(innerrelid != root->parse->resultRelation); +#ifdef USE_ASSERT_CHECKING + foreach_node(PlanRowMark, rc, root->rowMarks) + Assert(rc->rti != innerrelid && rc->prti != innerrelid); +#endif - /* We verify that exactly one reference gets removed from joinlist */ + /* We verify that exactly one JoinExpr gets removed */ nremoved = 0; - joinlist = remove_rel_from_joinlist(joinlist, innerrelid, &nremoved); + root->parse->jointree = (FromExpr *) + remove_join_from_jointree((Node *) root->parse->jointree, + sjinfo->ojrelid, &nremoved); if (nremoved != 1) - elog(ERROR, "failed to find relation %d in joinlist", innerrelid); + elog(ERROR, "failed to find join %d in jointree", sjinfo->ojrelid); - /* - * We can delete this SpecialJoinInfo from the list too, since it's no - * longer of interest. (Since we'll restart the foreach loop - * immediately, we don't bother with foreach_delete_current.) - */ - root->join_info_list = list_delete_cell(root->join_info_list, lc); + /* Track all the relids we've removed, for use below */ + removed_relids = bms_add_member(removed_relids, innerrelid); + removed_relids = bms_add_member(removed_relids, sjinfo->ojrelid); /* - * Restart the scan. This is necessary to ensure we find all - * removable joins independently of ordering of the join_info_list - * (note that removal of attr_needed bits may make a join appear - * removable that did not before). + * It's okay to keep scanning join_info_list for more removable joins, + * even though the data that join_is_removable consults is now + * slightly out of date. Removing a join can only delete attr_needed + * bits and join clauses, and any attr_needed bit or join clause that + * mentions the removed rel above its own join level would have + * prevented that rel from being removable. So what remains to be + * examined is unchanged by what we just did. + * + * The converse doesn't hold: dropping a join can make some other join + * removable that didn't look so before. That's why our caller loops + * until we report finding nothing more to remove. */ - goto restart; } - return joinlist; + if (bms_is_empty(removed_relids)) + return false; + + /* Clean up the traces that the removed rels have left elsewhere */ + remove_rels_from_query_tree(root, removed_relids); + + return true; } /* @@ -176,8 +208,15 @@ join_is_removable(PlannerInfo *root, SpecialJoinInfo *sjinfo) if (sjinfo->jointype != JOIN_LEFT) return false; - if (!bms_get_singleton_member(sjinfo->min_righthand, &innerrelid)) + /* + * We test the syntactic righthand side, not min_righthand, because the + * removal is done by deleting the whole righthand subtree of the join. + * (min_righthand can be a singleton when syn_righthand is not, but in + * such a case the attr_needed tests below would reject the join anyway.) + */ + if (!bms_get_singleton_member(sjinfo->syn_righthand, &innerrelid)) return false; + Assert(bms_equal(sjinfo->min_righthand, sjinfo->syn_righthand)); /* * Never try to eliminate a left join to the query result rel. Although @@ -319,712 +358,90 @@ join_is_removable(PlannerInfo *root, SpecialJoinInfo *sjinfo) } /* - * 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. - * - * This function serves as the common infrastructure for left-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 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. * - * 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). + * *nremoved is incremented by the number of JoinExprs removed (there should + * be exactly one, but the caller checks that). */ -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) { - 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); - Bitmapset *seen_serials = NULL; - - Assert(is_outer_join || is_self_join); - Assert(!is_outer_join || ojrelid > 0); - Assert(!is_outer_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) - { - root->outer_join_rels = bms_del_member(root->outer_join_rels, ojrelid); - root->all_query_rels = bms_del_member(root->all_query_rels, ojrelid); - } - - /* - * 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) - { - SpecialJoinInfo *sjinf = (SpecialJoinInfo *) lfirst(l); - - /* - * 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 - { - /* - * For self-join removal, replace relid references in - * semi_rhs_exprs. - */ - ChangeVarNodesExtended((Node *) sjinf->semi_rhs_exprs, relid, subst, - 0, replace_relid_callback); - } - } - - /* - * Likewise remove references from PlaceHolderVar data structures, - * removing any no-longer-needed placeholders entirely. We only remove - * PHVs for left-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 is no corresponding test in - * join_is_removable because it doesn't need to distinguish those cases. - */ - foreach(l, root->placeholder_list) - { - PlaceHolderInfo *phinfo = (PlaceHolderInfo *) lfirst(l); - - Assert(!is_outer_join || !bms_is_member(relid, phinfo->ph_lateral)); - - if (is_outer_join && - bms_is_subset(phinfo->ph_needed, joinrelids) && - bms_is_member(relid, phinfo->ph_eval_at) && - !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 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.) - */ - 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) + if (jtnode == NULL) + return NULL; + if (IsA(jtnode, RangeTblRef)) { - foreach(l, root->eq_classes) - { - EquivalenceClass *ec = (EquivalenceClass *) lfirst(l); - - remove_rel_from_eclass(root, ec, relid, ojrelid); - } + /* nothing to do here */ } - - /* - * 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 removal, we strip the removed rel and join from any - * PlaceHolderVar embedded in the surviving rels' restriction clauses and - * join clauses; 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++) + else if (IsA(jtnode, FromExpr)) { - 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 && rti != relid && root->glob->lastPHId != 0) - { - foreach_node(RestrictInfo, rinfo, otherrel->baserestrictinfo) - remove_rel_from_restrictinfo_phvs(rinfo, relid, ojrelid); - - /* - * Join clauses need the same treatment, but there's no value in - * processing any join clause more than once. So it's slightly - * annoying that we have to find them via the per-base-relation - * joininfo lists. Avoid duplicate processing by tracking the - * rinfo_serial numbers of join clauses we've already seen. (This - * doesn't work for is_clone clauses, so we must waste effort on - * them.) - */ - foreach_node(RestrictInfo, rinfo, otherrel->joininfo) - { - if (!rinfo->is_clone) /* else serial number is not unique */ - { - if (bms_is_member(rinfo->rinfo_serial, seen_serials)) - continue; /* saw it already */ - seen_serials = bms_add_member(seen_serials, - rinfo->rinfo_serial); - } - remove_rel_from_restrictinfo_phvs(rinfo, relid, ojrelid); - } - } - } -} - -/* - * Remove any references to relid or ojrelid from the RestrictInfo. - * - * 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); - 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); - 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); - 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); - 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); - 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); - 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. - * - * 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. - */ -static void -remove_rel_from_eclass(PlannerInfo *root, EquivalenceClass *ec, - int relid, int ojrelid) -{ - ListCell *lc; + FromExpr *f = (FromExpr *) jtnode; + ListCell *l; - /* - * 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); - } + foreach(l, f->fromlist) + lfirst(l) = remove_join_from_jointree((Node *) lfirst(l), + ojrelid, nremoved); } - - if (!bms_is_member(relid, ec->ec_relids) && - !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); - 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) + else if (IsA(jtnode, JoinExpr)) { - EquivalenceMember *cur_em = (EquivalenceMember *) lfirst(lc); + JoinExpr *j = (JoinExpr *) jtnode; - if (bms_is_member(relid, cur_em->em_relids) || - bms_is_member(ojrelid, cur_em->em_relids)) + if (j->rtindex == ojrelid) { - 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); - 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); + (*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)); - /* 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); + return jtnode; } /* - * Remove any references to relid or ojrelid from the PlaceHolderVars embedded - * in a RestrictInfo's clause. + * remove_rels_from_query_tree + * Delete all remaining references to the given relids from the query. * - * If it's an OR clause, we must also fix up the orclause, which is a parallel - * representation built from its own sub-RestrictInfos. We recurse into the - * sub-clauses for that, mirroring remove_rel_from_restrictinfo. + * 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 the relids can + * still appear in the nullingrels sets of surviving Vars and PlaceHolderVars, + * and in the phrels sets of PlaceHolderVars. ChangeVarNodes knows how to + * strip a relid out of all of those. */ static void -remove_rel_from_restrictinfo_phvs(RestrictInfo *rinfo, int relid, int ojrelid) +remove_rels_from_query_tree(PlannerInfo *root, Relids removed_relids) { - rinfo->clause = (Expr *) - remove_rel_from_phvs((Node *) rinfo->clause, relid, 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_phvs(rinfo2, relid, ojrelid); - } - } - else - { - RestrictInfo *rinfo2 = castNode(RestrictInfo, orarg); - - remove_rel_from_restrictinfo_phvs(rinfo2, relid, ojrelid); - } - } - } -} - -/* - * 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); -} + int relid = -1; -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); + /* Pass -1 for new_index to get the removal behavior */ + ChangeVarNodes((Node *) root->parse, relid, -1, 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); - } - - return (Node *) phv; - } - 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; + ChangeVarNodes((Node *) root->processed_tlist, relid, -1, 0); - 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)); - } + /* There could be references in the append_rel_list, too */ + if (root->append_rel_list != NIL) + ChangeVarNodes((Node *) root->append_rel_list, relid, -1, 0); } - - return result; } - /* * reduce_unique_semijoins * Check for semijoins that can be simplified to plain inner joins @@ -1033,14 +450,13 @@ remove_rel_from_joinlist(List *joinlist, int relid, int *nremoved) * Ideally this would happen during reduce_outer_joins, but we don't have * enough information at that point. * - * To perform the strength reduction when applicable, we need only delete - * the semijoin's SpecialJoinInfo from root->join_info_list. (We don't - * bother fixing the join type attributed to it in the query jointree, - * since that won't be consulted again.) + * Like the join removal cases, we do this on the query's jointree, so + * returning true means the caller must recompute the derived data. */ -void +bool reduce_unique_semijoins(PlannerInfo *root) { + bool changed = false; ListCell *lc; /* @@ -1091,15 +507,71 @@ reduce_unique_semijoins(PlannerInfo *root) NULL), innerrel->joininfo); - /* Test whether the innerrel is unique for those clauses. */ - if (!innerrel_is_unique(root, - joinrelids, sjinfo->min_lefthand, innerrel, - JOIN_SEMI, restrictlist, true)) - continue; + /* Test whether the innerrel is unique for those clauses. */ + if (!innerrel_is_unique(root, + joinrelids, sjinfo->min_lefthand, innerrel, + JOIN_SEMI, restrictlist, true)) + continue; + + /* OK, reduce the join to a plain inner join in the jointree. */ + if (!reduce_semijoin_in_jointree((Node *) root->parse->jointree, + sjinfo->syn_righthand)) + elog(ERROR, "failed to find semijoin in jointree"); + changed = true; + } + + return changed; +} + +/* + * reduce_semijoin_in_jointree + * Find the JoinExpr for the semijoin with the given syntactic righthand + * side, and turn it into an inner join. + * + * Semijoins have no RT index of their own, so we have to identify the one + * we want by the set of relids on its righthand side. + */ +static bool +reduce_semijoin_in_jointree(Node *jtnode, Relids syn_righthand) +{ + if (jtnode == NULL) + return false; + if (IsA(jtnode, RangeTblRef)) + { + /* nothing to do here */ + } + else if (IsA(jtnode, FromExpr)) + { + FromExpr *f = (FromExpr *) jtnode; + ListCell *l; + + foreach(l, f->fromlist) + { + if (reduce_semijoin_in_jointree((Node *) lfirst(l), syn_righthand)) + return true; + } + } + else if (IsA(jtnode, JoinExpr)) + { + JoinExpr *j = (JoinExpr *) jtnode; - /* OK, remove the SpecialJoinInfo from the list. */ - root->join_info_list = foreach_delete_current(root->join_info_list, lc); + if (j->jointype == JOIN_SEMI && + bms_equal(get_relids_in_jointree(j->rarg, true, false), + syn_righthand)) + { + j->jointype = JOIN_INNER; + return true; + } + if (reduce_semijoin_in_jointree(j->larg, syn_righthand)) + return true; + if (reduce_semijoin_in_jointree(j->rarg, syn_righthand)) + return true; } + else + elog(ERROR, "unrecognized jointree node type: %d", + (int) nodeTag(jtnode)); + + return false; } @@ -1548,7 +1020,7 @@ innerrel_is_unique(PlannerInfo *root, * A non-NULL extra_clauses indicates that we're checking for self-join and * correspondingly dealing with filtered clauses. */ -bool +static bool innerrel_is_unique_ext(PlannerInfo *root, Relids joinrelids, Relids outerrelids, @@ -1728,498 +1200,430 @@ is_innerrel_unique_for(PlannerInfo *root, } /* - * Update EC members to point to the remaining relation instead of the removed - * one, removing duplicates. + * Remove the toRemove relation after we have proven that it participates only + * in an unneeded unique self-join with toKeep. * - * Restriction clauses for base relations are already distributed to - * the respective baserestrictinfo lists (see - * generate_implied_equalities_for_column). The above code has already processed - * this list and updated these clauses to reference the remaining - * relation, so that we can skip them here based on their relids. + * The removal is done by deleting the relation's RangeTblRef from the + * jointree and then pointing everything that referenced it at the relation we + * are keeping. All the conditions that were attached to the removed relation + * thereby become conditions on the remaining one, which is what we want: + * we've proven that the two relations select the same rows. Note that + * this change requires us to hoist those conditions up to someplace + * syntactically enclosing toKeep. * - * Likewise, we have already processed the join clauses that join the - * removed relation to the remaining one. - * - * Finally, there might be join clauses tying the removed relation to - * some third relation. We can't just delete the source clauses and - * regenerate them from the EC because the corresponding equality - * operators might be missing (see the handling of ec_broken). - * Therefore, we will update the references in the source clauses. - * - * Derived clauses can be generated again, so it is simpler just to - * delete them. + * kmark and rmark are the PlanRowMarks (if any) for the kept and removed + * relations. We could re-locate those, but the caller already found them. */ static void -update_eclasses(EquivalenceClass *ec, int from, int to) +remove_self_join_rel(PlannerInfo *root, + RelOptInfo *toKeep, RelOptInfo *toRemove, + PlanRowMark *kmark, PlanRowMark *rmark) { - List *new_members = NIL; - List *new_sources = NIL; + Node *orphan_quals = NULL; + int nremoved = 0; + Node *hoist_quals = NULL; + bool found_relid = false; + + Assert(toKeep->relid > 0); + Assert(toRemove->relid > 0); + + /* We verify that exactly one reference gets removed from the jointree */ + root->parse->jointree = (FromExpr *) + remove_rel_from_jointree((Node *) root->parse->jointree, + toRemove->relid, + &orphan_quals, &nremoved); + if (nremoved != 1) + elog(ERROR, "failed to find relation %d in jointree", toRemove->relid); + /* The topmost FromExpr can't have gone away, so nothing can be orphaned */ + Assert(root->parse->jointree != NULL); + Assert(orphan_quals == NULL); /* - * 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. + * Replace all references to the removed relation. Note that this must + * happen after the jointree surgery, else we'd not be able to tell the + * two relations' RangeTblRefs apart. */ - Assert(ec->ec_childmembers == NULL); + ChangeVarNodes((Node *) root->parse, toRemove->relid, toKeep->relid, 0); - foreach_node(EquivalenceMember, em, ec->ec_members) - { - bool is_redundant = false; + /* + * 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 the second visit to a + * shared node finds nothing to change.) + */ + ChangeVarNodes((Node *) root->processed_tlist, toRemove->relid, + toKeep->relid, 0); + + /* There could be references in the append_rel_list, too */ + if (root->append_rel_list != NIL) + ChangeVarNodes((Node *) root->append_rel_list, toRemove->relid, + toKeep->relid, 0); + + /* Clean up the quals that the substitution has messed with */ + fixup_selfjoin_jointree(root, (Node *) root->parse->jointree, + toKeep->relid, + &hoist_quals, &found_relid); + /* We shouldn't have any leftover quals, and we must have found toKeep */ + Assert(hoist_quals == NULL); + Assert(found_relid); - if (!bms_is_member(from, em->em_relids)) + /* + * 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) + { + if (kmark) { - new_members = lappend(new_members, em); - continue; - } - - em->em_relids = adjust_relid_set(em->em_relids, from, to); - em->em_jdomain->jd_relids = adjust_relid_set(em->em_jdomain->jd_relids, from, to); - - /* We only process inner joins */ - ChangeVarNodesExtended((Node *) em->em_expr, from, to, 0, - replace_relid_callback); + Assert(kmark->markType == rmark->markType); - foreach_node(EquivalenceMember, other, new_members) + root->rowMarks = list_delete_ptr(root->rowMarks, rmark); + } + else { - if (!equal(em->em_relids, other->em_relids)) - continue; + /* Shouldn't have inheritance children yet. */ + Assert(rmark->rti == rmark->prti); - if (equal(em->em_expr, other->em_expr)) - { - is_redundant = true; - break; - } + rmark->rti = rmark->prti = toKeep->relid; } - - if (!is_redundant) - new_members = lappend(new_members, em); } +} - list_free(ec->ec_members); - ec->ec_members = new_members; - - ec_clear_derived_clauses(ec); - - /* Update EC source expressions */ - foreach_node(RestrictInfo, rinfo, ec->ec_sources) +/* + * remove_rel_from_jointree + * Delete the RangeTblRef for the given relation from the query's + * jointree. + * + * This is used for self-join elimination, where the removed relation's + * qual conditions must all be preserved (they will be transposed onto the + * remaining relation afterwards). Hence, if dropping the RangeTblRef leaves + * a JoinExpr or FromExpr with nothing under it, we can't simply drop that + * node; we hand its quals back to the caller in *orphan_quals, to be merged + * into the nearest enclosing node that still has some content. That's a + * valid transformation only for inner joins, but a jointree node can't become + * empty at an outer join here: remove_self_joins_one_group() insists that the + * two relations be on the same side of every outer join, so the relation we + * are keeping would have to be in the emptied subtree too. + * + * *nremoved is incremented by the number of RangeTblRefs removed (there + * should be exactly one, but the caller checks that). + */ +static Node * +remove_rel_from_jointree(Node *jtnode, int relid, + Node **orphan_quals, int *nremoved) +{ + if (jtnode == NULL) + return NULL; + if (IsA(jtnode, RangeTblRef)) { - bool is_redundant = false; + RangeTblRef *rtr = (RangeTblRef *) jtnode; - if (!bms_is_member(from, rinfo->required_relids)) + if (rtr->rtindex == relid) { - new_sources = lappend(new_sources, rinfo); - continue; + (*nremoved)++; + return NULL; } + } + else if (IsA(jtnode, FromExpr)) + { + FromExpr *f = (FromExpr *) jtnode; + List *newfromlist = NIL; + Node *sub_orphans = NULL; + ListCell *l; - ChangeVarNodesExtended((Node *) rinfo, from, to, 0, - replace_relid_callback); - - /* - * After switching the clause to the remaining relation, check it for - * redundancy with existing ones. We don't have to check for - * redundancy with derived clauses, because we've just deleted them. - */ - foreach_node(RestrictInfo, other, new_sources) + foreach(l, f->fromlist) { - if (!equal(rinfo->clause_relids, other->clause_relids)) - continue; + Node *newchild; - if (equal(rinfo->clause, other->clause)) - { - is_redundant = true; - break; - } + newchild = remove_rel_from_jointree((Node *) lfirst(l), relid, + &sub_orphans, nremoved); + if (newchild != NULL) + newfromlist = lappend(newfromlist, newchild); + } + f->fromlist = newfromlist; + f->quals = merge_quals(sub_orphans, f->quals); + if (newfromlist == NIL) + { + /* Nothing left here, so pass our quals up to the parent */ + *orphan_quals = merge_quals(f->quals, *orphan_quals); + return NULL; } + } + else if (IsA(jtnode, JoinExpr)) + { + JoinExpr *j = (JoinExpr *) jtnode; + Node *sub_orphans = NULL; + + j->larg = remove_rel_from_jointree(j->larg, relid, + &sub_orphans, nremoved); + j->rarg = remove_rel_from_jointree(j->rarg, relid, + &sub_orphans, nremoved); + if (j->larg == NULL || j->rarg == NULL) + { + Node *surviving = (j->larg != NULL) ? j->larg : j->rarg; + Node *quals = merge_quals(sub_orphans, j->quals); + + /* As explained above, this can only happen for an inner join */ + Assert(j->jointype == JOIN_INNER); + /* We can't have removed both children */ + Assert(surviving != NULL); - if (!is_redundant) - new_sources = lappend(new_sources, rinfo); + /* + * Replace the join by a FromExpr, so that the surviving side's + * rows are still filtered by the join's conditions. + */ + return (Node *) makeFromExpr(list_make1(surviving), quals); + } + /* A subtree that survives never hands any quals back to us */ + Assert(sub_orphans == NULL); } + else + elog(ERROR, "unrecognized jointree node type: %d", + (int) nodeTag(jtnode)); - list_free(ec->ec_sources); - ec->ec_sources = new_sources; - ec->ec_relids = adjust_relid_set(ec->ec_relids, from, to); + return jtnode; } /* - * "Logically" compares two RestrictInfo's ignoring the 'rinfo_serial' field, - * which makes almost every RestrictInfo unique. This type of comparison is - * useful when removing duplicates while moving RestrictInfo's from removed - * relation to remaining relation during self-join elimination. + * merge_quals + * Combine two jointree qual conditions. * - * XXX: In the future, we might remove the 'rinfo_serial' field completely and - * get rid of this function. + * quals1 should be the quals from the lower of the two jointree levels, + * so that those quals get applied first. + * + * Jointree quals have been through preprocess_expression() by now, so each + * one is either NULL or an implicitly-ANDed List. */ -static bool -restrict_infos_logically_equal(RestrictInfo *a, RestrictInfo *b) +static Node * +merge_quals(Node *quals1, Node *quals2) { - int saved_rinfo_serial = a->rinfo_serial; - bool result; - - a->rinfo_serial = b->rinfo_serial; - result = equal(a, b); - a->rinfo_serial = saved_rinfo_serial; - - return result; + if (quals1 == NULL) + return quals2; + if (quals2 == NULL) + return quals1; + return (Node *) list_concat(castNode(List, quals1), + castNode(List, quals2)); } /* - * This function adds all non-redundant clauses to the keeping relation - * during self-join elimination. That is a contradictory operation. On the - * one hand, we reduce the length of the `restrict` lists, which can - * impact planning or executing time. Additionally, we improve the - * accuracy of cardinality estimation. On the other hand, it is one more - * place that can make planning time much longer in specific cases. It - * would have been better to avoid calling the equal() function here, but - * it's the only way to detect duplicated inequality expressions. + * fixup_selfjoin_jointree + * Clean up the query's jointree quals after self-join elimination has + * merged one relation into another. (relid is the kept relation.) * - * (*keep_rinfo_list) is given by pointer because it might be altered by - * distribute_restrictinfo_to_rels(). + * See fixup_selfjoin_quals() for what needs fixing locally to each qual list. + * In addition, we need to check quals to see if they refer to relid, and if + * so make sure they get hoisted to someplace syntactically above relid. + * Do that using a "hoist_quals" in/out parameter similar to "orphan_quals" + * in remove_rel_from_jointree. (We can't readily merge these concerns into + * a single pass, since remove_rel_from_jointree must run before we relabel + * the removed rel's Vars.) In addition, *found_relid is set true if + * the subtree rooted at jtnode is found to contain relid's RangeTblRef, + * so that we can tell when to stop hoisting quals. + * If a qual gets hoisted up, we apply fixup_selfjoin_quals() to it only + * after it reaches its final level. This rule improves the odds of + * detecting duplicate quals. */ static void -add_non_redundant_clauses(PlannerInfo *root, - List *rinfo_candidates, - List **keep_rinfo_list, - Index removed_relid) +fixup_selfjoin_jointree(PlannerInfo *root, Node *jtnode, int relid, + Node **hoist_quals, bool *found_relid) { - foreach_node(RestrictInfo, rinfo, rinfo_candidates) + if (jtnode == NULL) + return; + if (IsA(jtnode, RangeTblRef)) { - bool is_redundant = false; + RangeTblRef *rtr = (RangeTblRef *) jtnode; - Assert(!bms_is_member(removed_relid, rinfo->required_relids)); + if (rtr->rtindex == relid) + { + Assert(!*found_relid); + *found_relid = true; + } + } + else if (IsA(jtnode, FromExpr)) + { + FromExpr *f = (FromExpr *) jtnode; + Node *sub_hoist_quals = NULL; + bool sub_found_relid = false; + ListCell *l; - foreach_node(RestrictInfo, src, (*keep_rinfo_list)) + foreach(l, f->fromlist) + fixup_selfjoin_jointree(root, (Node *) lfirst(l), relid, + &sub_hoist_quals, &sub_found_relid); + if (sub_found_relid) { - if (!bms_equal(src->clause_relids, rinfo->clause_relids)) - /* Can't compare trivially different clauses */ - continue; + /* This FromExpr covers relid, so OK to stop hoisting quals here */ + f->quals = merge_quals(sub_hoist_quals, f->quals); + Assert(!*found_relid); + *found_relid = true; + } + else + { + /* We might need to hoist some of our own quals too */ + List *hoistable = NIL; + List *keepable = NIL; - if (src == rinfo || - (rinfo->parent_ec != NULL && - src->parent_ec == rinfo->parent_ec) || - restrict_infos_logically_equal(rinfo, src)) + foreach_ptr(Node, qual, castNode(List, f->quals)) { - is_redundant = true; - break; + if (bms_is_member(relid, pull_varnos(root, qual))) + hoistable = lappend(hoistable, qual); + else + keepable = lappend(keepable, qual); } + f->quals = (Node *) keepable; + sub_hoist_quals = merge_quals(sub_hoist_quals, (Node *) hoistable); + *hoist_quals = merge_quals(sub_hoist_quals, *hoist_quals); } - if (!is_redundant) - distribute_restrictinfo_to_rels(root, rinfo); - } -} - -/* - * A custom callback for ChangeVarNodesExtended() providing Self-join - * elimination (SJE) related functionality - * - * SJE needs to skip the RangeTblRef node type. During SJE's last - * step, remove_rel_from_joinlist() removes remaining RangeTblRefs - * with target relid. If ChangeVarNodes() replaces the target relid - * before, remove_rel_from_joinlist() would fail to identify the nodes - * to delete. - * - * SJE also needs to change the relids within RestrictInfo's. - */ -static bool -replace_relid_callback(Node *node, ChangeVarNodes_context *context) -{ - if (IsA(node, RangeTblRef)) - { - return true; + f->quals = (Node *) fixup_selfjoin_quals(root, + castNode(List, f->quals), + relid); } - else if (IsA(node, RestrictInfo)) + else if (IsA(jtnode, JoinExpr)) { - RestrictInfo *rinfo = (RestrictInfo *) node; - int relid = -1; - bool is_req_equal = - (rinfo->required_relids == rinfo->clause_relids); - bool clause_relids_is_multiple = - (bms_membership(rinfo->clause_relids) == BMS_MULTIPLE); - - /* - * Recurse down into clauses if the target relation is present in - * clause_relids or required_relids. We must check required_relids - * because the relation not present in clause_relids might still be - * present somewhere in orclause. - */ - if (bms_is_member(context->rt_index, rinfo->clause_relids) || - bms_is_member(context->rt_index, rinfo->required_relids)) + JoinExpr *j = (JoinExpr *) jtnode; + Node *sub_hoist_quals = NULL; + bool sub_found_relid = false; + + fixup_selfjoin_jointree(root, j->larg, relid, + &sub_hoist_quals, &sub_found_relid); + fixup_selfjoin_jointree(root, j->rarg, relid, + &sub_hoist_quals, &sub_found_relid); + if (sub_found_relid) { - Relids new_clause_relids; - - ChangeVarNodesWalkExpression((Node *) rinfo->clause, context); - ChangeVarNodesWalkExpression((Node *) rinfo->orclause, context); - - new_clause_relids = adjust_relid_set(rinfo->clause_relids, - context->rt_index, - context->new_index); - - /* - * Incrementally adjust num_base_rels based on the change of - * clause_relids, which could contain both base relids and - * outer-join relids. This operation is legal until we remove - * only baserels. - */ - rinfo->num_base_rels -= bms_num_members(rinfo->clause_relids) - - bms_num_members(new_clause_relids); - - rinfo->clause_relids = new_clause_relids; - rinfo->left_relids = - adjust_relid_set(rinfo->left_relids, context->rt_index, context->new_index); - rinfo->right_relids = - adjust_relid_set(rinfo->right_relids, context->rt_index, context->new_index); + /* This JoinExpr covers relid, so OK to stop hoisting quals here */ + j->quals = merge_quals(sub_hoist_quals, j->quals); + Assert(!*found_relid); + *found_relid = true; } - - if (is_req_equal) - rinfo->required_relids = rinfo->clause_relids; else - rinfo->required_relids = - adjust_relid_set(rinfo->required_relids, context->rt_index, context->new_index); - - rinfo->outer_relids = - adjust_relid_set(rinfo->outer_relids, context->rt_index, context->new_index); - rinfo->incompatible_relids = - adjust_relid_set(rinfo->incompatible_relids, context->rt_index, context->new_index); - - if (rinfo->mergeopfamilies && - bms_get_singleton_member(rinfo->clause_relids, &relid) && - clause_relids_is_multiple && - relid == context->new_index && IsA(rinfo->clause, OpExpr)) { - Expr *leftOp; - Expr *rightOp; - - leftOp = (Expr *) get_leftop(rinfo->clause); - rightOp = (Expr *) get_rightop(rinfo->clause); + /* We might need to hoist some of our own quals too */ + List *hoistable = NIL; + List *keepable = NIL; - /* - * For self-join elimination, changing varnos could transform - * "t1.a = t2.a" into "t1.a = t1.a". That is always true as long - * as "t1.a" is not null. We use equal() to check for such a - * case, and then we replace the qual with a check for not null - * (NullTest). - */ - if (leftOp != NULL && equal(leftOp, rightOp)) + foreach_ptr(Node, qual, castNode(List, j->quals)) { - NullTest *ntest = makeNode(NullTest); - - ntest->arg = leftOp; - ntest->nulltesttype = IS_NOT_NULL; - ntest->argisrow = false; - ntest->location = -1; - rinfo->clause = (Expr *) ntest; - rinfo->mergeopfamilies = NIL; - rinfo->left_em = NULL; - rinfo->right_em = NULL; + if (bms_is_member(relid, pull_varnos(root, qual))) + hoistable = lappend(hoistable, qual); + else + keepable = lappend(keepable, qual); } - Assert(rinfo->orclause == NULL); + j->quals = (Node *) keepable; + sub_hoist_quals = merge_quals(sub_hoist_quals, (Node *) hoistable); + /* We should never need to hoist quals above an outer join */ + Assert(sub_hoist_quals == NULL || j->jointype == JOIN_INNER); + *hoist_quals = merge_quals(sub_hoist_quals, *hoist_quals); } - return true; + j->quals = (Node *) fixup_selfjoin_quals(root, + castNode(List, j->quals), + relid); } - - return false; + else + elog(ERROR, "unrecognized jointree node type: %d", + (int) nodeTag(jtnode)); } /* - * 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; +} +/* + * 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; /* - * 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; } /* @@ -2244,7 +1648,12 @@ split_selfjoin_quals(PlannerInfo *root, List *joinquals, List **selfjoinquals, Node *leftexpr; Node *rightexpr; - /* In general, clause looks like F(arg1) = G(arg2) */ + /* + * Since the given joinquals all came from + * generate_join_implied_equalities, they ought to look like equality + * operators on single-relation expressions. But let's check that. + * Anything that doesn't look like that can be dumped into ojoinquals. + */ if (!rinfo->mergeopfamilies || bms_num_members(rinfo->clause_relids) != 2 || bms_membership(rinfo->left_relids) != BMS_SINGLETON || @@ -2275,10 +1684,9 @@ split_selfjoin_quals(PlannerInfo *root, List *joinquals, List **selfjoinquals, * when we have cast of the same var to different (but compatible) * types. */ - ChangeVarNodesExtended(rightexpr, - bms_singleton_member(rinfo->right_relids), - bms_singleton_member(rinfo->left_relids), 0, - replace_relid_callback); + ChangeVarNodes(rightexpr, + bms_singleton_member(rinfo->right_relids), + bms_singleton_member(rinfo->left_relids), 0); if (equal(leftexpr, rightexpr)) sjoinquals = lappend(sjoinquals, rinfo); @@ -2314,8 +1722,7 @@ match_unique_clauses(PlannerInfo *root, RelOptInfo *outer, List *uclauses, bms_is_empty(rinfo->right_relids)); clause = (Expr *) copyObject(rinfo->clause); - ChangeVarNodesExtended((Node *) clause, relid, outer->relid, 0, - replace_relid_callback); + ChangeVarNodes((Node *) clause, relid, outer->relid, 0); iclause = bms_is_empty(rinfo->left_relids) ? get_rightop(clause) : get_leftop(clause); @@ -2360,12 +1767,23 @@ match_unique_clauses(PlannerInfo *root, RelOptInfo *outer, List *uclauses, * Find and remove unique self-joins in a group of base relations that have * the same Oid. * - * Returns a set of relids that were removed. + * Return true if we removed any joins. + * + * After a removal, we continue searching for more removals, even though the + * tests will be using derived data that is now partially stale. That is safe + * because we are trying to prove that a candidate pair of relations must + * match the same row, and the stale data can only omit quals, never invent + * them. The removed relation's quals are moved onto the kept relation in + * the jointree but not into its baserestrictinfo, and no other derived data + * changes. A proof made from a subset of the applicable quals remains valid + * when the rest are added, since extra quals can only remove rows from the + * join. So a pass may miss a removal that a later pass will find, but it + * cannot make one that isn't justified. */ -static Relids +static bool remove_self_joins_one_group(PlannerInfo *root, Relids relids) { - Relids result = NULL; + bool removed = false; int k; /* Index of kept relation */ int r = -1; /* Index of removed relation */ @@ -2373,8 +1791,8 @@ remove_self_joins_one_group(PlannerInfo *root, Relids relids) { RelOptInfo *rrel = root->simple_rel_array[r]; + /* k iterates over the relids after r */ k = r; - while ((k = bms_next_member(relids, k)) > 0) { Relids joinrelids = NULL; @@ -2394,8 +1812,8 @@ remove_self_joins_one_group(PlannerInfo *root, Relids relids) /* * It is impossible to eliminate the join of two relations if they - * belong to different rules of order. Otherwise, the planner - * can't find any variants of the correct query plan. + * are not on the same side of every outer join. Otherwise, the + * planner can't find any variants of the correct query plan. */ foreach(lc, root->join_info_list) { @@ -2509,32 +1927,35 @@ remove_self_joins_one_group(PlannerInfo *root, Relids relids) if (!match_unique_clauses(root, rrel, uclauses, krel->relid)) continue; + /* OK, remove rrel from the query */ + remove_self_join_rel(root, krel, rrel, kmark, rmark); + removed = true; + /* - * Remove rrel RelOptInfo from the planner structures and the - * corresponding row mark. + * Since relation r is now gone, we mustn't keep looking for + * matches to it. But we can keep scanning later relids members + * for additional join pairs. */ - remove_self_join_rel(root, kmark, rmark, krel, rrel, restrictlist); - - result = bms_add_member(result, r); - - /* We have removed the outer relation, try the next one. */ break; } } - return result; + return removed; } /* - * Gather indexes of base relations from the joinlist and try to eliminate self - * joins. + * Gather indexes of base relations from the joinlist and try to eliminate + * self-joins. + * + * Return true if we removed any joins. */ -static Relids -remove_self_joins_recurse(PlannerInfo *root, List *joinlist, Relids toRemove) +static bool +remove_self_joins_recurse(PlannerInfo *root, List *joinlist) { + bool removed = false; ListCell *jl; Relids relids = NULL; - SelfJoinCandidate *candidates = NULL; + SelfJoinCandidate *candidates; int i; int j; int numRels; @@ -2553,7 +1974,7 @@ remove_self_joins_recurse(PlannerInfo *root, List *joinlist, Relids toRemove) * We only consider ordinary relations as candidates to be * removed, and these relations should not have TABLESAMPLE * clauses specified. Removing a relation with TABLESAMPLE clause - * could potentially change the syntax of the query. Because of + * could potentially change the semantics of the query. Because of * UPDATE/DELETE EPQ mechanism, currently Query->resultRelation or * Query->mergeTargetRelation associated rel cannot be eliminated. */ @@ -2569,9 +1990,8 @@ remove_self_joins_recurse(PlannerInfo *root, List *joinlist, Relids toRemove) } else if (IsA(jlnode, List)) { - /* Recursively go inside the sub-joinlist */ - toRemove = remove_self_joins_recurse(root, (List *) jlnode, - toRemove); + /* Recursively perform SJE within the sub-joinlist */ + removed |= remove_self_joins_recurse(root, (List *) jlnode); } else elog(ERROR, "unrecognized joinlist node type: %d", @@ -2580,9 +2000,9 @@ remove_self_joins_recurse(PlannerInfo *root, List *joinlist, Relids toRemove) numRels = bms_num_members(relids); - /* Need at least two relations for the join */ + /* No work if not at least two relations at this level */ if (numRels < 2) - return toRemove; + return removed; /* ... but don't fail to report sub-removals */ /* * In order to find relations with the same oid we first build an array of @@ -2603,15 +2023,13 @@ remove_self_joins_recurse(PlannerInfo *root, List *joinlist, Relids toRemove) /* * Iteratively form a group of relation indexes with the same oid and - * launch the routine that detects self-joins in this group and removes - * excessive range table entries. + * launch the routine that detects self-joins in this group. * - * At the end of the iteration, exclude the group from the overall relids - * list. So each next iteration of the cycle will involve less and less - * value of relids. + * We remove considered relations from relids as we scan, so that that set + * should be empty at the end. */ i = 0; - for (j = 1; j < numRels + 1; j++) + for (j = 1; j <= numRels; j++) { if (j == numRels || candidates[j].reloid != candidates[i].reloid) { @@ -2619,7 +2037,6 @@ remove_self_joins_recurse(PlannerInfo *root, List *joinlist, Relids toRemove) { /* Create a group of relation indexes with the same oid */ Relids group = NULL; - Relids removed; while (i < j) { @@ -2628,35 +2045,25 @@ remove_self_joins_recurse(PlannerInfo *root, List *joinlist, Relids toRemove) } relids = bms_del_members(relids, group); - /* - * Try to remove self-joins from a group of identical entries. - * Make the next attempt iteratively - if something is deleted - * from a group, changes in clauses and equivalence classes - * can give us a chance to find more candidates. - */ - do - { - Assert(!bms_overlap(group, toRemove)); - removed = remove_self_joins_one_group(root, group); - toRemove = bms_add_members(toRemove, removed); - group = bms_del_members(group, removed); - } while (!bms_is_empty(removed) && - bms_membership(group) == BMS_MULTIPLE); - bms_free(removed); + /* Try to remove self-joins from the group */ + removed |= remove_self_joins_one_group(root, group); bms_free(group); } else { - /* Single relation, just remove it from the set */ - relids = bms_del_member(relids, candidates[i].relid); - i = j; + /* Nothing to do with this group, just drop it from the set */ + while (i < j) + { + relids = bms_del_member(relids, candidates[i].relid); + i++; + } } } } Assert(bms_is_empty(relids)); - return toRemove; + return removed; } /* @@ -2698,45 +2105,26 @@ self_join_candidates_cmp(const void *a, const void *b) * 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); } diff --git a/src/backend/optimizer/plan/initsplan.c b/src/backend/optimizer/plan/initsplan.c index f08a918146c..a2fb0b55a79 100644 --- a/src/backend/optimizer/plan/initsplan.c +++ b/src/backend/optimizer/plan/initsplan.c @@ -295,8 +295,6 @@ build_base_rel_tlists(PlannerInfo *root, List *final_tlist) * have a single owning relation; we keep their attr_needed info in * root->placeholder_list instead. Find or create the associated * PlaceHolderInfo entry, and update its ph_needed. - * - * See also add_vars_to_attr_needed. */ void add_vars_to_targetlist(PlannerInfo *root, List *vars, @@ -350,63 +348,6 @@ add_vars_to_targetlist(PlannerInfo *root, List *vars, } } -/* - * add_vars_to_attr_needed - * This does a subset of what add_vars_to_targetlist does: it just - * updates attr_needed for Vars and ph_needed for PlaceHolderVars. - * We assume the Vars are already in their relations' targetlists. - * - * This is used to rebuild attr_needed/ph_needed sets after removal - * of a useless outer join. The removed join clause might have been - * the only upper-level use of some other relation's Var, in which - * case we can reduce that Var's attr_needed and thereby possibly - * open the door to further join removals. But we can't tell that - * without tedious reconstruction of the attr_needed data. - * - * Note that if a Var's attr_needed is successfully reduced to empty, - * it will still be in the relation's targetlist even though we do - * not really need the scan plan node to emit it. The extra plan - * inefficiency seems tiny enough to not be worth spending planner - * cycles to get rid of it. - */ -void -add_vars_to_attr_needed(PlannerInfo *root, List *vars, - Relids where_needed) -{ - ListCell *temp; - - Assert(!bms_is_empty(where_needed)); - - foreach(temp, vars) - { - Node *node = (Node *) lfirst(temp); - - if (IsA(node, Var)) - { - Var *var = (Var *) node; - RelOptInfo *rel = find_base_rel(root, var->varno); - int attno = var->varattno; - - if (bms_is_subset(where_needed, rel->relids)) - continue; - Assert(attno >= rel->min_attr && attno <= rel->max_attr); - attno -= rel->min_attr; - rel->attr_needed[attno] = bms_add_members(rel->attr_needed[attno], - where_needed); - } - else if (IsA(node, PlaceHolderVar)) - { - PlaceHolderVar *phv = (PlaceHolderVar *) node; - PlaceHolderInfo *phinfo = find_placeholder_info(root, phv); - - phinfo->ph_needed = bms_add_members(phinfo->ph_needed, - where_needed); - } - else - elog(ERROR, "unrecognized node type: %d", (int) nodeTag(node)); - } -} - /***************************************************************************** * * GROUP BY @@ -1226,54 +1167,10 @@ extract_lateral_references(PlannerInfo *root, RelOptInfo *brel, Index rtindex) */ add_vars_to_targetlist(root, newvars, where_needed); - /* - * Remember the lateral references for rebuild_lateral_attr_needed and - * create_lateral_join_info. - */ + /* Remember the lateral references for create_lateral_join_info */ brel->lateral_vars = newvars; } -/* - * rebuild_lateral_attr_needed - * Put back attr_needed bits for Vars/PHVs needed for lateral references. - * - * This is used to rebuild attr_needed/ph_needed sets after removal of a - * useless outer join. It should match what find_lateral_references did, - * except that we call add_vars_to_attr_needed not add_vars_to_targetlist. - */ -void -rebuild_lateral_attr_needed(PlannerInfo *root) -{ - Index rti; - - /* We need do nothing if the query contains no LATERAL RTEs */ - if (!root->hasLateralRTEs) - return; - - /* Examine the same baserels that find_lateral_references did */ - for (rti = 1; rti < root->simple_rel_array_size; rti++) - { - RelOptInfo *brel = root->simple_rel_array[rti]; - Relids where_needed; - - if (brel == NULL) - continue; - if (brel->reloptkind != RELOPT_BASEREL) - continue; - - /* - * We don't need to repeat all of extract_lateral_references, since it - * kindly saved the extracted Vars/PHVs in lateral_vars. - */ - if (brel->lateral_vars == NIL) - continue; - - where_needed = bms_make_singleton(rti); - - add_vars_to_attr_needed(root, brel->lateral_vars, where_needed); - } -} - /* * create_lateral_join_info * Fill in the per-base-relation direct_lateral_relids, lateral_relids @@ -3227,9 +3124,6 @@ distribute_qual_to_rels(PlannerInfo *root, Node *clause, * var propagation is ensured by making ojscope include input rels from * both sides of the join. * - * See also rebuild_joinclause_attr_needed, which has to partially repeat - * this work after removal of an outer join. - * * Note: if the clause gets absorbed into an EquivalenceClass then this * may be unnecessary, but for now we have to do it to cover the case * where the EC becomes ec_broken and we end up reinserting the original @@ -3803,11 +3697,6 @@ process_implied_equality(PlannerInfo *root, * some of the Vars could have missed having that done because they only * appeared in single-relation clauses originally. So do it here for * safety. - * - * See also rebuild_joinclause_attr_needed, which has to partially repeat - * this work after removal of an outer join. (Since we will put this - * clause into the joininfo lists, that function needn't do any extra work - * to find it.) */ if (bms_membership(relids) == BMS_MULTIPLE) { @@ -3949,72 +3838,6 @@ get_join_domain_min_rels(PlannerInfo *root, Relids domain_relids) } -/* - * rebuild_joinclause_attr_needed - * Put back attr_needed bits for Vars/PHVs needed for join clauses. - * - * This is used to rebuild attr_needed/ph_needed sets after removal of a - * useless outer join. It should match what distribute_qual_to_rels did, - * except that we call add_vars_to_attr_needed not add_vars_to_targetlist. - */ -void -rebuild_joinclause_attr_needed(PlannerInfo *root) -{ - /* - * We must examine all join clauses, but there's no value in processing - * any join clause more than once. So it's slightly annoying that we have - * to find them via the per-base-relation joininfo lists. Avoid duplicate - * processing by tracking the rinfo_serial numbers of join clauses we've - * already seen. (This doesn't work for is_clone clauses, so we must - * waste effort on them.) - */ - Bitmapset *seen_serials = NULL; - Index rti; - - /* Scan all baserels for join clauses */ - for (rti = 1; rti < root->simple_rel_array_size; rti++) - { - RelOptInfo *brel = root->simple_rel_array[rti]; - ListCell *lc; - - if (brel == NULL) - continue; - if (brel->reloptkind != RELOPT_BASEREL) - continue; - - foreach(lc, brel->joininfo) - { - RestrictInfo *rinfo = (RestrictInfo *) lfirst(lc); - Relids relids = rinfo->required_relids; - - if (!rinfo->is_clone) /* else serial number is not unique */ - { - if (bms_is_member(rinfo->rinfo_serial, seen_serials)) - continue; /* saw it already */ - seen_serials = bms_add_member(seen_serials, - rinfo->rinfo_serial); - } - - if (bms_membership(relids) == BMS_MULTIPLE) - { - List *vars = pull_var_clause((Node *) rinfo->clause, - PVC_RECURSE_AGGREGATES | - PVC_RECURSE_WINDOWFUNCS | - PVC_INCLUDE_PLACEHOLDERS); - Relids where_needed; - - if (rinfo->is_clone) - where_needed = bms_intersect(relids, root->all_baserels); - else - where_needed = relids; - add_vars_to_attr_needed(root, vars, where_needed); - list_free(vars); - } - } - } -} - - /* * match_foreign_keys_to_quals * Match foreign-key constraints to equivalence classes and join quals @@ -4044,9 +3867,9 @@ match_foreign_keys_to_quals(PlannerInfo *root) /* * 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 don't use - * find_base_rel() here. We can ignore such FKs. + * isn't referenced by the jointree (typically because it's been + * removed by join removal), so that it won't have a RelOptInfo. Hence + * don't use find_base_rel() here. We can ignore such FKs. */ if (fkinfo->con_relid >= root->simple_rel_array_size || fkinfo->ref_relid >= root->simple_rel_array_size) diff --git a/src/backend/optimizer/plan/planmain.c b/src/backend/optimizer/plan/planmain.c index 02495e22e24..9792a6c752f 100644 --- a/src/backend/optimizer/plan/planmain.c +++ b/src/backend/optimizer/plan/planmain.c @@ -28,6 +28,7 @@ #include "optimizer/paths.h" #include "optimizer/placeholder.h" #include "optimizer/planmain.h" +#include "parser/parsetree.h" /* @@ -54,33 +55,71 @@ RelOptInfo * query_planner(PlannerInfo *root, query_pathkeys_callback qp_callback, void *qp_extra) { - Query *parse = root->parse; + Query *parse; List *joinlist; RelOptInfo *final_rel; /* - * Init planner lists to empty. + * The join simplification steps below work by modifying parse->jointree, + * and they make no attempt to update the information we derive from it. + * So whenever one of them succeeds, we must throw away all that derived + * information and recompute it from scratch, which we do by looping back + * to "restart". We cannot loop indefinitely, because each successful + * simplification either deletes a base relation from the jointree or + * turns a semijoin into an inner join, and neither of those can be undone + * by a later pass. * - * NOTE: append_rel_list was set up by subquery_planner, so do not touch - * here. + * These initial Asserts check that the state at entry is not too complex + * for the code below to restore. There mustn't be any EquivalenceClasses + * yet, and we should have only the top-level JoinDomain. */ + Assert(root->eq_classes == NIL); + Assert(list_length(root->join_domains) == 1); + +restart: + parse = root->parse; + + /* + * Initialize information derived from the jointree to empty. + * + * It's critical that this reset every field that the steps below will + * fill in, since we may be going around this loop more than once. + * + * NOTE: append_rel_list was created earlier, so do not clear it here; + * rowMarks ditto. Join simplification must update those if necessary. + */ + root->all_baserels = NULL; + root->outer_join_rels = NULL; + root->all_query_rels = NULL; root->join_rel_list = NIL; root->join_rel_hash = NULL; root->join_rel_level = NULL; root->join_cur_level = 0; + root->eq_classes = NIL; + root->ec_merging_done = false; root->canon_pathkeys = NIL; root->left_join_clauses = NIL; root->right_join_clauses = NIL; root->full_join_clauses = NIL; root->join_info_list = NIL; + root->last_rinfo_serial = 0; root->placeholder_list = NIL; root->placeholder_array = NULL; root->placeholder_array_size = 0; + root->placeholdersFrozen = false; root->agg_clause_list = NIL; root->group_expr_list = NIL; root->tlist_vars = NIL; root->fkey_list = NIL; root->initial_rels = NIL; + root->hasPseudoConstantQuals = false; + + /* + * We don't want to delete the top-level join domain, but get rid of other + * ones so as to reset the list to initial state. deconstruct_jointree + * will take care of (re)computing the top level's jd_relids. + */ + root->join_domains = list_truncate(root->join_domains, 1); /* * Set up arrays for accessing base relations and AppendRelInfos. @@ -227,19 +266,30 @@ query_planner(PlannerInfo *root, * Remove any useless outer joins. Ideally this would be done during * jointree preprocessing, but the necessary information isn't available * until we've built baserel data structures and classified qual clauses. + * If we remove a join, loop back to the top and redo what we did so far. */ - joinlist = remove_useless_joins(root, joinlist); + if (remove_useless_outer_joins(root)) + goto restart; /* * Also, reduce any semijoins with unique inner rels to plain inner joins. - * Likewise, this can't be done until now for lack of needed info. + * Likewise, this can't be done until now for lack of needed info, and we + * must loop around if we find any simplifications. */ - reduce_unique_semijoins(root); + if (reduce_unique_semijoins(root)) + goto restart; /* - * Remove self joins on a unique column. + * Remove self joins on a unique column. Again, this couldn't be done any + * earlier, and we must loop around if we find anything to remove. + */ + if (remove_useless_self_joins(root, joinlist)) + goto restart; + + /* + * No more join simplifications apply, so we're done looping. Code below + * this point does not need to be able to restart. */ - joinlist = remove_useless_self_joins(root, joinlist); /* * Now distribute "placeholders" to base rels as needed. This has to be @@ -274,6 +324,22 @@ query_planner(PlannerInfo *root, */ setup_eager_aggregation(root); + /* + * If there's a result relation, initialize all_result_relids to include + * it; and if we've verified that it is non-inheriting, mark it as a leaf + * target. add_other_rels_to_query() will expand these sets if the result + * relation has children. + */ + if (parse->resultRelation) + { + RangeTblEntry *rte = rt_fetch(parse->resultRelation, parse->rtable); + + root->all_result_relids = bms_make_singleton(parse->resultRelation); + if (!rte->inh) + root->leaf_result_relids = + bms_make_singleton(parse->resultRelation); + } + /* * Now expand appendrels by adding "otherrels" for their children. We * delay this to the end so that we have as much information as possible diff --git a/src/backend/optimizer/plan/planner.c b/src/backend/optimizer/plan/planner.c index a605387dcaa..c3c158a253d 100644 --- a/src/backend/optimizer/plan/planner.c +++ b/src/backend/optimizer/plan/planner.c @@ -803,9 +803,8 @@ subquery_planner(PlannerGlobal *glob, Query *parse, char *plan_name, root->eq_classes = NIL; root->ec_merging_done = false; root->last_rinfo_serial = 0; - root->all_result_relids = - parse->resultRelation ? bms_make_singleton(parse->resultRelation) : NULL; - root->leaf_result_relids = NULL; /* we'll find out leaf-ness later */ + root->all_result_relids = NULL; + root->leaf_result_relids = NULL; root->append_rel_list = NIL; root->row_identity_vars = NIL; root->rowMarks = NIL; @@ -978,19 +977,6 @@ subquery_planner(PlannerGlobal *glob, Query *parse, char *plan_name, list_length(rte->securityQuals)); } - /* - * If we have now verified that the query target relation is - * non-inheriting, mark it as a leaf target. - */ - if (parse->resultRelation) - { - RangeTblEntry *rte = rt_fetch(parse->resultRelation, parse->rtable); - - if (!rte->inh) - root->leaf_result_relids = - bms_make_singleton(parse->resultRelation); - } - /* * This would be a convenient time to check access permissions for all * relations mentioned in the query, since it would be better to fail now, diff --git a/src/backend/optimizer/util/joininfo.c b/src/backend/optimizer/util/joininfo.c index ef2f054c39e..f75e35f22ae 100644 --- a/src/backend/optimizer/util/joininfo.c +++ b/src/backend/optimizer/util/joininfo.c @@ -145,39 +145,3 @@ add_join_clause_to_rels(PlannerInfo *root, rel->joininfo = lappend(rel->joininfo, restrictinfo); } } - -/* - * remove_join_clause_from_rels - * Delete 'restrictinfo' from all the joininfo lists it is in - * - * This reverses the effect of add_join_clause_to_rels. It's used when we - * discover that a relation need not be joined at all. - * - * 'restrictinfo' describes the join clause - * 'join_relids' is the set of relations participating in the join clause - * (some of these could be outer joins) - */ -void -remove_join_clause_from_rels(PlannerInfo *root, - RestrictInfo *restrictinfo, - Relids join_relids) -{ - int cur_relid; - - cur_relid = -1; - while ((cur_relid = bms_next_member(join_relids, cur_relid)) >= 0) - { - RelOptInfo *rel = find_base_rel_ignore_join(root, cur_relid); - - /* We would only have added the clause to baserels */ - if (rel == NULL) - continue; - - /* - * Remove the restrictinfo from the list. Pointer comparison is - * sufficient. - */ - Assert(list_member_ptr(rel->joininfo, restrictinfo)); - rel->joininfo = list_delete_ptr(rel->joininfo, restrictinfo); - } -} diff --git a/src/backend/optimizer/util/placeholder.c b/src/backend/optimizer/util/placeholder.c index dd9b11885af..07171f84f61 100644 --- a/src/backend/optimizer/util/placeholder.c +++ b/src/backend/optimizer/util/placeholder.c @@ -316,33 +316,6 @@ fix_placeholder_input_needed_levels(PlannerInfo *root) } } -/* - * rebuild_placeholder_attr_needed - * Put back attr_needed bits for Vars/PHVs needed in PlaceHolderVars. - * - * This is used to rebuild attr_needed/ph_needed sets after removal of a - * useless outer join. It should match what - * fix_placeholder_input_needed_levels did, except that we call - * add_vars_to_attr_needed not add_vars_to_targetlist. - */ -void -rebuild_placeholder_attr_needed(PlannerInfo *root) -{ - ListCell *lc; - - foreach(lc, root->placeholder_list) - { - PlaceHolderInfo *phinfo = (PlaceHolderInfo *) lfirst(lc); - List *vars = pull_var_clause((Node *) phinfo->ph_var->phexpr, - PVC_RECURSE_AGGREGATES | - PVC_RECURSE_WINDOWFUNCS | - PVC_INCLUDE_PLACEHOLDERS); - - add_vars_to_attr_needed(root, vars, phinfo->ph_eval_at); - list_free(vars); - } -} - /* * add_placeholders_to_base_rels * Add any required PlaceHolderVars to base rels' targetlists. diff --git a/src/backend/rewrite/rewriteManip.c b/src/backend/rewrite/rewriteManip.c index b318ae8a670..6334765ba05 100644 --- a/src/backend/rewrite/rewriteManip.c +++ b/src/backend/rewrite/rewriteManip.c @@ -64,6 +64,7 @@ static bool contain_windowfuncs_walker(Node *node, void *context); static bool locate_windowfunc_walker(Node *node, locate_windowfunc_context *context); static bool checkExprHasSubLink_walker(Node *node, void *context); +static Relids adjust_relid_set(Relids relids, int oldrelid, int newrelid); static Node *add_nulling_relids_mutator(Node *node, add_nulling_relids_context *context); static Node *remove_nulling_relids_mutator(Node *node, @@ -528,23 +529,27 @@ OffsetVarNodes(Node *node, int offset, int sublevels_up) * * Find all Var nodes in the given tree belonging to a specific relation * (identified by sublevels_up and rt_index), and change their varno fields - * to 'new_index'. The varnosyn fields are changed too. Also, adjust other - * nodes that contain rangetable indexes, such as RangeTblRef and JoinExpr. + * to 'new_index' (see adjust_relid_set for the exact change behavior). + * The varnosyn fields are changed too. Also adjust other nodes that + * contain rangetable indexes, such as RangeTblRef and JoinExpr. * * NOTE: although this has the form of a walker, we cheat and modify the * nodes in-place. The given expression tree should have been copied * earlier to ensure that no unwanted side-effects occur! */ +typedef struct +{ + int rt_index; + int new_index; + int sublevels_up; +} ChangeVarNodes_context; + static bool ChangeVarNodes_walker(Node *node, ChangeVarNodes_context *context) { if (node == NULL) return false; - - if (context->callback && context->callback(node, context)) - return false; - if (IsA(node, Var)) { Var *var = (Var *) node; @@ -649,28 +654,14 @@ ChangeVarNodes_walker(Node *node, ChangeVarNodes_context *context) return expression_tree_walker(node, ChangeVarNodes_walker, context); } -/* - * ChangeVarNodesExtended - similar to ChangeVarNodes, but with an additional - * 'callback' param - * - * ChangeVarNodes changes a given node and all of its underlying nodes. This - * version of function additionally takes a callback, which has a chance to - * process a node before ChangeVarNodes_walker. A callback returns a boolean - * value indicating if the given node should be skipped from further processing - * by ChangeVarNodes_walker. The callback is called only for expressions and - * other children nodes of a Query processed by a walker. Initial processing - * of the root Query node doesn't invoke the callback. - */ void -ChangeVarNodesExtended(Node *node, int rt_index, int new_index, - int sublevels_up, ChangeVarNodes_callback callback) +ChangeVarNodes(Node *node, int rt_index, int new_index, int sublevels_up) { ChangeVarNodes_context context; context.rt_index = rt_index; context.new_index = new_index; context.sublevels_up = sublevels_up; - context.callback = callback; /* * Must be prepared to start with a Query or a bare expression tree; if @@ -717,36 +708,6 @@ ChangeVarNodesExtended(Node *node, int rt_index, int new_index, ChangeVarNodes_walker(node, &context); } -void -ChangeVarNodes(Node *node, int rt_index, int new_index, int sublevels_up) -{ - ChangeVarNodesExtended(node, rt_index, new_index, sublevels_up, NULL); -} - -/* - * ChangeVarNodesWalkExpression - process subexpression within a callback - * function passed to ChangeVarNodesExtended. - * - * This is intended to be used by a callback that needs to recursively - * process subexpressions of some node being visited by an outer - * ChangeVarNodesExtended call, instead of relying on ChangeVarNodes_walker's - * default recursion. We invoke ChangeVarNodes_walker directly rather than - * via expression_tree_walker, because expression_tree_walker only visits - * child nodes and would fail to process the passed node itself -- - * for example, a bare Var node would not get its varno adjusted. - * - * Because this calls ChangeVarNodes_walker directly, if the passed node is - * a Query, it will be treated as a sub-Query: sublevels_up is incremented - * before recursing into it, and Query-level fields (resultRelation, - * mergeTargetRelation, rowMarks, etc.) will not be adjusted. Do not apply - * this to a top-level Query node; use ChangeVarNodesExtended for that. - */ -bool -ChangeVarNodesWalkExpression(Node *node, ChangeVarNodes_context *context) -{ - return ChangeVarNodes_walker(node, context); -} - /* * adjust_relid_set - substitute newrelid for oldrelid in a Relid set * @@ -756,7 +717,7 @@ ChangeVarNodesWalkExpression(Node *node, ChangeVarNodes_context *context) * a special varno, this function does nothing. When newrelid is a special * varno, this function behaves as delete. */ -Relids +static Relids adjust_relid_set(Relids relids, int oldrelid, int newrelid) { if (!IS_SPECIAL_VARNO(oldrelid) && bms_is_member(oldrelid, relids)) diff --git a/src/include/optimizer/joininfo.h b/src/include/optimizer/joininfo.h index 117195fbcfa..aa26cc670f9 100644 --- a/src/include/optimizer/joininfo.h +++ b/src/include/optimizer/joininfo.h @@ -23,8 +23,5 @@ extern bool have_relevant_joinclause(PlannerInfo *root, extern void add_join_clause_to_rels(PlannerInfo *root, RestrictInfo *restrictinfo, Relids join_relids); -extern void remove_join_clause_from_rels(PlannerInfo *root, - RestrictInfo *restrictinfo, - Relids join_relids); #endif /* JOININFO_H */ diff --git a/src/include/optimizer/paths.h b/src/include/optimizer/paths.h index 17f2099ec3b..051e38c1189 100644 --- a/src/include/optimizer/paths.h +++ b/src/include/optimizer/paths.h @@ -137,7 +137,6 @@ extern bool process_equivalence(PlannerInfo *root, extern Expr *canonicalize_ec_expression(Expr *expr, Oid req_type, Oid req_collation); extern void reconsider_outer_join_clauses(PlannerInfo *root); -extern void rebuild_eclass_attr_needed(PlannerInfo *root); extern EquivalenceClass *get_eclass_for_sort_expr(PlannerInfo *root, Expr *expr, List *opfamilies, @@ -208,7 +207,6 @@ extern bool eclass_useful_for_merging(PlannerInfo *root, extern bool is_redundant_derived_clause(RestrictInfo *rinfo, List *clauselist); extern bool is_redundant_with_indexclauses(RestrictInfo *rinfo, List *indexclauses); -extern void ec_clear_derived_clauses(EquivalenceClass *ec); /* * pathkeys.c diff --git a/src/include/optimizer/placeholder.h b/src/include/optimizer/placeholder.h index 60798281090..2099075e670 100644 --- a/src/include/optimizer/placeholder.h +++ b/src/include/optimizer/placeholder.h @@ -23,7 +23,6 @@ extern PlaceHolderInfo *find_placeholder_info(PlannerInfo *root, PlaceHolderVar *phv); extern void find_placeholders_in_jointree(PlannerInfo *root); extern void fix_placeholder_input_needed_levels(PlannerInfo *root); -extern void rebuild_placeholder_attr_needed(PlannerInfo *root); extern void add_placeholders_to_base_rels(PlannerInfo *root); extern void add_placeholders_to_joinrel(PlannerInfo *root, RelOptInfo *joinrel, RelOptInfo *outer_rel, RelOptInfo *inner_rel, diff --git a/src/include/optimizer/planmain.h b/src/include/optimizer/planmain.h index 71c043a25e8..c23ab568b98 100644 --- a/src/include/optimizer/planmain.h +++ b/src/include/optimizer/planmain.h @@ -73,12 +73,9 @@ extern void add_other_rels_to_query(PlannerInfo *root); extern void build_base_rel_tlists(PlannerInfo *root, List *final_tlist); extern void add_vars_to_targetlist(PlannerInfo *root, List *vars, Relids where_needed); -extern void add_vars_to_attr_needed(PlannerInfo *root, List *vars, - Relids where_needed); extern void remove_useless_groupby_columns(PlannerInfo *root); extern void setup_eager_aggregation(PlannerInfo *root); extern void find_lateral_references(PlannerInfo *root); -extern void rebuild_lateral_attr_needed(PlannerInfo *root); extern void create_lateral_join_info(PlannerInfo *root); extern List *deconstruct_jointree(PlannerInfo *root); extern bool restriction_is_always_true(PlannerInfo *root, @@ -102,24 +99,19 @@ extern RestrictInfo *build_implied_join_equality(PlannerInfo *root, Expr *item2, Relids qualscope, Index security_level); -extern void rebuild_joinclause_attr_needed(PlannerInfo *root); extern void match_foreign_keys_to_quals(PlannerInfo *root); /* * prototypes for plan/analyzejoins.c */ -extern List *remove_useless_joins(PlannerInfo *root, List *joinlist); -extern void reduce_unique_semijoins(PlannerInfo *root); +extern bool remove_useless_outer_joins(PlannerInfo *root); +extern bool reduce_unique_semijoins(PlannerInfo *root); extern bool query_supports_distinctness(Query *query); extern bool query_is_distinct_for(Query *query, List *distinct_cols); extern bool innerrel_is_unique(PlannerInfo *root, Relids joinrelids, Relids outerrelids, RelOptInfo *innerrel, JoinType jointype, List *restrictlist, bool force_cache); -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 bool remove_useless_self_joins(PlannerInfo *root, List *joinlist); /* * prototypes for plan/setrefs.c diff --git a/src/include/rewrite/rewriteManip.h b/src/include/rewrite/rewriteManip.h index 9d234cb8741..2d15d8f8f95 100644 --- a/src/include/rewrite/rewriteManip.h +++ b/src/include/rewrite/rewriteManip.h @@ -41,30 +41,11 @@ typedef enum ReplaceVarsNoMatchOption REPLACEVARS_SUBSTITUTE_NULL, /* replace with a NULL Const */ } ReplaceVarsNoMatchOption; -typedef struct ChangeVarNodes_context ChangeVarNodes_context; - -typedef bool (*ChangeVarNodes_callback) (Node *node, - ChangeVarNodes_context *arg); - -struct ChangeVarNodes_context -{ - int rt_index; - int new_index; - int sublevels_up; - ChangeVarNodes_callback callback; -}; - -pg_nodiscard extern Relids adjust_relid_set(Relids relids, int oldrelid, int newrelid); extern void CombineRangeTables(List **dst_rtable, List **dst_perminfos, List *src_rtable, List *src_perminfos); extern void OffsetVarNodes(Node *node, int offset, int sublevels_up); extern void ChangeVarNodes(Node *node, int rt_index, int new_index, int sublevels_up); -extern void ChangeVarNodesExtended(Node *node, int rt_index, int new_index, - int sublevels_up, - ChangeVarNodes_callback callback); -extern bool ChangeVarNodesWalkExpression(Node *node, - ChangeVarNodes_context *context); extern void IncrementVarSublevelsUp(Node *node, int delta_sublevels_up, int min_sublevels_up); extern void IncrementVarSublevelsUp_rtable(List *rtable, diff --git a/src/test/regress/expected/join.out b/src/test/regress/expected/join.out index 9261e13442d..db4fcc5a5a0 100644 --- a/src/test/regress/expected/join.out +++ b/src/test/regress/expected/join.out @@ -7681,6 +7681,38 @@ where t1.a = s.c; ---------- (0 rows) +rollback; +-- join removal bug #19560: removing a join can leave an EquivalenceClass that +-- now yields a base restriction clause, so we must redo equivalence +-- processing from scratch +begin; +create temp table items (id text, owner text); +create temp table follows (item_id text, user_id text, + unique (user_id, item_id)); +insert into items values ('item1', 'alice'); +explain (costs off) +with viewer as (select 'bob' as id) +select count(*) from items + left join follows on follows.item_id = items.id and follows.user_id = 'bob' + left join viewer on true +where items.owner = viewer.id; + QUERY PLAN +--------------------------------------- + Aggregate + -> Seq Scan on items + Filter: (owner = 'bob'::text) +(3 rows) + +with viewer as (select 'bob' as id) +select count(*) from items + left join follows on follows.item_id = items.id and follows.user_id = 'bob' + left join viewer on true +where items.owner = viewer.id; + count +------- + 0 +(1 row) + rollback; -- check handling of semijoins after join removal: we must suppress -- unique-ification of known-constant values @@ -7706,17 +7738,17 @@ where exists (select 1 from t t4 Output: t1.a Index Cond: (t1.a = 1) -> HashAggregate - Output: t5.a + Output: t4.a, t5.a Group Key: t5.a -> Hash Join - Output: t5.a + Output: t4.a, t5.a Hash Cond: (t6.b = t4.b) -> Seq Scan on pg_temp.t t6 Output: t6.a, t6.b -> Hash - Output: t4.b, t5.b, t5.a + Output: t4.b, t4.a, t5.b, t5.a -> Hash Join - Output: t4.b, t5.b, t5.a + Output: t4.b, t4.a, t5.b, t5.a Inner Unique: true Hash Cond: (t5.b = t4.b) -> Seq Scan on pg_temp.t t5 @@ -8148,7 +8180,7 @@ on q1.ax = q2.a; Nested Loop Left Join Join Filter: (t2.a = t4.a) -> Seq Scan on sj t2 - Filter: ((b IS NULL) AND (a IS NOT NULL) AND ((c * c) = (c + 2))) + Filter: ((a IS NOT NULL) AND (b IS NULL) AND ((c * c) = (c + 2))) -> Seq Scan on sj t4 Filter: (c IS NOT NULL) (6 rows) @@ -8231,12 +8263,70 @@ select t1.a from sj t1 where t1.b in ( -> Seq Scan on public.sj t1 Output: t1.a, t1.b, t1.c -> Materialize - Output: t3.c, t3.b + Output: t3.b -> Seq Scan on public.sj t3 - Output: t3.c, t3.b + Output: t3.b Filter: (t3.c IS NOT NULL) (10 rows) +-- Check that quals get hoisted to the appropriate join level after SJE removal +explain (verbose, costs off) +select a2.a +from sj b1 + join sj a1 on b1.b = a1.a + join sj a2 on a2.a = a1.a and a2.b = a1.b; + QUERY PLAN +------------------------------------------------------------- + Nested Loop + Output: a2.a + Join Filter: (b1.b = a2.a) + -> Seq Scan on public.sj a2 + Output: a2.a, a2.b, a2.c + Filter: ((a2.a IS NOT NULL) AND (a2.b IS NOT NULL)) + -> Seq Scan on public.sj b1 + Output: b1.a, b1.b, b1.c +(8 rows) + +-- Same, when a semijoin removal happens first +explain (verbose, costs off) +select a1.a from sj b1 join sj a1 on a1.a = b1.b + where exists (select 1 from sj s where s.a = a1.a); + QUERY PLAN +----------------------------------------- + Nested Loop + Output: s.a + Inner Unique: true + Join Filter: (b1.b = s.a) + -> Seq Scan on public.sj b1 + Output: b1.a, b1.b, b1.c + -> Materialize + Output: s.a + -> Seq Scan on public.sj s + Output: s.a + Filter: (s.a IS NOT NULL) +(11 rows) + +-- A different case, where modified qual is on a lower join level +explain (verbose, costs off) +select a2.a +from ((sj b1 join sj a1 on true) join sj c1 on c1.b = a1.a) + join sj a2 on a2.a = a1.a and a2.b = a1.b; + QUERY PLAN +------------------------------------------------------------------- + Nested Loop + Output: a2.a + -> Nested Loop + Output: a2.a + Join Filter: (c1.b = a2.a) + -> Seq Scan on public.sj a2 + Output: a2.a, a2.b, a2.c + Filter: ((a2.a IS NOT NULL) AND (a2.b IS NOT NULL)) + -> Seq Scan on public.sj c1 + Output: c1.a, c1.b, c1.c + -> Seq Scan on public.sj b1 + Output: b1.a, b1.b, b1.c +(12 rows) + -- -- SJE corner case: uniqueness of an inner is [partially] derived from -- baserestrictinfo clauses. @@ -8567,15 +8657,15 @@ explain (costs off) select * from sj p join sj q on p.a = q.a -> Seq Scan on sj r (6 rows) --- FIXME this constant false filter doesn't look good. Should we merge --- equivalence classes? +-- Check that we detect constant-false condition after merging ECs. explain (costs off) select * from sj p, sj q where p.a = q.a and p.b = 1 and q.b = 2; - QUERY PLAN ------------------------------------------------------ - Seq Scan on sj q - Filter: ((a IS NOT NULL) AND (b = 2) AND (b = 1)) -(2 rows) + QUERY PLAN +-------------------------- + Result + Replaces: Scan on q + One-Time Filter: false +(3 rows) -- Check that attr_needed is updated correctly after self-join removal. In this -- test, the join of j1 with j2 is removed. k1.b is required at either j1 or j2. @@ -8711,11 +8801,9 @@ where s1.x = 1; -> Seq Scan on public.emp1 t1 Output: t1.id, t1.code -> Materialize - Output: t3.id -> Seq Scan on public.emp1 t3 - Output: t3.id Filter: (1 = 1) -(9 rows) +(7 rows) -- Check that PHVs do not impose any constraints on removing self joins explain (verbose, costs off) @@ -8765,14 +8853,14 @@ SELECT 1 FROM tbl_phv t1 LEFT JOIN (SELECT y FROM tbl_phv tr) t4 ON t4.y = t3.y ON true WHERE t3.extra IS NOT NULL AND t3.x = t1.x % 2; - QUERY PLAN ---------------------------------------------------------- + QUERY PLAN +-------------------------------------------------------------- Nested Loop Output: 1 -> Seq Scan on public.tbl_phv t1 Output: t1.x, t1.y - -> Index Scan using tbl_phv_idx on public.tbl_phv tr - Output: tr.x, tr.y + -> Index Only Scan using tbl_phv_idx on public.tbl_phv tr + Output: tr.x Index Cond: (tr.x = (t1.x % 2)) Filter: (1 IS NOT NULL) (8 rows) @@ -8953,7 +9041,7 @@ where t1.b = t2.b and t2.a = 3 and t1.a = 3 --------------------------------------------------------------------------------------------- Seq Scan on public.sl t2 Output: t2.a, t2.b, t2.c, t2.a, t2.b, t2.c - Filter: ((t2.c IS NOT NULL) AND (t2.b IS NOT NULL) AND (t2.a IS NOT NULL) AND (t2.a = 3)) + Filter: ((t2.b IS NOT NULL) AND (t2.c IS NOT NULL) AND (t2.a IS NOT NULL) AND (t2.a = 3)) (3 rows) -- Join qual isn't mergejoinable, but inner is unique. @@ -8995,10 +9083,35 @@ SELECT 1 AS c1 FROM sl sl1 LEFT JOIN (sl AS sl2 NATURAL JOIN sl AS sl3) -> Nested Loop Left Join Join Filter: sl3.bool_col -> Seq Scan on sl sl3 - Filter: (bool_col AND (a IS NOT NULL) AND (b IS NOT NULL) AND (c IS NOT NULL) AND (bool_col IS NOT NULL)) + Filter: ((a IS NOT NULL) AND (b IS NOT NULL) AND (c IS NOT NULL) AND (bool_col IS NOT NULL) AND bool_col) -> Seq Scan on sl sl4 (7 rows) +-- Check that quals of a jointree node that becomes empty when the self-join +-- is removed are not lost, and that they don't migrate above an outer join +EXPLAIN (COSTS OFF) +SELECT s.a FROM (SELECT * FROM sl WHERE c IS NOT NULL) s, sl t +WHERE t.a = s.a AND t.b = s.b; + QUERY PLAN +--------------------------------------------------------------------- + Seq Scan on sl + Filter: ((c IS NOT NULL) AND (a IS NOT NULL) AND (b IS NOT NULL)) +(2 rows) + +EXPLAIN (COSTS OFF) +SELECT t1.a, ss.a FROM sl t1 + LEFT JOIN (SELECT s.a FROM (SELECT * FROM sl WHERE c IS NOT NULL) s + JOIN sl t ON t.a = s.a AND t.b = s.b) ss + ON ss.a = t1.a; + QUERY PLAN +--------------------------------------------------------------------------- + Nested Loop Left Join + Join Filter: (sl.a = t1.a) + -> Seq Scan on sl t1 + -> Seq Scan on sl + Filter: ((c IS NOT NULL) AND (a IS NOT NULL) AND (b IS NOT NULL)) +(5 rows) + -- Check optimization disabling if it will violate special join conditions. -- Two identical joined relations satisfies self join removal conditions but -- stay in different special join infos. diff --git a/src/test/regress/sql/join.sql b/src/test/regress/sql/join.sql index 9248245045b..9533af8656e 100644 --- a/src/test/regress/sql/join.sql +++ b/src/test/regress/sql/join.sql @@ -2898,6 +2898,31 @@ where t1.a = s.c; rollback; +-- join removal bug #19560: removing a join can leave an EquivalenceClass that +-- now yields a base restriction clause, so we must redo equivalence +-- processing from scratch +begin; + +create temp table items (id text, owner text); +create temp table follows (item_id text, user_id text, + unique (user_id, item_id)); +insert into items values ('item1', 'alice'); + +explain (costs off) +with viewer as (select 'bob' as id) +select count(*) from items + left join follows on follows.item_id = items.id and follows.user_id = 'bob' + left join viewer on true +where items.owner = viewer.id; + +with viewer as (select 'bob' as id) +select count(*) from items + left join follows on follows.item_id = items.id and follows.user_id = 'bob' + left join viewer on true +where items.owner = viewer.id; + +rollback; + -- check handling of semijoins after join removal: we must suppress -- unique-ification of known-constant values begin; @@ -3164,6 +3189,24 @@ explain (verbose, costs off) select t1.a from sj t1 where t1.b in ( select t2.b from sj t2 join sj t3 on t2.c=t3.c); +-- Check that quals get hoisted to the appropriate join level after SJE removal +explain (verbose, costs off) +select a2.a +from sj b1 + join sj a1 on b1.b = a1.a + join sj a2 on a2.a = a1.a and a2.b = a1.b; + +-- Same, when a semijoin removal happens first +explain (verbose, costs off) +select a1.a from sj b1 join sj a1 on a1.a = b1.b + where exists (select 1 from sj s where s.a = a1.a); + +-- A different case, where modified qual is on a lower join level +explain (verbose, costs off) +select a2.a +from ((sj b1 join sj a1 on true) join sj c1 on c1.b = a1.a) + join sj a2 on a2.a = a1.a and a2.b = a1.b; + -- -- SJE corner case: uniqueness of an inner is [partially] derived from -- baserestrictinfo clauses. @@ -3312,8 +3355,7 @@ select 1 from (select y.* from sj x, sj y where x.a = y.a) q, explain (costs off) select * from sj p join sj q on p.a = q.a left join sj r on p.a + q.a = r.a; --- FIXME this constant false filter doesn't look good. Should we merge --- equivalence classes? +-- Check that we detect constant-false condition after merging ECs. explain (costs off) select * from sj p, sj q where p.a = q.a and p.b = 1 and q.b = 2; @@ -3511,6 +3553,18 @@ EXPLAIN (COSTS OFF) SELECT 1 AS c1 FROM sl sl1 LEFT JOIN (sl AS sl2 NATURAL JOIN sl AS sl3) ON sl2.bool_col LEFT JOIN sl AS sl4 ON sl2.bool_col; +-- Check that quals of a jointree node that becomes empty when the self-join +-- is removed are not lost, and that they don't migrate above an outer join +EXPLAIN (COSTS OFF) +SELECT s.a FROM (SELECT * FROM sl WHERE c IS NOT NULL) s, sl t +WHERE t.a = s.a AND t.b = s.b; + +EXPLAIN (COSTS OFF) +SELECT t1.a, ss.a FROM sl t1 + LEFT JOIN (SELECT s.a FROM (SELECT * FROM sl WHERE c IS NOT NULL) s + JOIN sl t ON t.a = s.a AND t.b = s.b) ss + ON ss.a = t1.a; + -- Check optimization disabling if it will violate special join conditions. -- Two identical joined relations satisfies self join removal conditions but -- stay in different special join infos. diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list index cf0ac5b351b..6cf4fab9b1c 100644 --- a/src/tools/pgindent/typedefs.list +++ b/src/tools/pgindent/typedefs.list @@ -431,7 +431,6 @@ CatalogId CatalogIdMapEntry CatalogIndexState ChangeContext -ChangeVarNodes_callback ChangeVarNodes_context ChannelName CheckPoint -- 2.52.0
v6-0002-De-klugify-remove_rels_from_query_tree-s-removal-.patch (text/x-diff, 10.4K) download From f9e07e53c7c7c4088f0e0c3850968be3d1178981 Mon Sep 17 00:00:00 2001 From: Tom Lane <tgl@sss.pgh.pa.us> Date: Wed, 26 Aug 2026 13:10:50 -0400 Subject: [PATCH v6 2/2] De-klugify remove_rels_from_query_tree's removal of OJ relids. To remove nullingrel bits referring to an outer join we're removing, the previous patch did this: ChangeVarNodes((Node *) root->parse, relid, -1, 0); That's at best a cowboy hack. For one thing, it's indistinguishable from other calls that exist in the tree today that replace a given relid with INNER_VAR, intending to update Var.varno fields not nullingrels. For another thing, if there were any Vars still referencing the deleted relation, it would silently change them to invalid INNER_VAR references rather than raising an alarm. Instead, let's tweak ChangeVarNodes' API slightly to have an explicit representation of the case that we're using it to remove nullingrel references: invent a new special varno INVALID_VAR and pass that value not -1. Then within ChangeVarNodes, add Asserts that we don't attempt to assign INVALID_VAR to any field that's an actual varno. In testing this, those Asserts fired on existing regression test queries. That turned out to be because ChangeVarNodes descended into stale subquery trees that were left behind by remove_useless_outer_joins, in the case where it detects that a left join to a subquery RTE can be removed. We don't need or want that to happen, so fix remove_useless_outer_joins to set those RTEs' subquery fields to NULL, as pull_up_simple_subquery has long done. (Thanks to Richard Guo for finding that bit.) Bug: #19560 Reported-by: Orestis Markou <orestis@orestis.gr> Author: Tom Lane <tgl@sss.pgh.pa.us> Reviewed-by: Richard Guo <guofenglinux@gmail.com> Discussion: https://postgr.es/m/1186816.1784573544@sss.pgh.pa.us Backpatch-through: 16 --- src/backend/optimizer/plan/analyzejoins.c | 25 ++++++++---- src/backend/rewrite/rewriteManip.c | 49 +++++++++++++++++++++-- src/include/nodes/primnodes.h | 4 ++ 3 files changed, 68 insertions(+), 10 deletions(-) diff --git a/src/backend/optimizer/plan/analyzejoins.c b/src/backend/optimizer/plan/analyzejoins.c index 7c77118c76a..b1bbd2fd6b7 100644 --- a/src/backend/optimizer/plan/analyzejoins.c +++ b/src/backend/optimizer/plan/analyzejoins.c @@ -155,6 +155,17 @@ remove_useless_outer_joins(PlannerInfo *root) removed_relids = bms_add_member(removed_relids, innerrelid); removed_relids = bms_add_member(removed_relids, sjinfo->ojrelid); + /* + * As in pull_up_simple_subquery, discard no-longer-needed subqueries. + * This is not just an optimization, but is necessary to prevent + * subsequent processing from descending into stale subtrees and + * seeing inconsistent data. (Although simple_rte_array[] will be + * rebuilt shortly, we can still use it to access the correct RTE in + * the parse tree.) + */ + if (root->simple_rte_array[innerrelid]->rtekind == RTE_SUBQUERY) + root->simple_rte_array[innerrelid]->subquery = NULL; + /* * It's okay to keep scanning join_info_list for more removable joins, * even though the data that join_is_removable consults is now @@ -413,10 +424,11 @@ remove_join_from_jointree(Node *jtnode, int ojrelid, int *nremoved) * * 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 the relids can + * 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 in the phrels sets of PlaceHolderVars. ChangeVarNodes knows how to - * strip a relid out of all of those. + * 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_rels_from_query_tree(PlannerInfo *root, Relids removed_relids) @@ -425,8 +437,7 @@ remove_rels_from_query_tree(PlannerInfo *root, Relids removed_relids) while ((relid = bms_next_member(removed_relids, relid)) >= 0) { - /* Pass -1 for new_index to get the removal behavior */ - ChangeVarNodes((Node *) root->parse, relid, -1, 0); + ChangeVarNodes((Node *) root->parse, relid, INVALID_VAR, 0); /* * processed_tlist shares some but not all of its nodes with @@ -434,11 +445,11 @@ remove_rels_from_query_tree(PlannerInfo *root, Relids removed_relids) * harmless: ChangeVarNodes works in-place, and removing a relid that * isn't there is idempotent.) */ - ChangeVarNodes((Node *) root->processed_tlist, relid, -1, 0); + ChangeVarNodes((Node *) root->processed_tlist, relid, INVALID_VAR, 0); /* There could be references in the append_rel_list, too */ if (root->append_rel_list != NIL) - ChangeVarNodes((Node *) root->append_rel_list, relid, -1, 0); + ChangeVarNodes((Node *) root->append_rel_list, relid, INVALID_VAR, 0); } } diff --git a/src/backend/rewrite/rewriteManip.c b/src/backend/rewrite/rewriteManip.c index 6334765ba05..52157d980b5 100644 --- a/src/backend/rewrite/rewriteManip.c +++ b/src/backend/rewrite/rewriteManip.c @@ -529,9 +529,13 @@ OffsetVarNodes(Node *node, int offset, int sublevels_up) * * Find all Var nodes in the given tree belonging to a specific relation * (identified by sublevels_up and rt_index), and change their varno fields - * to 'new_index' (see adjust_relid_set for the exact change behavior). - * The varnosyn fields are changed too. Also adjust other nodes that - * contain rangetable indexes, such as RangeTblRef and JoinExpr. + * to 'new_index', and update varnosyn and varnullingrels fields similarly. + * Also adjust other nodes that contain rangetable indexes, such as + * RangeTblRef and JoinExpr. + * + * Also, new_index can be INVALID_VAR to indicate that we are deleting the + * given relid from the tree. In this case we should only find rt_index + * in nullingrels sets, never in any varno field. * * NOTE: although this has the form of a walker, we cheat and modify the * nodes in-place. The given expression tree should have been copied @@ -557,12 +561,18 @@ ChangeVarNodes_walker(Node *node, ChangeVarNodes_context *context) if (var->varlevelsup == context->sublevels_up) { if (var->varno == context->rt_index) + { + Assert(context->new_index != INVALID_VAR); var->varno = context->new_index; + } var->varnullingrels = adjust_relid_set(var->varnullingrels, context->rt_index, context->new_index); if (var->varnosyn == context->rt_index) + { + Assert(context->new_index != INVALID_VAR); var->varnosyn = context->new_index; + } } return false; } @@ -572,7 +582,10 @@ ChangeVarNodes_walker(Node *node, ChangeVarNodes_context *context) if (context->sublevels_up == 0 && cexpr->cvarno == context->rt_index) + { + Assert(context->new_index != INVALID_VAR); cexpr->cvarno = context->new_index; + } return false; } if (IsA(node, RangeTblRef)) @@ -581,7 +594,10 @@ ChangeVarNodes_walker(Node *node, ChangeVarNodes_context *context) if (context->sublevels_up == 0 && rtr->rtindex == context->rt_index) + { + Assert(context->new_index != INVALID_VAR); rtr->rtindex = context->new_index; + } /* the subquery itself is visited separately */ return false; } @@ -591,7 +607,10 @@ ChangeVarNodes_walker(Node *node, ChangeVarNodes_context *context) if (context->sublevels_up == 0 && j->rtindex == context->rt_index) + { + Assert(context->new_index != INVALID_VAR); j->rtindex = context->new_index; + } /* fall through to examine children */ } if (IsA(node, PlaceHolderVar)) @@ -616,9 +635,15 @@ ChangeVarNodes_walker(Node *node, ChangeVarNodes_context *context) if (context->sublevels_up == 0) { if (rowmark->rti == context->rt_index) + { + Assert(context->new_index != INVALID_VAR); rowmark->rti = context->new_index; + } if (rowmark->prti == context->rt_index) + { + Assert(context->new_index != INVALID_VAR); rowmark->prti = context->new_index; + } } return false; } @@ -629,9 +654,15 @@ ChangeVarNodes_walker(Node *node, ChangeVarNodes_context *context) if (context->sublevels_up == 0) { if (appinfo->parent_relid == context->rt_index) + { + Assert(context->new_index != INVALID_VAR); appinfo->parent_relid = context->new_index; + } if (appinfo->child_relid == context->rt_index) + { + Assert(context->new_index != INVALID_VAR); appinfo->child_relid = context->new_index; + } } /* fall through to examine children */ } @@ -685,21 +716,33 @@ ChangeVarNodes(Node *node, int rt_index, int new_index, int sublevels_up) ListCell *l; if (qry->resultRelation == rt_index) + { + Assert(new_index != INVALID_VAR); qry->resultRelation = new_index; + } if (qry->mergeTargetRelation == rt_index) + { + Assert(new_index != INVALID_VAR); qry->mergeTargetRelation = new_index; + } /* this is unlikely to ever be used, but ... */ if (qry->onConflict && qry->onConflict->exclRelIndex == rt_index) + { + Assert(new_index != INVALID_VAR); qry->onConflict->exclRelIndex = new_index; + } foreach(l, qry->rowMarks) { RowMarkClause *rc = (RowMarkClause *) lfirst(l); if (rc->rti == rt_index) + { + Assert(new_index != INVALID_VAR); rc->rti = new_index; + } } } query_tree_walker(qry, ChangeVarNodes_walker, &context, 0); diff --git a/src/include/nodes/primnodes.h b/src/include/nodes/primnodes.h index 44f828cbb37..5a636d1f179 100644 --- a/src/include/nodes/primnodes.h +++ b/src/include/nodes/primnodes.h @@ -217,6 +217,9 @@ typedef struct Expr * row identity information during UPDATE/DELETE/MERGE. This value should * never be seen outside the planner. * + * INVALID_VAR should never appear as anything's varno. We use it in a + * few APIs to denote removal of an RTE. + * * varnullingrels is the set of RT indexes of outer joins that can force * the Var's value to null (at the point where it appears in the query). * See optimizer/README for discussion of that. @@ -244,6 +247,7 @@ typedef struct Expr #define OUTER_VAR (-2) /* reference to outer subplan */ #define INDEX_VAR (-3) /* reference to index column */ #define ROWID_VAR (-4) /* row identity column during planning */ +#define INVALID_VAR (-5) /* this is not a valid varno! */ #define IS_SPECIAL_VARNO(varno) ((int) (varno) < 0) -- 2.52.0
^ permalink raw reply [nested|flat] 74+ messages in thread

* Re: remove_useless_joins vs. bug #19560
  2026-07-20 18:52 remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-24 13:38 ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-07-25 16:46   ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-25 20:07     ` Re: remove_useless_joins vs. bug #19560 Thom Brown <thom@linux.com>
  2026-07-25 21:23       ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-26 02:15         ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-26 09:49           ` Re: remove_useless_joins vs. bug #19560 Thom Brown <thom@linux.com>
  2026-07-26 17:33             ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-26 17:35               ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-27 07:07                 ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-07-27 16:33                   ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-27 18:21                     ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-29 06:21                       ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-16 23:58                         ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-26 05:26                           ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-26 17:25                             ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
@ 2026-08-27 01:57                               ` Richard Guo <guofenglinux@gmail.com>
  2026-08-27 05:46                                 ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-27 15:53                                 ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  0 siblings, 2 replies; 74+ messages in thread

From: Richard Guo @ 2026-08-27 01:57 UTC (permalink / raw)
  To: Tom Lane <tgl@sss.pgh.pa.us>; +Cc: Thom Brown <thom@linux.com>; Jacob Brazeal <jacob.brazeal@gmail.com>; pgsql-hackers@lists.postgresql.org

On Thu, Aug 27, 2026 at 2:25 AM Tom Lane <tgl@sss.pgh.pa.us> wrote:
> I still don't like replacing this usage of ChangeVarNodes with
> substitute_phv_relids though.  While it's a kluge as-presented,
> I'm not sure that using substitute_phv_relids that way is much less
> of a kluge.  Moreover, if there were any leftover Vars in the tree,
> substitute_phv_relids wouldn't notice.  I think noticing that is a
> good thing, and the fact that it identified this oversight in
> remove_useless_outer_joins seems like evidence in favor of that.

That is a fair point.  The only rels we can remove are plain relations
and subqueries, and the subqueries are now set to NULL, so a Var of a
removed rel should never be left in the tree.  It is good to have the
Asserts to check that.

> So what I'd prefer to do is as in 0002 attached.  For simplicity of
> review, 0001 is the same as the v5 combined patch I presented before.
> (But it's rebased onto today's HEAD, which changes only line numbers,
> and I tweaked the commit message's claim about planning time per your
> other comments.)  0002 changes ChangeVarNodes' API to have a clean
> way to represent "we're removing this relid", and adds the fix you
> identified with a more extensive comment.

I reviewed v6 as a whole and it LGTM.  I have a few small changes to
suggest, see the attached delta on top of v6.

* The first one is to initialize all_result_relids/leaf_result_relids
in subquery_planner like we did before.  v5 moved that into
query_planner, but as far as I can tell the only reason was the Assert
in the old self-join code, which is gone now.  And I think the current
initialization can contradict the comment in pathnodes.h, as I
mentioned in [1]:point 1.

* In reduce_unique_semijoins, I think we should change the singleton
test to use syn_righthand, as I mentioned in [1]:point 3.

* A nit in the ChangeVarNodes comment about INVALID_VAR.  It says
rt_index should only be found in nullingrels sets, but a removed base
relid can also be in a PlaceHolderVar's phrels, which the comment in
remove_rels_from_query_tree already says.

* The Assert on resultRelation in remove_useless_outer_joins can be
dropped, because join_is_removable already rejects that case.

[1] https://postgr.es/m/CAMbWs4-4JN51woVH86hMSMmdLfNVXzRav8KHShhP6QGmbtLNDg@mail.gmail.com

> (Maybe it'd make sense to use this version of ChangeVarNodes in
> prepjointree too?  I didn't look into that.)

I don't think so.  The two callers of substitute_phv_relids in
prepjointree.c replace a relid with a set of relids, and
ChangeVarNodes can only take one new relid.  There is no place in
prepjointree.c that just deletes a relid.

- Richard

Attachments:

nocfbot.delta-v6.patch (application/octet-stream, 4.8K) download diff --git a/src/backend/optimizer/plan/analyzejoins.c b/src/backend/optimizer/plan/analyzejoins.c index b1bbd2fd6b7..2724dd73b3e 100644 --- a/src/backend/optimizer/plan/analyzejoins.c +++ b/src/backend/optimizer/plan/analyzejoins.c @@ -131,13 +131,11 @@ remove_useless_outer_joins(PlannerInfo *root) innerrelid = bms_singleton_member(sjinfo->syn_righthand); /* - * The removed rel had better not be one that the rest of the planner - * expects to find. It can't be, really: a result relation or a - * row-marked relation has junk columns in the query targetlist, and + * The removed rel had better not be row-marked. It can't be, really: + * a row-marked relation has junk columns in the query targetlist, and * join_is_removable would have seen those as uses of the rel from * "relation 0". But let's check. */ - Assert(innerrelid != root->parse->resultRelation); #ifdef USE_ASSERT_CHECKING foreach_node(PlanRowMark, rc, root->rowMarks) Assert(rc->rti != innerrelid && rc->prti != innerrelid); @@ -488,8 +486,13 @@ reduce_unique_semijoins(PlannerInfo *root) if (sjinfo->jointype != JOIN_SEMI) continue; - if (!bms_get_singleton_member(sjinfo->min_righthand, &innerrelid)) + /* + * We test the syntactic righthand side, since that's what identifies + * the JoinExpr we'll modify. + */ + if (!bms_get_singleton_member(sjinfo->syn_righthand, &innerrelid)) continue; + Assert(bms_equal(sjinfo->min_righthand, sjinfo->syn_righthand)); innerrel = find_base_rel(root, innerrelid); diff --git a/src/backend/optimizer/plan/planmain.c b/src/backend/optimizer/plan/planmain.c index 9792a6c752f..a15d1cbede4 100644 --- a/src/backend/optimizer/plan/planmain.c +++ b/src/backend/optimizer/plan/planmain.c @@ -28,7 +28,6 @@ #include "optimizer/paths.h" #include "optimizer/placeholder.h" #include "optimizer/planmain.h" -#include "parser/parsetree.h" /* @@ -324,22 +323,6 @@ restart: */ setup_eager_aggregation(root); - /* - * If there's a result relation, initialize all_result_relids to include - * it; and if we've verified that it is non-inheriting, mark it as a leaf - * target. add_other_rels_to_query() will expand these sets if the result - * relation has children. - */ - if (parse->resultRelation) - { - RangeTblEntry *rte = rt_fetch(parse->resultRelation, parse->rtable); - - root->all_result_relids = bms_make_singleton(parse->resultRelation); - if (!rte->inh) - root->leaf_result_relids = - bms_make_singleton(parse->resultRelation); - } - /* * Now expand appendrels by adding "otherrels" for their children. We * delay this to the end so that we have as much information as possible diff --git a/src/backend/optimizer/plan/planner.c b/src/backend/optimizer/plan/planner.c index c3c158a253d..a605387dcaa 100644 --- a/src/backend/optimizer/plan/planner.c +++ b/src/backend/optimizer/plan/planner.c @@ -803,8 +803,9 @@ subquery_planner(PlannerGlobal *glob, Query *parse, char *plan_name, root->eq_classes = NIL; root->ec_merging_done = false; root->last_rinfo_serial = 0; - root->all_result_relids = NULL; - root->leaf_result_relids = NULL; + root->all_result_relids = + parse->resultRelation ? bms_make_singleton(parse->resultRelation) : NULL; + root->leaf_result_relids = NULL; /* we'll find out leaf-ness later */ root->append_rel_list = NIL; root->row_identity_vars = NIL; root->rowMarks = NIL; @@ -977,6 +978,19 @@ subquery_planner(PlannerGlobal *glob, Query *parse, char *plan_name, list_length(rte->securityQuals)); } + /* + * If we have now verified that the query target relation is + * non-inheriting, mark it as a leaf target. + */ + if (parse->resultRelation) + { + RangeTblEntry *rte = rt_fetch(parse->resultRelation, parse->rtable); + + if (!rte->inh) + root->leaf_result_relids = + bms_make_singleton(parse->resultRelation); + } + /* * This would be a convenient time to check access permissions for all * relations mentioned in the query, since it would be better to fail now, diff --git a/src/backend/rewrite/rewriteManip.c b/src/backend/rewrite/rewriteManip.c index 52157d980b5..3653f00d383 100644 --- a/src/backend/rewrite/rewriteManip.c +++ b/src/backend/rewrite/rewriteManip.c @@ -534,8 +534,9 @@ OffsetVarNodes(Node *node, int offset, int sublevels_up) * RangeTblRef and JoinExpr. * * Also, new_index can be INVALID_VAR to indicate that we are deleting the - * given relid from the tree. In this case we should only find rt_index - * in nullingrels sets, never in any varno field. + * given relid from the tree. In this case we expect to find rt_index only + * in Relids fields (varnullingrels, phnullingrels, phrels), never in any + * field that identifies a single relation. * * NOTE: although this has the form of a walker, we cheat and modify the * nodes in-place. The given expression tree should have been copied
^ permalink raw reply [nested|flat] 74+ messages in thread

* Re: remove_useless_joins vs. bug #19560
  2026-07-20 18:52 remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-24 13:38 ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-07-25 16:46   ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-25 20:07     ` Re: remove_useless_joins vs. bug #19560 Thom Brown <thom@linux.com>
  2026-07-25 21:23       ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-26 02:15         ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-26 09:49           ` Re: remove_useless_joins vs. bug #19560 Thom Brown <thom@linux.com>
  2026-07-26 17:33             ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-26 17:35               ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-27 07:07                 ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-07-27 16:33                   ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-27 18:21                     ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-29 06:21                       ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-16 23:58                         ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-26 05:26                           ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-26 17:25                             ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-27 01:57                               ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
@ 2026-08-27 05:46                                 ` Richard Guo <guofenglinux@gmail.com>
  1 sibling, 0 replies; 74+ messages in thread

From: Richard Guo @ 2026-08-27 05:46 UTC (permalink / raw)
  To: Tom Lane <tgl@sss.pgh.pa.us>; +Cc: Thom Brown <thom@linux.com>; Jacob Brazeal <jacob.brazeal@gmail.com>; pgsql-hackers@lists.postgresql.org

On Thu, Aug 27, 2026 at 10:57 AM Richard Guo <guofenglinux@gmail.com> wrote:
> That is a fair point.  The only rels we can remove are plain relations
> and subqueries, and the subqueries are now set to NULL, so a Var of a
> removed rel should never be left in the tree.  It is good to have the
> Asserts to check that.

I found one more place where the new Assert fires.  If the removed rel
has RLS policies, its RTE still carries the RLS quals, and those quals
contain Vars of the rel.  ChangeVarNodes walks RTE.securityQuals, so
we hit the Assert.  As an example, run the query below in
rowsecurity.sql:

EXPLAIN (COSTS OFF)
SELECT c.cid FROM category c LEFT JOIN document d ON c.cid = d.did;

I think we can fix it by setting securityQuals to NIL next to where we
set subquery to NULL for the removed RTE.

I checked the other fields of RangeTblEntry and did not find any
similar issue.  The only other expression field that seems suspicious
is tablesample, but I believe it's safe, as its arguments cannot refer
to any rel of the same query level, so they never contain Vars we need
to change.

I've updated the delta patch to include the fix to this issue, along
with a test case.

- Richard

Attachments:

nocfbot.delta-v6.patch (application/octet-stream, 7.7K) download diff --git a/src/backend/optimizer/plan/analyzejoins.c b/src/backend/optimizer/plan/analyzejoins.c index b1bbd2fd6b7..a4a2809ac70 100644 --- a/src/backend/optimizer/plan/analyzejoins.c +++ b/src/backend/optimizer/plan/analyzejoins.c @@ -118,6 +118,7 @@ remove_useless_outer_joins(PlannerInfo *root) SpecialJoinInfo *sjinfo = (SpecialJoinInfo *) lfirst(lc); int innerrelid; int nremoved; + RangeTblEntry *rte; /* Skip if not removable */ if (!join_is_removable(root, sjinfo)) @@ -131,13 +132,11 @@ remove_useless_outer_joins(PlannerInfo *root) innerrelid = bms_singleton_member(sjinfo->syn_righthand); /* - * The removed rel had better not be one that the rest of the planner - * expects to find. It can't be, really: a result relation or a - * row-marked relation has junk columns in the query targetlist, and + * The removed rel had better not be row-marked. It can't be, really: + * a row-marked relation has junk columns in the query targetlist, and * join_is_removable would have seen those as uses of the rel from * "relation 0". But let's check. */ - Assert(innerrelid != root->parse->resultRelation); #ifdef USE_ASSERT_CHECKING foreach_node(PlanRowMark, rc, root->rowMarks) Assert(rc->rti != innerrelid && rc->prti != innerrelid); @@ -159,12 +158,15 @@ remove_useless_outer_joins(PlannerInfo *root) * As in pull_up_simple_subquery, discard no-longer-needed subqueries. * This is not just an optimization, but is necessary to prevent * subsequent processing from descending into stale subtrees and - * seeing inconsistent data. (Although simple_rte_array[] will be - * rebuilt shortly, we can still use it to access the correct RTE in - * the parse tree.) + * seeing inconsistent data. Likewise discard any securityQuals, + * which contain Vars of the removed rel. (Although + * simple_rte_array[] will be rebuilt shortly, we can still use it to + * access the correct RTE in the parse tree.) */ - if (root->simple_rte_array[innerrelid]->rtekind == RTE_SUBQUERY) - root->simple_rte_array[innerrelid]->subquery = NULL; + rte = root->simple_rte_array[innerrelid]; + if (rte->rtekind == RTE_SUBQUERY) + rte->subquery = NULL; + rte->securityQuals = NIL; /* * It's okay to keep scanning join_info_list for more removable joins, @@ -488,8 +490,13 @@ reduce_unique_semijoins(PlannerInfo *root) if (sjinfo->jointype != JOIN_SEMI) continue; - if (!bms_get_singleton_member(sjinfo->min_righthand, &innerrelid)) + /* + * We test the syntactic righthand side, since that's what identifies + * the JoinExpr we'll modify. + */ + if (!bms_get_singleton_member(sjinfo->syn_righthand, &innerrelid)) continue; + Assert(bms_equal(sjinfo->min_righthand, sjinfo->syn_righthand)); innerrel = find_base_rel(root, innerrelid); diff --git a/src/backend/optimizer/plan/planmain.c b/src/backend/optimizer/plan/planmain.c index 9792a6c752f..a15d1cbede4 100644 --- a/src/backend/optimizer/plan/planmain.c +++ b/src/backend/optimizer/plan/planmain.c @@ -28,7 +28,6 @@ #include "optimizer/paths.h" #include "optimizer/placeholder.h" #include "optimizer/planmain.h" -#include "parser/parsetree.h" /* @@ -324,22 +323,6 @@ restart: */ setup_eager_aggregation(root); - /* - * If there's a result relation, initialize all_result_relids to include - * it; and if we've verified that it is non-inheriting, mark it as a leaf - * target. add_other_rels_to_query() will expand these sets if the result - * relation has children. - */ - if (parse->resultRelation) - { - RangeTblEntry *rte = rt_fetch(parse->resultRelation, parse->rtable); - - root->all_result_relids = bms_make_singleton(parse->resultRelation); - if (!rte->inh) - root->leaf_result_relids = - bms_make_singleton(parse->resultRelation); - } - /* * Now expand appendrels by adding "otherrels" for their children. We * delay this to the end so that we have as much information as possible diff --git a/src/backend/optimizer/plan/planner.c b/src/backend/optimizer/plan/planner.c index c3c158a253d..a605387dcaa 100644 --- a/src/backend/optimizer/plan/planner.c +++ b/src/backend/optimizer/plan/planner.c @@ -803,8 +803,9 @@ subquery_planner(PlannerGlobal *glob, Query *parse, char *plan_name, root->eq_classes = NIL; root->ec_merging_done = false; root->last_rinfo_serial = 0; - root->all_result_relids = NULL; - root->leaf_result_relids = NULL; + root->all_result_relids = + parse->resultRelation ? bms_make_singleton(parse->resultRelation) : NULL; + root->leaf_result_relids = NULL; /* we'll find out leaf-ness later */ root->append_rel_list = NIL; root->row_identity_vars = NIL; root->rowMarks = NIL; @@ -977,6 +978,19 @@ subquery_planner(PlannerGlobal *glob, Query *parse, char *plan_name, list_length(rte->securityQuals)); } + /* + * If we have now verified that the query target relation is + * non-inheriting, mark it as a leaf target. + */ + if (parse->resultRelation) + { + RangeTblEntry *rte = rt_fetch(parse->resultRelation, parse->rtable); + + if (!rte->inh) + root->leaf_result_relids = + bms_make_singleton(parse->resultRelation); + } + /* * This would be a convenient time to check access permissions for all * relations mentioned in the query, since it would be better to fail now, diff --git a/src/backend/rewrite/rewriteManip.c b/src/backend/rewrite/rewriteManip.c index 52157d980b5..3653f00d383 100644 --- a/src/backend/rewrite/rewriteManip.c +++ b/src/backend/rewrite/rewriteManip.c @@ -534,8 +534,9 @@ OffsetVarNodes(Node *node, int offset, int sublevels_up) * RangeTblRef and JoinExpr. * * Also, new_index can be INVALID_VAR to indicate that we are deleting the - * given relid from the tree. In this case we should only find rt_index - * in nullingrels sets, never in any varno field. + * given relid from the tree. In this case we expect to find rt_index only + * in Relids fields (varnullingrels, phnullingrels, phrels), never in any + * field that identifies a single relation. * * NOTE: although this has the form of a walker, we cheat and modify the * nodes in-place. The given expression tree should have been copied diff --git a/src/test/regress/expected/rowsecurity.out b/src/test/regress/expected/rowsecurity.out index f42085e53a0..356f118a366 100644 --- a/src/test/regress/expected/rowsecurity.out +++ b/src/test/regress/expected/rowsecurity.out @@ -536,6 +536,17 @@ NOTICE: f_leak => awesome science fiction 9 | 22 | 1 | regress_rls_dave | awesome science fiction (4 rows) +-- a rel with RLS quals can still be removed by outer-join removal +EXPLAIN (COSTS OFF) +SELECT c.cid FROM category c LEFT JOIN document d ON c.cid = d.did; + QUERY PLAN +---------------------------------------------------- + Seq Scan on category c + InitPlan expr_1 + -> Index Scan using uaccount_pkey on uaccount + Index Cond: (pguser = CURRENT_USER) +(4 rows) + -- viewpoint from regress_rls_carol SET SESSION AUTHORIZATION regress_rls_carol; SELECT * FROM document WHERE f_leak(dtitle) ORDER BY did; diff --git a/src/test/regress/sql/rowsecurity.sql b/src/test/regress/sql/rowsecurity.sql index ed70b1b229e..99eaba28f5a 100644 --- a/src/test/regress/sql/rowsecurity.sql +++ b/src/test/regress/sql/rowsecurity.sql @@ -307,6 +307,10 @@ SELECT * FROM document NATURAL JOIN category WHERE f_leak(dtitle) ORDER BY did; SELECT * FROM document TABLESAMPLE BERNOULLI(50) REPEATABLE(0) WHERE f_leak(dtitle) ORDER BY did; +-- a rel with RLS quals can still be removed by outer-join removal +EXPLAIN (COSTS OFF) +SELECT c.cid FROM category c LEFT JOIN document d ON c.cid = d.did; + -- viewpoint from regress_rls_carol SET SESSION AUTHORIZATION regress_rls_carol; SELECT * FROM document WHERE f_leak(dtitle) ORDER BY did;
^ permalink raw reply [nested|flat] 74+ messages in thread

* Re: remove_useless_joins vs. bug #19560
  2026-07-20 18:52 remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-24 13:38 ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-07-25 16:46   ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-25 20:07     ` Re: remove_useless_joins vs. bug #19560 Thom Brown <thom@linux.com>
  2026-07-25 21:23       ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-26 02:15         ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-26 09:49           ` Re: remove_useless_joins vs. bug #19560 Thom Brown <thom@linux.com>
  2026-07-26 17:33             ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-26 17:35               ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-27 07:07                 ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-07-27 16:33                   ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-27 18:21                     ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-29 06:21                       ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-16 23:58                         ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-26 05:26                           ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-26 17:25                             ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-27 01:57                               ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
@ 2026-08-27 15:53                                 ` Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-28 07:29                                   ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  1 sibling, 1 reply; 74+ messages in thread

From: Tom Lane @ 2026-08-27 15:53 UTC (permalink / raw)
  To: Richard Guo <guofenglinux@gmail.com>; +Cc: Thom Brown <thom@linux.com>; Jacob Brazeal <jacob.brazeal@gmail.com>; pgsql-hackers@lists.postgresql.org

Richard Guo <guofenglinux@gmail.com> writes:
> I reviewed v6 as a whole and it LGTM.  I have a few small changes to
> suggest, see the attached delta on top of v6.

> * The first one is to initialize all_result_relids/leaf_result_relids
> in subquery_planner like we did before.  v5 moved that into
> query_planner, but as far as I can tell the only reason was the Assert
> in the old self-join code, which is gone now.  And I think the current
> initialization can contradict the comment in pathnodes.h, as I
> mentioned in [1]:point 1.

I don't like this on the grounds of consistency.  As things stand now,
we partially initialize those fields in subquery_planner and then
finish filling them in much later, during add_other_rels_to_query.
What I did in my proposed patch was to collect all of that processing
together, in successive steps near the end of query_planner.  This
makes it clear that those fields are not to be relied on before that
point, and in particular that they don't need to be reset in the
restart loop in the initial part of query_planner.  If we change it
back as you suggest, then it'll be really nonobvious why this derived
data is handled differently from other derived data.  And the fact
that it's only partially valid during the restart loop seems to me
to be a bug hazard: if someone tried to rely on these fields in
logic within that loop, it might seem to work as long as they'd not
tested it on inheritance/partitioning cases.  So I think moving this
logic is good cleanup, albeit maybe not strictly necessary to the
immediate problem.

I take your point that the early-exit-for-trivial-jointree path now
fails to set these fields at all, but I'd rather handle that by
adding a couple more lines in that path to fill them in.  Yup, it'd
be duplicate logic, but it seems cleaner that way.

> * The Assert on resultRelation in remove_useless_outer_joins can be
> dropped, because join_is_removable already rejects that case.

Well, yeah, but on that argument we could drop the entire stanza,
because it's just checking that join_is_removable didn't mess up.
Maybe we should?  I've not heard that anybody ever hit those Asserts.

Your other changes look good.

			regards, tom lane






^ permalink  raw  reply  [nested|flat] 74+ messages in thread

* Re: remove_useless_joins vs. bug #19560
  2026-07-20 18:52 remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-24 13:38 ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-07-25 16:46   ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-25 20:07     ` Re: remove_useless_joins vs. bug #19560 Thom Brown <thom@linux.com>
  2026-07-25 21:23       ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-26 02:15         ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-26 09:49           ` Re: remove_useless_joins vs. bug #19560 Thom Brown <thom@linux.com>
  2026-07-26 17:33             ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-26 17:35               ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-27 07:07                 ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-07-27 16:33                   ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-27 18:21                     ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-29 06:21                       ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-16 23:58                         ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-26 05:26                           ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-26 17:25                             ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-27 01:57                               ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-27 15:53                                 ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
@ 2026-08-28 07:29                                   ` Richard Guo <guofenglinux@gmail.com>
  2026-08-28 13:43                                     ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  0 siblings, 1 reply; 74+ messages in thread

From: Richard Guo @ 2026-08-28 07:29 UTC (permalink / raw)
  To: Tom Lane <tgl@sss.pgh.pa.us>; +Cc: Thom Brown <thom@linux.com>; Jacob Brazeal <jacob.brazeal@gmail.com>; pgsql-hackers@lists.postgresql.org

On Fri, Aug 28, 2026 at 12:53 AM Tom Lane <tgl@sss.pgh.pa.us> wrote:
> I don't like this on the grounds of consistency.  As things stand now,
> we partially initialize those fields in subquery_planner and then
> finish filling them in much later, during add_other_rels_to_query.
> What I did in my proposed patch was to collect all of that processing
> together, in successive steps near the end of query_planner.  This
> makes it clear that those fields are not to be relied on before that
> point, and in particular that they don't need to be reset in the
> restart loop in the initial part of query_planner.  If we change it
> back as you suggest, then it'll be really nonobvious why this derived
> data is handled differently from other derived data.  And the fact
> that it's only partially valid during the restart loop seems to me
> to be a bug hazard: if someone tried to rely on these fields in
> logic within that loop, it might seem to work as long as they'd not
> tested it on inheritance/partitioning cases.  So I think moving this
> logic is good cleanup, albeit maybe not strictly necessary to the
> immediate problem.
>
> I take your point that the early-exit-for-trivial-jointree path now
> fails to set these fields at all, but I'd rather handle that by
> adding a couple more lines in that path to fill them in.  Yup, it'd
> be duplicate logic, but it seems cleaner that way.

Fair enough.  I agree that keeping all of this together at the end of
query_planner makes it clear that these fields are not valid before
then, and that a half-filled set during the restart loop is a hazard.
Adding the few lines to the early-exit path sounds good to me.

> Well, yeah, but on that argument we could drop the entire stanza,
> because it's just checking that join_is_removable didn't mess up.
> Maybe we should?  I've not heard that anybody ever hit those Asserts.

I think so.  The resultRelation case is rejected explicitly in
join_is_removable:

    if (innerrelid == root->parse->resultRelation)
        return false;

and a row-marked rel is rejected by the attr_needed test, since
preprocess_targetlist adds junk columns for every row mark.

I'm not a fan of redundant Asserts, so I'd vote for dropping both.
But I'm fine with keeping both too, if you prefer.

- Richard






^ permalink  raw  reply  [nested|flat] 74+ messages in thread

* Re: remove_useless_joins vs. bug #19560
  2026-07-20 18:52 remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-24 13:38 ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-07-25 16:46   ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-25 20:07     ` Re: remove_useless_joins vs. bug #19560 Thom Brown <thom@linux.com>
  2026-07-25 21:23       ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-26 02:15         ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-26 09:49           ` Re: remove_useless_joins vs. bug #19560 Thom Brown <thom@linux.com>
  2026-07-26 17:33             ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-26 17:35               ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-27 07:07                 ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-07-27 16:33                   ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-27 18:21                     ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-29 06:21                       ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-16 23:58                         ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-26 05:26                           ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-26 17:25                             ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-27 01:57                               ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-27 15:53                                 ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-28 07:29                                   ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
@ 2026-08-28 13:43                                     ` Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-29 03:03                                       ` Re: remove_useless_joins vs. bug #19560 Tender Wang <tndrwang@gmail.com>
  2026-08-29 03:27                                       ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-09-17 02:40                                       ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-09-17 02:51                                       ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  0 siblings, 4 replies; 74+ messages in thread

From: Tom Lane @ 2026-08-28 13:43 UTC (permalink / raw)
  To: Richard Guo <guofenglinux@gmail.com>; +Cc: Thom Brown <thom@linux.com>; Jacob Brazeal <jacob.brazeal@gmail.com>; pgsql-hackers@lists.postgresql.org

Richard Guo <guofenglinux@gmail.com> writes:
> On Fri, Aug 28, 2026 at 12:53 AM Tom Lane <tgl@sss.pgh.pa.us> wrote:
>> I take your point that the early-exit-for-trivial-jointree path now
>> fails to set these fields at all, but I'd rather handle that by
>> adding a couple more lines in that path to fill them in.  Yup, it'd
>> be duplicate logic, but it seems cleaner that way.

> Fair enough.  I agree that keeping all of this together at the end of
> query_planner makes it clear that these fields are not valid before
> then, and that a half-filled set during the restart loop is a hazard.
> Adding the few lines to the early-exit path sounds good to me.

Cool.

>> Well, yeah, but on that argument we could drop the entire stanza,
>> because it's just checking that join_is_removable didn't mess up.
>> Maybe we should?  I've not heard that anybody ever hit those Asserts.

> I think so.

Sold.  I'll make it so and push.  Thanks for reviewing!

			regards, tom lane






^ permalink  raw  reply  [nested|flat] 74+ messages in thread

* Re: remove_useless_joins vs. bug #19560
  2026-07-20 18:52 remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-24 13:38 ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-07-25 16:46   ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-25 20:07     ` Re: remove_useless_joins vs. bug #19560 Thom Brown <thom@linux.com>
  2026-07-25 21:23       ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-26 02:15         ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-26 09:49           ` Re: remove_useless_joins vs. bug #19560 Thom Brown <thom@linux.com>
  2026-07-26 17:33             ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-26 17:35               ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-27 07:07                 ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-07-27 16:33                   ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-27 18:21                     ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-29 06:21                       ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-16 23:58                         ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-26 05:26                           ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-26 17:25                             ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-27 01:57                               ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-27 15:53                                 ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-28 07:29                                   ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-28 13:43                                     ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
@ 2026-08-29 03:03                                       ` Tender Wang <tndrwang@gmail.com>
  3 siblings, 0 replies; 74+ messages in thread

From: Tender Wang @ 2026-08-29 03:03 UTC (permalink / raw)
  To: Tom Lane <tgl@sss.pgh.pa.us>; +Cc: Richard Guo <guofenglinux@gmail.com>; Thom Brown <thom@linux.com>; Jacob Brazeal <jacob.brazeal@gmail.com>; pgsql-hackers@lists.postgresql.org

Hi,

Tom Lane <tgl@sss.pgh.pa.us> 于2026年8月28日周五 21:43写道:
>
> Richard Guo <guofenglinux@gmail.com> writes:
> > On Fri, Aug 28, 2026 at 12:53 AM Tom Lane <tgl@sss.pgh.pa.us> wrote:
> >> I take your point that the early-exit-for-trivial-jointree path now
> >> fails to set these fields at all, but I'd rather handle that by
> >> adding a couple more lines in that path to fill them in.  Yup, it'd
> >> be duplicate logic, but it seems cleaner that way.
>
> > Fair enough.  I agree that keeping all of this together at the end of
> > query_planner makes it clear that these fields are not valid before
> > then, and that a half-filled set during the restart loop is a hazard.
> > Adding the few lines to the early-exit path sounds good to me.
>
> Cool.
>
> >> Well, yeah, but on that argument we could drop the entire stanza,
> >> because it's just checking that join_is_removable didn't mess up.
> >> Maybe we should?  I've not heard that anybody ever hit those Asserts.
>
> > I think so.
>
> Sold.  I'll make it so and push.  Thanks for reviewing!

After 2ebf25e7d70a8, I hit a crash.

How to reproduce:

1. Run the regression tests.
2. Run the following query against the regression database:
psql (20devel)
Type "help" for help.

postgres=# \c regression
You are now connected to database "regression" as user "ubuntu".
regression=# SELECT
FROM (SELECT CASE
               WHEN NULL
                 THEN sample_1.a
               ELSE NULL
             END AS c2
      FROM public.shoelace_ok AS ref_2
           LEFT JOIN fkpart5.pk31 AS sample_1 ON ref_2.ok_quant =
sample_1.a) AS subq_0
     RIGHT JOIN public.ruletest_tbl2 AS ref_3 ON NULL,
     LATERAL (SELECT subq_0.c2 AS c0,
                     public.logging_agg_nonstrict(ref_4.a) AS c8
              FROM public.test_inh_check AS ref_4) AS subq_3;
server closed the connection unexpectedly
        This probably means the server terminated abnormally
        before or while processing the request.
The connection to the server was lost. Attempting reset: Succeeded.

The crash was originally found by SQLSmith. I reduced the original large
query to the reproducer above.


-- 
Thanks,
Tender Wang





^ permalink  raw  reply  [nested|flat] 74+ messages in thread

* Re: remove_useless_joins vs. bug #19560
  2026-07-20 18:52 remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-24 13:38 ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-07-25 16:46   ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-25 20:07     ` Re: remove_useless_joins vs. bug #19560 Thom Brown <thom@linux.com>
  2026-07-25 21:23       ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-26 02:15         ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-26 09:49           ` Re: remove_useless_joins vs. bug #19560 Thom Brown <thom@linux.com>
  2026-07-26 17:33             ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-26 17:35               ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-27 07:07                 ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-07-27 16:33                   ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-27 18:21                     ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-29 06:21                       ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-16 23:58                         ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-26 05:26                           ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-26 17:25                             ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-27 01:57                               ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-27 15:53                                 ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-28 07:29                                   ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-28 13:43                                     ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
@ 2026-08-29 03:27                                       ` Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-29 20:10                                         ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  3 siblings, 1 reply; 74+ messages in thread

From: Tom Lane @ 2026-08-29 03:27 UTC (permalink / raw)
  To: Tender Wang <tndrwang@gmail.com>; +Cc: Richard Guo <guofenglinux@gmail.com>; Thom Brown <thom@linux.com>; Jacob Brazeal <jacob.brazeal@gmail.com>; pgsql-hackers@lists.postgresql.org

Tender Wang <tndrwang@gmail.com> writes:
> After 2ebf25e7d70a8, I hit a crash.

Oh, interesting.  What we have here is:

> SELECT
> FROM (SELECT CASE
>                WHEN NULL
>                  THEN sample_1.a
>                ELSE NULL
>              END AS c2
>       FROM ...

What's apparently happening is that we pull up the sub-select,
and eval_const_expressions flattens the CASE to constant-NULL,
so we don't see the reference to sample_1.a and conclude that
sample_1 can be dropped from the query.  But when we do that,
we try to mutate the original copy of the sub-select's tlist
which still contains sample_1.a, and so we hit the Assert
saying we should no longer see any such Vars.

Not immediately sure what to do about that ... I don't think
that dropping the Asserts would fix it, even if that were
a pleasant answer which it's not.  If we allowed the Var
to become a reference to INVALID_VAR, then when we repeat
the eval_const_expressions run later, we're going to have
problems.  IIRC, there are places where eval_const_expressions
looks up Var properties such as null-ness, and that'd fail.

			regards, tom lane






^ permalink  raw  reply  [nested|flat] 74+ messages in thread

* Re: remove_useless_joins vs. bug #19560
  2026-07-20 18:52 remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-24 13:38 ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-07-25 16:46   ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-25 20:07     ` Re: remove_useless_joins vs. bug #19560 Thom Brown <thom@linux.com>
  2026-07-25 21:23       ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-26 02:15         ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-26 09:49           ` Re: remove_useless_joins vs. bug #19560 Thom Brown <thom@linux.com>
  2026-07-26 17:33             ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-26 17:35               ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-27 07:07                 ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-07-27 16:33                   ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-27 18:21                     ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-29 06:21                       ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-16 23:58                         ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-26 05:26                           ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-26 17:25                             ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-27 01:57                               ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-27 15:53                                 ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-28 07:29                                   ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-28 13:43                                     ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-29 03:27                                       ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
@ 2026-08-29 20:10                                         ` Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-30 06:50                                           ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  0 siblings, 1 reply; 74+ messages in thread

From: Tom Lane @ 2026-08-29 20:10 UTC (permalink / raw)
  To: Tender Wang <tndrwang@gmail.com>; +Cc: Richard Guo <guofenglinux@gmail.com>; Thom Brown <thom@linux.com>; Jacob Brazeal <jacob.brazeal@gmail.com>; pgsql-hackers@lists.postgresql.org

I wrote:
> What's apparently happening is that we pull up the sub-select,
> and eval_const_expressions flattens the CASE to constant-NULL,
> so we don't see the reference to sample_1.a and conclude that
> sample_1 can be dropped from the query.  But when we do that,
> we try to mutate the original copy of the sub-select's tlist
> which still contains sample_1.a, and so we hit the Assert
> saying we should no longer see any such Vars.

More specifically, the raw CASE expression gets pushed down into
the lateral subquery, wrapped in a PlaceHolderVar.  When we
pull it back up in extract_lateral_references(), we apply
expression preprocessing which flattens the CASE to constant-NULL.
So the lateral reference expression seen by the upper query has
no reference to sample_1, allowing join removal to remove sample_1.
But the PHV inside the subquery still has a reference, which makes
ChangeVarNodes fail, and even if we prevented that it'd still be
trouble when we repeat extract_lateral_references() after restarting.

So after contemplating my navel for awhile, the least grotty
solution I can see is to update the subquery's copy of the PHV
with the preprocessed expression, as attached.  I don't really
love doing that, but the alternatives I can think of are worse.
Anyone have another idea?

One interesting point about this query is that if you remove
the topmost right join ("RIGHT JOIN public.ruletest_tbl2 AS ref_3
ON NULL" in the original example, "right join int4_tbl i42 on false"
in my proposed regression test), there's no failure.  That's not
so surprising, because without that join we don't have to wrap the
CASE in a PlaceHolderVar, and then there's no discrepancy between what
the subquery contains and what the outer level thinks it contains.
But what is surprising is that we then fail to make the join removal,
which seems like a missed optimization.  I didn't poke into that, but
I think it'd be worth figuring out why the removal doesn't happen.

			regards, tom lane

Attachments:

put-back-preprocessed-PHV.patch (text/x-diff, 4.0K) download diff --git a/src/backend/optimizer/plan/initsplan.c b/src/backend/optimizer/plan/initsplan.c index a2fb0b55a79..1c60b7b5bcf 100644 --- a/src/backend/optimizer/plan/initsplan.c +++ b/src/backend/optimizer/plan/initsplan.c @@ -1118,9 +1118,9 @@ extract_lateral_references(PlannerInfo *root, RelOptInfo *brel, Index rtindex) newvars = NIL; foreach(lc, vars) { - Node *node = (Node *) lfirst(lc); + Node *orig_node = (Node *) lfirst(lc); + Node *node = copyObject(orig_node); - node = copyObject(node); if (IsA(node, Var)) { Var *var = (Var *) node; @@ -1141,9 +1141,27 @@ extract_lateral_references(PlannerInfo *root, RelOptInfo *brel, Index rtindex) * If we pulled the PHV out of a subquery RTE, its expression * needs to be preprocessed. subquery_planner() already did this * for level-zero PHVs in function and values RTEs, though. + * + * Furthermore, we modify the subquery by putting the preprocessed + * expression back into the subquery's PHV, after reversing the + * levelsup adjustment again. This is rather grotty: it'd be + * better if this processing didn't modify the subquery. However, + * it's essential for some optimization scenarios. For example, + * if the PHV contains a Var of our level that is deleted during + * preprocessing (say, by simplifying a CASE with constant test + * expression), join simplification may decide that it can remove + * the rel that is the source of the Var. If the subquery still + * contains a reference to that Var, trouble will ensue. */ if (levelsup > 0) + { + Expr *repl_expr; + phv->phexpr = preprocess_phv_expression(root, phv->phexpr); + repl_expr = copyObject(phv->phexpr); + IncrementVarSublevelsUp((Node *) repl_expr, levelsup, 0); + ((PlaceHolderVar *) orig_node)->phexpr = repl_expr; + } } else Assert(false); diff --git a/src/test/regress/expected/join.out b/src/test/regress/expected/join.out index db4fcc5a5a0..bebad6e4406 100644 --- a/src/test/regress/expected/join.out +++ b/src/test/regress/expected/join.out @@ -7043,6 +7043,35 @@ on lhs.id = rhs.id; -> Result (5 rows) +-- check handling of a removed Var that's pushed down into a subquery +-- (fallout from the fix for bug #19560) +explain (verbose, costs off) +select c1, c2 +from (select case when false then remov.id end as c1 + from int4_tbl i41 left join a remov on i41.f1 = remov.id) ss1 + right join int4_tbl i42 on false, + lateral (select ss1.c1 as c2 from int4_tbl i43 offset 0) ss2; + QUERY PLAN +---------------------------------------------- + Nested Loop + Output: (NULL::integer), ((NULL::integer)) + -> Nested Loop Left Join + Output: (NULL::integer) + Join Filter: false + -> Seq Scan on public.int4_tbl i42 + Output: i42.f1 + -> Result + Output: NULL::integer + Replaces: Scan on i41 + One-Time Filter: false + -> Memoize + Output: ((NULL::integer)) + Cache Key: (NULL::integer) + Cache Mode: binary + -> Seq Scan on public.int4_tbl i43 + Output: (NULL::integer) +(17 rows) + -- More tests of correct placement of pseudoconstant quals -- simple constant-false condition explain (costs off) diff --git a/src/test/regress/sql/join.sql b/src/test/regress/sql/join.sql index 9533af8656e..088aa26c69a 100644 --- a/src/test/regress/sql/join.sql +++ b/src/test/regress/sql/join.sql @@ -2581,6 +2581,15 @@ full join ) as rhs on lhs.id = rhs.id; +-- check handling of a removed Var that's pushed down into a subquery +-- (fallout from the fix for bug #19560) +explain (verbose, costs off) +select c1, c2 +from (select case when false then remov.id end as c1 + from int4_tbl i41 left join a remov on i41.f1 = remov.id) ss1 + right join int4_tbl i42 on false, + lateral (select ss1.c1 as c2 from int4_tbl i43 offset 0) ss2; + -- More tests of correct placement of pseudoconstant quals -- simple constant-false condition
^ permalink raw reply [nested|flat] 74+ messages in thread

* Re: remove_useless_joins vs. bug #19560
  2026-07-20 18:52 remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-24 13:38 ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-07-25 16:46   ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-25 20:07     ` Re: remove_useless_joins vs. bug #19560 Thom Brown <thom@linux.com>
  2026-07-25 21:23       ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-26 02:15         ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-26 09:49           ` Re: remove_useless_joins vs. bug #19560 Thom Brown <thom@linux.com>
  2026-07-26 17:33             ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-26 17:35               ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-27 07:07                 ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-07-27 16:33                   ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-27 18:21                     ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-29 06:21                       ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-16 23:58                         ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-26 05:26                           ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-26 17:25                             ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-27 01:57                               ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-27 15:53                                 ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-28 07:29                                   ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-28 13:43                                     ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-29 03:27                                       ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-29 20:10                                         ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
@ 2026-08-30 06:50                                           ` Richard Guo <guofenglinux@gmail.com>
  2026-08-30 15:33                                             ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-30 16:20                                             ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  0 siblings, 2 replies; 74+ messages in thread

From: Richard Guo @ 2026-08-30 06:50 UTC (permalink / raw)
  To: Tom Lane <tgl@sss.pgh.pa.us>; +Cc: Tender Wang <tndrwang@gmail.com>; Thom Brown <thom@linux.com>; Jacob Brazeal <jacob.brazeal@gmail.com>; pgsql-hackers@lists.postgresql.org

On Sun, Aug 30, 2026 at 5:10 AM Tom Lane <tgl@sss.pgh.pa.us> wrote:
> So after contemplating my navel for awhile, the least grotty
> solution I can see is to update the subquery's copy of the PHV
> with the preprocessed expression, as attached.  I don't really
> love doing that, but the alternatives I can think of are worse.
> Anyone have another idea?

I looked at the patch.  I noticed a couple of problems with putting
the preprocessed expression back into the subquery.

One is that preprocess_expression is not something we can run twice on
the same expression.  If join removal restarts query_planner,
extract_lateral_references runs again and preprocesses the PHV copy
that we wrote back in the previous round.  If that expression contains
a SubPlan by then, we can hit "Assert(!IsA(node, SubPlan))" in several
places.  For instance:

explain (verbose, costs off)
select c1, c2
from (select case when false then remov.id else (select i41.f1) end as c1
      from int4_tbl i41 left join a remov on i41.f1 = remov.id) ss1
     right join int4_tbl i42 on false,
     lateral (select ss1.c1 as c2 from int4_tbl i43 offset 0) ss2;

TRAP: failed Assert("!IsA(node, SubPlan)")

The other one is that find_lateral_references ignores appendrel
otherrels.  The appendrel children created by pull_up_simple_union_all
are copies of the arm RTEs, so the PHV copies in those child
subqueries are never fixed, and we still hit the original Assert:

explain (verbose, costs off)
select c1, c2
from (select case when false then remov.id end as c1
      from int4_tbl i41 left join a remov on i41.f1 = remov.id) ss1
     right join int4_tbl i42 on false,
     lateral ((select ss1.c1 as c2 from int4_tbl i43 offset 0)
              union all
              (select ss1.c1 from int4_tbl i44 offset 0)) ss2;

TRAP: failed Assert("context->new_index != INVALID_VAR")

I tried a few different things, and I found another way to fix it,
which is to preprocess these PHV copies once in subquery_planner, in
the loop where we already flatten join aliases in LATERAL subqueries,
and not preprocess them again in extract_lateral_references.  That
covers the appendrel children too, since they are marked LATERAL as
well.

One consequence is that a not-yet-planned subquery can now contain
SubPlans, within a PHV of an upper query level.  (This applies to your
patch as well.)  This seems to be new.  AFAICT, an unplanned subquery
never held SubPlans before.  Fortunately, most of the tree walkers
that run on the subquery before SS_replace_correlation_vars replaces
the outer PHV with a Param cope with that.  The exception is
flatten_join_alias_vars, which descends into every PHV and asserts on
SubPlans.  I changed it to leave PHVs of upper levels alone; such a
PHV cannot contain join aliases of the level being flattened anyway.

Also, the edge case in identify_current_nestloop_params that
substitutes the ph_var copy for a nestloop-param PHV was there because
the copy from the subquery could still contain SubLinks.  That is no
longer possible, but I kept the substitution, since it still avoids
evaluating duplicate SubPlans when the PHV contains a sublink.  I
updated the comment accordingly and added an Assert.

- Richard

Attachments:

v2-0001-Fix-stale-copies-of-PHVs-in-LATERAL-subqueries.patch (application/octet-stream, 16.1K) download From 10bbab6257e742aa80b298733be6aba34623c20c Mon Sep 17 00:00:00 2001 From: Richard Guo <guofenglinux@gmail.com> Date: Sun, 30 Aug 2026 08:21:21 +0900 Subject: [PATCH v2] Fix stale copies of PHVs in LATERAL subqueries When a LATERAL subquery references an output of another subquery that gets pulled up, and that output must be wrapped in a PlaceHolderVar because of an intermediate outer join, the PHV expression is pushed down into the LATERAL subquery. That copy is not preprocessed along with the outer query's expressions, since planning of the subquery happens later. So the two copies can diverge. That used to be harmless, because the subquery's copy is never evaluated and is matched to the outer PHV by phid only. But since commit 2ebf25e7d, join removal edits the whole query tree to remove references to the removed rel, and it walks into subqueries. If join removal deletes the rel whose Var survives only in the subquery's copy, we hit an Assert in ChangeVarNodes. To fix, preprocess the PHV copies within each LATERAL subquery RTE in subquery_planner, right where we already flatten join alias Vars in such subqueries, so that they match the preprocessed PHVs of the outer query. extract_lateral_references no longer needs to preprocess the copies it pulls out of subqueries, and it must not, since preprocessing is not something we can safely do twice on the same expression. One consequence is that a not-yet-planned subquery can now contain SubPlans, within a PHV of an upper query level. Teach flatten_join_alias_vars_mutator to leave such PHVs alone, as process_sublinks_mutator already does; a PHV of an upper level cannot contain join aliases of the level being flattened anyway. Also update the comment in identify_current_nestloop_params, since the subquery's copy of a PHV can no longer contain unprocessed SubLinks. We still prefer the PlaceHolderInfo's copy there, to avoid evaluating duplicate SubPlans. --- src/backend/optimizer/plan/initsplan.c | 15 ++-- src/backend/optimizer/plan/planner.c | 53 ++++++++++-- src/backend/optimizer/util/paramassign.c | 23 +++--- src/backend/optimizer/util/var.c | 10 ++- src/include/optimizer/planner.h | 1 - src/test/regress/expected/join.out | 100 +++++++++++++++++++++++ src/test/regress/sql/join.sql | 30 +++++++ 7 files changed, 199 insertions(+), 33 deletions(-) diff --git a/src/backend/optimizer/plan/initsplan.c b/src/backend/optimizer/plan/initsplan.c index a2fb0b55a79..9b73c0dc771 100644 --- a/src/backend/optimizer/plan/initsplan.c +++ b/src/backend/optimizer/plan/initsplan.c @@ -29,7 +29,6 @@ #include "optimizer/paths.h" #include "optimizer/placeholder.h" #include "optimizer/planmain.h" -#include "optimizer/planner.h" #include "optimizer/restrictinfo.h" #include "parser/analyze.h" #include "rewrite/rewriteManip.h" @@ -1133,17 +1132,13 @@ extract_lateral_references(PlannerInfo *root, RelOptInfo *brel, Index rtindex) PlaceHolderVar *phv = (PlaceHolderVar *) node; int levelsup = phv->phlevelsup; - /* Have to work harder to adjust the contained expression too */ - if (levelsup != 0) - IncrementVarSublevelsUp(node, -levelsup, 0); - /* - * If we pulled the PHV out of a subquery RTE, its expression - * needs to be preprocessed. subquery_planner() already did this - * for level-zero PHVs in function and values RTEs, though. + * Have to work harder to adjust the contained expression too. + * (Its expression has already been preprocessed by + * subquery_planner(), so we must not do that again here.) */ - if (levelsup > 0) - phv->phexpr = preprocess_phv_expression(root, phv->phexpr); + if (levelsup != 0) + IncrementVarSublevelsUp(node, -levelsup, 0); } else Assert(false); diff --git a/src/backend/optimizer/plan/planner.c b/src/backend/optimizer/plan/planner.c index c3c158a253d..85c24dbf09b 100644 --- a/src/backend/optimizer/plan/planner.c +++ b/src/backend/optimizer/plan/planner.c @@ -146,6 +146,7 @@ typedef struct /* Local functions */ static Node *preprocess_expression(PlannerInfo *root, Node *expr, int kind); +static void preprocess_subquery_phvs(PlannerInfo *root, Query *subquery); static void preprocess_qual_conditions(PlannerInfo *root, Node *jtnode); static Bitmapset *find_having_conflicts(Query *parse, Index group_rtindex); static Oid having_var_grouping_eqop(Var *var, void *context); @@ -1151,6 +1152,17 @@ subquery_planner(PlannerGlobal *glob, Query *parse, char *plan_name, rte->subquery = (Query *) flatten_join_alias_vars(root, root->parse, (Node *) rte->subquery); + + /* + * Likewise, any PlaceHolderVars of our level that were pushed + * into the subquery have to be preprocessed now, so that they + * match the preprocessed PHVs of this level. Otherwise, a Var + * that preprocessing simplifies away at this level could remain + * in the subquery, and join removal could later delete that Var's + * rel. + */ + if (rte->lateral && root->glob->lastPHId != 0) + preprocess_subquery_phvs(root, rte->subquery); } else if (rte->rtekind == RTE_FUNCTION) { @@ -1645,20 +1657,43 @@ group_var_eqop(Query *parse, Var *var) } /* - * preprocess_phv_expression - * Do preprocessing on a PlaceHolderVar expression that's been pulled up. + * preprocess_subquery_phvs + * Preprocess the expressions of PlaceHolderVars of the current query + * level that appear within a LATERAL subquery. * * If a LATERAL subquery references an output of another subquery, and that * output must be wrapped in a PlaceHolderVar because of an intermediate outer - * join, then we'll push the PlaceHolderVar expression down into the subquery - * and later pull it back up during find_lateral_references, which runs after - * subquery_planner has preprocessed all the expressions that were in the - * current query level to start with. So we need to preprocess it then. + * join, then we'll push the PlaceHolderVar expression down into the subquery. + * Planning of the subquery won't preprocess it, since it belongs to our + * level, so we do that here. We modify the PHVs in place. This has to + * handle PHVs at any depth of sub-subqueries, so we temporarily adjust the + * expression's level to ours. */ -Expr * -preprocess_phv_expression(PlannerInfo *root, Expr *expr) +static void +preprocess_subquery_phvs(PlannerInfo *root, Query *subquery) { - return (Expr *) preprocess_expression(root, (Node *) expr, EXPRKIND_PHV); + List *vars = pull_vars_of_level((Node *) subquery, 1); + + foreach_ptr(Node, node, vars) + { + PlaceHolderVar *phv; + int levelsup; + Node *expr; + + if (!IsA(node, PlaceHolderVar)) + continue; + + phv = (PlaceHolderVar *) node; + levelsup = phv->phlevelsup; + + /* Adjust the expression to our level, preprocess it, and adjust back */ + expr = copyObject((Node *) phv->phexpr); + IncrementVarSublevelsUp(expr, -levelsup, 0); + expr = preprocess_expression(root, expr, EXPRKIND_PHV); + IncrementVarSublevelsUp(expr, levelsup, 0); + + phv->phexpr = (Expr *) expr; + } } /*-------------------- diff --git a/src/backend/optimizer/util/paramassign.c b/src/backend/optimizer/util/paramassign.c index 222de1450b2..6a1be4551bd 100644 --- a/src/backend/optimizer/util/paramassign.c +++ b/src/backend/optimizer/util/paramassign.c @@ -677,19 +677,18 @@ identify_current_nestloop_params(PlannerInfo *root, /* * Deal with an edge case: if the PHV was pulled up out of a * subquery and it contains a subquery that was originally - * pushed down from this query level, then that will still be - * represented as a SubLink, because SS_process_sublinks won't - * recurse into outer PHVs, so it didn't get transformed - * during expression preprocessing in the subquery. We need a - * version of the PHV that has a SubPlan, which we can get - * from the current query level's placeholder_list. This is - * quite grotty of course, but dealing with it earlier in the - * handling of subplan params would be just as grotty, and it - * might end up being a waste of cycles if we don't decide to - * treat the PHV as a NestLoopParam. (Perhaps that whole - * mechanism should be redesigned someday, but today is not - * that day.) + * pushed down from this query level, then the copy of the PHV + * we got from the subquery has its own SubPlan for that, + * distinct from the one in the current query level's + * placeholder_list. We'd rather use the placeholder_list's + * version of the PHV, so that we don't end up evaluating + * duplicate SubPlans. + * + * Note that the subquery's copy cannot contain any SubLinks: + * subquery_planner preprocessed the PHVs of this query level + * within the subquery before the subquery was planned. */ + Assert(!checkExprHasSubLink((Node *) phv)); if (root->parse->hasSubLinks) { phv = copyObject(phinfo->ph_var); diff --git a/src/backend/optimizer/util/var.c b/src/backend/optimizer/util/var.c index 907a255c36f..546480b625b 100644 --- a/src/backend/optimizer/util/var.c +++ b/src/backend/optimizer/util/var.c @@ -933,7 +933,15 @@ flatten_join_alias_vars_mutator(Node *node, if (IsA(node, PlaceHolderVar)) { /* Copy the PlaceHolderVar node with correct mutation of subnodes */ - PlaceHolderVar *phv; + PlaceHolderVar *phv = (PlaceHolderVar *) node; + + /* + * A PHV of an upper query level can't contain join aliases of the + * target level, and its expression may have been preprocessed by that + * level already, so leave it alone. + */ + if (phv->phlevelsup > context->sublevels_up) + return node; /* no need to copy, really */ phv = (PlaceHolderVar *) expression_tree_mutator(node, flatten_join_alias_vars_mutator, diff --git a/src/include/optimizer/planner.h b/src/include/optimizer/planner.h index 9c4950b340f..d181c2f143c 100644 --- a/src/include/optimizer/planner.h +++ b/src/include/optimizer/planner.h @@ -77,7 +77,6 @@ extern void mark_partial_aggref(Aggref *agg, AggSplit aggsplit); extern Path *get_cheapest_fractional_path(RelOptInfo *rel, double tuple_fraction); -extern Expr *preprocess_phv_expression(PlannerInfo *root, Expr *expr); extern RelOptInfo *create_unique_paths(PlannerInfo *root, RelOptInfo *rel, SpecialJoinInfo *sjinfo); diff --git a/src/test/regress/expected/join.out b/src/test/regress/expected/join.out index db4fcc5a5a0..35898293b4c 100644 --- a/src/test/regress/expected/join.out +++ b/src/test/regress/expected/join.out @@ -7043,6 +7043,106 @@ on lhs.id = rhs.id; -> Result (5 rows) +-- check handling of a removed Var that's pushed down into a subquery +-- (fallout from the fix for bug #19560) +explain (verbose, costs off) +select c1, c2 +from (select case when false then remov.id end as c1 + from int4_tbl i41 left join a remov on i41.f1 = remov.id) ss1 + right join int4_tbl i42 on false, + lateral (select ss1.c1 as c2 from int4_tbl i43 offset 0) ss2; + QUERY PLAN +---------------------------------------------- + Nested Loop + Output: (NULL::integer), ((NULL::integer)) + -> Nested Loop Left Join + Output: (NULL::integer) + Join Filter: false + -> Seq Scan on public.int4_tbl i42 + Output: i42.f1 + -> Result + Output: NULL::integer + Replaces: Scan on i41 + One-Time Filter: false + -> Memoize + Output: ((NULL::integer)) + Cache Key: (NULL::integer) + Cache Mode: binary + -> Seq Scan on public.int4_tbl i43 + Output: (NULL::integer) +(17 rows) + +-- likewise, where the subquery is a UNION ALL whose arms are appendrel +-- children that are not simple enough to be pulled up +explain (verbose, costs off) +select c1, c2 +from (select case when false then remov.id end as c1 + from int4_tbl i41 left join a remov on i41.f1 = remov.id) ss1 + right join int4_tbl i42 on false, + lateral ((select ss1.c1 as c2 from int4_tbl i43 offset 0) + union all + (select ss1.c1 from int4_tbl i44 offset 0)) ss2; + QUERY PLAN +--------------------------------------------------- + Nested Loop + Output: (NULL::integer), ((NULL::integer)) + -> Nested Loop Left Join + Output: (NULL::integer) + Join Filter: false + -> Seq Scan on public.int4_tbl i42 + Output: i42.f1 + -> Result + Output: NULL::integer + Replaces: Scan on i41 + One-Time Filter: false + -> Memoize + Output: ((NULL::integer)) + Cache Key: (NULL::integer) + Cache Mode: binary + -> Append + -> Seq Scan on public.int4_tbl i43 + Output: (NULL::integer) + -> Seq Scan on public.int4_tbl i44 + Output: (NULL::integer) +(20 rows) + +-- likewise, where the PHV contains a SubPlan and the subquery has a join, so +-- that its planner runs flatten_join_alias_vars over the outer-level PHV +explain (verbose, costs off) +select c1, c2 +from (select case when false then remov.id else (select i41.f1) end as c1 + from int4_tbl i41 left join a remov on i41.f1 = remov.id) ss1 + right join int4_tbl i42 on false, + lateral (select ss1.c1 as c2 from int4_tbl i43 join int4_tbl i44 on true + offset 0) ss2; + QUERY PLAN +--------------------------------------------------------- + Nested Loop + Output: ((SubPlan expr_1)), (((SubPlan expr_1))) + -> Nested Loop Left Join + Output: ((SubPlan expr_1)) + Join Filter: false + -> Seq Scan on public.int4_tbl i42 + Output: i42.f1 + -> Result + Output: (SubPlan expr_1) + Replaces: Scan on i41 + One-Time Filter: false + SubPlan expr_1 + -> Result + Output: i41.f1 + -> Memoize + Output: (((SubPlan expr_1))) + Cache Key: ((SubPlan expr_1)) + Cache Mode: binary + -> Nested Loop + Output: ((SubPlan expr_1)) + -> Seq Scan on public.int4_tbl i43 + Output: i43.f1 + -> Materialize + -> Seq Scan on public.int4_tbl i44 +(24 rows) + -- More tests of correct placement of pseudoconstant quals -- simple constant-false condition explain (costs off) diff --git a/src/test/regress/sql/join.sql b/src/test/regress/sql/join.sql index 9533af8656e..dc17b7d1d49 100644 --- a/src/test/regress/sql/join.sql +++ b/src/test/regress/sql/join.sql @@ -2581,6 +2581,36 @@ full join ) as rhs on lhs.id = rhs.id; +-- check handling of a removed Var that's pushed down into a subquery +-- (fallout from the fix for bug #19560) +explain (verbose, costs off) +select c1, c2 +from (select case when false then remov.id end as c1 + from int4_tbl i41 left join a remov on i41.f1 = remov.id) ss1 + right join int4_tbl i42 on false, + lateral (select ss1.c1 as c2 from int4_tbl i43 offset 0) ss2; + +-- likewise, where the subquery is a UNION ALL whose arms are appendrel +-- children that are not simple enough to be pulled up +explain (verbose, costs off) +select c1, c2 +from (select case when false then remov.id end as c1 + from int4_tbl i41 left join a remov on i41.f1 = remov.id) ss1 + right join int4_tbl i42 on false, + lateral ((select ss1.c1 as c2 from int4_tbl i43 offset 0) + union all + (select ss1.c1 from int4_tbl i44 offset 0)) ss2; + +-- likewise, where the PHV contains a SubPlan and the subquery has a join, so +-- that its planner runs flatten_join_alias_vars over the outer-level PHV +explain (verbose, costs off) +select c1, c2 +from (select case when false then remov.id else (select i41.f1) end as c1 + from int4_tbl i41 left join a remov on i41.f1 = remov.id) ss1 + right join int4_tbl i42 on false, + lateral (select ss1.c1 as c2 from int4_tbl i43 join int4_tbl i44 on true + offset 0) ss2; + -- More tests of correct placement of pseudoconstant quals -- simple constant-false condition -- 2.37.1 (Apple Git-137.1)
^ permalink raw reply [nested|flat] 74+ messages in thread

* Re: remove_useless_joins vs. bug #19560
  2026-07-20 18:52 remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-24 13:38 ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-07-25 16:46   ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-25 20:07     ` Re: remove_useless_joins vs. bug #19560 Thom Brown <thom@linux.com>
  2026-07-25 21:23       ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-26 02:15         ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-26 09:49           ` Re: remove_useless_joins vs. bug #19560 Thom Brown <thom@linux.com>
  2026-07-26 17:33             ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-26 17:35               ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-27 07:07                 ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-07-27 16:33                   ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-27 18:21                     ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-29 06:21                       ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-16 23:58                         ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-26 05:26                           ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-26 17:25                             ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-27 01:57                               ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-27 15:53                                 ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-28 07:29                                   ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-28 13:43                                     ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-29 03:27                                       ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-29 20:10                                         ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-30 06:50                                           ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
@ 2026-08-30 15:33                                             ` Tom Lane <tgl@sss.pgh.pa.us>
  1 sibling, 0 replies; 74+ messages in thread

From: Tom Lane @ 2026-08-30 15:33 UTC (permalink / raw)
  To: Richard Guo <guofenglinux@gmail.com>; +Cc: Tender Wang <tndrwang@gmail.com>; Thom Brown <thom@linux.com>; Jacob Brazeal <jacob.brazeal@gmail.com>; pgsql-hackers@lists.postgresql.org

Richard Guo <guofenglinux@gmail.com> writes:
> I looked at the patch.  I noticed a couple of problems with putting
> the preprocessed expression back into the subquery.

Thanks for spotting these issues.

> One is that preprocess_expression is not something we can run twice on
> the same expression.

Hmm, is that really true?  I'm moderately certain that there are
existing code paths where that can happen.  I see your point about
hitting !IsA(node, SubPlan) assertions, but I wonder if that's
connected to the unpleasantly incestuous relationship between
SS_process_sublinks and SS_replace_correlation_vars.  That line of
thinking probably leads to the same endpoint though, namely that
we want to do this somewhere else.

I'll study this some more and look for additional holes in it.

> One consequence is that a not-yet-planned subquery can now contain
> SubPlans, within a PHV of an upper query level.  (This applies to your
> patch as well.)  This seems to be new.  AFAICT, an unplanned subquery
> never held SubPlans before.  Fortunately, most of the tree walkers
> that run on the subquery before SS_replace_correlation_vars replaces
> the outer PHV with a Param cope with that.  The exception is
> flatten_join_alias_vars, which descends into every PHV and asserts on
> SubPlans.  I changed it to leave PHVs of upper levels alone; such a
> PHV cannot contain join aliases of the level being flattened anyway.

I wonder if we should try to run SS_replace_correlation_vars earlier.
That's rather a scary change to be contemplating for stable branches
though, precisely because of these hard-to-foresee interactions.

			regards, tom lane





^ permalink  raw  reply  [nested|flat] 74+ messages in thread

* Re: remove_useless_joins vs. bug #19560
  2026-07-20 18:52 remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-24 13:38 ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-07-25 16:46   ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-25 20:07     ` Re: remove_useless_joins vs. bug #19560 Thom Brown <thom@linux.com>
  2026-07-25 21:23       ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-26 02:15         ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-26 09:49           ` Re: remove_useless_joins vs. bug #19560 Thom Brown <thom@linux.com>
  2026-07-26 17:33             ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-26 17:35               ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-27 07:07                 ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-07-27 16:33                   ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-27 18:21                     ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-29 06:21                       ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-16 23:58                         ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-26 05:26                           ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-26 17:25                             ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-27 01:57                               ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-27 15:53                                 ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-28 07:29                                   ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-28 13:43                                     ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-29 03:27                                       ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-29 20:10                                         ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-30 06:50                                           ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
@ 2026-08-30 16:20                                             ` Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-31 01:54                                               ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-31 01:55                                               ` Re: remove_useless_joins vs. bug #19560 Tender Wang <tndrwang@gmail.com>
  1 sibling, 2 replies; 74+ messages in thread

From: Tom Lane @ 2026-08-30 16:20 UTC (permalink / raw)
  To: Richard Guo <guofenglinux@gmail.com>; +Cc: Tender Wang <tndrwang@gmail.com>; Thom Brown <thom@linux.com>; Jacob Brazeal <jacob.brazeal@gmail.com>; pgsql-hackers@lists.postgresql.org

Richard Guo <guofenglinux@gmail.com> writes:
> ... The exception is
> flatten_join_alias_vars, which descends into every PHV and asserts on
> SubPlans.  I changed it to leave PHVs of upper levels alone; such a
> PHV cannot contain join aliases of the level being flattened anyway.

BTW, this comment reminds me strongly of an earlier draft I had,
which eliminated the assertion failure by just not letting
ChangeVarNodes recurse into outer-level PHVs, on the grounds that
we can ignore their contents until they get replaced by Params.
That didn't seem terribly principled on its own, so I also made
eval_const_expressions not do anything to outer-level PHVs, but
then I started to wonder just how far the implications should extend.
When I realized that a localized fix in extract_lateral_references()
seemed possible I gave up on that approach.  But maybe it's the way
to go.  It has the attractive property of removing useless work.
Attached is as far as I got with the idea before switching to the
other way.

			regards, tom lane

Attachments:

skip-outer-level-PHVs.patch (text/x-diff, 5.2K) download diff --git a/src/backend/optimizer/util/clauses.c b/src/backend/optimizer/util/clauses.c index 8da4ed617b5..2e7e3ccf45b 100644 --- a/src/backend/optimizer/util/clauses.c +++ b/src/backend/optimizer/util/clauses.c @@ -1703,23 +1703,30 @@ find_nonnullable_rels_walker(Node *node, bool top_level) PlaceHolderVar *phv = (PlaceHolderVar *) node; /* - * If the contained expression forces any rels non-nullable, so does - * the PHV. + * We can ignore outer-level PHVs: they cannot contain any Vars of the + * current level, so they can't force anything non-nullable. */ - result = find_nonnullable_rels_walker((Node *) phv->phexpr, top_level); + if (phv->phlevelsup == 0) + { + /* + * If the contained expression forces any rels non-nullable, so + * does the PHV. + */ + result = find_nonnullable_rels_walker((Node *) phv->phexpr, + top_level); - /* - * If the PHV's syntactic scope is exactly one rel, it will be forced - * to be evaluated at that rel, and so it will behave like a Var of - * that rel: if the rel's entire output goes to null, so will the PHV. - * (If the syntactic scope is a join, we know that the PHV will go to - * null if the whole join does; but that is AND semantics while we - * need OR semantics for find_nonnullable_rels' result, so we can't do - * anything with the knowledge.) - */ - if (phv->phlevelsup == 0 && - bms_membership(phv->phrels) == BMS_SINGLETON) - result = bms_add_members(result, phv->phrels); + /* + * If the PHV's syntactic scope is exactly one rel, it will be + * forced to be evaluated at that rel, and so it will behave like + * a Var of that rel: if the rel's entire output goes to null, so + * will the PHV. (If the syntactic scope is a join, we know that + * the PHV will go to null if the whole join does; but that is AND + * semantics while we need OR semantics for find_nonnullable_rels' + * result, so we can't do anything with the knowledge.) + */ + if (bms_membership(phv->phrels) == BMS_SINGLETON) + result = bms_add_members(result, phv->phrels); + } } return result; } @@ -1954,7 +1961,13 @@ find_nonnullable_vars_walker(Node *node, bool top_level) { PlaceHolderVar *phv = (PlaceHolderVar *) node; - result = find_nonnullable_vars_walker((Node *) phv->phexpr, top_level); + /* + * We can ignore outer-level PHVs: they cannot contain any Vars of the + * current level, so they can't force anything non-nullable. + */ + if (phv->phlevelsup == 0) + result = find_nonnullable_vars_walker((Node *) phv->phexpr, + top_level); } return result; } @@ -4150,20 +4163,31 @@ eval_const_expressions_mutator(Node *node, return (Node *) newcdomain; } case T_PlaceHolderVar: - - /* - * In estimation mode, just strip the PlaceHolderVar node - * altogether; this amounts to estimating that the contained value - * won't be forced to null by an outer join. In regular mode we - * just use the default behavior (ie, simplify the expression but - * leave the PlaceHolderVar node intact). - */ - if (context->estimate) { PlaceHolderVar *phv = (PlaceHolderVar *) node; - return eval_const_expressions_mutator((Node *) phv->phexpr, - context); + /* + * If it's an outer-level PHV, we should return it unmodified. + * Descending into the contents is risky because there may be + * since-deleted Vars there. In any case the current query + * level is not going to do anything with the PHV except + * replace it with a Param (cf. SS_replace_correlation_vars), + * so the effort would be wasted. But we do copy the subtree, + * just to conform to this function's API spec. + */ + if (phv->phlevelsup > 0) + return copyObject(node); + + /* + * In estimation mode, just strip the PlaceHolderVar node + * altogether; this amounts to estimating that the contained + * value won't be forced to null by an outer join. In regular + * mode we just use the default behavior (ie, simplify the + * expression but leave the PlaceHolderVar node intact). + */ + if (context->estimate) + return eval_const_expressions_mutator((Node *) phv->phexpr, + context); } break; case T_ConvertRowtypeExpr: diff --git a/src/backend/rewrite/rewriteManip.c b/src/backend/rewrite/rewriteManip.c index 3653f00d383..90a8db11e92 100644 --- a/src/backend/rewrite/rewriteManip.c +++ b/src/backend/rewrite/rewriteManip.c @@ -627,7 +627,18 @@ ChangeVarNodes_walker(Node *node, ChangeVarNodes_context *context) context->rt_index, context->new_index); } - /* fall through to examine children */ + + /* + * If it's an outer-level PHV, do not recurse into its contents. Such + * a PHV must have been pushed into this query level without + * expression preprocessing, so it may contain Vars that we think are + * due to be deleted, triggering our INVALID_VAR assertions. There is + * no need to modify such a PHV anyway, since it will be replaced by a + * Param before anything very interesting happens. + */ + if (phv->phlevelsup > 0) + return node; + /* else fall through to examine children */ } if (IsA(node, PlanRowMark)) {
^ permalink raw reply [nested|flat] 74+ messages in thread

* Re: remove_useless_joins vs. bug #19560
  2026-07-20 18:52 remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-24 13:38 ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-07-25 16:46   ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-25 20:07     ` Re: remove_useless_joins vs. bug #19560 Thom Brown <thom@linux.com>
  2026-07-25 21:23       ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-26 02:15         ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-26 09:49           ` Re: remove_useless_joins vs. bug #19560 Thom Brown <thom@linux.com>
  2026-07-26 17:33             ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-26 17:35               ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-27 07:07                 ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-07-27 16:33                   ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-27 18:21                     ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-29 06:21                       ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-16 23:58                         ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-26 05:26                           ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-26 17:25                             ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-27 01:57                               ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-27 15:53                                 ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-28 07:29                                   ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-28 13:43                                     ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-29 03:27                                       ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-29 20:10                                         ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-30 06:50                                           ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-30 16:20                                             ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
@ 2026-08-31 01:54                                               ` Richard Guo <guofenglinux@gmail.com>
  2026-09-03 14:55                                                 ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  1 sibling, 1 reply; 74+ messages in thread

From: Richard Guo @ 2026-08-31 01:54 UTC (permalink / raw)
  To: Tom Lane <tgl@sss.pgh.pa.us>; +Cc: Tender Wang <tndrwang@gmail.com>; Thom Brown <thom@linux.com>; Jacob Brazeal <jacob.brazeal@gmail.com>; pgsql-hackers@lists.postgresql.org

On Mon, Aug 31, 2026 at 1:20 AM Tom Lane <tgl@sss.pgh.pa.us> wrote:
> BTW, this comment reminds me strongly of an earlier draft I had,
> which eliminated the assertion failure by just not letting
> ChangeVarNodes recurse into outer-level PHVs, on the grounds that
> we can ignore their contents until they get replaced by Params.

+  /*
+   * If it's an outer-level PHV, do not recurse into its contents. Such
+   * a PHV must have been pushed into this query level without
+   * expression preprocessing, so it may contain Vars that we think are
+   * due to be deleted, triggering our INVALID_VAR assertions.  There is
+   * no need to modify such a PHV anyway, since it will be replaced by a
+   * Param before anything very interesting happens.
+   */
+  if (phv->phlevelsup > 0)
+      return node;

(Typo: I assume you meant to return false here.)

I'm kind of nervous about this change.  AFAIU, the premise that an
outer-level PHV "will be replaced by a Param before anything very
interesting happens" only holds within the subquery: there the PHV
node is replaced by a Param during expression preprocessing, before
the subquery's plan is built.  But copies of its content can escape
back to the PHV's own query level before that replacement, and AFAICS
we do quite a few things with them at that level.  I think
extract_lateral_references is an example of that.

I'm also not sure about skipping outer-level PHVs in
eval_const_expressions.  I'm worried that that can cause us to carry
the raw expressions in the outer query somewhere.

- Richard





^ permalink  raw  reply  [nested|flat] 74+ messages in thread

* Re: remove_useless_joins vs. bug #19560
  2026-07-20 18:52 remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-24 13:38 ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-07-25 16:46   ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-25 20:07     ` Re: remove_useless_joins vs. bug #19560 Thom Brown <thom@linux.com>
  2026-07-25 21:23       ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-26 02:15         ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-26 09:49           ` Re: remove_useless_joins vs. bug #19560 Thom Brown <thom@linux.com>
  2026-07-26 17:33             ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-26 17:35               ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-27 07:07                 ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-07-27 16:33                   ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-27 18:21                     ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-29 06:21                       ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-16 23:58                         ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-26 05:26                           ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-26 17:25                             ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-27 01:57                               ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-27 15:53                                 ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-28 07:29                                   ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-28 13:43                                     ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-29 03:27                                       ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-29 20:10                                         ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-30 06:50                                           ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-30 16:20                                             ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-31 01:54                                               ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
@ 2026-09-03 14:55                                                 ` Tom Lane <tgl@sss.pgh.pa.us>
  2026-09-09 08:04                                                   ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  0 siblings, 1 reply; 74+ messages in thread

From: Tom Lane @ 2026-09-03 14:55 UTC (permalink / raw)
  To: Richard Guo <guofenglinux@gmail.com>; +Cc: Tender Wang <tndrwang@gmail.com>; Thom Brown <thom@linux.com>; Jacob Brazeal <jacob.brazeal@gmail.com>; pgsql-hackers@lists.postgresql.org

[ after a good deal of navel-gazing... ]

Richard Guo <guofenglinux@gmail.com> writes:
> I'm also not sure about skipping outer-level PHVs in
> eval_const_expressions.  I'm worried that that can cause us to carry
> the raw expressions in the outer query somewhere.

It still feels to me that that's the right thing to do.  With your
v2 patch, subquery_planner will have taken care of preprocessing
any outer-level PHVs before the subquery's own preprocessing starts.
If we do that over again, the best-case result is that we waste
cycles.  The worst-case result is that we end up with an expression
that looks different from what it looks like in the outer level
and then that causes problems.  (I don't have any specific ideas
in mind about how the doubly-processed expression could come to be
different.  But if we accept your point that "it's unsafe to do
preprocessing twice", it seems like this is fertile ground for
trouble.)

I think that your v2 patch is fundamentally the right way forward,
but I'm worried that it's not complete yet.  In particular it
seems very strange that only flatten_join_alias_vars_mutator needs
to worry about skipping outer-level PHVs.  I already explained why
I think eval_const_expressions should too, and I wonder if there
are not other places that should as well.  Fundamentally it seems
like the policy across the board ought to be that subqueries keep
their hands off upper-level PHVs.  Now, once we've applied
SS_replace_correlation_vars, the question is moot because all such
PHVs will have been replaced by Params, but anything that runs
before that needs a close look.

			regards, tom lane






^ permalink  raw  reply  [nested|flat] 74+ messages in thread

* Re: remove_useless_joins vs. bug #19560
  2026-07-20 18:52 remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-24 13:38 ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-07-25 16:46   ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-25 20:07     ` Re: remove_useless_joins vs. bug #19560 Thom Brown <thom@linux.com>
  2026-07-25 21:23       ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-26 02:15         ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-26 09:49           ` Re: remove_useless_joins vs. bug #19560 Thom Brown <thom@linux.com>
  2026-07-26 17:33             ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-26 17:35               ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-27 07:07                 ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-07-27 16:33                   ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-27 18:21                     ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-29 06:21                       ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-16 23:58                         ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-26 05:26                           ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-26 17:25                             ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-27 01:57                               ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-27 15:53                                 ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-28 07:29                                   ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-28 13:43                                     ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-29 03:27                                       ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-29 20:10                                         ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-30 06:50                                           ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-30 16:20                                             ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-31 01:54                                               ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-09-03 14:55                                                 ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
@ 2026-09-09 08:04                                                   ` Richard Guo <guofenglinux@gmail.com>
  2026-09-09 14:54                                                     ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  0 siblings, 1 reply; 74+ messages in thread

From: Richard Guo @ 2026-09-09 08:04 UTC (permalink / raw)
  To: Tom Lane <tgl@sss.pgh.pa.us>; +Cc: Tender Wang <tndrwang@gmail.com>; Thom Brown <thom@linux.com>; Jacob Brazeal <jacob.brazeal@gmail.com>; pgsql-hackers@lists.postgresql.org

On Thu, Sep 3, 2026 at 11:55 PM Tom Lane <tgl@sss.pgh.pa.us> wrote:
> It still feels to me that that's the right thing to do.  With your
> v2 patch, subquery_planner will have taken care of preprocessing
> any outer-level PHVs before the subquery's own preprocessing starts.

Hmm, not for all of them.  My v2 patch only preprocesses the
outer-level PHVs that were pushed into LATERAL subquery RTEs, since
that is where find_lateral_references pulls them from.  It does not
touch PHVs that were pushed into a SubLink's subselect, and for those
the subquery's own preprocessing is still the only thing that folds
them.

For example:

create table t (id int primary key);

select (select ss1.c1 from int4_tbl i43 offset 0)
from (select case when false then remov.id end as c1
      from int4_tbl i41 left join t remov on i41.f1 = remov.id) ss1
     right join int4_tbl i42 on true;

The subselect references ss1.c1, whose value is a PHV wrapping "case
when false then remov.id end".  At the outer level that CaseExpr lives
only inside the subselect, and eval_const_expressions does not descend
into a sub-Query, so the outer level never folds it.  It gets folded
only when the subselect is planned and its own eval_const_expressions
recurses into the upper-level PHV.

If eval_const_expressions skips outer-level PHVs, that fold no longer
happens, and the raw CaseExpr ends up in the SubPlan's args.  For this
query the consequence is that remov.id stays referenced, and the
i41/remov join fails to be removed.

> If we do that over again, the best-case result is that we waste
> cycles.  The worst-case result is that we end up with an expression
> that looks different from what it looks like in the outer level
> and then that causes problems.  (I don't have any specific ideas
> in mind about how the doubly-processed expression could come to be
> different.  But if we accept your point that "it's unsafe to do
> preprocessing twice", it seems like this is fertile ground for
> trouble.)

I think I didn't state my earlier point clearly, sorry about that.
What I meant is that preprocess_expression as a whole is not safe to
run twice, because its SS_process_sublinks step would hit
Assert(!IsA(node, SubPlan)) on the SubPlans that the first run
created.  eval_const_expressions by itself does seem safe to run
twice, and I'm pretty certain that there are existing code paths where
that can happen, for example preprocess_expression deliberately
re-runs it for EXPRKIND_RTFUNC_LATERAL.

I'm not too worried about the wasted cycles.  ISTM a walk over an
already-simplified expression is cheap.  Your worst-case concern is
fair, but I don't think a second eval_const_expressions pass can
produce a different-looking expression in a way that would cause
problems, otherwise we should already see related bug reports from the
places that already run it twice.

> I think that your v2 patch is fundamentally the right way forward,
> but I'm worried that it's not complete yet.  In particular it
> seems very strange that only flatten_join_alias_vars_mutator needs
> to worry about skipping outer-level PHVs.  I already explained why
> I think eval_const_expressions should too, and I wonder if there
> are not other places that should as well.  Fundamentally it seems
> like the policy across the board ought to be that subqueries keep
> their hands off upper-level PHVs.  Now, once we've applied
> SS_replace_correlation_vars, the question is moot because all such
> PHVs will have been replaced by Params, but anything that runs
> before that needs a close look.

I went through the steps that run before SS_replace_correlation_vars.
They are the earlier steps of preprocess_expression:

1. flatten_join_alias_vars: descends and level-dependent, so it must
skip outer-level PHVs.

2. eval_const_expressions: level-independent, so it's safe on an
outer-level PHV, and as shown above it needs to run on them.

3. canonicalize_qual: only restructures AND/OR/NOT; a PHV is an
opaque leaf to it, so it never descends into the phexpr.

4. convert_saop_to_hashed_saop: descends, but only sets hashfuncid on
ScalarArrayOpExprs.  That's level-independent and idempotent.

5. SS_process_sublinks: already skips outer-level PHVs.

So flatten_join_alias_vars isn't alone.  SS_process_sublinks already
skips.

- Richard






^ permalink  raw  reply  [nested|flat] 74+ messages in thread

* Re: remove_useless_joins vs. bug #19560
  2026-07-20 18:52 remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-24 13:38 ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-07-25 16:46   ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-25 20:07     ` Re: remove_useless_joins vs. bug #19560 Thom Brown <thom@linux.com>
  2026-07-25 21:23       ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-26 02:15         ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-26 09:49           ` Re: remove_useless_joins vs. bug #19560 Thom Brown <thom@linux.com>
  2026-07-26 17:33             ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-26 17:35               ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-27 07:07                 ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-07-27 16:33                   ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-27 18:21                     ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-29 06:21                       ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-16 23:58                         ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-26 05:26                           ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-26 17:25                             ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-27 01:57                               ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-27 15:53                                 ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-28 07:29                                   ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-28 13:43                                     ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-29 03:27                                       ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-29 20:10                                         ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-30 06:50                                           ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-30 16:20                                             ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-31 01:54                                               ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-09-03 14:55                                                 ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-09-09 08:04                                                   ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
@ 2026-09-09 14:54                                                     ` Tom Lane <tgl@sss.pgh.pa.us>
  2026-09-10 09:33                                                       ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  0 siblings, 1 reply; 74+ messages in thread

From: Tom Lane @ 2026-09-09 14:54 UTC (permalink / raw)
  To: Richard Guo <guofenglinux@gmail.com>; +Cc: Tender Wang <tndrwang@gmail.com>; Thom Brown <thom@linux.com>; Jacob Brazeal <jacob.brazeal@gmail.com>; pgsql-hackers@lists.postgresql.org

Richard Guo <guofenglinux@gmail.com> writes:
> On Thu, Sep 3, 2026 at 11:55 PM Tom Lane <tgl@sss.pgh.pa.us> wrote:
>> It still feels to me that that's the right thing to do.  With your
>> v2 patch, subquery_planner will have taken care of preprocessing
>> any outer-level PHVs before the subquery's own preprocessing starts.

> Hmm, not for all of them.  My v2 patch only preprocesses the
> outer-level PHVs that were pushed into LATERAL subquery RTEs, since
> that is where find_lateral_references pulls them from.  It does not
> touch PHVs that were pushed into a SubLink's subselect, and for those
> the subquery's own preprocessing is still the only thing that folds
> them.

Ugh.  That sounds like a recipe for bugs; I don't think we want
different PHVs in the same query level to be folded at different
times if we can help it.

> I think I didn't state my earlier point clearly, sorry about that.
> What I meant is that preprocess_expression as a whole is not safe to
> run twice, because its SS_process_sublinks step would hit
> Assert(!IsA(node, SubPlan)) on the SubPlans that the first run
> created.

Right.  We could of course drop that Assert in favor of ignoring
SubPlans there.  But the interaction between SS_process_sublinks and
SS_replace_correlation_vars is delicate enough that I doubt we want to
risk running that sequence twice.

> eval_const_expressions by itself does seem safe to run
> twice, and I'm pretty certain that there are existing code paths where
> that can happen, for example preprocess_expression deliberately
> re-runs it for EXPRKIND_RTFUNC_LATERAL.

The hole in this logic is the assumption that eval_const_expressions
will act the same with Vars of upper query levels as with Vars of the
current query level.  That's visibly not so at present --- see for
example const-simplification of NullTest nodes on known-not-null Vars.
var_is_nonnullable just throws up its hands if var->varlevelsup != 0.
(Arguably that's a bug, or at least an oversight: couldn't it crawl
up the PlannerInfo tree to the appropriate level?  But my point is
that we shouldn't assume that this will always work perfectly.)

> I'm not too worried about the wasted cycles.  ISTM a walk over an
> already-simplified expression is cheap.

It's not *that* cheap; we will for example be repeating operator
volatility lookups, not to mention copying the tree.  But I agree
that this concern is much weaker than correctness.

>> I think that your v2 patch is fundamentally the right way forward,
>> but I'm worried that it's not complete yet.  In particular it
>> seems very strange that only flatten_join_alias_vars_mutator needs
>> to worry about skipping outer-level PHVs.

> I went through the steps that run before SS_replace_correlation_vars.

Thanks for doing that analysis.  I remain concerned though about
inconsistent processing of PHV contents.  I think the sketch I'd
rather see is that we simply ignore the contents of any uplevel
PHV during subquery processing, relying on the singly-preprocessed
version sitting in the owning query level's PlaceHolderInfo when
it comes time to do something interesting with it.

			regards, tom lane






^ permalink  raw  reply  [nested|flat] 74+ messages in thread

* Re: remove_useless_joins vs. bug #19560
  2026-07-20 18:52 remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-24 13:38 ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-07-25 16:46   ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-25 20:07     ` Re: remove_useless_joins vs. bug #19560 Thom Brown <thom@linux.com>
  2026-07-25 21:23       ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-26 02:15         ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-26 09:49           ` Re: remove_useless_joins vs. bug #19560 Thom Brown <thom@linux.com>
  2026-07-26 17:33             ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-26 17:35               ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-27 07:07                 ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-07-27 16:33                   ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-27 18:21                     ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-29 06:21                       ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-16 23:58                         ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-26 05:26                           ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-26 17:25                             ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-27 01:57                               ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-27 15:53                                 ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-28 07:29                                   ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-28 13:43                                     ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-29 03:27                                       ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-29 20:10                                         ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-30 06:50                                           ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-30 16:20                                             ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-31 01:54                                               ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-09-03 14:55                                                 ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-09-09 08:04                                                   ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-09-09 14:54                                                     ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
@ 2026-09-10 09:33                                                       ` Richard Guo <guofenglinux@gmail.com>
  2026-09-13 17:32                                                         ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  0 siblings, 1 reply; 74+ messages in thread

From: Richard Guo @ 2026-09-10 09:33 UTC (permalink / raw)
  To: Tom Lane <tgl@sss.pgh.pa.us>; +Cc: Tender Wang <tndrwang@gmail.com>; Thom Brown <thom@linux.com>; Jacob Brazeal <jacob.brazeal@gmail.com>; pgsql-hackers@lists.postgresql.org

On Wed, Sep 9, 2026 at 11:54 PM Tom Lane <tgl@sss.pgh.pa.us> wrote:
> The hole in this logic is the assumption that eval_const_expressions
> will act the same with Vars of upper query levels as with Vars of the
> current query level.  That's visibly not so at present --- see for
> example const-simplification of NullTest nodes on known-not-null Vars.
> var_is_nonnullable just throws up its hands if var->varlevelsup != 0.
> (Arguably that's a bug, or at least an oversight: couldn't it crawl
> up the PlannerInfo tree to the appropriate level?  But my point is
> that we shouldn't assume that this will always work perfectly.)

Ah, I see your point.  Right, that makes eval_const_expressions not
that level-independent.  That means my argument for letting the
subquery fold the pushed-down copies of PHVs doesn't hold.

Now I think your suggestion is the right way to go.  We should
preprocess each of the upper-level PHVs once at the level it belongs
to, and then the subquery can leave them alone.

I think a straightforward way to achieve that is that in
subquery_planner, we walk the whole query tree and preprocess all of
the current level's PHVs that got pushed down into subqueries, up
front before anything consumes them.  Then the subquery's own
processing can just ignore upper-level PHVs.  eval_const_expressions
returns them as-is, and flatten_join_alias_vars stops descending into
them.

This still keeps the copies around rather than relying solely on the
PlaceHolderInfo, but since they'd be folded the same way as the
owning-level version, maybe it still gets the consistency we want to
have.

I tried coding with this idea and ended up with the attached v3.

One problem with this is that we walk the whole query tree to find
those copies, which costs some planning cycles.  We could gate it on
root->glob->lastPHId != 0 to skip queries with no PHVs at all, but
beyond that I don't have a good way to narrow it down.

Another thing to note.  The copies' SubLinks would turn into SubPlans
in this early pass, so a few SubPlan/InitPlan numbers shift in the
regression output.  Just renumbering.

- Richard

Attachments:

v3-0001-Fix-stale-copies-of-PHVs-in-subqueries.patch (application/octet-stream, 26.5K) download From 6b5428489be17d6d1e281e9a720769af163d3470 Mon Sep 17 00:00:00 2001 From: Richard Guo <guofenglinux@gmail.com> Date: Sun, 30 Aug 2026 08:21:21 +0900 Subject: [PATCH v3] Fix stale copies of PHVs in subqueries When a subquery references an output of another subquery that gets pulled up, and that output must be wrapped in a PlaceHolderVar because of an intermediate outer join, the PHV expression is pushed down into the subquery. That copy is not preprocessed along with the outer query's expressions, so the two copies can diverge. This used to be harmless, but since commit 2ebf25e7d join removal edits the whole query tree, walking into subqueries, and can trip an assert in ChangeVarNodes if it removes a rel whose Var survives only in such a copy. To fix, preprocess these copies at their owning query level, early in subquery_planner, before anything can consume them (in particular before SubLinks are turned into SubPlans). This covers copies pushed into both LATERAL subquery RTEs and SubLink subselects, and handles nested copies innermost-first. extract_lateral_references no longer preprocesses the copies it pulls out. Correspondingly, the subquery's own processing must leave the contents of an upper-level PHV alone, since the owning level has already preprocessed them: eval_const_expressions returns such a PHV unchanged, and flatten_join_alias_vars no longer recurses into it. --- src/backend/optimizer/plan/initsplan.c | 15 +- src/backend/optimizer/plan/planner.c | 96 +++++++++++-- src/backend/optimizer/plan/subselect.c | 13 +- src/backend/optimizer/util/clauses.c | 35 +++-- src/backend/optimizer/util/paramassign.c | 23 ++- src/backend/optimizer/util/var.c | 28 +++- src/include/optimizer/planner.h | 1 - src/test/regress/expected/groupingsets.out | 4 +- src/test/regress/expected/join.out | 160 ++++++++++++++++++++- src/test/regress/sql/join.sql | 47 ++++++ src/tools/pgindent/typedefs.list | 1 + 11 files changed, 355 insertions(+), 68 deletions(-) diff --git a/src/backend/optimizer/plan/initsplan.c b/src/backend/optimizer/plan/initsplan.c index fb6f81453ea..8893e37c8f7 100644 --- a/src/backend/optimizer/plan/initsplan.c +++ b/src/backend/optimizer/plan/initsplan.c @@ -29,7 +29,6 @@ #include "optimizer/paths.h" #include "optimizer/placeholder.h" #include "optimizer/planmain.h" -#include "optimizer/planner.h" #include "optimizer/restrictinfo.h" #include "parser/analyze.h" #include "rewrite/rewriteManip.h" @@ -1132,17 +1131,13 @@ extract_lateral_references(PlannerInfo *root, RelOptInfo *brel, Index rtindex) PlaceHolderVar *phv = (PlaceHolderVar *) node; int levelsup = phv->phlevelsup; - /* Have to work harder to adjust the contained expression too */ - if (levelsup != 0) - IncrementVarSublevelsUp(node, -levelsup, 0); - /* - * If we pulled the PHV out of a subquery RTE, its expression - * needs to be preprocessed. subquery_planner() already did this - * for level-zero PHVs in function and values RTEs, though. + * Have to work harder to adjust the contained expression too. + * (Its expression has already been preprocessed by + * subquery_planner(), so we must not do that again here.) */ - if (levelsup > 0) - phv->phexpr = preprocess_phv_expression(root, phv->phexpr); + if (levelsup != 0) + IncrementVarSublevelsUp(node, -levelsup, 0); } else Assert(false); diff --git a/src/backend/optimizer/plan/planner.c b/src/backend/optimizer/plan/planner.c index c3c158a253d..8cd2e8a71eb 100644 --- a/src/backend/optimizer/plan/planner.c +++ b/src/backend/optimizer/plan/planner.c @@ -144,8 +144,18 @@ typedef struct Index group_rtindex; } having_grouping_ctx; +/* Context for preprocess_subquery_phvs_walker */ +typedef struct +{ + PlannerInfo *root; + int sublevels_up; +} preprocess_subquery_phvs_context; + /* Local functions */ static Node *preprocess_expression(PlannerInfo *root, Node *expr, int kind); +static void preprocess_subquery_phvs(PlannerInfo *root); +static bool preprocess_subquery_phvs_walker(Node *node, + preprocess_subquery_phvs_context *context); static void preprocess_qual_conditions(PlannerInfo *root, Node *jtnode); static Bitmapset *find_having_conflicts(Query *parse, Index group_rtindex); static Oid having_var_grouping_eqop(Var *var, void *context); @@ -1022,6 +1032,14 @@ subquery_planner(PlannerGlobal *glob, Query *parse, char *plan_name, */ root->hasHavingQual = (parse->havingQual != NULL); + /* + * Preprocess any PlaceHolderVars of our level that were pushed down into + * subqueries. This must happen before anything can consume those copies, + * in particular before SubLinks below are turned into SubPlans. + */ + if (root->glob->lastPHId != 0) + preprocess_subquery_phvs(root); + /* * Do expression preprocessing on targetlist and quals, as well as other * random expressions in the querytree. Note that we do not need to @@ -1645,20 +1663,74 @@ group_var_eqop(Query *parse, Var *var) } /* - * preprocess_phv_expression - * Do preprocessing on a PlaceHolderVar expression that's been pulled up. - * - * If a LATERAL subquery references an output of another subquery, and that - * output must be wrapped in a PlaceHolderVar because of an intermediate outer - * join, then we'll push the PlaceHolderVar expression down into the subquery - * and later pull it back up during find_lateral_references, which runs after - * subquery_planner has preprocessed all the expressions that were in the - * current query level to start with. So we need to preprocess it then. + * preprocess_subquery_phvs + * Preprocess copies of this level's PlaceHolderVars that were pushed + * down into subqueries. + * + * When a subquery (a LATERAL RTE or a SubLink's subselect) references a + * pulled-up output that must be wrapped in a PlaceHolderVar, the PHV + * expression is pushed down into the subquery. The subquery's own planning + * leaves that copy alone, since it belongs to our level, so we need to + * preprocess it. We modify the PHVs in place, temporarily adjusting each to + * our level, and handle nested copies innermost-first. */ -Expr * -preprocess_phv_expression(PlannerInfo *root, Expr *expr) +static void +preprocess_subquery_phvs(PlannerInfo *root) +{ + preprocess_subquery_phvs_context context; + + context.root = root; + context.sublevels_up = 0; + (void) query_tree_walker(root->parse, preprocess_subquery_phvs_walker, + &context, 0); +} + +static bool +preprocess_subquery_phvs_walker(Node *node, + preprocess_subquery_phvs_context *context) { - return (Expr *) preprocess_expression(root, (Node *) expr, EXPRKIND_PHV); + if (node == NULL) + return false; + if (IsA(node, Query)) + { + bool result; + + context->sublevels_up++; + result = query_tree_walker((Query *) node, + preprocess_subquery_phvs_walker, + context, 0); + context->sublevels_up--; + return result; + } + if (IsA(node, PlaceHolderVar)) + { + PlaceHolderVar *phv = (PlaceHolderVar *) node; + + /* Handle any nested copies within the expression first */ + (void) expression_tree_walker(node, preprocess_subquery_phvs_walker, + context); + + /* + * Is this a copy of one of our PHVs that is pushed down into a + * subquery? + */ + if (context->sublevels_up > 0 && + phv->phlevelsup == context->sublevels_up) + { + int levelsup = phv->phlevelsup; + Node *expr; + + /* Adjust the expression to our level, preprocess, adjust back */ + expr = copyObject((Node *) phv->phexpr); + IncrementVarSublevelsUp(expr, -levelsup, 0); + expr = preprocess_expression(context->root, expr, EXPRKIND_PHV); + IncrementVarSublevelsUp(expr, levelsup, 0); + phv->phexpr = (Expr *) expr; + } + return false; + } + return expression_tree_walker(node, preprocess_subquery_phvs_walker, + context); } /*-------------------- diff --git a/src/backend/optimizer/plan/subselect.c b/src/backend/optimizer/plan/subselect.c index 2cf5c15a309..ae7c489b432 100644 --- a/src/backend/optimizer/plan/subselect.c +++ b/src/backend/optimizer/plan/subselect.c @@ -371,13 +371,14 @@ build_subplan(PlannerInfo *root, Plan *plan, Path *path, * already been adjusted to have the correct varlevelsup, phlevelsup, * agglevelsup, or retlevelsup. * - * If it's a PlaceHolderVar, Aggref, GroupingFunc, or ReturningExpr, - * its arguments might contain SubLinks, which have not yet been - * processed (see the comments for SS_replace_correlation_vars). Do - * that now. + * If it's an Aggref, GroupingFunc, or ReturningExpr, its arguments + * might contain SubLinks, which have not yet been processed (see the + * comments for SS_replace_correlation_vars). Do that now. A + * PlaceHolderVar needs no such treatment: subquery_planner already + * preprocessed the PHVs of its owning level, so its expression is + * fully processed and may already contain SubPlans. */ - if (IsA(arg, PlaceHolderVar) || - IsA(arg, Aggref) || + if (IsA(arg, Aggref) || IsA(arg, GroupingFunc) || IsA(arg, ReturningExpr)) arg = SS_process_sublinks(root, arg, false); diff --git a/src/backend/optimizer/util/clauses.c b/src/backend/optimizer/util/clauses.c index 55cebe4a74b..a83b8bdd0ac 100644 --- a/src/backend/optimizer/util/clauses.c +++ b/src/backend/optimizer/util/clauses.c @@ -3407,9 +3407,8 @@ eval_const_expressions_mutator(Node *node, /* * Return a SubPlan unchanged --- too late to do anything with it. - * - * XXX should we ereport() here instead? Probably this routine - * should never be invoked after SubPlan creation. + * This can happen in estimation mode, which runs after SubPlans + * have been created. */ return node; case T_RelabelType: @@ -4215,20 +4214,28 @@ eval_const_expressions_mutator(Node *node, return (Node *) newcdomain; } case T_PlaceHolderVar: - - /* - * In estimation mode, just strip the PlaceHolderVar node - * altogether; this amounts to estimating that the contained value - * won't be forced to null by an outer join. In regular mode we - * just use the default behavior (ie, simplify the expression but - * leave the PlaceHolderVar node intact). - */ - if (context->estimate) { PlaceHolderVar *phv = (PlaceHolderVar *) node; - return eval_const_expressions_mutator((Node *) phv->phexpr, - context); + /* + * Leave a PHV of an upper query level alone: its expression + * belongs to that level, which has already preprocessed it. + * But we do copy the subtree, just to conform to this + * function's API spec. + */ + if (phv->phlevelsup > 0) + return copyObject(node); + + /* + * In estimation mode, just strip the PlaceHolderVar node + * altogether; this amounts to estimating that the contained + * value won't be forced to null by an outer join. In regular + * mode we just use the default behavior (ie, simplify the + * expression but leave the PlaceHolderVar node intact). + */ + if (context->estimate) + return eval_const_expressions_mutator((Node *) phv->phexpr, + context); } break; case T_ConvertRowtypeExpr: diff --git a/src/backend/optimizer/util/paramassign.c b/src/backend/optimizer/util/paramassign.c index 222de1450b2..6a1be4551bd 100644 --- a/src/backend/optimizer/util/paramassign.c +++ b/src/backend/optimizer/util/paramassign.c @@ -677,19 +677,18 @@ identify_current_nestloop_params(PlannerInfo *root, /* * Deal with an edge case: if the PHV was pulled up out of a * subquery and it contains a subquery that was originally - * pushed down from this query level, then that will still be - * represented as a SubLink, because SS_process_sublinks won't - * recurse into outer PHVs, so it didn't get transformed - * during expression preprocessing in the subquery. We need a - * version of the PHV that has a SubPlan, which we can get - * from the current query level's placeholder_list. This is - * quite grotty of course, but dealing with it earlier in the - * handling of subplan params would be just as grotty, and it - * might end up being a waste of cycles if we don't decide to - * treat the PHV as a NestLoopParam. (Perhaps that whole - * mechanism should be redesigned someday, but today is not - * that day.) + * pushed down from this query level, then the copy of the PHV + * we got from the subquery has its own SubPlan for that, + * distinct from the one in the current query level's + * placeholder_list. We'd rather use the placeholder_list's + * version of the PHV, so that we don't end up evaluating + * duplicate SubPlans. + * + * Note that the subquery's copy cannot contain any SubLinks: + * subquery_planner preprocessed the PHVs of this query level + * within the subquery before the subquery was planned. */ + Assert(!checkExprHasSubLink((Node *) phv)); if (root->parse->hasSubLinks) { phv = copyObject(phinfo->ph_var); diff --git a/src/backend/optimizer/util/var.c b/src/backend/optimizer/util/var.c index 907a255c36f..c061bb5c4ab 100644 --- a/src/backend/optimizer/util/var.c +++ b/src/backend/optimizer/util/var.c @@ -932,12 +932,30 @@ flatten_join_alias_vars_mutator(Node *node, } if (IsA(node, PlaceHolderVar)) { - /* Copy the PlaceHolderVar node with correct mutation of subnodes */ - PlaceHolderVar *phv; + PlaceHolderVar *phv = (PlaceHolderVar *) node; + + /* + * Don't recurse into a PHV of an outer query level: its expression is + * already preprocessed by that level and may contain SubPlans, and it + * holds no join aliases of the target level anyway. A PHV above the + * target level needs nothing fixed, so return it as-is; a pushed-down + * copy still needs its relid sets fixed below, so shallow-copy it + * instead of recursing. + */ + if (phv->phlevelsup > context->sublevels_up) + return node; /* no need to copy, really */ - phv = (PlaceHolderVar *) expression_tree_mutator(node, - flatten_join_alias_vars_mutator, - context); + if (phv->phlevelsup > 0) + { + PlaceHolderVar *newphv = makeNode(PlaceHolderVar); + + memcpy(newphv, phv, sizeof(PlaceHolderVar)); + phv = newphv; + } + else + phv = (PlaceHolderVar *) expression_tree_mutator(node, + flatten_join_alias_vars_mutator, + context); /* now fix PlaceHolderVar's relid sets */ if (phv->phlevelsup == context->sublevels_up) { diff --git a/src/include/optimizer/planner.h b/src/include/optimizer/planner.h index 9c4950b340f..d181c2f143c 100644 --- a/src/include/optimizer/planner.h +++ b/src/include/optimizer/planner.h @@ -77,7 +77,6 @@ extern void mark_partial_aggref(Aggref *agg, AggSplit aggsplit); extern Path *get_cheapest_fractional_path(RelOptInfo *rel, double tuple_fraction); -extern Expr *preprocess_phv_expression(PlannerInfo *root, Expr *expr); extern RelOptInfo *create_unique_paths(PlannerInfo *root, RelOptInfo *rel, SpecialJoinInfo *sjinfo); diff --git a/src/test/regress/expected/groupingsets.out b/src/test/regress/expected/groupingsets.out index c3f00771f6e..08d5ce3156d 100644 --- a/src/test/regress/expected/groupingsets.out +++ b/src/test/regress/expected/groupingsets.out @@ -2387,12 +2387,12 @@ select (select grouping(v1)) from (values ((select 1))) v(v1) group by cube(v1); MixedAggregate Hash Key: (InitPlan expr_3).col1 Group Key: () - InitPlan expr_2 + InitPlan expr_1 -> Result InitPlan expr_3 -> Result -> Result - SubPlan expr_1 + SubPlan expr_2 -> Result (10 rows) diff --git a/src/test/regress/expected/join.out b/src/test/regress/expected/join.out index 051c3539930..75544fe6aa3 100644 --- a/src/test/regress/expected/join.out +++ b/src/test/regress/expected/join.out @@ -5182,7 +5182,7 @@ where i8.q2 = 123; QUERY PLAN --------------------------------------------------------------------- Nested Loop - Output: i8.q1, i8.q2, (InitPlan expr_1).col1, false, (i8.q2) + Output: i8.q1, i8.q2, (InitPlan expr_2).col1, false, (i8.q2) InitPlan expr_1 -> Result Output: true @@ -5195,7 +5195,7 @@ where i8.q2 = 123; -> Nested Loop Output: i8.q1, i8.q2, (i8.q2) -> Subquery Scan on ss1 - Output: ss1.y, (InitPlan expr_1).col1 + Output: ss1.y, (InitPlan expr_2).col1 -> Limit Output: NULL::integer -> Result @@ -5209,7 +5209,7 @@ where i8.q2 = 123; Output: (i8.q2) -> Result Output: i8.q2 - One-Time Filter: ((InitPlan expr_1).col1) + One-Time Filter: ((InitPlan expr_2).col1) (29 rows) explain (verbose, costs off) @@ -5225,7 +5225,7 @@ where i8.q2 = 123; QUERY PLAN --------------------------------------------------------------------- Nested Loop - Output: i8.q1, i8.q2, (InitPlan expr_1).col1, false, (i8.q2) + Output: i8.q1, i8.q2, (InitPlan expr_2).col1, false, (i8.q2) InitPlan expr_1 -> Result Output: true @@ -5239,7 +5239,7 @@ where i8.q2 = 123; -> Nested Loop Output: i8.q1, i8.q2, (i8.q2) -> Seq Scan on public.int4_tbl i4 - Output: i4.f1, (InitPlan expr_1).col1 + Output: i4.f1, (InitPlan expr_2).col1 Filter: (i4.f1 = 0) -> Nested Loop Output: i8.q1, i8.q2, (i8.q2) @@ -5250,7 +5250,7 @@ where i8.q2 = 123; Output: (i8.q2) -> Result Output: i8.q2 - One-Time Filter: ((InitPlan expr_1).col1) + One-Time Filter: ((InitPlan expr_2).col1) (27 rows) -- Test proper handling of appendrel PHVs during useless-RTE removal @@ -7282,6 +7282,154 @@ on lhs.id = rhs.id; -> Result (5 rows) +-- check handling of a removed Var that's pushed down into a subquery +-- (fallout from the fix for bug #19560) +explain (verbose, costs off) +select c1, c2 +from (select case when false then remov.id end as c1 + from int4_tbl i41 left join a remov on i41.f1 = remov.id) ss1 + right join int4_tbl i42 on false, + lateral (select ss1.c1 as c2 from int4_tbl i43 offset 0) ss2; + QUERY PLAN +---------------------------------------------- + Nested Loop + Output: (NULL::integer), ((NULL::integer)) + -> Nested Loop Left Join + Output: (NULL::integer) + Join Filter: false + -> Seq Scan on public.int4_tbl i42 + Output: i42.f1 + -> Result + Output: NULL::integer + Replaces: Scan on i41 + One-Time Filter: false + -> Memoize + Output: ((NULL::integer)) + Cache Key: (NULL::integer) + Cache Mode: binary + -> Seq Scan on public.int4_tbl i43 + Output: (NULL::integer) +(17 rows) + +-- likewise, where the subquery is a UNION ALL whose arms are appendrel +-- children that are not simple enough to be pulled up +explain (verbose, costs off) +select c1, c2 +from (select case when false then remov.id end as c1 + from int4_tbl i41 left join a remov on i41.f1 = remov.id) ss1 + right join int4_tbl i42 on false, + lateral ((select ss1.c1 as c2 from int4_tbl i43 offset 0) + union all + (select ss1.c1 from int4_tbl i44 offset 0)) ss2; + QUERY PLAN +--------------------------------------------------- + Nested Loop + Output: (NULL::integer), ((NULL::integer)) + -> Nested Loop Left Join + Output: (NULL::integer) + Join Filter: false + -> Seq Scan on public.int4_tbl i42 + Output: i42.f1 + -> Result + Output: NULL::integer + Replaces: Scan on i41 + One-Time Filter: false + -> Memoize + Output: ((NULL::integer)) + Cache Key: (NULL::integer) + Cache Mode: binary + -> Append + -> Seq Scan on public.int4_tbl i43 + Output: (NULL::integer) + -> Seq Scan on public.int4_tbl i44 + Output: (NULL::integer) +(20 rows) + +-- likewise, where the PHV contains a SubPlan and the subquery has a join, so +-- that its planner runs flatten_join_alias_vars over the outer-level PHV +explain (verbose, costs off) +select c1, c2 +from (select case when false then remov.id else (select i41.f1) end as c1 + from int4_tbl i41 left join a remov on i41.f1 = remov.id) ss1 + right join int4_tbl i42 on false, + lateral (select ss1.c1 as c2 from int4_tbl i43 join int4_tbl i44 on true + offset 0) ss2; + QUERY PLAN +--------------------------------------------------------- + Nested Loop + Output: ((SubPlan expr_2)), (((SubPlan expr_2))) + -> Nested Loop Left Join + Output: ((SubPlan expr_2)) + Join Filter: false + -> Seq Scan on public.int4_tbl i42 + Output: i42.f1 + -> Result + Output: (SubPlan expr_2) + Replaces: Scan on i41 + One-Time Filter: false + SubPlan expr_2 + -> Result + Output: i41.f1 + -> Memoize + Output: (((SubPlan expr_2))) + Cache Key: ((SubPlan expr_2)) + Cache Mode: binary + -> Nested Loop + Output: ((SubPlan expr_2)) + -> Seq Scan on public.int4_tbl i43 + Output: i43.f1 + -> Materialize + -> Seq Scan on public.int4_tbl i44 +(24 rows) + +-- likewise, where the PHV copy is pushed into a SubLink's subselect rather +-- than a LATERAL subquery +explain (verbose, costs off) +select (select ss1.c1 from int4_tbl i43 offset 0) as c2 +from (select case when false then remov.id end as c1 + from int4_tbl i41 left join a remov on i41.f1 = remov.id) ss1 + right join int4_tbl i42 on true; + QUERY PLAN +--------------------------------------------- + Nested Loop Left Join + Output: (SubPlan expr_1) + -> Seq Scan on public.int4_tbl i42 + Output: i42.f1 + -> Materialize + Output: (NULL::integer) + -> Seq Scan on public.int4_tbl i41 + Output: NULL::integer + SubPlan expr_1 + -> Seq Scan on public.int4_tbl i43 + Output: (NULL::integer) +(11 rows) + +-- likewise, where the pushed-down PHV's expression itself contains a SubLink, +-- so it must be preprocessed once at the outer level rather than again while +-- building the SubPlan that references it +explain (verbose, costs off) +select (select ss1.c1 from int4_tbl i43 offset 0) as c2 +from (select case when false then remov.id else (select i41.f1) end as c1 + from int4_tbl i41 left join a remov on i41.f1 = remov.id) ss1 + right join int4_tbl i42 on true; + QUERY PLAN +--------------------------------------------- + Nested Loop Left Join + Output: (SubPlan expr_2) + -> Seq Scan on public.int4_tbl i42 + Output: i42.f1 + -> Materialize + Output: ((SubPlan expr_1)) + -> Seq Scan on public.int4_tbl i41 + Output: (SubPlan expr_1) + SubPlan expr_1 + -> Result + Output: i41.f1 + SubPlan expr_2 + -> Seq Scan on public.int4_tbl i43 + Output: ((SubPlan expr_1)) +(14 rows) + -- More tests of correct placement of pseudoconstant quals -- simple constant-false condition explain (costs off) diff --git a/src/test/regress/sql/join.sql b/src/test/regress/sql/join.sql index c30fd339f13..fb83a96e939 100644 --- a/src/test/regress/sql/join.sql +++ b/src/test/regress/sql/join.sql @@ -2699,6 +2699,53 @@ full join ) as rhs on lhs.id = rhs.id; +-- check handling of a removed Var that's pushed down into a subquery +-- (fallout from the fix for bug #19560) +explain (verbose, costs off) +select c1, c2 +from (select case when false then remov.id end as c1 + from int4_tbl i41 left join a remov on i41.f1 = remov.id) ss1 + right join int4_tbl i42 on false, + lateral (select ss1.c1 as c2 from int4_tbl i43 offset 0) ss2; + +-- likewise, where the subquery is a UNION ALL whose arms are appendrel +-- children that are not simple enough to be pulled up +explain (verbose, costs off) +select c1, c2 +from (select case when false then remov.id end as c1 + from int4_tbl i41 left join a remov on i41.f1 = remov.id) ss1 + right join int4_tbl i42 on false, + lateral ((select ss1.c1 as c2 from int4_tbl i43 offset 0) + union all + (select ss1.c1 from int4_tbl i44 offset 0)) ss2; + +-- likewise, where the PHV contains a SubPlan and the subquery has a join, so +-- that its planner runs flatten_join_alias_vars over the outer-level PHV +explain (verbose, costs off) +select c1, c2 +from (select case when false then remov.id else (select i41.f1) end as c1 + from int4_tbl i41 left join a remov on i41.f1 = remov.id) ss1 + right join int4_tbl i42 on false, + lateral (select ss1.c1 as c2 from int4_tbl i43 join int4_tbl i44 on true + offset 0) ss2; + +-- likewise, where the PHV copy is pushed into a SubLink's subselect rather +-- than a LATERAL subquery +explain (verbose, costs off) +select (select ss1.c1 from int4_tbl i43 offset 0) as c2 +from (select case when false then remov.id end as c1 + from int4_tbl i41 left join a remov on i41.f1 = remov.id) ss1 + right join int4_tbl i42 on true; + +-- likewise, where the pushed-down PHV's expression itself contains a SubLink, +-- so it must be preprocessed once at the outer level rather than again while +-- building the SubPlan that references it +explain (verbose, costs off) +select (select ss1.c1 from int4_tbl i43 offset 0) as c2 +from (select case when false then remov.id else (select i41.f1) end as c1 + from int4_tbl i41 left join a remov on i41.f1 = remov.id) ss1 + right join int4_tbl i42 on true; + -- More tests of correct placement of pseudoconstant quals -- simple constant-false condition diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list index 7aedaafab90..2fb1502da3b 100644 --- a/src/tools/pgindent/typedefs.list +++ b/src/tools/pgindent/typedefs.list @@ -4167,6 +4167,7 @@ postprocess_result_function pqbool pqsigfunc pqsigfunc_legacy +preprocess_subquery_phvs_context printQueryOpt printTableContent printTableFooter -- 2.37.1 (Apple Git-137.1)
^ permalink raw reply [nested|flat] 74+ messages in thread

* Re: remove_useless_joins vs. bug #19560
  2026-07-20 18:52 remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-24 13:38 ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-07-25 16:46   ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-25 20:07     ` Re: remove_useless_joins vs. bug #19560 Thom Brown <thom@linux.com>
  2026-07-25 21:23       ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-26 02:15         ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-26 09:49           ` Re: remove_useless_joins vs. bug #19560 Thom Brown <thom@linux.com>
  2026-07-26 17:33             ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-26 17:35               ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-27 07:07                 ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-07-27 16:33                   ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-27 18:21                     ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-29 06:21                       ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-16 23:58                         ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-26 05:26                           ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-26 17:25                             ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-27 01:57                               ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-27 15:53                                 ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-28 07:29                                   ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-28 13:43                                     ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-29 03:27                                       ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-29 20:10                                         ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-30 06:50                                           ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-30 16:20                                             ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-31 01:54                                               ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-09-03 14:55                                                 ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-09-09 08:04                                                   ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-09-09 14:54                                                     ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-09-10 09:33                                                       ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
@ 2026-09-13 17:32                                                         ` Tom Lane <tgl@sss.pgh.pa.us>
  2026-09-14 05:10                                                           ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  0 siblings, 1 reply; 74+ messages in thread

From: Tom Lane @ 2026-09-13 17:32 UTC (permalink / raw)
  To: Richard Guo <guofenglinux@gmail.com>; +Cc: Tender Wang <tndrwang@gmail.com>; Thom Brown <thom@linux.com>; Jacob Brazeal <jacob.brazeal@gmail.com>; pgsql-hackers@lists.postgresql.org

Richard Guo <guofenglinux@gmail.com> writes:
> I think a straightforward way to achieve that is that in
> subquery_planner, we walk the whole query tree and preprocess all of
> the current level's PHVs that got pushed down into subqueries, up
> front before anything consumes them.  Then the subquery's own
> processing can just ignore upper-level PHVs.  eval_const_expressions
> returns them as-is, and flatten_join_alias_vars stops descending into
> them.

> This still keeps the copies around rather than relying solely on the
> PlaceHolderInfo, but since they'd be folded the same way as the
> owning-level version, maybe it still gets the consistency we want to
> have.

Yeah.  Since we need to back-patch this, let's not get too aggressive
about optimizing such cases.  Maybe later we could look into avoiding
the duplicate processing in a master-only patch.

> One problem with this is that we walk the whole query tree to find
> those copies, which costs some planning cycles.  We could gate it on
> root->glob->lastPHId != 0 to skip queries with no PHVs at all, but
> beyond that I don't have a good way to narrow it down.

I see you did put in that gate, and again I think that's enough for
now.  We could conceivably try to track which query levels own PHVs,
and then only recurse down from those levels.  But I fear that'd be
about as hard to keep straight as hasSubLinks, which has caused us
plenty of heartburn in the past.  Again, let's leave such optimization
for another day.

In short, LGTM, please push.

			regards, tom lane






^ permalink  raw  reply  [nested|flat] 74+ messages in thread

* Re: remove_useless_joins vs. bug #19560
  2026-07-20 18:52 remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-24 13:38 ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-07-25 16:46   ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-25 20:07     ` Re: remove_useless_joins vs. bug #19560 Thom Brown <thom@linux.com>
  2026-07-25 21:23       ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-26 02:15         ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-26 09:49           ` Re: remove_useless_joins vs. bug #19560 Thom Brown <thom@linux.com>
  2026-07-26 17:33             ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-26 17:35               ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-27 07:07                 ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-07-27 16:33                   ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-27 18:21                     ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-29 06:21                       ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-16 23:58                         ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-26 05:26                           ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-26 17:25                             ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-27 01:57                               ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-27 15:53                                 ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-28 07:29                                   ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-28 13:43                                     ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-29 03:27                                       ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-29 20:10                                         ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-30 06:50                                           ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-30 16:20                                             ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-31 01:54                                               ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-09-03 14:55                                                 ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-09-09 08:04                                                   ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-09-09 14:54                                                     ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-09-10 09:33                                                       ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-09-13 17:32                                                         ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
@ 2026-09-14 05:10                                                           ` Richard Guo <guofenglinux@gmail.com>
  2026-09-15 16:28                                                             ` Re: remove_useless_joins vs. bug #19560 Fujii Masao <masao.fujii@gmail.com>
  0 siblings, 1 reply; 74+ messages in thread

From: Richard Guo @ 2026-09-14 05:10 UTC (permalink / raw)
  To: Tom Lane <tgl@sss.pgh.pa.us>; +Cc: Tender Wang <tndrwang@gmail.com>; Thom Brown <thom@linux.com>; Jacob Brazeal <jacob.brazeal@gmail.com>; pgsql-hackers@lists.postgresql.org

On Mon, Sep 14, 2026 at 2:32 AM Tom Lane <tgl@sss.pgh.pa.us> wrote:
> In short, LGTM, please push.

Thanks!  Pushed and back-patched to v16.

- Richard






^ permalink  raw  reply  [nested|flat] 74+ messages in thread

* Re: remove_useless_joins vs. bug #19560
  2026-07-20 18:52 remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-24 13:38 ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-07-25 16:46   ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-25 20:07     ` Re: remove_useless_joins vs. bug #19560 Thom Brown <thom@linux.com>
  2026-07-25 21:23       ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-26 02:15         ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-26 09:49           ` Re: remove_useless_joins vs. bug #19560 Thom Brown <thom@linux.com>
  2026-07-26 17:33             ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-26 17:35               ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-27 07:07                 ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-07-27 16:33                   ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-27 18:21                     ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-29 06:21                       ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-16 23:58                         ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-26 05:26                           ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-26 17:25                             ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-27 01:57                               ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-27 15:53                                 ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-28 07:29                                   ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-28 13:43                                     ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-29 03:27                                       ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-29 20:10                                         ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-30 06:50                                           ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-30 16:20                                             ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-31 01:54                                               ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-09-03 14:55                                                 ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-09-09 08:04                                                   ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-09-09 14:54                                                     ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-09-10 09:33                                                       ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-09-13 17:32                                                         ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-09-14 05:10                                                           ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
@ 2026-09-15 16:28                                                             ` Fujii Masao <masao.fujii@gmail.com>
  2026-09-16 00:38                                                               ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-09-16 04:56                                                               ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  0 siblings, 2 replies; 74+ messages in thread

From: Fujii Masao @ 2026-09-15 16:28 UTC (permalink / raw)
  To: Richard Guo <guofenglinux@gmail.com>; +Cc: Tom Lane <tgl@sss.pgh.pa.us>; Tender Wang <tndrwang@gmail.com>; Thom Brown <thom@linux.com>; Jacob Brazeal <jacob.brazeal@gmail.com>; pgsql-hackers@lists.postgresql.org

On Mon, Sep 14, 2026 at 2:10 PM Richard Guo <guofenglinux@gmail.com> wrote:
>
> On Mon, Sep 14, 2026 at 2:32 AM Tom Lane <tgl@sss.pgh.pa.us> wrote:
> > In short, LGTM, please push.
>
> Thanks!  Pushed and back-patched to v16.

Thanks for working on this!

I used Codex to review this commit, and it reported two cases that could
cause assertion failures. I confirmed that both cases actually cause
assertion failures:

(1)
CREATE TEMP TABLE t(a integer);

EXPLAIN (COSTS OFF)
  SELECT z.c2
  FROM t b
  LEFT JOIN (
    SELECT COALESCE(s.c, 0) AS c2
    FROM t x
    LEFT JOIN (SELECT (SELECT i.a) AS c FROM t i) s ON true
  ) ss ON true
  CROSS JOIN LATERAL (SELECT ss.c2 OFFSET 0) z;

TRAP: failed Assert("!IsA(node, SubPlan)"), File: "var.c", Line: 993, PID: 68500
0   postgres                            0x0000000101106872
ExceptionalCondition + 178
1   postgres                            0x0000000100db49be
flatten_join_alias_vars_mutator + 1438
2   postgres                            0x0000000100caaf3e
expression_tree_mutator_impl + 8078
3   postgres                            0x0000000100db48a9
flatten_join_alias_vars_mutator + 1161
4   postgres                            0x0000000100caaa42
expression_tree_mutator_impl + 6802
5   postgres                            0x0000000100db4a71
flatten_join_alias_vars_mutator + 1617
6   postgres                            0x0000000100ca9f19
expression_tree_mutator_impl + 3945
7   postgres                            0x0000000100db4a71
flatten_join_alias_vars_mutator + 1617
8   postgres                            0x0000000100db4414
flatten_join_alias_vars + 116
9   postgres                            0x0000000100d5c9f1
preprocess_expression + 97
10  postgres                            0x0000000100d60671
preprocess_subquery_phvs_walker + 241
11  postgres                            0x0000000100ca78a2
expression_tree_walker_impl + 2610
12  postgres                            0x0000000100d606a9
preprocess_subquery_phvs_walker + 297
13  postgres                            0x0000000100ca7d82
expression_tree_walker_impl + 3858
14  postgres                            0x0000000100d606a9
preprocess_subquery_phvs_walker + 297
15  postgres                            0x0000000100ca8973
query_tree_walker_impl + 83
16  postgres                            0x0000000100d605cc
preprocess_subquery_phvs_walker + 76
17  postgres                            0x0000000100ca8e3d
range_table_entry_walker_impl + 173
18  postgres                            0x0000000100ca8d58
range_table_walker_impl + 152
19  postgres                            0x0000000100ca8c9a
query_tree_walker_impl + 890
20  postgres                            0x0000000100d5c985
preprocess_subquery_phvs + 53
21  postgres                            0x0000000100d5b66e
subquery_planner + 1758
22  postgres                            0x0000000100d5a471
standard_planner + 1201
23  postgres                            0x0000000100d59f9f planner + 95
24  postgres                            0x0000000100eee3a4 pg_plan_query + 132
25  postgres                            0x0000000100afd776
standard_ExplainOneQuery + 214
26  postgres                            0x0000000100afd496 ExplainOneQuery + 182
27  postgres                            0x0000000100afd218 ExplainQuery + 376
28  postgres                            0x0000000100ef8f8f
standard_ProcessUtility + 2159
29  postgres                            0x0000000100ef8719 ProcessUtility + 313
30  postgres                            0x0000000100ef7f2c
PortalRunUtility + 236
31  postgres                            0x0000000100ef6bee FillPortalStore + 238
32  postgres                            0x0000000100ef67c1 PortalRun + 641
33  postgres                            0x0000000100ef18a8
exec_simple_query + 1400
34  postgres                            0x0000000100ef09e5 PostgresMain + 2981
35  postgres                            0x0000000100ee9528 BackendMain + 168
36  postgres                            0x0000000100dd6f89
postmaster_child_launch + 377
37  postgres                            0x0000000100ddd535 BackendStartup + 277
38  postgres                            0x0000000100ddbaa5 ServerLoop + 341
39  postgres                            0x0000000100dda8a9 PostmasterMain + 5753
40  postgres                            0x0000000100c73933 main + 771
41  dyld                                0x00007ff810660530 start + 3056

(2)
CREATE TEMP TABLE t(a integer);

EXPLAIN (COSTS OFF)
  SELECT q.c
  FROM (
    (SELECT (SELECT i.a) AS c FROM t i) s
    FULL JOIN t b(c) USING (c)
  ) j
  CROSS JOIN LATERAL (SELECT j.c OFFSET 0) q;

TRAP: failed Assert("!checkExprHasSubLink((Node *) phv)"), File:
"paramassign.c", Line: 691, PID: 68067
0   postgres                            0x000000010c53a872
ExceptionalCondition + 178
1   postgres                            0x000000010c1cc030
identify_current_nestloop_params + 544
2   postgres                            0x000000010c18336e
create_nestloop_plan + 734
3   postgres                            0x000000010c17a261
create_join_plan + 113
4   postgres                            0x000000010c178e0d
create_plan_recurse + 109
5   postgres                            0x000000010c178ce5 create_plan + 101
6   postgres                            0x000000010c18e4aa
standard_planner + 1258
7   postgres                            0x000000010c18df9f planner + 95
8   postgres                            0x000000010c3223a4 pg_plan_query + 132
9   postgres                            0x000000010bf31776
standard_ExplainOneQuery + 214
10  postgres                            0x000000010bf31496 ExplainOneQuery + 182
11  postgres                            0x000000010bf31218 ExplainQuery + 376
12  postgres                            0x000000010c32cf8f
standard_ProcessUtility + 2159
13  postgres                            0x000000010c32c719 ProcessUtility + 313
14  postgres                            0x000000010c32bf2c
PortalRunUtility + 236
15  postgres                            0x000000010c32abee FillPortalStore + 238
16  postgres                            0x000000010c32a7c1 PortalRun + 641
17  postgres                            0x000000010c3258a8
exec_simple_query + 1400
18  postgres                            0x000000010c3249e5 PostgresMain + 2981
19  postgres                            0x000000010c31d528 BackendMain + 168
20  postgres                            0x000000010c20af89
postmaster_child_launch + 377
21  postgres                            0x000000010c211535 BackendStartup + 277
22  postgres                            0x000000010c20faa5 ServerLoop + 341
23  postgres                            0x000000010c20e8a9 PostmasterMain + 5753
24  postgres                            0x000000010c0a7933 main + 771
25  dyld                                0x00007ff810660530 start + 3056

Regards,

-- 
Fujii Masao






^ permalink  raw  reply  [nested|flat] 74+ messages in thread

* Re: remove_useless_joins vs. bug #19560
  2026-07-20 18:52 remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-24 13:38 ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-07-25 16:46   ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-25 20:07     ` Re: remove_useless_joins vs. bug #19560 Thom Brown <thom@linux.com>
  2026-07-25 21:23       ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-26 02:15         ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-26 09:49           ` Re: remove_useless_joins vs. bug #19560 Thom Brown <thom@linux.com>
  2026-07-26 17:33             ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-26 17:35               ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-27 07:07                 ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-07-27 16:33                   ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-27 18:21                     ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-29 06:21                       ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-16 23:58                         ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-26 05:26                           ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-26 17:25                             ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-27 01:57                               ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-27 15:53                                 ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-28 07:29                                   ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-28 13:43                                     ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-29 03:27                                       ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-29 20:10                                         ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-30 06:50                                           ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-30 16:20                                             ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-31 01:54                                               ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-09-03 14:55                                                 ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-09-09 08:04                                                   ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-09-09 14:54                                                     ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-09-10 09:33                                                       ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-09-13 17:32                                                         ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-09-14 05:10                                                           ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-09-15 16:28                                                             ` Re: remove_useless_joins vs. bug #19560 Fujii Masao <masao.fujii@gmail.com>
@ 2026-09-16 00:38                                                               ` Richard Guo <guofenglinux@gmail.com>
  2026-09-16 05:16                                                                 ` Re: remove_useless_joins vs. bug #19560 Fujii Masao <masao.fujii@gmail.com>
  1 sibling, 1 reply; 74+ messages in thread

From: Richard Guo @ 2026-09-16 00:38 UTC (permalink / raw)
  To: Fujii Masao <masao.fujii@gmail.com>; +Cc: Tom Lane <tgl@sss.pgh.pa.us>; Tender Wang <tndrwang@gmail.com>; Thom Brown <thom@linux.com>; Jacob Brazeal <jacob.brazeal@gmail.com>; pgsql-hackers@lists.postgresql.org

On Wed, Sep 16, 2026 at 1:28 AM Fujii Masao <masao.fujii@gmail.com> wrote:
> On Mon, Sep 14, 2026 at 2:10 PM Richard Guo <guofenglinux@gmail.com> wrote:
> > Thanks!  Pushed and back-patched to v16.

> I used Codex to review this commit, and it reported two cases that could
> cause assertion failures. I confirmed that both cases actually cause
> assertion failures:

Thanks for the report!  I expected some fallout from this commit,
though I didn't expect them quite so soon :-)

I'll take a look.

- Richard






^ permalink  raw  reply  [nested|flat] 74+ messages in thread

* Re: remove_useless_joins vs. bug #19560
  2026-07-20 18:52 remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-24 13:38 ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-07-25 16:46   ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-25 20:07     ` Re: remove_useless_joins vs. bug #19560 Thom Brown <thom@linux.com>
  2026-07-25 21:23       ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-26 02:15         ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-26 09:49           ` Re: remove_useless_joins vs. bug #19560 Thom Brown <thom@linux.com>
  2026-07-26 17:33             ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-26 17:35               ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-27 07:07                 ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-07-27 16:33                   ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-27 18:21                     ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-29 06:21                       ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-16 23:58                         ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-26 05:26                           ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-26 17:25                             ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-27 01:57                               ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-27 15:53                                 ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-28 07:29                                   ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-28 13:43                                     ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-29 03:27                                       ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-29 20:10                                         ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-30 06:50                                           ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-30 16:20                                             ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-31 01:54                                               ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-09-03 14:55                                                 ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-09-09 08:04                                                   ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-09-09 14:54                                                     ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-09-10 09:33                                                       ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-09-13 17:32                                                         ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-09-14 05:10                                                           ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-09-15 16:28                                                             ` Re: remove_useless_joins vs. bug #19560 Fujii Masao <masao.fujii@gmail.com>
  2026-09-16 00:38                                                               ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
@ 2026-09-16 05:16                                                                 ` Fujii Masao <masao.fujii@gmail.com>
  2026-09-16 06:58                                                                   ` Re: remove_useless_joins vs. bug #19560 Tender Wang <tndrwang@gmail.com>
  2026-09-16 07:02                                                                   ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  0 siblings, 2 replies; 74+ messages in thread

From: Fujii Masao @ 2026-09-16 05:16 UTC (permalink / raw)
  To: Richard Guo <guofenglinux@gmail.com>; +Cc: Tom Lane <tgl@sss.pgh.pa.us>; Tender Wang <tndrwang@gmail.com>; Thom Brown <thom@linux.com>; Jacob Brazeal <jacob.brazeal@gmail.com>; pgsql-hackers@lists.postgresql.org

On Wed, Sep 16, 2026 at 9:39 AM Richard Guo <guofenglinux@gmail.com> wrote:
> Thanks for the report!  I expected some fallout from this commit,
> though I didn't expect them quite so soon :-)
>
> I'll take a look.

Thanks!

And, here's another related issue, though it seems to have been introduced by
commit 2ebf25e7d70.


CREATE TABLE t(a integer PRIMARY KEY);

EXPLAIN (COSTS OFF)
  SELECT u.c2
  FROM (
    SELECT CASE WHEN false THEN r.a END AS c
    FROM t l LEFT JOIN t r ON l.a = r.a
  ) s
  RIGHT JOIN t b ON true
  CROSS JOIN LATERAL (
    SELECT (SELECT s.c) AS c2
    UNION ALL
    SELECT (SELECT s.c)
  ) u;

TRAP: failed Assert("context->new_index != INVALID_VAR"), File:
"rewriteManip.c", Line: 566, PID: 6615
0   postgres                            0x0000000104f38ee2
ExceptionalCondition + 178
1   postgres                            0x0000000104c92fec
ChangeVarNodes_walker + 124
2   postgres                            0x0000000104ad9986
expression_tree_walker_impl + 1654
3   postgres                            0x0000000104c93448
ChangeVarNodes_walker + 1240
4   postgres                            0x0000000104ada53d
expression_tree_walker_impl + 4653
5   postgres                            0x0000000104c93448
ChangeVarNodes_walker + 1240
6   postgres                            0x0000000104ada222
expression_tree_walker_impl + 3858
7   postgres                            0x0000000104ad971a
expression_tree_walker_impl + 1034
8   postgres                            0x0000000104c93448
ChangeVarNodes_walker + 1240
9   postgres                            0x0000000104ada222
expression_tree_walker_impl + 3858
10  postgres                            0x0000000104ada5a2
expression_tree_walker_impl + 4754
11  postgres                            0x0000000104c93448
ChangeVarNodes_walker + 1240
12  postgres                            0x0000000104ada222
expression_tree_walker_impl + 3858
13  postgres                            0x0000000104c93448
ChangeVarNodes_walker + 1240
14  postgres                            0x0000000104c92f5e ChangeVarNodes + 494
15  postgres                            0x0000000104b73a74
remove_rels_from_query_tree + 132
16  postgres                            0x0000000104b73409
remove_useless_outer_joins + 457
17  postgres                            0x0000000104b8c1b3 query_planner + 1123
18  postgres                            0x0000000104b8f749
grouping_planner + 1209
19  postgres                            0x0000000104b8e775
subquery_planner + 4933
20  postgres                            0x0000000104b8c911
standard_planner + 1201
21  postgres                            0x0000000104b8c43f planner + 95
22  postgres                            0x0000000104d20854 pg_plan_query + 132
23  postgres                            0x000000010492fef6
standard_ExplainOneQuery + 214
24  postgres                            0x000000010492fc16 ExplainOneQuery + 182
25  postgres                            0x000000010492f998 ExplainQuery + 376
26  postgres                            0x0000000104d2b43f
standard_ProcessUtility + 2159
27  postgres                            0x0000000104d2abc9 ProcessUtility + 313
28  postgres                            0x0000000104d2a3dc
PortalRunUtility + 236
29  postgres                            0x0000000104d2909e FillPortalStore + 238
30  postgres                            0x0000000104d28c71 PortalRun + 641
31  postgres                            0x0000000104d23d58
exec_simple_query + 1400
32  postgres                            0x0000000104d22e95 PostgresMain + 2981
33  postgres                            0x0000000104d1b9d8 BackendMain + 168
34  postgres                            0x0000000104c09429
postmaster_child_launch + 377
35  postgres                            0x0000000104c0f9d5 BackendStartup + 277
36  postgres                            0x0000000104c0df45 ServerLoop + 341
37  postgres                            0x0000000104c0cd49 PostmasterMain + 5753
38  postgres                            0x0000000104aa5dd3 main + 771
39  dyld                                0x00007ff810660530 start + 3056

Regards,

-- 
Fujii Masao






^ permalink  raw  reply  [nested|flat] 74+ messages in thread

* Re: remove_useless_joins vs. bug #19560
  2026-07-20 18:52 remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-24 13:38 ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-07-25 16:46   ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-25 20:07     ` Re: remove_useless_joins vs. bug #19560 Thom Brown <thom@linux.com>
  2026-07-25 21:23       ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-26 02:15         ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-26 09:49           ` Re: remove_useless_joins vs. bug #19560 Thom Brown <thom@linux.com>
  2026-07-26 17:33             ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-26 17:35               ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-27 07:07                 ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-07-27 16:33                   ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-27 18:21                     ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-29 06:21                       ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-16 23:58                         ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-26 05:26                           ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-26 17:25                             ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-27 01:57                               ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-27 15:53                                 ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-28 07:29                                   ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-28 13:43                                     ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-29 03:27                                       ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-29 20:10                                         ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-30 06:50                                           ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-30 16:20                                             ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-31 01:54                                               ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-09-03 14:55                                                 ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-09-09 08:04                                                   ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-09-09 14:54                                                     ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-09-10 09:33                                                       ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-09-13 17:32                                                         ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-09-14 05:10                                                           ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-09-15 16:28                                                             ` Re: remove_useless_joins vs. bug #19560 Fujii Masao <masao.fujii@gmail.com>
  2026-09-16 00:38                                                               ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-09-16 05:16                                                                 ` Re: remove_useless_joins vs. bug #19560 Fujii Masao <masao.fujii@gmail.com>
@ 2026-09-16 06:58                                                                   ` Tender Wang <tndrwang@gmail.com>
  1 sibling, 0 replies; 74+ messages in thread

From: Tender Wang @ 2026-09-16 06:58 UTC (permalink / raw)
  To: Fujii Masao <masao.fujii@gmail.com>; Richard Guo <guofenglinux@gmail.com>; +Cc: Tom Lane <tgl@sss.pgh.pa.us>; Thom Brown <thom@linux.com>; Jacob Brazeal <jacob.brazeal@gmail.com>; pgsql-hackers@lists.postgresql.org

Fujii Masao <masao.fujii@gmail.com> 于2026年9月16日周三 13:16写道:
>
> On Wed, Sep 16, 2026 at 9:39 AM Richard Guo <guofenglinux@gmail.com> wrote:
> > Thanks for the report!  I expected some fallout from this commit,
> > though I didn't expect them quite so soon :-)
> >
> > I'll take a look.
>
> Thanks!
>
> And, here's another related issue, though it seems to have been introduced by
> commit 2ebf25e7d70.
>
>
> CREATE TABLE t(a integer PRIMARY KEY);
>
> EXPLAIN (COSTS OFF)
>   SELECT u.c2
>   FROM (
>     SELECT CASE WHEN false THEN r.a END AS c
>     FROM t l LEFT JOIN t r ON l.a = r.a
>   ) s
>   RIGHT JOIN t b ON true
>   CROSS JOIN LATERAL (
>     SELECT (SELECT s.c) AS c2
>     UNION ALL
>     SELECT (SELECT s.c)
>   ) u;
>

It seems root->append_rel_list was not processed in preprocess_subquery_phvs().
I tried a quick fix as follows:

diff --git a/src/backend/optimizer/plan/planner.c
b/src/backend/optimizer/plan/planner.c
index 8d30131855a..fa15855411b 100644
inline patch 1: src/backend/optimizer/plan/planner.c (+2/-0 lines) download inline-1.patch--- a/src/backend/optimizer/plan/planner.c +++ b/src/backend/optimizer/plan/planner.c @@ -1643,6 +1643,9 @@ preprocess_subquery_phvs(PlannerInfo *root) context.sublevels_up = 0; (void) query_tree_walker(root->parse, preprocess_subquery_phvs_walker, &context, 0); + if (root->append_rel_list != NIL) + (void) expression_tree_walker((Node *)
root->append_rel_list, preprocess_subquery_phvs_walker, + &context); } -- Thanks, Tender Wang ^ permalink raw reply [nested|flat] 74+ messages in thread

* Re: remove_useless_joins vs. bug #19560
  2026-07-20 18:52 remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-24 13:38 ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-07-25 16:46   ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-25 20:07     ` Re: remove_useless_joins vs. bug #19560 Thom Brown <thom@linux.com>
  2026-07-25 21:23       ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-26 02:15         ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-26 09:49           ` Re: remove_useless_joins vs. bug #19560 Thom Brown <thom@linux.com>
  2026-07-26 17:33             ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-26 17:35               ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-27 07:07                 ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-07-27 16:33                   ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-27 18:21                     ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-29 06:21                       ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-16 23:58                         ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-26 05:26                           ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-26 17:25                             ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-27 01:57                               ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-27 15:53                                 ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-28 07:29                                   ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-28 13:43                                     ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-29 03:27                                       ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-29 20:10                                         ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-30 06:50                                           ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-30 16:20                                             ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-31 01:54                                               ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-09-03 14:55                                                 ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-09-09 08:04                                                   ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-09-09 14:54                                                     ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-09-10 09:33                                                       ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-09-13 17:32                                                         ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-09-14 05:10                                                           ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-09-15 16:28                                                             ` Re: remove_useless_joins vs. bug #19560 Fujii Masao <masao.fujii@gmail.com>
  2026-09-16 00:38                                                               ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-09-16 05:16                                                                 ` Re: remove_useless_joins vs. bug #19560 Fujii Masao <masao.fujii@gmail.com>
@ 2026-09-16 07:02                                                                   ` Richard Guo <guofenglinux@gmail.com>
  1 sibling, 0 replies; 74+ messages in thread

From: Richard Guo @ 2026-09-16 07:02 UTC (permalink / raw)
  To: Fujii Masao <masao.fujii@gmail.com>; +Cc: Tom Lane <tgl@sss.pgh.pa.us>; Tender Wang <tndrwang@gmail.com>; Thom Brown <thom@linux.com>; Jacob Brazeal <jacob.brazeal@gmail.com>; pgsql-hackers@lists.postgresql.org

On Wed, Sep 16, 2026 at 2:16 PM Fujii Masao <masao.fujii@gmail.com> wrote:
> And, here's another related issue, though it seems to have been introduced by
> commit 2ebf25e7d70.

> CREATE TABLE t(a integer PRIMARY KEY);
>
> EXPLAIN (COSTS OFF)
>   SELECT u.c2
>   FROM (
>     SELECT CASE WHEN false THEN r.a END AS c
>     FROM t l LEFT JOIN t r ON l.a = r.a
>   ) s
>   RIGHT JOIN t b ON true
>   CROSS JOIN LATERAL (
>     SELECT (SELECT s.c) AS c2
>     UNION ALL
>     SELECT (SELECT s.c)
>   ) u;
>
> TRAP: failed Assert("context->new_index != INVALID_VAR"), File:
> "rewriteManip.c", Line: 566, PID: 6615

Thanks!  I just had a look into this.  What happens is that when s is
pulled up, its output c becomes a PHV wrapping the CASE expression,
since s is on the nullable side of the RIGHT JOIN.  The two sublinks
"(SELECT s.c)" in the LATERAL subquery each get a copy of that PHV.
Then, because the UNION ALL arms are simple, they are pulled up too,
and their target expressions, ie those two sublinks, are moved into
the appendrel's translated_vars.  However, the current walk never
looks at root->append_rel_list, so the PHV copies inside the sublinks
are never preprocessed.  At the outer level the CASE folds to NULL,
but the copies still reference r.a, and join removal of r then finds
that reference.

The patch I posted upthread fixes this too, since it preprocesses the
copies from within preprocess_expression, which the translated_vars go
through as well.  I'll add this case to its regression tests.  Really
nice catch!

- Richard






^ permalink  raw  reply  [nested|flat] 74+ messages in thread

* Re: remove_useless_joins vs. bug #19560
  2026-07-20 18:52 remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-24 13:38 ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-07-25 16:46   ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-25 20:07     ` Re: remove_useless_joins vs. bug #19560 Thom Brown <thom@linux.com>
  2026-07-25 21:23       ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-26 02:15         ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-26 09:49           ` Re: remove_useless_joins vs. bug #19560 Thom Brown <thom@linux.com>
  2026-07-26 17:33             ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-26 17:35               ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-27 07:07                 ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-07-27 16:33                   ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-27 18:21                     ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-29 06:21                       ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-16 23:58                         ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-26 05:26                           ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-26 17:25                             ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-27 01:57                               ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-27 15:53                                 ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-28 07:29                                   ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-28 13:43                                     ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-29 03:27                                       ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-29 20:10                                         ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-30 06:50                                           ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-30 16:20                                             ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-31 01:54                                               ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-09-03 14:55                                                 ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-09-09 08:04                                                   ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-09-09 14:54                                                     ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-09-10 09:33                                                       ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-09-13 17:32                                                         ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-09-14 05:10                                                           ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-09-15 16:28                                                             ` Re: remove_useless_joins vs. bug #19560 Fujii Masao <masao.fujii@gmail.com>
@ 2026-09-16 04:56                                                               ` Richard Guo <guofenglinux@gmail.com>
  2026-09-19 13:14                                                                 ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  1 sibling, 1 reply; 74+ messages in thread

From: Richard Guo @ 2026-09-16 04:56 UTC (permalink / raw)
  To: Fujii Masao <masao.fujii@gmail.com>; +Cc: Tom Lane <tgl@sss.pgh.pa.us>; Tender Wang <tndrwang@gmail.com>; Thom Brown <thom@linux.com>; Jacob Brazeal <jacob.brazeal@gmail.com>; pgsql-hackers@lists.postgresql.org

On Wed, Sep 16, 2026 at 1:28 AM Fujii Masao <masao.fujii@gmail.com> wrote:
> EXPLAIN (COSTS OFF)
>   SELECT z.c2
>   FROM t b
>   LEFT JOIN (
>     SELECT COALESCE(s.c, 0) AS c2
>     FROM t x
>     LEFT JOIN (SELECT (SELECT i.a) AS c FROM t i) s ON true
>   ) ss ON true
>   CROSS JOIN LATERAL (SELECT ss.c2 OFFSET 0) z;

For this one, the pushed-down copy of PHV has the form
PHV(COALESCE(PHV(SubLink))), i.e. one copy nested directly inside
another.  preprocess_subquery_phvs_walker preprocesses the inner one
first and then the outer one, and the outer one's preprocessing runs
into the SubPlan just created in the inner one and trips the Assert.
I think this one is easy to fix.  We can just stop the walker from
descending into a copy, since preprocessing the copy's expression
takes care of anything nested inside it.


> EXPLAIN (COSTS OFF)
>   SELECT q.c
>   FROM (
>     (SELECT (SELECT i.a) AS c FROM t i) s
>     FULL JOIN t b(c) USING (c)
>   ) j
>   CROSS JOIN LATERAL (SELECT j.c OFFSET 0) q;

This one is kind of nastier.  Currently the walk preprocessing the
pushed-down copies runs at the start of subquery_planner, but copies
can also be inserted later, when flatten_join_alias_vars expands a
join alias Var of the outer level within a LATERAL subquery and the
alias expression contains a PHV, just as shown in the second query.
Such copies are never preprocessed, so a SubLink within them survives
into the subquery's lateral references.

I think we have to insist that the preprocessing happens after join
alias expansion, which is what my v2 patch in [1] did.  But that patch
was not complete: as I explained in [2], it doesn't handle copies that
were pushed into a SubLink's subselect.  I think we can cover those by
also running the preprocessing in preprocess_expression, right before
SS_process_sublinks.  That way each upper-level PHV is preprocessed
exactly once, at the level it belongs to, and always after join alias
expansion.

Hence, the attached fix.

[1] https://postgr.es/m/CAMbWs4-5aHFeGy9ArFbozdpxy4xFEtWgXzGTW7KoYOjzX9nXGA@mail.gmail.com
[1] https://postgr.es/m/CAMbWs4_BN_0+mHvS3xpH8WOU47PN3bV5zh3Ny56JLHnB-bamww@mail.gmail.com

- Richard

Attachments:

v1-0001-Fix-preprocessing-of-PHV-copies-pushed-down-into-.patch (application/octet-stream, 18.2K) download From f69466a28f538ad5f771ee4d922cce0aa1fed356 Mon Sep 17 00:00:00 2001 From: Richard Guo <guofenglinux@gmail.com> Date: Wed, 16 Sep 2026 10:23:05 +0900 Subject: [PATCH v1] Fix preprocessing of PHV copies pushed down into subqueries Commit e28cf96e9 preprocessed the copies of a query level's PlaceHolderVars that were pushed down into its subqueries in a single walk at the start of subquery_planner. That was wrong in two ways. First, such copies can also be inserted later, when a join alias Var of the outer level is expanded within a LATERAL subquery or a SubLink's subselect and the alias expression contains a PHV. Those copies were never preprocessed, so a SubLink within them survived into the subquery's lateral references or into a SubPlan's argument list, tripping an assertion in identify_current_nestloop_params or failing in cost_qual_eval. Second, when a pushed-down copy directly contains another PHV of the same level, the walk preprocessed the inner one first and then the outer one, so the outer one's preprocessing ran into the SubPlans just created in the inner one and tripped an assertion in flatten_join_alias_vars. To fix, preprocess the copies right after join alias expansion instead: within preprocess_expression, just before SubLinks are turned into SubPlans, and for LATERAL subquery RTEs, right after their aliases are flattened. Preprocessing a copy handles everything within it, including any further copies nested inside its SubLinks, so the walker no longer looks inside a copy. Back-patch to v16, as with commit e28cf96e9. Reported-by: Fujii Masao <masao.fujii@gmail.com> Author: Richard Guo <guofenglinux@gmail.com> Discussion: https://postgr.es/m/CAHGQGwH-acRnAk1=Ki4EiAJEt67+Rz=_jyg7pbP_c6BK4oHZ4Q@mail.gmail.com Backpatch-through: 16 --- src/backend/optimizer/plan/planner.c | 52 ++++++----- src/backend/optimizer/plan/subselect.c | 7 +- src/backend/optimizer/util/var.c | 9 +- src/test/regress/expected/join.out | 117 ++++++++++++++++++++++--- src/test/regress/sql/join.sql | 26 ++++++ 5 files changed, 170 insertions(+), 41 deletions(-) diff --git a/src/backend/optimizer/plan/planner.c b/src/backend/optimizer/plan/planner.c index 8d30131855a..55a35aa3397 100644 --- a/src/backend/optimizer/plan/planner.c +++ b/src/backend/optimizer/plan/planner.c @@ -153,13 +153,13 @@ typedef struct /* Local functions */ static Node *preprocess_expression(PlannerInfo *root, Node *expr, int kind); -static void preprocess_subquery_phvs(PlannerInfo *root); -static bool preprocess_subquery_phvs_walker(Node *node, - preprocess_subquery_phvs_context *context); static void preprocess_qual_conditions(PlannerInfo *root, Node *jtnode); static Bitmapset *find_having_conflicts(Query *parse, Index group_rtindex); static Oid having_var_grouping_eqop(Var *var, void *context); static Oid group_var_eqop(Query *parse, Var *var); +static void preprocess_subquery_phvs(PlannerInfo *root, Node *node); +static bool preprocess_subquery_phvs_walker(Node *node, + preprocess_subquery_phvs_context *context); static void grouping_planner(PlannerInfo *root, double tuple_fraction, SetOperationStmt *setops); static grouping_sets_data *preprocess_grouping_sets(PlannerInfo *root); @@ -1004,14 +1004,6 @@ subquery_planner(PlannerGlobal *glob, Query *parse, char *plan_name, */ root->hasHavingQual = (parse->havingQual != NULL); - /* - * Preprocess any PlaceHolderVars of our level that were pushed down into - * subqueries. This must happen before anything can consume those copies, - * in particular before SubLinks below are turned into SubPlans. - */ - if (root->glob->lastPHId != 0) - preprocess_subquery_phvs(root); - /* * Do expression preprocessing on targetlist and quals, as well as other * random expressions in the querytree. Note that we do not need to @@ -1129,6 +1121,14 @@ subquery_planner(PlannerGlobal *glob, Query *parse, char *plan_name, rte->subquery = (Query *) flatten_join_alias_vars(root, root->parse, (Node *) rte->subquery); + + /* + * Likewise for copies of our PlaceHolderVars in the subquery. + * This must be done after the alias expansion above, which can + * insert such copies. + */ + if (rte->lateral && root->glob->lastPHId != 0) + preprocess_subquery_phvs(root, (Node *) rte->subquery); } else if (rte->rtekind == RTE_FUNCTION) { @@ -1463,6 +1463,15 @@ preprocess_expression(PlannerInfo *root, Node *expr, int kind) convert_saop_to_hashed_saop(expr); } + /* + * Preprocess any copies of our PlaceHolderVars within SubLink subselects. + * This must be done after join alias expansion, which can insert such + * copies, and before the SubLinks are turned into SubPlans, which collect + * those copies as SubPlan arguments. + */ + if (root->parse->hasSubLinks && root->glob->lastPHId != 0) + preprocess_subquery_phvs(root, expr); + /* Expand SubLinks to SubPlans */ if (root->parse->hasSubLinks) expr = SS_process_sublinks(root, expr, (kind == EXPRKIND_QUAL)); @@ -1625,24 +1634,25 @@ group_var_eqop(Query *parse, Var *var) /* * preprocess_subquery_phvs * Preprocess copies of this level's PlaceHolderVars that were pushed - * down into subqueries. + * down into subqueries within the given tree. * * When a subquery (a LATERAL RTE or a SubLink's subselect) references a * pulled-up output that must be wrapped in a PlaceHolderVar, the PHV * expression is pushed down into the subquery. The subquery's own planning * leaves that copy alone, since it belongs to our level, so we need to * preprocess it. We modify the PHVs in place, temporarily adjusting each to - * our level, and handle nested copies innermost-first. + * our level. Preprocessing a copy's expression takes care of everything + * within it, including any further copies nested inside SubLinks there, so + * we don't look inside a copy ourselves. */ static void -preprocess_subquery_phvs(PlannerInfo *root) +preprocess_subquery_phvs(PlannerInfo *root, Node *node) { preprocess_subquery_phvs_context context; context.root = root; context.sublevels_up = 0; - (void) query_tree_walker(root->parse, preprocess_subquery_phvs_walker, - &context, 0); + (void) preprocess_subquery_phvs_walker(node, &context); } static bool @@ -1666,9 +1676,9 @@ preprocess_subquery_phvs_walker(Node *node, { PlaceHolderVar *phv = (PlaceHolderVar *) node; - /* Handle any nested copies within the expression first */ - (void) expression_tree_walker(node, preprocess_subquery_phvs_walker, - context); + /* A PHV of an upper level can't contain anything of our level */ + if (phv->phlevelsup > context->sublevels_up) + return false; /* * Is this a copy of one of our PHVs that is pushed down into a @@ -1686,8 +1696,10 @@ preprocess_subquery_phvs_walker(Node *node, expr = preprocess_expression(context->root, expr, EXPRKIND_PHV); IncrementVarSublevelsUp(expr, levelsup, 0); phv->phexpr = (Expr *) expr; + return false; } - return false; + + /* Otherwise, it's ours or a lower level's; look inside it */ } return expression_tree_walker(node, preprocess_subquery_phvs_walker, context); diff --git a/src/backend/optimizer/plan/subselect.c b/src/backend/optimizer/plan/subselect.c index ae7c489b432..5760b616813 100644 --- a/src/backend/optimizer/plan/subselect.c +++ b/src/backend/optimizer/plan/subselect.c @@ -2255,9 +2255,10 @@ process_sublinks_mutator(Node *node, process_sublinks_context *context) /* * Don't recurse into the arguments of an outer PHV, Aggref, GroupingFunc, * or ReturningExpr here. Any SubLinks in the arguments have to be dealt - * with at the outer query level; they'll be handled when build_subplan - * collects the PHV, Aggref, GroupingFunc, or ReturningExpr into the - * arguments to be passed down to the current subplan. + * with at the outer query level; for an Aggref, GroupingFunc, or + * ReturningExpr they'll be handled when build_subplan collects it into + * the arguments to be passed down to the current subplan, while an outer + * PHV's expression has already been preprocessed by its owning level. */ if (IsA(node, PlaceHolderVar)) { diff --git a/src/backend/optimizer/util/var.c b/src/backend/optimizer/util/var.c index aca7399cd8c..5dfa2e52d84 100644 --- a/src/backend/optimizer/util/var.c +++ b/src/backend/optimizer/util/var.c @@ -943,11 +943,10 @@ flatten_join_alias_vars_mutator(Node *node, return node; /* no need to copy, really */ /* - * A pushed-down copy of a target-level PHV was already preprocessed - * by preprocess_subquery_phvs, so it may contain SubPlans and holds - * no unflattened target-level aliases; shallow-copy it instead of - * recursing. Any other PHV is recursed into, as it may still hold - * target-level aliases. + * A pushed-down copy of a target-level PHV is preprocessed by + * preprocess_subquery_phvs, which handles its target-level aliases + * and may leave SubPlans in it; so don't recurse into it. Any other + * PHV may still hold target-level aliases, so recurse. */ if (phv->phlevelsup == context->sublevels_up && context->sublevels_up > 0) diff --git a/src/test/regress/expected/join.out b/src/test/regress/expected/join.out index 75544fe6aa3..1f000d641eb 100644 --- a/src/test/regress/expected/join.out +++ b/src/test/regress/expected/join.out @@ -5182,7 +5182,7 @@ where i8.q2 = 123; QUERY PLAN --------------------------------------------------------------------- Nested Loop - Output: i8.q1, i8.q2, (InitPlan expr_2).col1, false, (i8.q2) + Output: i8.q1, i8.q2, (InitPlan expr_1).col1, false, (i8.q2) InitPlan expr_1 -> Result Output: true @@ -5195,7 +5195,7 @@ where i8.q2 = 123; -> Nested Loop Output: i8.q1, i8.q2, (i8.q2) -> Subquery Scan on ss1 - Output: ss1.y, (InitPlan expr_2).col1 + Output: ss1.y, (InitPlan expr_1).col1 -> Limit Output: NULL::integer -> Result @@ -5209,7 +5209,7 @@ where i8.q2 = 123; Output: (i8.q2) -> Result Output: i8.q2 - One-Time Filter: ((InitPlan expr_2).col1) + One-Time Filter: ((InitPlan expr_1).col1) (29 rows) explain (verbose, costs off) @@ -5225,7 +5225,7 @@ where i8.q2 = 123; QUERY PLAN --------------------------------------------------------------------- Nested Loop - Output: i8.q1, i8.q2, (InitPlan expr_2).col1, false, (i8.q2) + Output: i8.q1, i8.q2, (InitPlan expr_1).col1, false, (i8.q2) InitPlan expr_1 -> Result Output: true @@ -5239,7 +5239,7 @@ where i8.q2 = 123; -> Nested Loop Output: i8.q1, i8.q2, (i8.q2) -> Seq Scan on public.int4_tbl i4 - Output: i4.f1, (InitPlan expr_2).col1 + Output: i4.f1, (InitPlan expr_1).col1 Filter: (i4.f1 = 0) -> Nested Loop Output: i8.q1, i8.q2, (i8.q2) @@ -5250,7 +5250,7 @@ where i8.q2 = 123; Output: (i8.q2) -> Result Output: i8.q2 - One-Time Filter: ((InitPlan expr_2).col1) + One-Time Filter: ((InitPlan expr_1).col1) (27 rows) -- Test proper handling of appendrel PHVs during useless-RTE removal @@ -7357,25 +7357,25 @@ from (select case when false then remov.id else (select i41.f1) end as c1 QUERY PLAN --------------------------------------------------------- Nested Loop - Output: ((SubPlan expr_2)), (((SubPlan expr_2))) + Output: ((SubPlan expr_1)), (((SubPlan expr_1))) -> Nested Loop Left Join - Output: ((SubPlan expr_2)) + Output: ((SubPlan expr_1)) Join Filter: false -> Seq Scan on public.int4_tbl i42 Output: i42.f1 -> Result - Output: (SubPlan expr_2) + Output: (SubPlan expr_1) Replaces: Scan on i41 One-Time Filter: false - SubPlan expr_2 + SubPlan expr_1 -> Result Output: i41.f1 -> Memoize - Output: (((SubPlan expr_2))) - Cache Key: ((SubPlan expr_2)) + Output: (((SubPlan expr_1))) + Cache Key: ((SubPlan expr_1)) Cache Mode: binary -> Nested Loop - Output: ((SubPlan expr_2)) + Output: ((SubPlan expr_1)) -> Seq Scan on public.int4_tbl i43 Output: i43.f1 -> Materialize @@ -7430,6 +7430,97 @@ from (select case when false then remov.id else (select i41.f1) end as c1 Output: ((SubPlan expr_1)) (14 rows) +-- likewise, where the pushed-down PHV's expression contains another PHV of +-- the same level, which must not be preprocessed separately from its parent +explain (verbose, costs off) +select ss3.c2 +from int4_tbl i41 + left join (select coalesce(ss1.c1, 0) as c1 + from int4_tbl i42 + left join (select (select i43.f1) as c1 + from int4_tbl i43) ss1 on true) ss2 + on true, + lateral (select ss2.c1 as c2 from int4_tbl i44 offset 0) ss3; + QUERY PLAN +--------------------------------------------------------------- + Nested Loop + Output: ((COALESCE(((SubPlan expr_1)), 0))) + -> Nested Loop Left Join + Output: (COALESCE(((SubPlan expr_1)), 0)) + -> Seq Scan on public.int4_tbl i41 + Output: i41.f1 + -> Materialize + Output: (COALESCE(((SubPlan expr_1)), 0)) + -> Nested Loop Left Join + Output: COALESCE(((SubPlan expr_1)), 0) + -> Seq Scan on public.int4_tbl i42 + Output: i42.f1 + -> Materialize + Output: ((SubPlan expr_1)) + -> Seq Scan on public.int4_tbl i43 + Output: (SubPlan expr_1) + SubPlan expr_1 + -> Result + Output: i43.f1 + -> Memoize + Output: ((COALESCE(((SubPlan expr_1)), 0))) + Cache Key: (COALESCE(((SubPlan expr_1)), 0)) + Cache Mode: binary + -> Seq Scan on public.int4_tbl i44 + Output: (COALESCE(((SubPlan expr_1)), 0)) +(25 rows) + +-- likewise, where the PHV copy is only inserted into the LATERAL subquery by +-- expanding a join alias Var of the outer level +explain (verbose, costs off) +select ss2.c2 +from ((select (select i41.f1) as c1 from int4_tbl i41) ss1 + full join int4_tbl i42(c1) using (c1)) j, + lateral (select j.c1 as c2 from int4_tbl i43 offset 0) ss2; + QUERY PLAN +------------------------------------------------------ + Nested Loop + Output: (COALESCE(((SubPlan expr_1)), i42.c1)) + -> Hash Full Join + Output: ((SubPlan expr_1)), i42.c1 + Hash Cond: (((SubPlan expr_1)) = i42.c1) + -> Seq Scan on public.int4_tbl i41 + Output: (SubPlan expr_1) + SubPlan expr_1 + -> Result + Output: i41.f1 + -> Hash + Output: i42.c1 + -> Seq Scan on public.int4_tbl i42 + Output: i42.c1 + -> Seq Scan on public.int4_tbl i43 + Output: COALESCE(((SubPlan expr_1)), i42.c1) +(16 rows) + +-- likewise, where the join alias is expanded within a SubLink's subselect +explain (verbose, costs off) +select (select j.c1 from int4_tbl i43 offset 0) as c2 +from ((select (select i41.f1) as c1 from int4_tbl i41) ss1 + full join int4_tbl i42(c1) using (c1)) j; + QUERY PLAN +-------------------------------------------------------- + Hash Full Join + Output: (SubPlan expr_2) + Hash Cond: (((SubPlan expr_1)) = i42.c1) + -> Seq Scan on public.int4_tbl i41 + Output: (SubPlan expr_1) + SubPlan expr_1 + -> Result + Output: i41.f1 + -> Hash + Output: i42.c1 + -> Seq Scan on public.int4_tbl i42 + Output: i42.c1 + SubPlan expr_2 + -> Seq Scan on public.int4_tbl i43 + Output: COALESCE(((SubPlan expr_1)), i42.c1) +(15 rows) + -- More tests of correct placement of pseudoconstant quals -- simple constant-false condition explain (costs off) diff --git a/src/test/regress/sql/join.sql b/src/test/regress/sql/join.sql index fb83a96e939..e3955305e42 100644 --- a/src/test/regress/sql/join.sql +++ b/src/test/regress/sql/join.sql @@ -2746,6 +2746,32 @@ from (select case when false then remov.id else (select i41.f1) end as c1 from int4_tbl i41 left join a remov on i41.f1 = remov.id) ss1 right join int4_tbl i42 on true; +-- likewise, where the pushed-down PHV's expression contains another PHV of +-- the same level, which must not be preprocessed separately from its parent +explain (verbose, costs off) +select ss3.c2 +from int4_tbl i41 + left join (select coalesce(ss1.c1, 0) as c1 + from int4_tbl i42 + left join (select (select i43.f1) as c1 + from int4_tbl i43) ss1 on true) ss2 + on true, + lateral (select ss2.c1 as c2 from int4_tbl i44 offset 0) ss3; + +-- likewise, where the PHV copy is only inserted into the LATERAL subquery by +-- expanding a join alias Var of the outer level +explain (verbose, costs off) +select ss2.c2 +from ((select (select i41.f1) as c1 from int4_tbl i41) ss1 + full join int4_tbl i42(c1) using (c1)) j, + lateral (select j.c1 as c2 from int4_tbl i43 offset 0) ss2; + +-- likewise, where the join alias is expanded within a SubLink's subselect +explain (verbose, costs off) +select (select j.c1 from int4_tbl i43 offset 0) as c2 +from ((select (select i41.f1) as c1 from int4_tbl i41) ss1 + full join int4_tbl i42(c1) using (c1)) j; + -- More tests of correct placement of pseudoconstant quals -- simple constant-false condition -- 2.37.1 (Apple Git-137.1)
^ permalink raw reply [nested|flat] 74+ messages in thread

* Re: remove_useless_joins vs. bug #19560
  2026-07-20 18:52 remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-24 13:38 ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-07-25 16:46   ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-25 20:07     ` Re: remove_useless_joins vs. bug #19560 Thom Brown <thom@linux.com>
  2026-07-25 21:23       ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-26 02:15         ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-26 09:49           ` Re: remove_useless_joins vs. bug #19560 Thom Brown <thom@linux.com>
  2026-07-26 17:33             ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-26 17:35               ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-27 07:07                 ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-07-27 16:33                   ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-27 18:21                     ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-29 06:21                       ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-16 23:58                         ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-26 05:26                           ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-26 17:25                             ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-27 01:57                               ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-27 15:53                                 ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-28 07:29                                   ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-28 13:43                                     ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-29 03:27                                       ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-29 20:10                                         ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-30 06:50                                           ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-30 16:20                                             ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-31 01:54                                               ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-09-03 14:55                                                 ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-09-09 08:04                                                   ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-09-09 14:54                                                     ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-09-10 09:33                                                       ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-09-13 17:32                                                         ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-09-14 05:10                                                           ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-09-15 16:28                                                             ` Re: remove_useless_joins vs. bug #19560 Fujii Masao <masao.fujii@gmail.com>
  2026-09-16 04:56                                                               ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
@ 2026-09-19 13:14                                                                 ` Richard Guo <guofenglinux@gmail.com>
  2026-09-25 11:43                                                                   ` Re: remove_useless_joins vs. bug #19560 Ayush Tiwari <ayushtiwari.slg01@gmail.com>
  0 siblings, 1 reply; 74+ messages in thread

From: Richard Guo @ 2026-09-19 13:14 UTC (permalink / raw)
  To: Fujii Masao <masao.fujii@gmail.com>; +Cc: Tom Lane <tgl@sss.pgh.pa.us>; Tender Wang <tndrwang@gmail.com>; Thom Brown <thom@linux.com>; Jacob Brazeal <jacob.brazeal@gmail.com>; pgsql-hackers@lists.postgresql.org

On Wed, Sep 16, 2026 at 1:56 PM Richard Guo <guofenglinux@gmail.com> wrote:
> I think we have to insist that the preprocessing happens after join
> alias expansion, which is what my v2 patch in [1] did.  But that patch
> was not complete: as I explained in [2], it doesn't handle copies that
> were pushed into a SubLink's subselect.  I think we can cover those by
> also running the preprocessing in preprocess_expression, right before
> SS_process_sublinks.  That way each upper-level PHV is preprocessed
> exactly once, at the level it belongs to, and always after join alias
> expansion.
>
> Hence, the attached fix.

I've pushed this patch and back-patched it to v16.

- Richard






^ permalink  raw  reply  [nested|flat] 74+ messages in thread

* Re: remove_useless_joins vs. bug #19560
  2026-07-20 18:52 remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-24 13:38 ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-07-25 16:46   ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-25 20:07     ` Re: remove_useless_joins vs. bug #19560 Thom Brown <thom@linux.com>
  2026-07-25 21:23       ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-26 02:15         ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-26 09:49           ` Re: remove_useless_joins vs. bug #19560 Thom Brown <thom@linux.com>
  2026-07-26 17:33             ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-26 17:35               ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-27 07:07                 ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-07-27 16:33                   ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-27 18:21                     ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-29 06:21                       ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-16 23:58                         ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-26 05:26                           ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-26 17:25                             ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-27 01:57                               ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-27 15:53                                 ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-28 07:29                                   ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-28 13:43                                     ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-29 03:27                                       ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-29 20:10                                         ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-30 06:50                                           ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-30 16:20                                             ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-31 01:54                                               ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-09-03 14:55                                                 ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-09-09 08:04                                                   ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-09-09 14:54                                                     ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-09-10 09:33                                                       ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-09-13 17:32                                                         ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-09-14 05:10                                                           ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-09-15 16:28                                                             ` Re: remove_useless_joins vs. bug #19560 Fujii Masao <masao.fujii@gmail.com>
  2026-09-16 04:56                                                               ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-09-19 13:14                                                                 ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
@ 2026-09-25 11:43                                                                   ` Ayush Tiwari <ayushtiwari.slg01@gmail.com>
  2026-10-03 18:43                                                                     ` Re: remove_useless_joins vs. bug #19560 Ayush Tiwari <ayushtiwari.slg01@gmail.com>
  2026-10-04 06:14                                                                     ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  0 siblings, 2 replies; 74+ messages in thread

From: Ayush Tiwari @ 2026-09-25 11:43 UTC (permalink / raw)
  To: Richard Guo <guofenglinux@gmail.com>; +Cc: Tom Lane <tgl@sss.pgh.pa.us>; pgsql-hackers@lists.postgresql.org

Hi,

Could there be one more case here with a PHV inside an outer-level
aggregate? On master at e27f3b2cad7, after bee81f78646, this still
trips an assertion:

    create table t (a int);

    explain (verbose, costs off)
    select (select sum(ss.c) from t i offset 0)
    from (select (select s.a) as c from t s) ss
         right join t o on true;

    TRAP: failed Assert("!IsA(node, SubPlan)"), File: "subselect.c"

IIUC, build_subplan() already leaves a bare PHV argument alone, but
an Aggref argument can contain the same preprocessed PHV. Walking
the Aggref seems to enter that PHV again and reach the SubPlan
created earlier.

Would it make sense to skip PHVs during that argument walk too,
while still processing other SubLinks in the argument? The attached
patch tries that, with small tests for sum() and GROUPING().

I haven't seen a wrong result or crash without assertions though.

Regards,
Ayush

Attachments:

v1-0001-Don-t-reprocess-PHV-copies-within-outer-level-agg.patch (application/octet-stream, 7.4K) download From f17e2ce536ffe11487c7d286e8779cdb616f2a90 Mon Sep 17 00:00:00 2001 From: Ayush Tiwari <ayushtiwari.slg01@gmail.com> Date: Fri, 25 Sep 2026 13:25:58 +0530 Subject: [PATCH v1] Don't reprocess PHV copies within outer-level aggregate arguments Commit e28cf96e9 arranged for each query level to preprocess the copies of its PlaceHolderVars that were pushed down into subqueries, so such a copy may already contain SubPlans by the time build_subplan collects it as an argument for a SubPlan. Accordingly, build_subplan stopped running SS_process_sublinks on a PlaceHolderVar argument. However, it still runs SS_process_sublinks on the arguments of an outer-level Aggref, GroupingFunc, or ReturningExpr, and those arguments can contain the same already-preprocessed PHV copies, as in select (select sum(ss.c) from t i offset 0) from (select (select s.a) as c from t s) ss right join t o on true; Walking into such a copy there trips the assertion in process_sublinks_mutator that it never sees a SubPlan. Builds without assertions just copy the SubPlan, which seems harmless. To fix, skip PlaceHolderVars when processing SubLinks within those arguments, just as for a bare PlaceHolderVar argument. Any other SubLinks in the arguments are still processed there, as before. Oversight in e28cf96e9, which was back-patched to v16. --- src/backend/optimizer/plan/subselect.c | 17 +++++++-- src/test/regress/expected/join.out | 53 ++++++++++++++++++++++++++ src/test/regress/sql/join.sql | 14 +++++++ 3 files changed, 81 insertions(+), 3 deletions(-) diff --git a/src/backend/optimizer/plan/subselect.c b/src/backend/optimizer/plan/subselect.c index 5760b616813..1a8fb6e78a4 100644 --- a/src/backend/optimizer/plan/subselect.c +++ b/src/backend/optimizer/plan/subselect.c @@ -50,6 +50,7 @@ typedef struct process_sublinks_context { PlannerInfo *root; bool isTopQual; + bool skipPHVs; /* all PHVs are already preprocessed */ } process_sublinks_context; typedef struct finalize_primnode_context @@ -376,12 +377,20 @@ build_subplan(PlannerInfo *root, Plan *plan, Path *path, * comments for SS_replace_correlation_vars). Do that now. A * PlaceHolderVar needs no such treatment: subquery_planner already * preprocessed the PHVs of its owning level, so its expression is - * fully processed and may already contain SubPlans. + * fully processed and may already contain SubPlans. That's also true + * of any PlaceHolderVar within the arguments, so skip those. */ if (IsA(arg, Aggref) || IsA(arg, GroupingFunc) || IsA(arg, ReturningExpr)) - arg = SS_process_sublinks(root, arg, false); + { + process_sublinks_context context; + + context.root = root; + context.isTopQual = false; + context.skipPHVs = true; + arg = process_sublinks_mutator(arg, &context); + } splan->parParam = lappend_int(splan->parParam, pitem->paramId); splan->args = lappend(splan->args, arg); @@ -2217,6 +2226,7 @@ SS_process_sublinks(PlannerInfo *root, Node *expr, bool isQual) context.root = root; context.isTopQual = isQual; + context.skipPHVs = false; return process_sublinks_mutator(expr, &context); } @@ -2226,6 +2236,7 @@ process_sublinks_mutator(Node *node, process_sublinks_context *context) process_sublinks_context locContext; locContext.root = context->root; + locContext.skipPHVs = context->skipPHVs; if (node == NULL) return NULL; @@ -2262,7 +2273,7 @@ process_sublinks_mutator(Node *node, process_sublinks_context *context) */ if (IsA(node, PlaceHolderVar)) { - if (((PlaceHolderVar *) node)->phlevelsup > 0) + if (((PlaceHolderVar *) node)->phlevelsup > 0 || context->skipPHVs) return node; } else if (IsA(node, Aggref)) diff --git a/src/test/regress/expected/join.out b/src/test/regress/expected/join.out index 94e158d0dc6..38c25e7be69 100644 --- a/src/test/regress/expected/join.out +++ b/src/test/regress/expected/join.out @@ -7430,6 +7430,59 @@ from (select case when false then remov.id else (select i41.f1) end as c1 Output: ((SubPlan expr_1)) (14 rows) +-- likewise, where the PHV copy is within the argument of an outer-level +-- aggregate, which is processed for SubLinks while building the SubPlan +explain (verbose, costs off) +select (select sum(ss1.c1) from int4_tbl i43 offset 0) as c2 +from (select (select i41.f1) as c1 from int4_tbl i41) ss1 + right join int4_tbl i42 on true; + QUERY PLAN +--------------------------------------------------- + Aggregate + Output: (SubPlan expr_2) + -> Nested Loop Left Join + Output: ((SubPlan expr_1)) + -> Seq Scan on public.int4_tbl i42 + Output: i42.f1 + -> Materialize + Output: ((SubPlan expr_1)) + -> Seq Scan on public.int4_tbl i41 + Output: (SubPlan expr_1) + SubPlan expr_1 + -> Result + Output: i41.f1 + SubPlan expr_2 + -> Seq Scan on public.int4_tbl i43 + Output: sum(((SubPlan expr_1))) +(16 rows) + +-- likewise, where the PHV copy is within an outer-level GROUPING() +explain (verbose, costs off) +select (select grouping(ss1.c1) from int4_tbl i43 offset 0) as c2 +from (select (select i41.f1) as c1 from int4_tbl i41) ss1 + right join int4_tbl i42 on true +group by ss1.c1; + QUERY PLAN +--------------------------------------------------- + HashAggregate + Output: (SubPlan expr_2), ((SubPlan expr_1)) + Group Key: ((SubPlan expr_1)) + -> Nested Loop Left Join + Output: ((SubPlan expr_1)) + -> Seq Scan on public.int4_tbl i42 + Output: i42.f1 + -> Materialize + Output: ((SubPlan expr_1)) + -> Seq Scan on public.int4_tbl i41 + Output: (SubPlan expr_1) + SubPlan expr_1 + -> Result + Output: i41.f1 + SubPlan expr_2 + -> Seq Scan on public.int4_tbl i43 + Output: GROUPING(((SubPlan expr_1))) +(17 rows) + -- likewise, where the pushed-down PHV's expression contains another PHV of -- the same level, which must not be preprocessed separately from its parent explain (verbose, costs off) diff --git a/src/test/regress/sql/join.sql b/src/test/regress/sql/join.sql index 576a90dfc1b..70d7e393576 100644 --- a/src/test/regress/sql/join.sql +++ b/src/test/regress/sql/join.sql @@ -2746,6 +2746,20 @@ from (select case when false then remov.id else (select i41.f1) end as c1 from int4_tbl i41 left join a remov on i41.f1 = remov.id) ss1 right join int4_tbl i42 on true; +-- likewise, where the PHV copy is within the argument of an outer-level +-- aggregate, which is processed for SubLinks while building the SubPlan +explain (verbose, costs off) +select (select sum(ss1.c1) from int4_tbl i43 offset 0) as c2 +from (select (select i41.f1) as c1 from int4_tbl i41) ss1 + right join int4_tbl i42 on true; + +-- likewise, where the PHV copy is within an outer-level GROUPING() +explain (verbose, costs off) +select (select grouping(ss1.c1) from int4_tbl i43 offset 0) as c2 +from (select (select i41.f1) as c1 from int4_tbl i41) ss1 + right join int4_tbl i42 on true +group by ss1.c1; + -- likewise, where the pushed-down PHV's expression contains another PHV of -- the same level, which must not be preprocessed separately from its parent explain (verbose, costs off) -- 2.34.1
^ permalink raw reply [nested|flat] 74+ messages in thread

* Re: remove_useless_joins vs. bug #19560
  2026-07-20 18:52 remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-24 13:38 ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-07-25 16:46   ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-25 20:07     ` Re: remove_useless_joins vs. bug #19560 Thom Brown <thom@linux.com>
  2026-07-25 21:23       ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-26 02:15         ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-26 09:49           ` Re: remove_useless_joins vs. bug #19560 Thom Brown <thom@linux.com>
  2026-07-26 17:33             ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-26 17:35               ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-27 07:07                 ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-07-27 16:33                   ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-27 18:21                     ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-29 06:21                       ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-16 23:58                         ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-26 05:26                           ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-26 17:25                             ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-27 01:57                               ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-27 15:53                                 ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-28 07:29                                   ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-28 13:43                                     ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-29 03:27                                       ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-29 20:10                                         ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-30 06:50                                           ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-30 16:20                                             ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-31 01:54                                               ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-09-03 14:55                                                 ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-09-09 08:04                                                   ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-09-09 14:54                                                     ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-09-10 09:33                                                       ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-09-13 17:32                                                         ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-09-14 05:10                                                           ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-09-15 16:28                                                             ` Re: remove_useless_joins vs. bug #19560 Fujii Masao <masao.fujii@gmail.com>
  2026-09-16 04:56                                                               ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-09-19 13:14                                                                 ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-09-25 11:43                                                                   ` Re: remove_useless_joins vs. bug #19560 Ayush Tiwari <ayushtiwari.slg01@gmail.com>
@ 2026-10-03 18:43                                                                     ` Ayush Tiwari <ayushtiwari.slg01@gmail.com>
  1 sibling, 0 replies; 74+ messages in thread

From: Ayush Tiwari @ 2026-10-03 18:43 UTC (permalink / raw)
  To: Richard Guo <guofenglinux@gmail.com>; +Cc: Tom Lane <tgl@sss.pgh.pa.us>; pgsql-hackers@lists.postgresql.org

Hi,

On Fri, 25 Sept 2026 at 17:13, Ayush Tiwari <ayushtiwari.slg01@gmail.com> wrote:
>
> Hi,
>
> Could there be one more case here with a PHV inside an outer-level
> aggregate? On master at e27f3b2cad7, after bee81f78646, this still
> trips an assertion:
>
>     create table t (a int);
>
>     explain (verbose, costs off)
>     select (select sum(ss.c) from t i offset 0)
>     from (select (select s.a) as c from t s) ss
>          right join t o on true;
>
>     TRAP: failed Assert("!IsA(node, SubPlan)"), File: "subselect.c"
>
> IIUC, build_subplan() already leaves a bare PHV argument alone, but
> an Aggref argument can contain the same preprocessed PHV. Walking
> the Aggref seems to enter that PHV again and reach the SubPlan
> created earlier.
>
> Would it make sense to skip PHVs during that argument walk too,
> while still processing other SubLinks in the argument? The attached
> patch tries that, with small tests for sum() and GROUPING().
>
> I haven't seen a wrong result or crash without assertions though.

Resending attachment for commitfest entry.

Regards,
Ayush

Attachments:

v1-0001-Don-t-reprocess-PHV-copies-within-outer-level-agg.patch (application/octet-stream, 7.4K) download From f17e2ce536ffe11487c7d286e8779cdb616f2a90 Mon Sep 17 00:00:00 2001 From: Ayush Tiwari <ayushtiwari.slg01@gmail.com> Date: Fri, 25 Sep 2026 13:25:58 +0530 Subject: [PATCH v1] Don't reprocess PHV copies within outer-level aggregate arguments Commit e28cf96e9 arranged for each query level to preprocess the copies of its PlaceHolderVars that were pushed down into subqueries, so such a copy may already contain SubPlans by the time build_subplan collects it as an argument for a SubPlan. Accordingly, build_subplan stopped running SS_process_sublinks on a PlaceHolderVar argument. However, it still runs SS_process_sublinks on the arguments of an outer-level Aggref, GroupingFunc, or ReturningExpr, and those arguments can contain the same already-preprocessed PHV copies, as in select (select sum(ss.c) from t i offset 0) from (select (select s.a) as c from t s) ss right join t o on true; Walking into such a copy there trips the assertion in process_sublinks_mutator that it never sees a SubPlan. Builds without assertions just copy the SubPlan, which seems harmless. To fix, skip PlaceHolderVars when processing SubLinks within those arguments, just as for a bare PlaceHolderVar argument. Any other SubLinks in the arguments are still processed there, as before. Oversight in e28cf96e9, which was back-patched to v16. --- src/backend/optimizer/plan/subselect.c | 17 +++++++-- src/test/regress/expected/join.out | 53 ++++++++++++++++++++++++++ src/test/regress/sql/join.sql | 14 +++++++ 3 files changed, 81 insertions(+), 3 deletions(-) diff --git a/src/backend/optimizer/plan/subselect.c b/src/backend/optimizer/plan/subselect.c index 5760b616813..1a8fb6e78a4 100644 --- a/src/backend/optimizer/plan/subselect.c +++ b/src/backend/optimizer/plan/subselect.c @@ -50,6 +50,7 @@ typedef struct process_sublinks_context { PlannerInfo *root; bool isTopQual; + bool skipPHVs; /* all PHVs are already preprocessed */ } process_sublinks_context; typedef struct finalize_primnode_context @@ -376,12 +377,20 @@ build_subplan(PlannerInfo *root, Plan *plan, Path *path, * comments for SS_replace_correlation_vars). Do that now. A * PlaceHolderVar needs no such treatment: subquery_planner already * preprocessed the PHVs of its owning level, so its expression is - * fully processed and may already contain SubPlans. + * fully processed and may already contain SubPlans. That's also true + * of any PlaceHolderVar within the arguments, so skip those. */ if (IsA(arg, Aggref) || IsA(arg, GroupingFunc) || IsA(arg, ReturningExpr)) - arg = SS_process_sublinks(root, arg, false); + { + process_sublinks_context context; + + context.root = root; + context.isTopQual = false; + context.skipPHVs = true; + arg = process_sublinks_mutator(arg, &context); + } splan->parParam = lappend_int(splan->parParam, pitem->paramId); splan->args = lappend(splan->args, arg); @@ -2217,6 +2226,7 @@ SS_process_sublinks(PlannerInfo *root, Node *expr, bool isQual) context.root = root; context.isTopQual = isQual; + context.skipPHVs = false; return process_sublinks_mutator(expr, &context); } @@ -2226,6 +2236,7 @@ process_sublinks_mutator(Node *node, process_sublinks_context *context) process_sublinks_context locContext; locContext.root = context->root; + locContext.skipPHVs = context->skipPHVs; if (node == NULL) return NULL; @@ -2262,7 +2273,7 @@ process_sublinks_mutator(Node *node, process_sublinks_context *context) */ if (IsA(node, PlaceHolderVar)) { - if (((PlaceHolderVar *) node)->phlevelsup > 0) + if (((PlaceHolderVar *) node)->phlevelsup > 0 || context->skipPHVs) return node; } else if (IsA(node, Aggref)) diff --git a/src/test/regress/expected/join.out b/src/test/regress/expected/join.out index 94e158d0dc6..38c25e7be69 100644 --- a/src/test/regress/expected/join.out +++ b/src/test/regress/expected/join.out @@ -7430,6 +7430,59 @@ from (select case when false then remov.id else (select i41.f1) end as c1 Output: ((SubPlan expr_1)) (14 rows) +-- likewise, where the PHV copy is within the argument of an outer-level +-- aggregate, which is processed for SubLinks while building the SubPlan +explain (verbose, costs off) +select (select sum(ss1.c1) from int4_tbl i43 offset 0) as c2 +from (select (select i41.f1) as c1 from int4_tbl i41) ss1 + right join int4_tbl i42 on true; + QUERY PLAN +--------------------------------------------------- + Aggregate + Output: (SubPlan expr_2) + -> Nested Loop Left Join + Output: ((SubPlan expr_1)) + -> Seq Scan on public.int4_tbl i42 + Output: i42.f1 + -> Materialize + Output: ((SubPlan expr_1)) + -> Seq Scan on public.int4_tbl i41 + Output: (SubPlan expr_1) + SubPlan expr_1 + -> Result + Output: i41.f1 + SubPlan expr_2 + -> Seq Scan on public.int4_tbl i43 + Output: sum(((SubPlan expr_1))) +(16 rows) + +-- likewise, where the PHV copy is within an outer-level GROUPING() +explain (verbose, costs off) +select (select grouping(ss1.c1) from int4_tbl i43 offset 0) as c2 +from (select (select i41.f1) as c1 from int4_tbl i41) ss1 + right join int4_tbl i42 on true +group by ss1.c1; + QUERY PLAN +--------------------------------------------------- + HashAggregate + Output: (SubPlan expr_2), ((SubPlan expr_1)) + Group Key: ((SubPlan expr_1)) + -> Nested Loop Left Join + Output: ((SubPlan expr_1)) + -> Seq Scan on public.int4_tbl i42 + Output: i42.f1 + -> Materialize + Output: ((SubPlan expr_1)) + -> Seq Scan on public.int4_tbl i41 + Output: (SubPlan expr_1) + SubPlan expr_1 + -> Result + Output: i41.f1 + SubPlan expr_2 + -> Seq Scan on public.int4_tbl i43 + Output: GROUPING(((SubPlan expr_1))) +(17 rows) + -- likewise, where the pushed-down PHV's expression contains another PHV of -- the same level, which must not be preprocessed separately from its parent explain (verbose, costs off) diff --git a/src/test/regress/sql/join.sql b/src/test/regress/sql/join.sql index 576a90dfc1b..70d7e393576 100644 --- a/src/test/regress/sql/join.sql +++ b/src/test/regress/sql/join.sql @@ -2746,6 +2746,20 @@ from (select case when false then remov.id else (select i41.f1) end as c1 from int4_tbl i41 left join a remov on i41.f1 = remov.id) ss1 right join int4_tbl i42 on true; +-- likewise, where the PHV copy is within the argument of an outer-level +-- aggregate, which is processed for SubLinks while building the SubPlan +explain (verbose, costs off) +select (select sum(ss1.c1) from int4_tbl i43 offset 0) as c2 +from (select (select i41.f1) as c1 from int4_tbl i41) ss1 + right join int4_tbl i42 on true; + +-- likewise, where the PHV copy is within an outer-level GROUPING() +explain (verbose, costs off) +select (select grouping(ss1.c1) from int4_tbl i43 offset 0) as c2 +from (select (select i41.f1) as c1 from int4_tbl i41) ss1 + right join int4_tbl i42 on true +group by ss1.c1; + -- likewise, where the pushed-down PHV's expression contains another PHV of -- the same level, which must not be preprocessed separately from its parent explain (verbose, costs off) -- 2.34.1
^ permalink raw reply [nested|flat] 74+ messages in thread

* Re: remove_useless_joins vs. bug #19560
  2026-07-20 18:52 remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-24 13:38 ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-07-25 16:46   ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-25 20:07     ` Re: remove_useless_joins vs. bug #19560 Thom Brown <thom@linux.com>
  2026-07-25 21:23       ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-26 02:15         ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-26 09:49           ` Re: remove_useless_joins vs. bug #19560 Thom Brown <thom@linux.com>
  2026-07-26 17:33             ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-26 17:35               ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-27 07:07                 ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-07-27 16:33                   ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-27 18:21                     ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-29 06:21                       ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-16 23:58                         ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-26 05:26                           ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-26 17:25                             ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-27 01:57                               ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-27 15:53                                 ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-28 07:29                                   ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-28 13:43                                     ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-29 03:27                                       ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-29 20:10                                         ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-30 06:50                                           ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-30 16:20                                             ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-31 01:54                                               ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-09-03 14:55                                                 ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-09-09 08:04                                                   ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-09-09 14:54                                                     ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-09-10 09:33                                                       ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-09-13 17:32                                                         ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-09-14 05:10                                                           ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-09-15 16:28                                                             ` Re: remove_useless_joins vs. bug #19560 Fujii Masao <masao.fujii@gmail.com>
  2026-09-16 04:56                                                               ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-09-19 13:14                                                                 ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-09-25 11:43                                                                   ` Re: remove_useless_joins vs. bug #19560 Ayush Tiwari <ayushtiwari.slg01@gmail.com>
@ 2026-10-04 06:14                                                                     ` Richard Guo <guofenglinux@gmail.com>
  2026-10-06 02:04                                                                       ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  1 sibling, 1 reply; 74+ messages in thread

From: Richard Guo @ 2026-10-04 06:14 UTC (permalink / raw)
  To: Ayush Tiwari <ayushtiwari.slg01@gmail.com>; +Cc: Tom Lane <tgl@sss.pgh.pa.us>; pgsql-hackers@lists.postgresql.org

On Fri, Sep 25, 2026 at 8:43 PM Ayush Tiwari
<ayushtiwari.slg01@gmail.com> wrote:
> Would it make sense to skip PHVs during that argument walk too,
> while still processing other SubLinks in the argument? The attached
> patch tries that, with small tests for sum() and GROUPING().

Skipping PHVs in build_subplan looks right to me.  Any PHV found
within the arguments of an outer-level Aggref is a pushed-down copy
that its owning level has already preprocessed, so there is nothing
left to do in it.  The flag looks ugly though, but I don't have a
better fix than that.

I plan to push this fix soon if there are no objections.

- Richard






^ permalink  raw  reply  [nested|flat] 74+ messages in thread

* Re: remove_useless_joins vs. bug #19560
  2026-07-20 18:52 remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-24 13:38 ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-07-25 16:46   ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-25 20:07     ` Re: remove_useless_joins vs. bug #19560 Thom Brown <thom@linux.com>
  2026-07-25 21:23       ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-26 02:15         ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-26 09:49           ` Re: remove_useless_joins vs. bug #19560 Thom Brown <thom@linux.com>
  2026-07-26 17:33             ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-26 17:35               ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-27 07:07                 ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-07-27 16:33                   ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-27 18:21                     ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-29 06:21                       ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-16 23:58                         ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-26 05:26                           ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-26 17:25                             ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-27 01:57                               ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-27 15:53                                 ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-28 07:29                                   ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-28 13:43                                     ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-29 03:27                                       ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-29 20:10                                         ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-30 06:50                                           ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-30 16:20                                             ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-31 01:54                                               ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-09-03 14:55                                                 ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-09-09 08:04                                                   ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-09-09 14:54                                                     ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-09-10 09:33                                                       ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-09-13 17:32                                                         ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-09-14 05:10                                                           ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-09-15 16:28                                                             ` Re: remove_useless_joins vs. bug #19560 Fujii Masao <masao.fujii@gmail.com>
  2026-09-16 04:56                                                               ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-09-19 13:14                                                                 ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-09-25 11:43                                                                   ` Re: remove_useless_joins vs. bug #19560 Ayush Tiwari <ayushtiwari.slg01@gmail.com>
  2026-10-04 06:14                                                                     ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
@ 2026-10-06 02:04                                                                       ` Richard Guo <guofenglinux@gmail.com>
  0 siblings, 0 replies; 74+ messages in thread

From: Richard Guo @ 2026-10-06 02:04 UTC (permalink / raw)
  To: Ayush Tiwari <ayushtiwari.slg01@gmail.com>; +Cc: Tom Lane <tgl@sss.pgh.pa.us>; pgsql-hackers@lists.postgresql.org

On Sun, Oct 4, 2026 at 3:14 PM Richard Guo <guofenglinux@gmail.com> wrote:
> Skipping PHVs in build_subplan looks right to me.  Any PHV found
> within the arguments of an outer-level Aggref is a pushed-down copy
> that its owning level has already preprocessed, so there is nothing
> left to do in it.  The flag looks ugly though, but I don't have a
> better fix than that.
>
> I plan to push this fix soon if there are no objections.

Done.

- Richard






^ permalink  raw  reply  [nested|flat] 74+ messages in thread

* Re: remove_useless_joins vs. bug #19560
  2026-07-20 18:52 remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-24 13:38 ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-07-25 16:46   ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-25 20:07     ` Re: remove_useless_joins vs. bug #19560 Thom Brown <thom@linux.com>
  2026-07-25 21:23       ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-26 02:15         ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-26 09:49           ` Re: remove_useless_joins vs. bug #19560 Thom Brown <thom@linux.com>
  2026-07-26 17:33             ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-26 17:35               ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-27 07:07                 ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-07-27 16:33                   ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-27 18:21                     ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-29 06:21                       ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-16 23:58                         ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-26 05:26                           ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-26 17:25                             ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-27 01:57                               ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-27 15:53                                 ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-28 07:29                                   ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-28 13:43                                     ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-29 03:27                                       ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-29 20:10                                         ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-30 06:50                                           ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-30 16:20                                             ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
@ 2026-08-31 01:55                                               ` Tender Wang <tndrwang@gmail.com>
  2026-08-31 07:32                                                 ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  1 sibling, 1 reply; 74+ messages in thread

From: Tender Wang @ 2026-08-31 01:55 UTC (permalink / raw)
  To: Tom Lane <tgl@sss.pgh.pa.us>; +Cc: Richard Guo <guofenglinux@gmail.com>; Thom Brown <thom@linux.com>; Jacob Brazeal <jacob.brazeal@gmail.com>; pgsql-hackers@lists.postgresql.org

Tom Lane <tgl@sss.pgh.pa.us> 于2026年8月31日周一 00:20写道:
>
> Richard Guo <guofenglinux@gmail.com> writes:
> > ... The exception is
> > flatten_join_alias_vars, which descends into every PHV and asserts on
> > SubPlans.  I changed it to leave PHVs of upper levels alone; such a
> > PHV cannot contain join aliases of the level being flattened anyway.
>
> BTW, this comment reminds me strongly of an earlier draft I had,
> which eliminated the assertion failure by just not letting
> ChangeVarNodes recurse into outer-level PHVs, on the grounds that
> we can ignore their contents until they get replaced by Params.
> That didn't seem terribly principled on its own, so I also made
> eval_const_expressions not do anything to outer-level PHVs, but
> then I started to wonder just how far the implications should extend.
> When I realized that a localized fix in extract_lateral_references()
> seemed possible I gave up on that approach.  But maybe it's the way
> to go.  It has the attractive property of removing useless work.
> Attached is as far as I got with the idea before switching to the
> other way.

Thanks for the fix. It fixes the crash I reported earlier.

While testing the patched version, I found another crash with the
following query:

regression=# explain SELECT
FROM public.rtest_vview4 AS ref_0
     LEFT JOIN (fkpart5.pk AS sample_0
                LEFT JOIN pg_catalog.pg_stat_user_functions AS ref_1 ON NULL)
        ON NULL
     INNER JOIN public.skip_wal_skip_rewrite_index AS sample_5 ON
sample_0.a IS NULL,
     LATERAL (SELECT
              WHERE ref_1.schemaname IS NULL) AS subq_1;
server closed the connection unexpectedly
This probably means the server terminated abnormally
before or while processing the request.
The connection to the server was lost. Attempting reset: Succeeded.


-- 
Thanks,
Tender Wang






^ permalink  raw  reply  [nested|flat] 74+ messages in thread

* Re: remove_useless_joins vs. bug #19560
  2026-07-20 18:52 remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-24 13:38 ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-07-25 16:46   ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-25 20:07     ` Re: remove_useless_joins vs. bug #19560 Thom Brown <thom@linux.com>
  2026-07-25 21:23       ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-26 02:15         ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-26 09:49           ` Re: remove_useless_joins vs. bug #19560 Thom Brown <thom@linux.com>
  2026-07-26 17:33             ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-26 17:35               ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-27 07:07                 ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-07-27 16:33                   ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-27 18:21                     ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-29 06:21                       ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-16 23:58                         ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-26 05:26                           ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-26 17:25                             ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-27 01:57                               ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-27 15:53                                 ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-28 07:29                                   ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-28 13:43                                     ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-29 03:27                                       ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-29 20:10                                         ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-30 06:50                                           ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-30 16:20                                             ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-31 01:55                                               ` Re: remove_useless_joins vs. bug #19560 Tender Wang <tndrwang@gmail.com>
@ 2026-08-31 07:32                                                 ` Richard Guo <guofenglinux@gmail.com>
  2026-08-31 15:56                                                   ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  0 siblings, 1 reply; 74+ messages in thread

From: Richard Guo @ 2026-08-31 07:32 UTC (permalink / raw)
  To: Tender Wang <tndrwang@gmail.com>; +Cc: Tom Lane <tgl@sss.pgh.pa.us>; Thom Brown <thom@linux.com>; Jacob Brazeal <jacob.brazeal@gmail.com>; pgsql-hackers@lists.postgresql.org

On Mon, Aug 31, 2026 at 10:55 AM Tender Wang <tndrwang@gmail.com> wrote:
> regression=# explain SELECT
> FROM public.rtest_vview4 AS ref_0
>      LEFT JOIN (fkpart5.pk AS sample_0
>                 LEFT JOIN pg_catalog.pg_stat_user_functions AS ref_1 ON NULL)
>         ON NULL
>      INNER JOIN public.skip_wal_skip_rewrite_index AS sample_5 ON
> sample_0.a IS NULL,
>      LATERAL (SELECT
>               WHERE ref_1.schemaname IS NULL) AS subq_1;
> server closed the connection unexpectedly

Interesting.  What's happening is that "sample_0.a IS NULL" causes the
upper left join to be reduced to an antijoin.  "n.nspname IS NULL"
then becomes redundant and is discarded by check_redundant_nullability_qual,
so its Var is not counted in attr_needed; but the qual itself still
exists in the jointree.  Join removal thus sees no reference to n and
removes the p/n join, and then ChangeVarNodes finds n.nspname still
sitting in the tree and hits the Assert.

According to that, I can reproduce this same issue with the query
below:

create table t (a int primary key);

select 1 from t t1 left join
  (t t2 left join t t3 on t3.a = t2.a) on true
where t2.a is null and t3.a is null;

I think the real problem is that we leave a qual in the tree after
deciding that it is redundant.  So the attached patch removes such
quals from the jointree at the end of reduce_outer_joins.

With the quals removed before deconstruct_jointree,
check_redundant_nullability_qual has nothing left to do, so I think we
can get rid of it in passing.

- Richard

Attachments:

v1-0001-Remove-quals-made-redundant-by-reducing-outer-joi.patch (application/octet-stream, 13.6K) download From 0f1409bb76a742765c4dd6b7b359524ad52de085 Mon Sep 17 00:00:00 2001 From: Richard Guo <guofenglinux@gmail.com> Date: Mon, 31 Aug 2026 15:15:23 +0900 Subject: [PATCH v1] Remove quals made redundant by reducing outer joins to antijoins When reduce_outer_joins reduces an outer join to an antijoin, any IS NULL qual on a Var from the antijoin's nullable side is necessarily true. Previously, such quals were discarded later in distribute_qual_to_rels, mainly to avoid bogus selectivity estimates. But that discard was one-sided: the qual remained in the jointree, while its Vars were not counted in attr_needed. Since commit 2ebf25e7d, join removal edits the jointree and expects it to contain no other references to a removed rel, so it could remove a rel that such a discarded qual still references, and then trip an assertion on the qual's stale Var. To fix, remove these quals from the jointree at the end of reduce_outer_joins. With the quals gone before deconstruct_jointree, check_redundant_nullability_qual has nothing left to detect, so remove it. --- src/backend/optimizer/plan/initsplan.c | 61 ------------ src/backend/optimizer/prep/prepjointree.c | 107 ++++++++++++++++++++-- src/test/regress/expected/join.out | 35 +++++++ src/test/regress/sql/join.sql | 18 ++++ 4 files changed, 153 insertions(+), 68 deletions(-) diff --git a/src/backend/optimizer/plan/initsplan.c b/src/backend/optimizer/plan/initsplan.c index a2fb0b55a79..fb6f81453ea 100644 --- a/src/backend/optimizer/plan/initsplan.c +++ b/src/backend/optimizer/plan/initsplan.c @@ -146,7 +146,6 @@ static void distribute_qual_to_rels(PlannerInfo *root, Node *clause, bool has_clone, bool is_clone, List **postponed_oj_qual_list); -static bool check_redundant_nullability_qual(PlannerInfo *root, Node *clause); static Relids get_join_domain_min_rels(PlannerInfo *root, Relids domain_relids); static void check_mergejoinable(RestrictInfo *restrictinfo); static void check_hashjoinable(RestrictInfo *restrictinfo); @@ -2871,10 +2870,6 @@ distribute_quals_to_rels(PlannerInfo *root, List *clauses, * 'qualscope' identifies what level of JOIN the qual came from syntactically. * 'ojscope' is needed if we decide to force the qual up to the outer-join * level, which will be ojscope not necessarily qualscope. - * - * At the time this is called, root->join_info_list must contain entries for - * at least those special joins that are syntactically below this qual. - * (We now need that only for detection of redundant IS NULL quals.) */ static void distribute_qual_to_rels(PlannerInfo *root, Node *clause, @@ -3078,15 +3073,6 @@ distribute_qual_to_rels(PlannerInfo *root, Node *clause, */ is_pushed_down = true; - /* - * It's possible that this is an IS NULL clause that's redundant with - * a lower antijoin; if so we can just discard it. We need not test - * in any of the other cases, because this will only be possible for - * pushed-down clauses. - */ - if (check_redundant_nullability_qual(root, clause)) - return; - /* Feed qual to the equivalence machinery, if allowed by caller */ maybe_equivalence = allow_equivalence; @@ -3253,53 +3239,6 @@ distribute_qual_to_rels(PlannerInfo *root, Node *clause, distribute_restrictinfo_to_rels(root, restrictinfo); } -/* - * check_redundant_nullability_qual - * Check to see if the qual is an IS NULL qual that is redundant with - * a lower JOIN_ANTI join. - * - * We want to suppress redundant IS NULL quals, not so much to save cycles - * as to avoid generating bogus selectivity estimates for them. So if - * redundancy is detected here, distribute_qual_to_rels() just throws away - * the qual. - */ -static bool -check_redundant_nullability_qual(PlannerInfo *root, Node *clause) -{ - Var *forced_null_var; - ListCell *lc; - - /* Check for IS NULL, and identify the Var forced to NULL */ - forced_null_var = find_forced_null_var(clause); - if (forced_null_var == NULL) - return false; - - /* - * If the Var comes from the nullable side of a lower antijoin, the IS - * NULL condition is necessarily true. If it's not nulled by anything, - * there is no point in searching the join_info_list. Otherwise, we need - * to find out whether the nulling rel is an antijoin. - */ - if (forced_null_var->varnullingrels == NULL) - return false; - - foreach(lc, root->join_info_list) - { - SpecialJoinInfo *sjinfo = (SpecialJoinInfo *) lfirst(lc); - - /* - * This test will not succeed if sjinfo->ojrelid is zero, which is - * possible for an antijoin that was converted from a semijoin; but in - * such a case the Var couldn't have come from its nullable side. - */ - if (sjinfo->jointype == JOIN_ANTI && sjinfo->ojrelid != 0 && - bms_is_member(sjinfo->ojrelid, forced_null_var->varnullingrels)) - return true; - } - - return false; -} - /* * add_base_clause_to_rel * Add 'restrictinfo' as a baserestrictinfo to the base relation denoted diff --git a/src/backend/optimizer/prep/prepjointree.c b/src/backend/optimizer/prep/prepjointree.c index 5931501e470..4328640b936 100644 --- a/src/backend/optimizer/prep/prepjointree.c +++ b/src/backend/optimizer/prep/prepjointree.c @@ -98,6 +98,7 @@ typedef struct reduce_outer_joins_pass2_state { Relids inner_reduced; /* OJ relids reduced to plain inner joins */ List *partial_reduced; /* List of partially reduced FULL joins */ + Relids anti_reduced; /* OJ relids reduced to antijoins */ } reduce_outer_joins_pass2_state; typedef struct reduce_outer_joins_partial_state @@ -164,6 +165,9 @@ static void reduce_outer_joins_pass2(Node *jtnode, List *forced_null_vars); static void report_reduced_full_join(reduce_outer_joins_pass2_state *state2, int rtindex, Relids relids); +static void remove_redundant_nullability_quals_recurse(Node *jtnode, + Relids antijoins); +static Node *remove_redundant_nullability_quals(Node *quals, Relids antijoins); static bool forced_null_var_is_attnotnull(PlannerInfo *root, List *forced_null_vars, reduce_outer_joins_pass1_state *state); @@ -3242,9 +3246,8 @@ flatten_simple_union_all(PlannerInfo *root) * due to lower-level outer joins, then only null-extended rows could pass * the upper WHERE, and we can conclude that what the query is really * specifying is an anti-semijoin. We change the join type from JOIN_LEFT - * to JOIN_ANTI. The IS NULL clause then becomes redundant, and must be - * removed to prevent bogus selectivity calculations, but we leave it to - * distribute_qual_to_rels to get rid of such clauses. + * to JOIN_ANTI. The IS NULL clause then becomes redundant, and is removed + * at the end of this phase; see remove_redundant_nullability_quals_recurse. * * A whole-row Var works too. "WHERE b IS NULL" in row-format semantics is * true when b's whole-row value is NULL or when every column of b is NULL; @@ -3292,6 +3295,7 @@ reduce_outer_joins(PlannerInfo *root) state2.inner_reduced = NULL; state2.partial_reduced = NIL; + state2.anti_reduced = NULL; reduce_outer_joins_pass2((Node *) root->parse->jointree, state1, &state2, @@ -3334,6 +3338,89 @@ reduce_outer_joins(PlannerInfo *root) full_join_relids, statep->unreduced_side); } + + /* + * Finally, remove any quals made redundant by reducing outer joins to + * antijoins. + */ + if (!bms_is_empty(state2.anti_reduced)) + remove_redundant_nullability_quals_recurse((Node *) root->parse->jointree, + state2.anti_reduced); +} + +/* + * remove_redundant_nullability_quals_recurse + * Remove quals made redundant by reducing outer joins to antijoins. + * + * An IS NULL qual on a Var from the nullable side of a lower antijoin is + * necessarily true. Removing such quals is not just an optimization: they + * would generate bogus selectivity estimates, and they would retain references + * to rels that join removal might later delete. + */ +static void +remove_redundant_nullability_quals_recurse(Node *jtnode, Relids antijoins) +{ + if (jtnode == NULL) + return; + if (IsA(jtnode, RangeTblRef)) + { + /* nothing to do here */ + } + else if (IsA(jtnode, FromExpr)) + { + FromExpr *f = (FromExpr *) jtnode; + ListCell *l; + + foreach(l, f->fromlist) + remove_redundant_nullability_quals_recurse(lfirst(l), antijoins); + f->quals = remove_redundant_nullability_quals(f->quals, antijoins); + } + else if (IsA(jtnode, JoinExpr)) + { + JoinExpr *j = (JoinExpr *) jtnode; + + remove_redundant_nullability_quals_recurse(j->larg, antijoins); + remove_redundant_nullability_quals_recurse(j->rarg, antijoins); + j->quals = remove_redundant_nullability_quals(j->quals, antijoins); + } + else + elog(ERROR, "unrecognized jointree node type: %d", + (int) nodeTag(jtnode)); +} + +/* + * remove_redundant_nullability_quals + * Remove redundant IS NULL quals from one implicit-AND qual list. + */ +static Node * +remove_redundant_nullability_quals(Node *quals, Relids antijoins) +{ + if (quals == NULL) + return NULL; + if (IsA(quals, List)) + { + List *newquals = NIL; + ListCell *l; + + foreach(l, (List *) quals) + { + Node *clause = (Node *) lfirst(l); + Var *var = find_forced_null_var(clause); + + if (var && bms_overlap(var->varnullingrels, antijoins)) + continue; + newquals = lappend(newquals, clause); + } + quals = (Node *) newquals; + } + else + { + Var *var = find_forced_null_var(quals); + + if (var && bms_overlap(var->varnullingrels, antijoins)) + quals = NULL; + } + return quals; } /* @@ -3449,9 +3536,11 @@ reduce_outer_joins_pass1(Node *jtnode) * * Returns info in state2 about outer joins that were successfully simplified. * Joins that were fully reduced to inner joins are all added to - * state2->inner_reduced. If a full join is reduced to a left join, - * it needs its own entry in state2->partial_reduced, since that will - * require custom processing to remove only the correct nullingrel markers. + * state2->inner_reduced, and joins that became antijoins are all added to + * state2->anti_reduced. If a full join is reduced to a left join or an + * antijoin, it also needs its own entry in state2->partial_reduced, since + * that will require custom processing to remove only the correct nullingrel + * markers. */ static void reduce_outer_joins_pass2(Node *jtnode, @@ -3644,7 +3733,8 @@ reduce_outer_joins_pass2(Node *jtnode, /* * Apply the jointype change, if any, to both jointree node and RTE. - * Also, if we changed an RTE to INNER, add its RTI to inner_reduced. + * Also, if we changed an RTE to INNER, add its RTI to inner_reduced; + * if we changed it to ANTI, add its RTI to anti_reduced. */ if (rtindex && jointype != j->jointype) { @@ -3656,6 +3746,9 @@ reduce_outer_joins_pass2(Node *jtnode, if (jointype == JOIN_INNER) state2->inner_reduced = bms_add_member(state2->inner_reduced, rtindex); + else if (jointype == JOIN_ANTI) + state2->anti_reduced = bms_add_member(state2->anti_reduced, + rtindex); } j->jointype = jointype; diff --git a/src/test/regress/expected/join.out b/src/test/regress/expected/join.out index db4fcc5a5a0..3a5255de7bf 100644 --- a/src/test/regress/expected/join.out +++ b/src/test/regress/expected/join.out @@ -4105,6 +4105,41 @@ where t2 is null; 2 (2 rows) +-- Test that quals made redundant by reducing an outer join to an antijoin are +-- removed from the jointree +-- (fallout from the fix for bug #19560) +create temp table tbl_anti_pk (a int primary key); +-- t3.a IS NULL is redundant, and the t2/t3 join can be removed +explain (costs off) +select 1 from tbl_anti_pk t1 left join + (tbl_anti_pk t2 left join tbl_anti_pk t3 on t3.a = t2.a) on true +where t2.a is null and t3.a is null; + QUERY PLAN +---------------------------------------- + Nested Loop Anti Join + -> Seq Scan on tbl_anti_pk t1 + -> Materialize + -> Seq Scan on tbl_anti_pk t2 +(4 rows) + +-- the redundant qual can also be a degenerate ON clause of an upper join +explain (costs off) +select 1 from tbl_anti_pk t1 left join + (tbl_anti_pk t2 left join + (tbl_anti_pk t3 left join tbl_anti_pk t5 on t5.a = t3.a) on t3.a = t2.a) + on t3.a is null and t5.a is null; + QUERY PLAN +---------------------------------------------------- + Nested Loop Left Join + -> Seq Scan on tbl_anti_pk t1 + -> Materialize + -> Hash Anti Join + Hash Cond: (t2.a = t3.a) + -> Seq Scan on tbl_anti_pk t2 + -> Hash + -> Seq Scan on tbl_anti_pk t3 +(8 rows) + rollback; -- -- regression test for bogus RTE_GROUP entries diff --git a/src/test/regress/sql/join.sql b/src/test/regress/sql/join.sql index 9533af8656e..8f1ffccdd4e 100644 --- a/src/test/regress/sql/join.sql +++ b/src/test/regress/sql/join.sql @@ -1187,6 +1187,24 @@ where t2 is null; select * from (values (1), (2)) v(x) left join tbl_zero t2 on t2 is not null where t2 is null; +-- Test that quals made redundant by reducing an outer join to an antijoin are +-- removed from the jointree +-- (fallout from the fix for bug #19560) +create temp table tbl_anti_pk (a int primary key); + +-- t3.a IS NULL is redundant, and the t2/t3 join can be removed +explain (costs off) +select 1 from tbl_anti_pk t1 left join + (tbl_anti_pk t2 left join tbl_anti_pk t3 on t3.a = t2.a) on true +where t2.a is null and t3.a is null; + +-- the redundant qual can also be a degenerate ON clause of an upper join +explain (costs off) +select 1 from tbl_anti_pk t1 left join + (tbl_anti_pk t2 left join + (tbl_anti_pk t3 left join tbl_anti_pk t5 on t5.a = t3.a) on t3.a = t2.a) + on t3.a is null and t5.a is null; + rollback; -- -- 2.37.1 (Apple Git-137.1)
^ permalink raw reply [nested|flat] 74+ messages in thread

* Re: remove_useless_joins vs. bug #19560
  2026-07-20 18:52 remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-24 13:38 ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-07-25 16:46   ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-25 20:07     ` Re: remove_useless_joins vs. bug #19560 Thom Brown <thom@linux.com>
  2026-07-25 21:23       ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-26 02:15         ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-26 09:49           ` Re: remove_useless_joins vs. bug #19560 Thom Brown <thom@linux.com>
  2026-07-26 17:33             ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-26 17:35               ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-27 07:07                 ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-07-27 16:33                   ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-27 18:21                     ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-29 06:21                       ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-16 23:58                         ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-26 05:26                           ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-26 17:25                             ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-27 01:57                               ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-27 15:53                                 ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-28 07:29                                   ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-28 13:43                                     ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-29 03:27                                       ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-29 20:10                                         ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-30 06:50                                           ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-30 16:20                                             ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-31 01:55                                               ` Re: remove_useless_joins vs. bug #19560 Tender Wang <tndrwang@gmail.com>
  2026-08-31 07:32                                                 ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
@ 2026-08-31 15:56                                                   ` Tom Lane <tgl@sss.pgh.pa.us>
  2026-09-01 02:07                                                     ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  0 siblings, 1 reply; 74+ messages in thread

From: Tom Lane @ 2026-08-31 15:56 UTC (permalink / raw)
  To: Richard Guo <guofenglinux@gmail.com>; +Cc: Tender Wang <tndrwang@gmail.com>; Thom Brown <thom@linux.com>; Jacob Brazeal <jacob.brazeal@gmail.com>; pgsql-hackers@lists.postgresql.org

Richard Guo <guofenglinux@gmail.com> writes:
> According to that, I can reproduce this same issue with the query
> below:

> create table t (a int primary key);

> select 1 from t t1 left join
>   (t t2 left join t t3 on t3.a = t2.a) on true
> where t2.a is null and t3.a is null;

> I think the real problem is that we leave a qual in the tree after
> deciding that it is redundant.  So the attached patch removes such
> quals from the jointree at the end of reduce_outer_joins.

+1 for concept.

> With the quals removed before deconstruct_jointree,
> check_redundant_nullability_qual has nothing left to do, so I think we
> can get rid of it in passing.

Right, what this is really doing is moving that processing out of
the deconstruct_jointree phase and requiring reduce_outer_joins to
clean up its own mess.  Our git history shows I'm to blame for the
way it's done now, but I sure don't remember why I did it like that.
This way seems clearly neater: fewer moving parts, less inconsistency
between different representations of the query.

A few nits, mostly about commentary:

* Your commit message explains this as
"check_redundant_nullability_qual has nothing left to detect, so
remove it".  But as I just said, it's better to think of this change
as moving this processing to an earlier phase, so that should be
explained differently.

* The comment for find_forced_null_var says it's used by initsplan.c.
But what that is referencing is the call from
check_redundant_nullability_qual; the usage is moving to
prepjointree.c, so that comment needs a small adjustment.

* The new comment for remove_redundant_nullability_quals_recurse says
"they would retain references to rels that join removal might later
delete", but I don't think that's quite accurate.  If we didn't do
this qual-removal in either phase, then the Var reference would still
be there and join removal would not think it can remove the join.
So it seems to me that better wording would be like "they could
prevent join removal".  But that puts the lie to the claim that this
is "not just an optimization", so the whole sentence needs a bit of
reworking.

* I feel like the naming of remove_redundant_nullability_quals
and remove_redundant_nullability_quals_recurse is a bit weird.
Usually our pattern is that a function named like foo_recurse
is an inner workhorse for a function named foo.  This is the
other way around, which seems like it'd confuse readers.

* I don't understand the coding in remove_redundant_nullability_quals.
We require quals to be in implicit-AND format by this point, so they
should be either NIL or a List.  Is the last stanza actually
reachable?  (Maybe you are comparing this to find_forced_null_vars,
but the reason that handles both Lists and not-Lists is that it
processes a List via self-recursion.  This doesn't, so I think it
could just be a simple foreach loop over the argument.  Maybe use
castNode(List, quals) to enforce the assumption.)


What I'm taking away from all this is that 2ebf25e7d is forcing us
to be neater about management of the parse tree, which is probably
a good thing overall.

			regards, tom lane






^ permalink  raw  reply  [nested|flat] 74+ messages in thread

* Re: remove_useless_joins vs. bug #19560
  2026-07-20 18:52 remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-24 13:38 ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-07-25 16:46   ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-25 20:07     ` Re: remove_useless_joins vs. bug #19560 Thom Brown <thom@linux.com>
  2026-07-25 21:23       ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-26 02:15         ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-26 09:49           ` Re: remove_useless_joins vs. bug #19560 Thom Brown <thom@linux.com>
  2026-07-26 17:33             ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-26 17:35               ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-27 07:07                 ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-07-27 16:33                   ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-27 18:21                     ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-29 06:21                       ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-16 23:58                         ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-26 05:26                           ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-26 17:25                             ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-27 01:57                               ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-27 15:53                                 ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-28 07:29                                   ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-28 13:43                                     ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-29 03:27                                       ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-29 20:10                                         ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-30 06:50                                           ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-30 16:20                                             ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-31 01:55                                               ` Re: remove_useless_joins vs. bug #19560 Tender Wang <tndrwang@gmail.com>
  2026-08-31 07:32                                                 ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-31 15:56                                                   ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
@ 2026-09-01 02:07                                                     ` Richard Guo <guofenglinux@gmail.com>
  2026-09-01 15:35                                                       ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-09-02 03:42                                                       ` Re: remove_useless_joins vs. bug #19560 Tender Wang <tndrwang@gmail.com>
  0 siblings, 2 replies; 74+ messages in thread

From: Richard Guo @ 2026-09-01 02:07 UTC (permalink / raw)
  To: Tom Lane <tgl@sss.pgh.pa.us>; +Cc: Tender Wang <tndrwang@gmail.com>; Thom Brown <thom@linux.com>; Jacob Brazeal <jacob.brazeal@gmail.com>; pgsql-hackers@lists.postgresql.org

On Tue, Sep 1, 2026 at 12:56 AM Tom Lane <tgl@sss.pgh.pa.us> wrote:
> Richard Guo <guofenglinux@gmail.com> writes:
> > I think the real problem is that we leave a qual in the tree after
> > deciding that it is redundant.  So the attached patch removes such
> > quals from the jointree at the end of reduce_outer_joins.

> +1 for concept.

Thanks for reviewing this!

> * Your commit message explains this as
> "check_redundant_nullability_qual has nothing left to detect, so
> remove it".  But as I just said, it's better to think of this change
> as moving this processing to an earlier phase, so that should be
> explained differently.

Agreed.  I've reworded the commit message to explain it that way.

> * The comment for find_forced_null_var says it's used by initsplan.c.
> But what that is referencing is the call from
> check_redundant_nullability_qual; the usage is moving to
> prepjointree.c, so that comment needs a small adjustment.

Fixed.

> * The new comment for remove_redundant_nullability_quals_recurse says
> "they would retain references to rels that join removal might later
> delete", but I don't think that's quite accurate.  If we didn't do
> this qual-removal in either phase, then the Var reference would still
> be there and join removal would not think it can remove the join.
> So it seems to me that better wording would be like "they could
> prevent join removal".  But that puts the lie to the claim that this
> is "not just an optimization", so the whole sentence needs a bit of
> reworking.

Right.  I've reworked that sentence to say that "Keeping such a qual
would not be wrong, but it would generate bogus selectivity estimates,
and it could prevent join removal from later removing the rel(s) it
references."

> * I feel like the naming of remove_redundant_nullability_quals
> and remove_redundant_nullability_quals_recurse is a bit weird.
> Usually our pattern is that a function named like foo_recurse
> is an inner workhorse for a function named foo.  This is the
> other way around, which seems like it'd confuse readers.

I've renamed the jointree walker to remove_redundant_nullability_quals
(it recurses into itself, so there is no wrapper to pair a "_recurse"
with), and the helper that processes one qual list to
strip_redundant_nullability_quals.  Not sure if this is the best
naming though.

> * I don't understand the coding in remove_redundant_nullability_quals.
> We require quals to be in implicit-AND format by this point, so they
> should be either NIL or a List.  Is the last stanza actually
> reachable?

Good catch.  You're right, it is not reachable.  It's now a simple
loop over castNode(List, quals), as you suggested.


> What I'm taking away from all this is that 2ebf25e7d is forcing us
> to be neater about management of the parse tree, which is probably
> a good thing overall.

Agreed.  Before 2ebf25e7d, there were quite a few cases where an
expression was removed logically but still present in the parse tree
physically, and nothing ever walked the tree afterwards expecting
consistency.  Now the new Asserts are shaking out all these cases, and
in the end we'll get a much neater parse tree.

- Richard

Attachments:

v2-0001-Remove-quals-made-redundant-by-reducing-outer-joi.patch (application/octet-stream, 14.6K) download From d2f7bdcc4a945bd0c841aa7249299f9ba5d80398 Mon Sep 17 00:00:00 2001 From: Richard Guo <guofenglinux@gmail.com> Date: Mon, 31 Aug 2026 15:15:23 +0900 Subject: [PATCH v2] Remove quals made redundant by reducing outer joins to antijoins When reduce_outer_joins reduces an outer join to an antijoin, any IS NULL qual on a Var from the antijoin's nullable side is necessarily true. Previously, such quals were discarded later in distribute_qual_to_rels, mainly to avoid bogus selectivity estimates. But that discard was one-sided: the qual remained in the jointree, while its Vars were not counted in attr_needed. Since commit 2ebf25e7d, join removal edits the jointree and expects it to contain no other references to a removed rel, so it could remove a rel that such a discarded qual still references, and then trip an assertion on the qual's stale Var. To fix, move this processing to an earlier phase: such quals are now removed from the jointree by reduce_outer_joins itself. This way later phases see a consistent query tree, and check_redundant_nullability_qual is no longer needed, so remove it. --- src/backend/optimizer/plan/initsplan.c | 61 --------------- src/backend/optimizer/prep/prepjointree.c | 92 +++++++++++++++++++++-- src/backend/optimizer/util/clauses.c | 11 +-- src/test/regress/expected/join.out | 35 +++++++++ src/test/regress/sql/join.sql | 18 +++++ 5 files changed, 144 insertions(+), 73 deletions(-) diff --git a/src/backend/optimizer/plan/initsplan.c b/src/backend/optimizer/plan/initsplan.c index a2fb0b55a79..fb6f81453ea 100644 --- a/src/backend/optimizer/plan/initsplan.c +++ b/src/backend/optimizer/plan/initsplan.c @@ -146,7 +146,6 @@ static void distribute_qual_to_rels(PlannerInfo *root, Node *clause, bool has_clone, bool is_clone, List **postponed_oj_qual_list); -static bool check_redundant_nullability_qual(PlannerInfo *root, Node *clause); static Relids get_join_domain_min_rels(PlannerInfo *root, Relids domain_relids); static void check_mergejoinable(RestrictInfo *restrictinfo); static void check_hashjoinable(RestrictInfo *restrictinfo); @@ -2871,10 +2870,6 @@ distribute_quals_to_rels(PlannerInfo *root, List *clauses, * 'qualscope' identifies what level of JOIN the qual came from syntactically. * 'ojscope' is needed if we decide to force the qual up to the outer-join * level, which will be ojscope not necessarily qualscope. - * - * At the time this is called, root->join_info_list must contain entries for - * at least those special joins that are syntactically below this qual. - * (We now need that only for detection of redundant IS NULL quals.) */ static void distribute_qual_to_rels(PlannerInfo *root, Node *clause, @@ -3078,15 +3073,6 @@ distribute_qual_to_rels(PlannerInfo *root, Node *clause, */ is_pushed_down = true; - /* - * It's possible that this is an IS NULL clause that's redundant with - * a lower antijoin; if so we can just discard it. We need not test - * in any of the other cases, because this will only be possible for - * pushed-down clauses. - */ - if (check_redundant_nullability_qual(root, clause)) - return; - /* Feed qual to the equivalence machinery, if allowed by caller */ maybe_equivalence = allow_equivalence; @@ -3253,53 +3239,6 @@ distribute_qual_to_rels(PlannerInfo *root, Node *clause, distribute_restrictinfo_to_rels(root, restrictinfo); } -/* - * check_redundant_nullability_qual - * Check to see if the qual is an IS NULL qual that is redundant with - * a lower JOIN_ANTI join. - * - * We want to suppress redundant IS NULL quals, not so much to save cycles - * as to avoid generating bogus selectivity estimates for them. So if - * redundancy is detected here, distribute_qual_to_rels() just throws away - * the qual. - */ -static bool -check_redundant_nullability_qual(PlannerInfo *root, Node *clause) -{ - Var *forced_null_var; - ListCell *lc; - - /* Check for IS NULL, and identify the Var forced to NULL */ - forced_null_var = find_forced_null_var(clause); - if (forced_null_var == NULL) - return false; - - /* - * If the Var comes from the nullable side of a lower antijoin, the IS - * NULL condition is necessarily true. If it's not nulled by anything, - * there is no point in searching the join_info_list. Otherwise, we need - * to find out whether the nulling rel is an antijoin. - */ - if (forced_null_var->varnullingrels == NULL) - return false; - - foreach(lc, root->join_info_list) - { - SpecialJoinInfo *sjinfo = (SpecialJoinInfo *) lfirst(lc); - - /* - * This test will not succeed if sjinfo->ojrelid is zero, which is - * possible for an antijoin that was converted from a semijoin; but in - * such a case the Var couldn't have come from its nullable side. - */ - if (sjinfo->jointype == JOIN_ANTI && sjinfo->ojrelid != 0 && - bms_is_member(sjinfo->ojrelid, forced_null_var->varnullingrels)) - return true; - } - - return false; -} - /* * add_base_clause_to_rel * Add 'restrictinfo' as a baserestrictinfo to the base relation denoted diff --git a/src/backend/optimizer/prep/prepjointree.c b/src/backend/optimizer/prep/prepjointree.c index 5931501e470..18f05caac3b 100644 --- a/src/backend/optimizer/prep/prepjointree.c +++ b/src/backend/optimizer/prep/prepjointree.c @@ -98,6 +98,7 @@ typedef struct reduce_outer_joins_pass2_state { Relids inner_reduced; /* OJ relids reduced to plain inner joins */ List *partial_reduced; /* List of partially reduced FULL joins */ + Relids anti_reduced; /* OJ relids reduced to antijoins */ } reduce_outer_joins_pass2_state; typedef struct reduce_outer_joins_partial_state @@ -164,6 +165,9 @@ static void reduce_outer_joins_pass2(Node *jtnode, List *forced_null_vars); static void report_reduced_full_join(reduce_outer_joins_pass2_state *state2, int rtindex, Relids relids); +static void remove_redundant_nullability_quals(Node *jtnode, + Relids antijoins); +static Node *strip_redundant_nullability_quals(Node *quals, Relids antijoins); static bool forced_null_var_is_attnotnull(PlannerInfo *root, List *forced_null_vars, reduce_outer_joins_pass1_state *state); @@ -3242,9 +3246,8 @@ flatten_simple_union_all(PlannerInfo *root) * due to lower-level outer joins, then only null-extended rows could pass * the upper WHERE, and we can conclude that what the query is really * specifying is an anti-semijoin. We change the join type from JOIN_LEFT - * to JOIN_ANTI. The IS NULL clause then becomes redundant, and must be - * removed to prevent bogus selectivity calculations, but we leave it to - * distribute_qual_to_rels to get rid of such clauses. + * to JOIN_ANTI. The IS NULL clause then becomes redundant, and is removed + * at the end of this phase; see remove_redundant_nullability_quals. * * A whole-row Var works too. "WHERE b IS NULL" in row-format semantics is * true when b's whole-row value is NULL or when every column of b is NULL; @@ -3292,6 +3295,7 @@ reduce_outer_joins(PlannerInfo *root) state2.inner_reduced = NULL; state2.partial_reduced = NIL; + state2.anti_reduced = NULL; reduce_outer_joins_pass2((Node *) root->parse->jointree, state1, &state2, @@ -3334,6 +3338,74 @@ reduce_outer_joins(PlannerInfo *root) full_join_relids, statep->unreduced_side); } + + /* + * Finally, remove any quals made redundant by reducing outer joins to + * antijoins. + */ + if (!bms_is_empty(state2.anti_reduced)) + remove_redundant_nullability_quals((Node *) root->parse->jointree, + state2.anti_reduced); +} + +/* + * remove_redundant_nullability_quals + * Remove quals made redundant by reducing outer joins to antijoins. + * + * An IS NULL qual on a Var from the nullable side of a lower antijoin is + * necessarily true. Keeping such a qual would not be wrong, but it would + * generate bogus selectivity estimates, and it could prevent join removal + * from later removing the rel(s) it references. + */ +static void +remove_redundant_nullability_quals(Node *jtnode, Relids antijoins) +{ + if (jtnode == NULL) + return; + if (IsA(jtnode, RangeTblRef)) + { + /* nothing to do here */ + } + else if (IsA(jtnode, FromExpr)) + { + FromExpr *f = (FromExpr *) jtnode; + ListCell *l; + + foreach(l, f->fromlist) + remove_redundant_nullability_quals(lfirst(l), antijoins); + f->quals = strip_redundant_nullability_quals(f->quals, antijoins); + } + else if (IsA(jtnode, JoinExpr)) + { + JoinExpr *j = (JoinExpr *) jtnode; + + remove_redundant_nullability_quals(j->larg, antijoins); + remove_redundant_nullability_quals(j->rarg, antijoins); + j->quals = strip_redundant_nullability_quals(j->quals, antijoins); + } + else + elog(ERROR, "unrecognized jointree node type: %d", + (int) nodeTag(jtnode)); +} + +/* + * strip_redundant_nullability_quals + * Strip redundant IS NULL quals from one implicit-AND qual list. + */ +static Node * +strip_redundant_nullability_quals(Node *quals, Relids antijoins) +{ + List *newquals = NIL; + + foreach_ptr(Node, clause, castNode(List, quals)) + { + Var *var = find_forced_null_var(clause); + + if (var && bms_overlap(var->varnullingrels, antijoins)) + continue; + newquals = lappend(newquals, clause); + } + return (Node *) newquals; } /* @@ -3449,9 +3521,11 @@ reduce_outer_joins_pass1(Node *jtnode) * * Returns info in state2 about outer joins that were successfully simplified. * Joins that were fully reduced to inner joins are all added to - * state2->inner_reduced. If a full join is reduced to a left join, - * it needs its own entry in state2->partial_reduced, since that will - * require custom processing to remove only the correct nullingrel markers. + * state2->inner_reduced, and joins that became antijoins are all added to + * state2->anti_reduced. If a full join is reduced to a left join or an + * antijoin, it also needs its own entry in state2->partial_reduced, since + * that will require custom processing to remove only the correct nullingrel + * markers. */ static void reduce_outer_joins_pass2(Node *jtnode, @@ -3644,7 +3718,8 @@ reduce_outer_joins_pass2(Node *jtnode, /* * Apply the jointype change, if any, to both jointree node and RTE. - * Also, if we changed an RTE to INNER, add its RTI to inner_reduced. + * Also, if we changed an RTE to INNER, add its RTI to inner_reduced; + * if we changed it to ANTI, add its RTI to anti_reduced. */ if (rtindex && jointype != j->jointype) { @@ -3656,6 +3731,9 @@ reduce_outer_joins_pass2(Node *jtnode, if (jointype == JOIN_INNER) state2->inner_reduced = bms_add_member(state2->inner_reduced, rtindex); + else if (jointype == JOIN_ANTI) + state2->anti_reduced = bms_add_member(state2->anti_reduced, + rtindex); } j->jointype = jointype; diff --git a/src/backend/optimizer/util/clauses.c b/src/backend/optimizer/util/clauses.c index 8da4ed617b5..43e3f9c1ea9 100644 --- a/src/backend/optimizer/util/clauses.c +++ b/src/backend/optimizer/util/clauses.c @@ -2033,11 +2033,12 @@ find_forced_null_vars(Node *node) * *only* nullness of the particular Var, not any other conditions. * * This is just the single-clause case of find_forced_null_vars(), without - * any allowance for AND conditions. It's used by initsplan.c on individual - * qual clauses. The reason for not just applying find_forced_null_vars() - * is that if an AND of an IS NULL clause with something else were to somehow - * survive AND/OR flattening, initsplan.c might get fooled into discarding - * the whole clause when only the IS NULL part of it had been proved redundant. + * any allowance for AND conditions. It's used by prepjointree.c on + * individual qual clauses. The reason for not just applying + * find_forced_null_vars() is that if an AND of an IS NULL clause with + * something else were to somehow survive AND/OR flattening, prepjointree.c + * might get fooled into discarding the whole clause when only the IS NULL + * part of it had been proved redundant. */ Var * find_forced_null_var(Node *node) diff --git a/src/test/regress/expected/join.out b/src/test/regress/expected/join.out index db4fcc5a5a0..3a5255de7bf 100644 --- a/src/test/regress/expected/join.out +++ b/src/test/regress/expected/join.out @@ -4105,6 +4105,41 @@ where t2 is null; 2 (2 rows) +-- Test that quals made redundant by reducing an outer join to an antijoin are +-- removed from the jointree +-- (fallout from the fix for bug #19560) +create temp table tbl_anti_pk (a int primary key); +-- t3.a IS NULL is redundant, and the t2/t3 join can be removed +explain (costs off) +select 1 from tbl_anti_pk t1 left join + (tbl_anti_pk t2 left join tbl_anti_pk t3 on t3.a = t2.a) on true +where t2.a is null and t3.a is null; + QUERY PLAN +---------------------------------------- + Nested Loop Anti Join + -> Seq Scan on tbl_anti_pk t1 + -> Materialize + -> Seq Scan on tbl_anti_pk t2 +(4 rows) + +-- the redundant qual can also be a degenerate ON clause of an upper join +explain (costs off) +select 1 from tbl_anti_pk t1 left join + (tbl_anti_pk t2 left join + (tbl_anti_pk t3 left join tbl_anti_pk t5 on t5.a = t3.a) on t3.a = t2.a) + on t3.a is null and t5.a is null; + QUERY PLAN +---------------------------------------------------- + Nested Loop Left Join + -> Seq Scan on tbl_anti_pk t1 + -> Materialize + -> Hash Anti Join + Hash Cond: (t2.a = t3.a) + -> Seq Scan on tbl_anti_pk t2 + -> Hash + -> Seq Scan on tbl_anti_pk t3 +(8 rows) + rollback; -- -- regression test for bogus RTE_GROUP entries diff --git a/src/test/regress/sql/join.sql b/src/test/regress/sql/join.sql index 9533af8656e..8f1ffccdd4e 100644 --- a/src/test/regress/sql/join.sql +++ b/src/test/regress/sql/join.sql @@ -1187,6 +1187,24 @@ where t2 is null; select * from (values (1), (2)) v(x) left join tbl_zero t2 on t2 is not null where t2 is null; +-- Test that quals made redundant by reducing an outer join to an antijoin are +-- removed from the jointree +-- (fallout from the fix for bug #19560) +create temp table tbl_anti_pk (a int primary key); + +-- t3.a IS NULL is redundant, and the t2/t3 join can be removed +explain (costs off) +select 1 from tbl_anti_pk t1 left join + (tbl_anti_pk t2 left join tbl_anti_pk t3 on t3.a = t2.a) on true +where t2.a is null and t3.a is null; + +-- the redundant qual can also be a degenerate ON clause of an upper join +explain (costs off) +select 1 from tbl_anti_pk t1 left join + (tbl_anti_pk t2 left join + (tbl_anti_pk t3 left join tbl_anti_pk t5 on t5.a = t3.a) on t3.a = t2.a) + on t3.a is null and t5.a is null; + rollback; -- -- 2.37.1 (Apple Git-137.1)
^ permalink raw reply [nested|flat] 74+ messages in thread

* Re: remove_useless_joins vs. bug #19560
  2026-07-20 18:52 remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-24 13:38 ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-07-25 16:46   ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-25 20:07     ` Re: remove_useless_joins vs. bug #19560 Thom Brown <thom@linux.com>
  2026-07-25 21:23       ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-26 02:15         ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-26 09:49           ` Re: remove_useless_joins vs. bug #19560 Thom Brown <thom@linux.com>
  2026-07-26 17:33             ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-26 17:35               ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-27 07:07                 ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-07-27 16:33                   ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-27 18:21                     ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-29 06:21                       ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-16 23:58                         ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-26 05:26                           ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-26 17:25                             ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-27 01:57                               ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-27 15:53                                 ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-28 07:29                                   ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-28 13:43                                     ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-29 03:27                                       ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-29 20:10                                         ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-30 06:50                                           ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-30 16:20                                             ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-31 01:55                                               ` Re: remove_useless_joins vs. bug #19560 Tender Wang <tndrwang@gmail.com>
  2026-08-31 07:32                                                 ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-31 15:56                                                   ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-09-01 02:07                                                     ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
@ 2026-09-01 15:35                                                       ` Tom Lane <tgl@sss.pgh.pa.us>
  2026-09-02 05:37                                                         ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  1 sibling, 1 reply; 74+ messages in thread

From: Tom Lane @ 2026-09-01 15:35 UTC (permalink / raw)
  To: Richard Guo <guofenglinux@gmail.com>; +Cc: Tender Wang <tndrwang@gmail.com>; Thom Brown <thom@linux.com>; Jacob Brazeal <jacob.brazeal@gmail.com>; pgsql-hackers@lists.postgresql.org

Richard Guo <guofenglinux@gmail.com> writes:
> On Tue, Sep 1, 2026 at 12:56 AM Tom Lane <tgl@sss.pgh.pa.us> wrote:
>> * I feel like the naming of remove_redundant_nullability_quals
>> and remove_redundant_nullability_quals_recurse is a bit weird.
>> Usually our pattern is that a function named like foo_recurse
>> is an inner workhorse for a function named foo.  This is the
>> other way around, which seems like it'd confuse readers.

> I've renamed the jointree walker to remove_redundant_nullability_quals
> (it recurses into itself, so there is no wrapper to pair a "_recurse"
> with), and the helper that processes one qual list to
> strip_redundant_nullability_quals.  Not sure if this is the best
> naming though.

Yeah, naming is always hard.  I don't have a better suggestion than
this.

v2 patch LGTM.  I might say "incomplete" rather than "one-sided"
in the commit message, but that's getting *really* nit-picky.

			regards, tom lane






^ permalink  raw  reply  [nested|flat] 74+ messages in thread

* Re: remove_useless_joins vs. bug #19560
  2026-07-20 18:52 remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-24 13:38 ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-07-25 16:46   ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-25 20:07     ` Re: remove_useless_joins vs. bug #19560 Thom Brown <thom@linux.com>
  2026-07-25 21:23       ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-26 02:15         ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-26 09:49           ` Re: remove_useless_joins vs. bug #19560 Thom Brown <thom@linux.com>
  2026-07-26 17:33             ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-26 17:35               ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-27 07:07                 ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-07-27 16:33                   ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-27 18:21                     ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-29 06:21                       ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-16 23:58                         ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-26 05:26                           ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-26 17:25                             ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-27 01:57                               ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-27 15:53                                 ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-28 07:29                                   ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-28 13:43                                     ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-29 03:27                                       ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-29 20:10                                         ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-30 06:50                                           ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-30 16:20                                             ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-31 01:55                                               ` Re: remove_useless_joins vs. bug #19560 Tender Wang <tndrwang@gmail.com>
  2026-08-31 07:32                                                 ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-31 15:56                                                   ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-09-01 02:07                                                     ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-09-01 15:35                                                       ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
@ 2026-09-02 05:37                                                         ` Richard Guo <guofenglinux@gmail.com>
  0 siblings, 0 replies; 74+ messages in thread

From: Richard Guo @ 2026-09-02 05:37 UTC (permalink / raw)
  To: Tom Lane <tgl@sss.pgh.pa.us>; +Cc: Tender Wang <tndrwang@gmail.com>; Thom Brown <thom@linux.com>; Jacob Brazeal <jacob.brazeal@gmail.com>; pgsql-hackers@lists.postgresql.org

On Wed, Sep 2, 2026 at 12:35 AM Tom Lane <tgl@sss.pgh.pa.us> wrote:
> v2 patch LGTM.  I might say "incomplete" rather than "one-sided"
> in the commit message, but that's getting *really* nit-picky.

Thanks!  I've updated the commit message to say "incomplete", and then
pushed and back-patched it to v16.

That leaves us with just the lateral PHV issue in this thread.

- Richard






^ permalink  raw  reply  [nested|flat] 74+ messages in thread

* Re: remove_useless_joins vs. bug #19560
  2026-07-20 18:52 remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-24 13:38 ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-07-25 16:46   ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-25 20:07     ` Re: remove_useless_joins vs. bug #19560 Thom Brown <thom@linux.com>
  2026-07-25 21:23       ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-26 02:15         ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-26 09:49           ` Re: remove_useless_joins vs. bug #19560 Thom Brown <thom@linux.com>
  2026-07-26 17:33             ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-26 17:35               ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-27 07:07                 ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-07-27 16:33                   ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-27 18:21                     ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-29 06:21                       ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-16 23:58                         ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-26 05:26                           ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-26 17:25                             ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-27 01:57                               ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-27 15:53                                 ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-28 07:29                                   ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-28 13:43                                     ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-29 03:27                                       ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-29 20:10                                         ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-30 06:50                                           ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-30 16:20                                             ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-31 01:55                                               ` Re: remove_useless_joins vs. bug #19560 Tender Wang <tndrwang@gmail.com>
  2026-08-31 07:32                                                 ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-31 15:56                                                   ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-09-01 02:07                                                     ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
@ 2026-09-02 03:42                                                       ` Tender Wang <tndrwang@gmail.com>
  1 sibling, 0 replies; 74+ messages in thread

From: Tender Wang @ 2026-09-02 03:42 UTC (permalink / raw)
  To: Richard Guo <guofenglinux@gmail.com>; +Cc: Tom Lane <tgl@sss.pgh.pa.us>; Thom Brown <thom@linux.com>; Jacob Brazeal <jacob.brazeal@gmail.com>; pgsql-hackers@lists.postgresql.org

Richard Guo <guofenglinux@gmail.com> 于2026年9月1日周二 10:08写道:
> Agreed.  Before 2ebf25e7d, there were quite a few cases where an
> expression was removed logically but still present in the parse tree
> physically, and nothing ever walked the tree afterwards expecting
> consistency.  Now the new Asserts are shaking out all these cases, and
> in the end we'll get a much neater parse tree.
>

I tested v2 and reviewed the changes.  LGTM.

One minor comment: the header comment for reduce_outer_joins() still says:
...
Attempt to reduce outer joins to plain inner joins.
...

But the function can also reduce a LEFT JOIN to an ANTI JOIN (and perform
other join-type reductions), so perhaps this could be updated to something
more general, for example:
...
Attempt to reduce outer joins to simpler join types.
...

-- 
Thanks,
Tender Wang






^ permalink  raw  reply  [nested|flat] 74+ messages in thread

* Re: remove_useless_joins vs. bug #19560
  2026-07-20 18:52 remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-24 13:38 ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-07-25 16:46   ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-25 20:07     ` Re: remove_useless_joins vs. bug #19560 Thom Brown <thom@linux.com>
  2026-07-25 21:23       ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-26 02:15         ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-26 09:49           ` Re: remove_useless_joins vs. bug #19560 Thom Brown <thom@linux.com>
  2026-07-26 17:33             ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-26 17:35               ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-27 07:07                 ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-07-27 16:33                   ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-27 18:21                     ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-29 06:21                       ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-16 23:58                         ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-26 05:26                           ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-26 17:25                             ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-27 01:57                               ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-27 15:53                                 ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-28 07:29                                   ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-28 13:43                                     ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
@ 2026-09-17 02:40                                       ` Richard Guo <guofenglinux@gmail.com>
  3 siblings, 0 replies; 74+ messages in thread

From: Richard Guo @ 2026-09-17 02:40 UTC (permalink / raw)
  To: Tom Lane <tgl@sss.pgh.pa.us>; +Cc: Thom Brown <thom@linux.com>; Jacob Brazeal <jacob.brazeal@gmail.com>; pgsql-hackers@lists.postgresql.org

On Fri, Aug 28, 2026 at 10:43 PM Tom Lane <tgl@sss.pgh.pa.us> wrote:
> Sold.  I'll make it so and push.  Thanks for reviewing!

Fuzzing with Claude, I ran into an assertion failure that comes from
commit 2ebf25e7d:

create table t1 (a int, b int, c int);
create table t2 (a int primary key, b int, c int);

select j.x from (t1 s(x) left join t2 on s.x = t2.a) j;
server closed the connection unexpectedly

TRAP: failed Assert("context->new_index != INVALID_VAR")

This is because that since the join has an alias, j.x is a Var with
varno pointing to s and varnosyn pointing to the join.  When the join
is removed, ChangeVarNodes() notices that varnosyn still references
the join's RT index, so the Assert fires.

I think this varnosyn is fine to keep.  The join is only removed from
the jointree; its RTE stays in the rangetable through to the final
plan, so varnosyn still names a valid RTE.  And join removal didn't
touch varnosyn before 2ebf25e7d either.

Attached is a fix.

- Richard

Attachments:

v1-0001-Fix-join-removal-when-Vars-reference-the-removed-.patch (application/octet-stream, 4.2K) download From b7a872195b4b79ccf407853792e57e9c56cf93ca Mon Sep 17 00:00:00 2001 From: Richard Guo <guofenglinux@gmail.com> Date: Thu, 17 Sep 2026 11:09:41 +0900 Subject: [PATCH v1] Fix join removal when Vars reference the removed join via its alias When a join has an alias, the parser marks every Var referenced through that alias with the join's RT index as its syntactic referent (varnosyn), even though varno points at the underlying base relation. Since commit 2ebf25e7d, join removal strips the removed relids from the query tree using ChangeVarNodes() with INVALID_VAR, which asserts that the relid doesn't appear in any field identifying a single relation. A varnosyn that names the removed join violates that, so a query like SELECT j.x FROM (t1 s(x) LEFT JOIN t2 ON s.x = t2.a) j; with t2.a unique fails an assertion. In non-assert builds, varnosyn is silently set to INVALID_VAR. Such syntactic references are still valid after the removal: the join is only taken out of the jointree, and its RTE remains in the rangetable through to the finished plan. So, when deleting a relid, leave varnosyn unchanged, as join removal did before 2ebf25e7d. Back-patch to v16, as with commit 2ebf25e7d. --- src/backend/rewrite/rewriteManip.c | 11 ++++++----- src/test/regress/expected/join.out | 10 ++++++++++ src/test/regress/sql/join.sql | 4 ++++ 3 files changed, 20 insertions(+), 5 deletions(-) diff --git a/src/backend/rewrite/rewriteManip.c b/src/backend/rewrite/rewriteManip.c index 3653f00d383..7011275f8c6 100644 --- a/src/backend/rewrite/rewriteManip.c +++ b/src/backend/rewrite/rewriteManip.c @@ -536,7 +536,9 @@ OffsetVarNodes(Node *node, int offset, int sublevels_up) * Also, new_index can be INVALID_VAR to indicate that we are deleting the * given relid from the tree. In this case we expect to find rt_index only * in Relids fields (varnullingrels, phnullingrels, phrels), never in any - * field that identifies a single relation. + * field that identifies a single relation. The exception is varnosyn, + * which may name an aliased join being removed; the join's RTE remains in + * the rangetable, so we leave such syntactic references unchanged. * * NOTE: although this has the form of a walker, we cheat and modify the * nodes in-place. The given expression tree should have been copied @@ -569,11 +571,10 @@ ChangeVarNodes_walker(Node *node, ChangeVarNodes_context *context) var->varnullingrels = adjust_relid_set(var->varnullingrels, context->rt_index, context->new_index); - if (var->varnosyn == context->rt_index) - { - Assert(context->new_index != INVALID_VAR); + /* when deleting, leave syntactic refs to a removed join alone */ + if (var->varnosyn == context->rt_index && + context->new_index != INVALID_VAR) var->varnosyn = context->new_index; - } } return false; } diff --git a/src/test/regress/expected/join.out b/src/test/regress/expected/join.out index 75544fe6aa3..b8c0b2920fb 100644 --- a/src/test/regress/expected/join.out +++ b/src/test/regress/expected/join.out @@ -7727,6 +7727,16 @@ select c.id, ss.a from c -> Seq Scan on c (7 rows) +-- check join removal when Vars reference the removed join via its alias +explain (costs off) +select j.b_id, (select j.b_id) from (a left join b on a.b_id = b.id) j; + QUERY PLAN +------------------ + Seq Scan on a + SubPlan expr_1 + -> Result +(3 rows) + -- check the case when the placeholder relates to an outer join and its -- inner in the press field but actually uses only the outer side of the join explain (costs off) diff --git a/src/test/regress/sql/join.sql b/src/test/regress/sql/join.sql index fb83a96e939..683a3550df1 100644 --- a/src/test/regress/sql/join.sql +++ b/src/test/regress/sql/join.sql @@ -2866,6 +2866,10 @@ select c.id, ss.a from c left join (select d.a from onerow, d left join b on d.a = b.id) ss on c.id = ss.a; +-- check join removal when Vars reference the removed join via its alias +explain (costs off) +select j.b_id, (select j.b_id) from (a left join b on a.b_id = b.id) j; + -- check the case when the placeholder relates to an outer join and its -- inner in the press field but actually uses only the outer side of the join explain (costs off) -- 2.37.1 (Apple Git-137.1)
^ permalink raw reply [nested|flat] 74+ messages in thread

* Re: remove_useless_joins vs. bug #19560
  2026-07-20 18:52 remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-24 13:38 ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-07-25 16:46   ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-25 20:07     ` Re: remove_useless_joins vs. bug #19560 Thom Brown <thom@linux.com>
  2026-07-25 21:23       ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-26 02:15         ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-26 09:49           ` Re: remove_useless_joins vs. bug #19560 Thom Brown <thom@linux.com>
  2026-07-26 17:33             ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-26 17:35               ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-27 07:07                 ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-07-27 16:33                   ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-27 18:21                     ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-29 06:21                       ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-16 23:58                         ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-26 05:26                           ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-26 17:25                             ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-27 01:57                               ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-27 15:53                                 ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-28 07:29                                   ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-28 13:43                                     ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
@ 2026-09-17 02:51                                       ` Tom Lane <tgl@sss.pgh.pa.us>
  2026-09-17 07:15                                         ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  3 siblings, 1 reply; 74+ messages in thread

From: Tom Lane @ 2026-09-17 02:51 UTC (permalink / raw)
  To: Richard Guo <guofenglinux@gmail.com>; +Cc: Thom Brown <thom@linux.com>; Jacob Brazeal <jacob.brazeal@gmail.com>; pgsql-hackers@lists.postgresql.org

Richard Guo <guofenglinux@gmail.com> writes:
> Fuzzing with Claude, I ran into an assertion failure that comes from
> commit 2ebf25e7d:
> create table t1 (a int, b int, c int);
> create table t2 (a int primary key, b int, c int);
> select j.x from (t1 s(x) left join t2 on s.x = t2.a) j;
> server closed the connection unexpectedly

Ugh.

> I think this varnosyn is fine to keep.  The join is only removed from
> the jointree; its RTE stays in the rangetable through to the final
> plan, so varnosyn still names a valid RTE.  And join removal didn't
> touch varnosyn before 2ebf25e7d either.

True.

> Attached is a fix.

The main consumer of varnosyn is ruleutils.c, so I don't like
the fact that this test case isn't showing what ruleutils will
do with the Var.  If we make it be "explain verbose", do we
get a display of the problematic Var?

			regards, tom lane






^ permalink  raw  reply  [nested|flat] 74+ messages in thread

* Re: remove_useless_joins vs. bug #19560
  2026-07-20 18:52 remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-24 13:38 ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-07-25 16:46   ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-25 20:07     ` Re: remove_useless_joins vs. bug #19560 Thom Brown <thom@linux.com>
  2026-07-25 21:23       ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-26 02:15         ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-26 09:49           ` Re: remove_useless_joins vs. bug #19560 Thom Brown <thom@linux.com>
  2026-07-26 17:33             ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-26 17:35               ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-27 07:07                 ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-07-27 16:33                   ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-27 18:21                     ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-29 06:21                       ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-16 23:58                         ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-26 05:26                           ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-26 17:25                             ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-27 01:57                               ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-27 15:53                                 ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-28 07:29                                   ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-28 13:43                                     ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-09-17 02:51                                       ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
@ 2026-09-17 07:15                                         ` Richard Guo <guofenglinux@gmail.com>
  2026-09-18 19:22                                           ` Re: remove_useless_joins vs. bug #19560 Haibo Yan <tristan.yim@gmail.com>
  2026-09-19 14:05                                           ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  0 siblings, 2 replies; 74+ messages in thread

From: Richard Guo @ 2026-09-17 07:15 UTC (permalink / raw)
  To: Tom Lane <tgl@sss.pgh.pa.us>; +Cc: Thom Brown <thom@linux.com>; Jacob Brazeal <jacob.brazeal@gmail.com>; pgsql-hackers@lists.postgresql.org

On Thu, Sep 17, 2026 at 11:52 AM Tom Lane <tgl@sss.pgh.pa.us> wrote:
> The main consumer of varnosyn is ruleutils.c, so I don't like
> the fact that this test case isn't showing what ruleutils will
> do with the Var.  If we make it be "explain verbose", do we
> get a display of the problematic Var?

The Var is displayed, but not via varnosyn.  ruleutils.c uses varnosyn
only when dpns->plan is NULL, and EXPLAIN always sets the plan before
deparsing an expression, so it prints the semantic referent (a.b_id).

But I think it'd still be better to use "explain verbose", so at least
what ruleutils prints is recorded.  I'll make that change before push.

- Richard






^ permalink  raw  reply  [nested|flat] 74+ messages in thread

* Re: remove_useless_joins vs. bug #19560
  2026-07-20 18:52 remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-24 13:38 ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-07-25 16:46   ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-25 20:07     ` Re: remove_useless_joins vs. bug #19560 Thom Brown <thom@linux.com>
  2026-07-25 21:23       ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-26 02:15         ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-26 09:49           ` Re: remove_useless_joins vs. bug #19560 Thom Brown <thom@linux.com>
  2026-07-26 17:33             ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-26 17:35               ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-27 07:07                 ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-07-27 16:33                   ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-27 18:21                     ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-29 06:21                       ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-16 23:58                         ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-26 05:26                           ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-26 17:25                             ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-27 01:57                               ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-27 15:53                                 ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-28 07:29                                   ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-28 13:43                                     ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-09-17 02:51                                       ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-09-17 07:15                                         ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
@ 2026-09-18 19:22                                           ` Haibo Yan <tristan.yim@gmail.com>
  2026-09-19 01:45                                             ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  1 sibling, 1 reply; 74+ messages in thread

From: Haibo Yan @ 2026-09-18 19:22 UTC (permalink / raw)
  To: Richard Guo <guofenglinux@gmail.com>; +Cc: Tom Lane <tgl@sss.pgh.pa.us>; Thom Brown <thom@linux.com>; Jacob Brazeal <jacob.brazeal@gmail.com>; pgsql-hackers@lists.postgresql.org

On Thu, Sep 17, 2026 at 12:15 AM Richard Guo <guofenglinux@gmail.com> wrote:
>
> On Thu, Sep 17, 2026 at 11:52 AM Tom Lane <tgl@sss.pgh.pa.us> wrote:
> > The main consumer of varnosyn is ruleutils.c, so I don't like
> > the fact that this test case isn't showing what ruleutils will
> > do with the Var.  If we make it be "explain verbose", do we
> > get a display of the problematic Var?
>
> The Var is displayed, but not via varnosyn.  ruleutils.c uses varnosyn
> only when dpns->plan is NULL, and EXPLAIN always sets the plan before
> deparsing an expression, so it prints the semantic referent (a.b_id).
>
> But I think it'd still be better to use "explain verbose", so at least
> what ruleutils prints is recorded.  I'll make that change before push.
>
> - Richard
>
>
Hi Richard,

I found what looks like a regression from e28cf96e935
("Fix stale copies of PHVs in subqueries").  In particular, I think there is
still a way for an upper-level PHV containing an unprocessed SubLink to get
into a subquery after preprocess_subquery_phvs() has already run.

Here is a reproducer on current master:
    create table t (a int, b int);
    create table u (c int, d int);

    select 1
    from (t left join (select (select 1) as x) s on true) j
    where (select 1 where j is null) is null;


On current master I get:
    ERROR:  unrecognized node type: 22


There are similar failures with RIGHT/FULL JOIN.  For example, a nested join
shape can instead reach:
    ERROR:  cannot handle unplanned sub-select

I bisected this to e28cf96e935.  The cases I tested work on e28cf96e935^ and
fail on e28cf96e935/current master.  I also reproduced the regression on
REL_16_STABLE and REL_18_STABLE; source inspection shows the same relevant
code in the other branches to which this was back-patched.

The problem seems to be an ordering hole in the new PHV preprocessing scheme.

preprocess_subquery_phvs() runs early in subquery_planner(), on the assumption
that copies of upper-level PHVs in lower-level queries will be preprocessed at
their owning level before the lower query sees them.  Later, however,
flatten_join_alias_vars() can expand a whole-row join alias inside a lower
Query and introduce a fresh upper-level PHV there.

One way this happens is when a joinaliasvars entry is already a PHV because a
pulled-up subquery was on the nullable side of an outer join.  Another is when
add_nullingrels_if_needed() has to wrap the RowExpr produced by whole-row
join-alias expansion in a new PHV.

At that point preprocess_subquery_phvs() has already run, so the newly
introduced PHV can still contain a raw SubLink.

Later process_sublinks_mutator() deliberately leaves an upper-level PHV alone,
consistent with the new assumption that its contents were already processed at
its owning level.  build_subplan() makes the same assumption after
e28cf96e935.
The result is that the raw SubLink survives inside the PHV.

With some instrumentation, for a failing case I see the SubPlan argument reach
build_subplan() as a PHV whose phexpr is still T_SubLink, whereas in a
corresponding working case the expression has already become a Param.

I also tried the obvious experiment of restoring the old
    IsA(arg, PlaceHolderVar)

case in build_subplan() so that SS_process_sublinks() is run there.  That fixes
these reproducers, but it is not a valid fix: it trips
    Assert(!IsA(node, SubLink))


in process_sublinks_mutator() on the join.sql tests added by e28cf96e935,
resulting in many regression failures.  So I don't think simply
restoring the old
build_subplan behavior is the answer.

This seems to violate the invariant established by e28cf96e935: an
upper-level PHV
encountered by a lower query may be left untouched only if all such copies have
already been preprocessed at their owning level.  flatten_join_alias_vars() can
create or push down another such copy after that preprocessing pass.

I think the fix therefore needs to be on the producing/preprocessing side rather
than in build_subplan() -- either ensuring these alias-generated PHVs
are processed
at their owning level before they can be copied down, or arranging another
appropriately scoped PHV preprocessing step after join-alias flattening.

I have not tried to turn either of those into a patch yet, since I
wanted to check
whether you agree with this diagnosis first.

Regards,
Haibo






^ permalink  raw  reply  [nested|flat] 74+ messages in thread

* Re: remove_useless_joins vs. bug #19560
  2026-07-20 18:52 remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-24 13:38 ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-07-25 16:46   ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-25 20:07     ` Re: remove_useless_joins vs. bug #19560 Thom Brown <thom@linux.com>
  2026-07-25 21:23       ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-26 02:15         ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-26 09:49           ` Re: remove_useless_joins vs. bug #19560 Thom Brown <thom@linux.com>
  2026-07-26 17:33             ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-26 17:35               ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-27 07:07                 ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-07-27 16:33                   ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-27 18:21                     ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-29 06:21                       ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-16 23:58                         ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-26 05:26                           ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-26 17:25                             ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-27 01:57                               ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-27 15:53                                 ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-28 07:29                                   ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-28 13:43                                     ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-09-17 02:51                                       ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-09-17 07:15                                         ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-09-18 19:22                                           ` Re: remove_useless_joins vs. bug #19560 Haibo Yan <tristan.yim@gmail.com>
@ 2026-09-19 01:45                                             ` Richard Guo <guofenglinux@gmail.com>
  0 siblings, 0 replies; 74+ messages in thread

From: Richard Guo @ 2026-09-19 01:45 UTC (permalink / raw)
  To: Haibo Yan <tristan.yim@gmail.com>; +Cc: Tom Lane <tgl@sss.pgh.pa.us>; Thom Brown <thom@linux.com>; Jacob Brazeal <jacob.brazeal@gmail.com>; pgsql-hackers@lists.postgresql.org

On Sat, Sep 19, 2026 at 4:22 AM Haibo Yan <tristan.yim@gmail.com> wrote:
> I found what looks like a regression from e28cf96e935
> ("Fix stale copies of PHVs in subqueries").  In particular, I think there is
> still a way for an upper-level PHV containing an unprocessed SubLink to get
> into a subquery after preprocess_subquery_phvs() has already run.

This is the same bug reported by Fujii-san earlier, which is fixed in
my v1-0001-Fix-preprocessing-of-PHV-copies-pushed-down-into-.patch.

- Richard






^ permalink  raw  reply  [nested|flat] 74+ messages in thread

* Re: remove_useless_joins vs. bug #19560
  2026-07-20 18:52 remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-24 13:38 ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-07-25 16:46   ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-25 20:07     ` Re: remove_useless_joins vs. bug #19560 Thom Brown <thom@linux.com>
  2026-07-25 21:23       ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-26 02:15         ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-26 09:49           ` Re: remove_useless_joins vs. bug #19560 Thom Brown <thom@linux.com>
  2026-07-26 17:33             ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-26 17:35               ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-27 07:07                 ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-07-27 16:33                   ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-27 18:21                     ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-29 06:21                       ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-16 23:58                         ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-26 05:26                           ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-26 17:25                             ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-27 01:57                               ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-27 15:53                                 ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-28 07:29                                   ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-28 13:43                                     ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-09-17 02:51                                       ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-09-17 07:15                                         ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
@ 2026-09-19 14:05                                           ` Richard Guo <guofenglinux@gmail.com>
  2026-09-26 17:44                                             ` Re: remove_useless_joins vs. bug #19560 Noah Misch <noah@leadboat.com>
  1 sibling, 1 reply; 74+ messages in thread

From: Richard Guo @ 2026-09-19 14:05 UTC (permalink / raw)
  To: Tom Lane <tgl@sss.pgh.pa.us>; +Cc: Thom Brown <thom@linux.com>; Jacob Brazeal <jacob.brazeal@gmail.com>; pgsql-hackers@lists.postgresql.org

On Thu, Sep 17, 2026 at 4:15 PM Richard Guo <guofenglinux@gmail.com> wrote:
> But I think it'd still be better to use "explain verbose", so at least
> what ruleutils prints is recorded.  I'll make that change before push.

Also pushed this one.

- Richard






^ permalink  raw  reply  [nested|flat] 74+ messages in thread

* Re: remove_useless_joins vs. bug #19560
  2026-07-20 18:52 remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-24 13:38 ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-07-25 16:46   ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-25 20:07     ` Re: remove_useless_joins vs. bug #19560 Thom Brown <thom@linux.com>
  2026-07-25 21:23       ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-26 02:15         ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-26 09:49           ` Re: remove_useless_joins vs. bug #19560 Thom Brown <thom@linux.com>
  2026-07-26 17:33             ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-26 17:35               ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-27 07:07                 ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-07-27 16:33                   ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-27 18:21                     ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-29 06:21                       ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-16 23:58                         ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-26 05:26                           ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-26 17:25                             ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-27 01:57                               ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-27 15:53                                 ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-28 07:29                                   ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-28 13:43                                     ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-09-17 02:51                                       ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-09-17 07:15                                         ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-09-19 14:05                                           ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
@ 2026-09-26 17:44                                             ` Noah Misch <noah@leadboat.com>
  2026-09-26 18:05                                               ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  0 siblings, 1 reply; 74+ messages in thread

From: Noah Misch @ 2026-09-26 17:44 UTC (permalink / raw)
  To: Tom Lane <tgl@sss.pgh.pa.us>; Richard Guo <guofenglinux@gmail.com>; +Cc: Thom Brown <thom@linux.com>; Jacob Brazeal <jacob.brazeal@gmail.com>; pgsql-hackers@lists.postgresql.org; underdog@theori.io

security@ received a report about a regression in commit 2ebf25e.  On
2026-09-12, I told the reporter that we handle defects in unreleased code as
non-vulnerabilities and asked them to report it to pgsql-hackers.  I didn't
find that report, so I'm forwarding it here.  From some searches of this
thread, I also don't think this repeats any of the followup fixes already
done.  I'm attaching the reporter's materials.  I'll file a v19 open item,
since v19 is projected to reach a GA release before the 2026-11 back branch
releases.


<reporter_message_body>

I am reporting an RLS confidentiality bypass introduced by the recent
jointree-rewrite self-join elimination change.

An ordinary authenticated role can join an RLS-protected table directly to
an existing default owner-executed, ID-only view of the same table.
The direct RTE carries the attacker's RLS securityQuals, while the
view-derived RTE is checked as the table-owning view owner and carries
none.
The new SJE implementation groups the RTEs by physical relation OID without
comparing their security qualifiers or permission identities. It removes
the lower relation ID and retains the later one; because a pulled-up view
RTE is appended after the parent RTEs, the owner-context entry is
deterministically retained in either SQL FROM order. Replanning produces
one scan without the RLS predicate.

I reproduced the leak on master 798bdcae89debabc59fa8afc6d690fec584db32f
and REL_18_STABLE c0b3980507f459c09b5324b6536c9e1c31fad378.
Exact PostgreSQL 18.6 is a negative control across the expanded matrix. The
relevant REL_18_STABLE rewrite was committed after 18.6 and no inspected
release tag contains it as of 2026-09-08, so I recommend pre-release P0
handling and High confidentiality severity if shipped. PostgreSQL 18.0
through 18.6 are not claimed as affected.

The hardened reproducer grants no table-level SELECT and no SELECT on the
policy column. It grants only the output columns plus SELECT on the
existing views. With SJE off, the attacker receives one authorized row;
with SJE on, it receives both the authorized and foreign-tenant rows. The
same leak occurs through IN (SELECT ...) and through an
invoker-view/owner-view pair with no direct table syntax when the attacker
chooses the unsafe view order. Owner-view predicates that survive SJE bound
the leaked row set. Removing the secret-column privilege still yields
permission denied, so this is an RLS bypass rather than a column-ACL bypass.

The attached package contains the detailed analysis, expanded standalone
SQL reproducer, validation evidence, and a conservative guard that excludes
RTEs carrying securityQuals from SJE. I applied that guard to the affected
master, rebuilt it, and verified that every demonstrated entry path retains
RLS.

Please confirm receipt. I will keep the details private while the affected
branches are triaged and corrected.

Regards,  Yonghwa Lee, Xint by Theori

___


Yonghwa Lee 이용화

Senior Security Engineer

Xint

underdog@theori.io

</reporter_message_body>

Attachments:

report.md (text/plain, 10.4K) download # SJE-RLS-001: self-join elimination drops RLS policy across owner-view and invoker permission contexts ## Summary A newly rewritten self-join elimination (SJE) optimization can merge two range-table entries for the same physical table even when they have different permission and row-security contexts. In the minimal query, one entry is a direct reference evaluated as a low-privilege attacker and carries an RLS `securityQuals` expression. The other originates from an ordinary owner-executed, ID-only view (`security_invoker=false`, the default) and carries no RLS qualifier because the view owner owns the table. SJE groups the entries by physical relation OID, eliminates the attacker-context entry, and rewrites its Vars to the owner-context entry. Replanning then produces a single scan without the RLS predicate. This is deterministic for a direct-table/owner-view pair in either SQL FROM order: the pulled-up view RTE is appended after the parent query's RTEs, and SJE always keeps the higher relation ID. The exposed rows are bounded by any surviving owner-view predicates, and exposed columns remain bounded by ordinary table/column ACLs. Nevertheless, an ID-only reporting view can be composed with separately granted table columns to read those columns across tenants. The reproducer also confirms an `IN (SELECT ...)` entry path and a two-view variant with no direct table syntax. This is an RLS confidentiality bypass, not an ACL bypass. ## Security classification - Release status as of 2026-09-08: **not present in a released PostgreSQL tag** - Recommended handling: **pre-release P0**; block affected branch releases until fixed - Severity if shipped: **High confidentiality impact**, not Critical - Suggested CVSS 3.1 if shipped: **6.5** (`AV:N/AC:L/PR:L/UI:N/S:U/C:H/I:N/A:N`) - CWE: CWE-862 (Missing Authorization) / CWE-200 (Exposure of Sensitive Information) No write-policy or availability impact was demonstrated. ## Affected commits Confirmed dynamically: - master `798bdcae89debabc59fa8afc6d690fec584db32f` - `REL_18_STABLE` `c0b3980507f459c09b5324b6536c9e1c31fad378` Negative control: - exact PostgreSQL 18.6 `724edf9bde9d356724ad384a2e196edc3c9f80f7` is not affected and retains the RLS filter. The `REL_18_STABLE` jointree-rewrite commit was made on 2026-08-28, after the 18.6 release commit dated 2026-08-11, and it is not an ancestor of that release. Although self-join elimination already exists in PostgreSQL 18, the older implementation preserved the RLS predicate in the complete expanded test matrix. Therefore PostgreSQL 18.0 through 18.6 must not be listed as affected. The jointree-rewrite SJE change was introduced to the inspected branches by: ```text master: 2ebf25e7d70a8fce31ace78d723fa9271ab8af72 REL_16_STABLE: 986870baa06bc70245ee731d83486d4ed529c223 REL_17_STABLE: 13466d1f78394a8ec2d6d0b1c9d8bf5ac3acb99 REL_18_STABLE: 9f25197bf27c4c4a02d754842bc4055d83be735b REL_19_STABLE: 0ab90a5c94188ab0a2113e36c73f093f741129c1 ``` All listed branches should be audited. The commit presence alone should not be interpreted as a released vulnerable version. ## Threat model and prerequisites The attacker is an ordinary authenticated SQL role with: - `USAGE` on the application schema; - column-level `SELECT` on the RLS-protected table columns returned by the query (`id` and `secret` in the reproducer), but no table-level `SELECT` and no privilege on the policy column `tenant`; - `SELECT` on an existing, ordinary owner-executed view that exposes the table's unique key; and - the ability to issue an arbitrary `SELECT` combining that table and view. The table owner created both the RLS policy and the view, a common application pattern. The attacker does not need table ownership, view creation, policy modification, `BYPASSRLS`, superuser, `CREATEROLE`, or operating-system access. This does not bypass column ACLs: removing the attacker's `secret` column privilege produces `permission denied`. It bypasses row authorization for columns the attacker is otherwise allowed to read. A second confirmed form uses no direct table syntax. A `security_invoker=true` view exposes the already-authorized `id` and `secret` columns, while an owner-executed view exposes only `id`. Putting the invoker view first and owner view second makes the owner-context RTE the retained entry and leaks the same foreign row. The underlying column privileges required by the invoker view are still enforced. ## Reproduction Run `reproducer.sql` as a PostgreSQL superuser on a fresh database built from an affected commit: ```sh psql -X -v ON_ERROR_STOP=1 -f reproducer.sql postgres ``` The script creates a table containing one attacker row and one foreign-tenant row. It grants the attacker only the two output columns, creates a default owner-executed ID view, and runs the same query with SJE off and on. It then exercises reverse FROM order, a filtered owner view, an `IN (SELECT ...)` form, a two-view form, and invoker/barrier negative controls. Expected security metadata: ```text table_select | id_select | tenant_select | secret_select | rls_active -------------+-----------+---------------+---------------+----------- f | t | f | t | t ``` Observed on master and `REL_18_STABLE`: ```text enable_self_join_elimination = off id | secret ----+--------- 1 | allowed enable_self_join_elimination = on id | secret ----+----------- 1 | allowed 2 | forbidden ``` The affected `EXPLAIN (VERBOSE, COSTS OFF)` contains a single scan without `tenant = CURRENT_USER`: ```text Seq Scan on sje_rls_probe.secrets t Output: t.id, t.secret ``` On exact 18.6, the result remains one row and the plan retains the RLS filter. Additional confirmed results on the affected master build are: ```text direct table + owner view, either FROM order, SJE on: {1,2} direct table WHERE id IN (owner view), SJE off/on: {1} / {1,2} invoker view then owner view, SJE off/on: {1} / {1,2} owner view then invoker view, SJE on: {1} (fail-closed) ``` An owner view filtered by a non-key predicate exposed only the foreign row selected by that predicate. Its plan retained the view predicate but omitted the RLS predicate. Thus view quals can bound the leaked row set; they are not the security condition being dropped. A unique-key predicate prevented SJE in one negative control, so the report does not claim every filtered view is exploitable. ## Root cause 1. View rewriting sets `checkAsUser` to the view owner for a default owner-executed view (`rewriteHandler.c`, `ApplyRetrieveRule()` in the inspected tree). 2. RLS expansion uses that permission identity. The direct attacker RTE receives the `tenant = CURRENT_USER` expression in `securityQuals`; the owner-context view RTE does not. 3. The new SJE candidate collector accepts ordinary relations without checking `securityQuals` or permission identity. 4. Candidates are sorted and grouped only by relation OID. 5. Within a group, the lower relation ID is the removal candidate and the later relation ID is retained. A base RTE pulled up from an owner view is appended at the end, making the unsafe choice deterministic for the direct-table form regardless of FROM order. 6. SJE removes one RTE from the jointree and rewrites its Vars to the retained RTE. When planner state is recomputed, the removed direct or invoker RTE's RLS qualifier is no longer present. Its `RTEPermissionInfo` is not discarded, so ordinary ACL checks remain effective. The relevant candidate check currently resembles: ```c if (rte->rtekind == RTE_RELATION && rte->relkind == RELKIND_RELATION && rte->tablesample == NULL && ...) relids = bms_add_member(relids, varno); ``` Grouping then compares only `root->simple_rte_array[i]->relid` (the physical table OID). Neither `securityQuals` nor the permission identity participates in candidate equivalence. The older 18.6 implementation transferred the removed relation's `baserestrictinfo` to the retained relation, which preserved the RLS predicate in this test. The jointree rewrite invalidates and rebuilds planner state, exposing the loss. ## Controls and mitigations The following independent negative controls prevent the minimal leak when applied to all relevant views: - define the view with `security_invoker=true`; or - define the view with `security_barrier=true`. These can mitigate known application views but do not repair the optimizer invariant globally. `ALTER TABLE ... FORCE ROW LEVEL SECURITY` can make a non-superuser, non-`BYPASSRLS` table owner subject to policy and thereby remove the differing owner context. It is application-dependent and is not a substitute for fixing SJE; superusers and `BYPASSRLS` roles remain outside that protection. `SET enable_self_join_elimination = off` is useful for diagnosis, but it is a `USERSET` option. A hostile database role can turn it back on, so it is not an enforceable security mitigation unless query execution is otherwise constrained. ## Recommended fix The safest immediate fix is to exclude any RTE with `securityQuals != NIL` from SJE. The attached `proposed-fix.patch` implements this conservative guard. It was applied to the affected master source, rebuilt, and dynamically verified to block the direct, reversed, `IN`, filtered-view, and two-view variants while retaining RLS. A more permissive future implementation would need to prove that both RTEs have equivalent permission identities and semantically equivalent security qualifiers, and then preserve those qualifiers correctly during jointree rewriting. Comparing relation OIDs alone is insufficient. Add regression coverage for: 1. a direct attacker RTE joined to a default owner-executed view of the same RLS table; 2. column-only grants, including no grant on the policy column; 3. both possible kept/removed RTE orderings; 4. sublink-to-semijoin conversion using `IN (SELECT ...)`; 5. owner/invoker view pairs in both FROM orders; 6. owner views with surviving non-key quals; 7. prepared statements and role changes; 8. `security_invoker` and `security_barrier` controls; and 9. a non-RLS self-join proving the optimization still fires. ## Independent validation The original reproducer was independently rerun on fresh master, `REL_18_STABLE`, and exact 18.6 builds. A second validation round exercised the expanded variants on the affected master, reran the complete matrix on exact 18.6, and rebuilt master with the proposed guard. The leak appeared only on the unpatched post-change build. Full results are in `evidence/expanded-validation.md`.
SJE-RLS-001-submit-ready-2026-09-07.zip (application/x-zip-compressed, 10.9K) download ^ permalink raw reply [nested|flat] 74+ messages in thread

* Re: remove_useless_joins vs. bug #19560
  2026-07-20 18:52 remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-24 13:38 ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-07-25 16:46   ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-25 20:07     ` Re: remove_useless_joins vs. bug #19560 Thom Brown <thom@linux.com>
  2026-07-25 21:23       ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-26 02:15         ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-26 09:49           ` Re: remove_useless_joins vs. bug #19560 Thom Brown <thom@linux.com>
  2026-07-26 17:33             ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-26 17:35               ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-27 07:07                 ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-07-27 16:33                   ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-27 18:21                     ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-29 06:21                       ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-16 23:58                         ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-26 05:26                           ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-26 17:25                             ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-27 01:57                               ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-27 15:53                                 ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-28 07:29                                   ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-28 13:43                                     ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-09-17 02:51                                       ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-09-17 07:15                                         ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-09-19 14:05                                           ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-09-26 17:44                                             ` Re: remove_useless_joins vs. bug #19560 Noah Misch <noah@leadboat.com>
@ 2026-09-26 18:05                                               ` Tom Lane <tgl@sss.pgh.pa.us>
  2026-09-26 19:27                                                 ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  0 siblings, 1 reply; 74+ messages in thread

From: Tom Lane @ 2026-09-26 18:05 UTC (permalink / raw)
  To: Noah Misch <noah@leadboat.com>; +Cc: Richard Guo <guofenglinux@gmail.com>; Thom Brown <thom@linux.com>; Jacob Brazeal <jacob.brazeal@gmail.com>; pgsql-hackers@lists.postgresql.org; underdog@theori.io

Noah Misch <noah@leadboat.com> writes:
> security@ received a report about a regression in commit 2ebf25e.  On
> 2026-09-12, I told the reporter that we handle defects in unreleased code as
> non-vulnerabilities and asked them to report it to pgsql-hackers.  I didn't
> find that report, so I'm forwarding it here.
> ...
> The new SJE implementation groups the RTEs by physical relation OID without
> comparing their security qualifiers or permission identities.

Right.  I think the appropriate fix is probably to require
that the checkAsUser values match in RTEs we want to combine.
If we do that, I'm not sure that we need to consider securityQuals
as such (but I've not tried it so maybe I'm missing something).

The code 2ebf25e7d removed doesn't appear to have any particular
consideration for either checkAsUser or securityQuals, so I wonder
how it worked before.

			regards, tom lane






^ permalink  raw  reply  [nested|flat] 74+ messages in thread

* Re: remove_useless_joins vs. bug #19560
  2026-07-20 18:52 remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-24 13:38 ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-07-25 16:46   ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-25 20:07     ` Re: remove_useless_joins vs. bug #19560 Thom Brown <thom@linux.com>
  2026-07-25 21:23       ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-26 02:15         ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-26 09:49           ` Re: remove_useless_joins vs. bug #19560 Thom Brown <thom@linux.com>
  2026-07-26 17:33             ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-26 17:35               ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-27 07:07                 ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-07-27 16:33                   ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-27 18:21                     ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-29 06:21                       ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-16 23:58                         ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-26 05:26                           ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-26 17:25                             ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-27 01:57                               ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-27 15:53                                 ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-28 07:29                                   ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-28 13:43                                     ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-09-17 02:51                                       ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-09-17 07:15                                         ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-09-19 14:05                                           ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-09-26 17:44                                             ` Re: remove_useless_joins vs. bug #19560 Noah Misch <noah@leadboat.com>
  2026-09-26 18:05                                               ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
@ 2026-09-26 19:27                                                 ` Tom Lane <tgl@sss.pgh.pa.us>
  2026-09-27 16:32                                                   ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  0 siblings, 1 reply; 74+ messages in thread

From: Tom Lane @ 2026-09-26 19:27 UTC (permalink / raw)
  To: Noah Misch <noah@leadboat.com>; +Cc: Richard Guo <guofenglinux@gmail.com>; Thom Brown <thom@linux.com>; Jacob Brazeal <jacob.brazeal@gmail.com>; pgsql-hackers@lists.postgresql.org; underdog@theori.io

I wrote:
> Right.  I think the appropriate fix is probably to require
> that the checkAsUser values match in RTEs we want to combine.
> If we do that, I'm not sure that we need to consider securityQuals
> as such (but I've not tried it so maybe I'm missing something).

Concretely, about like this.  This fixes the given reproducer.
I've not put thought into what sort of test cases we might want
to add.

			regards, tom lane

Attachments:

sje-must-compare-user-ids-too.patch (text/x-diff, 3.9K) download diff --git a/src/backend/optimizer/plan/analyzejoins.c b/src/backend/optimizer/plan/analyzejoins.c index 2252185564c..d95a8b78dc6 100644 --- a/src/backend/optimizer/plan/analyzejoins.c +++ b/src/backend/optimizer/plan/analyzejoins.c @@ -37,23 +37,26 @@ #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" /* * Utility structure. A sorting procedure is needed to simplify the search - * of SJE-candidate baserels referencing the same database relation. Having - * collected all baserels from the query jointree, the planner sorts them - * according to the reloid value, groups them with the next pass and attempts - * to remove self-joins. + * for SJE-candidate baserels, which must reference the same database relation + * with the same reader permissions (checkAsUser value). Having collected + * all baserels from the query jointree, remove_self_joins_recurse sorts them + * according to the reloid and useroid values, groups them with the next pass + * and attempts to remove self-joins. * - * Preliminary sorting prevents quadratic behavior that can be harmful in the - * case of numerous joins. + * This preliminary sorting prevents quadratic behavior that can be harmful + * in the case of numerous joins. */ typedef struct { int relid; Oid reloid; + Oid useroid; } SelfJoinCandidate; bool enable_self_join_elimination; @@ -2011,16 +2014,27 @@ remove_self_joins_recurse(PlannerInfo *root, List *joinlist) return removed; /* ... but don't fail to report sub-removals */ /* - * In order to find relations with the same oid we first build an array of - * candidates and then sort it by oid. + * In order to find relations with the same reloid/useroid we first build + * an array of candidates and then sort it by the oids. */ candidates = palloc_array(SelfJoinCandidate, numRels); i = -1; j = 0; while ((i = bms_next_member(relids, i)) >= 0) { + RangeTblEntry *rte = root->simple_rte_array[i]; + candidates[j].relid = i; - candidates[j].reloid = root->simple_rte_array[i]->relid; + candidates[j].reloid = rte->relid; + if (rte->perminfoindex != 0) + { + RTEPermissionInfo *perminfo; + + perminfo = getRTEPermissionInfo(root->parse->rteperminfos, rte); + candidates[j].useroid = perminfo->checkAsUser; + } + else + candidates[j].useroid = InvalidOid; j++; } @@ -2028,7 +2042,7 @@ remove_self_joins_recurse(PlannerInfo *root, List *joinlist) self_join_candidates_cmp); /* - * Iteratively form a group of relation indexes with the same oid and + * Iteratively form a group of relation indexes with the same oids and * launch the routine that detects self-joins in this group. * * We remove considered relations from relids as we scan, so that that set @@ -2037,11 +2051,13 @@ remove_self_joins_recurse(PlannerInfo *root, List *joinlist) i = 0; for (j = 1; j <= numRels; j++) { - if (j == numRels || candidates[j].reloid != candidates[i].reloid) + if (j == numRels || + candidates[j].reloid != candidates[i].reloid || + candidates[j].useroid != candidates[i].useroid) { if (j - i >= 2) { - /* Create a group of relation indexes with the same oid */ + /* Create a group of relation indexes with the same oids */ Relids group = NULL; while (i < j) @@ -2073,7 +2089,7 @@ remove_self_joins_recurse(PlannerInfo *root, List *joinlist) } /* - * Compare self-join candidates by their oids. + * Compare self-join candidates by their reloid and then useroid. */ static int self_join_candidates_cmp(const void *a, const void *b) @@ -2083,6 +2099,8 @@ self_join_candidates_cmp(const void *a, const void *b) if (ca->reloid != cb->reloid) return (ca->reloid < cb->reloid ? -1 : 1); + else if (ca->useroid != cb->useroid) + return (ca->useroid < cb->useroid ? -1 : 1); else return 0; }
^ permalink raw reply [nested|flat] 74+ messages in thread

* Re: remove_useless_joins vs. bug #19560
  2026-07-20 18:52 remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-24 13:38 ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-07-25 16:46   ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-25 20:07     ` Re: remove_useless_joins vs. bug #19560 Thom Brown <thom@linux.com>
  2026-07-25 21:23       ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-26 02:15         ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-26 09:49           ` Re: remove_useless_joins vs. bug #19560 Thom Brown <thom@linux.com>
  2026-07-26 17:33             ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-26 17:35               ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-27 07:07                 ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-07-27 16:33                   ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-27 18:21                     ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-29 06:21                       ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-16 23:58                         ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-26 05:26                           ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-26 17:25                             ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-27 01:57                               ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-27 15:53                                 ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-28 07:29                                   ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-28 13:43                                     ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-09-17 02:51                                       ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-09-17 07:15                                         ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-09-19 14:05                                           ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-09-26 17:44                                             ` Re: remove_useless_joins vs. bug #19560 Noah Misch <noah@leadboat.com>
  2026-09-26 18:05                                               ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-09-26 19:27                                                 ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
@ 2026-09-27 16:32                                                   ` Tom Lane <tgl@sss.pgh.pa.us>
  2026-09-29 14:10                                                     ` Re: remove_useless_joins vs. bug #19560 Ayush Tiwari <ayushtiwari.slg01@gmail.com>
  0 siblings, 1 reply; 74+ messages in thread

From: Tom Lane @ 2026-09-27 16:32 UTC (permalink / raw)
  To: Noah Misch <noah@leadboat.com>; +Cc: Richard Guo <guofenglinux@gmail.com>; Thom Brown <thom@linux.com>; Jacob Brazeal <jacob.brazeal@gmail.com>; pgsql-hackers@lists.postgresql.org; underdog@theori.io

I wrote:
> Concretely, about like this.  This fixes the given reproducer.
> I've not put thought into what sort of test cases we might want
> to add.

Now with test cases, a commit message explaining why do it like
this, and a bit of additional comment-polishing.

			regards, tom lane

Attachments:

v1-0001-Prevent-self-join-elimination-when-RTEs-checkAsUs.patch (text/x-diff, 10.3K) download From f438b142782374232786e12d5aca66265f48d1cb Mon Sep 17 00:00:00 2001 From: Tom Lane <tgl@sss.pgh.pa.us> Date: Sun, 27 Sep 2026 12:29:11 -0400 Subject: [PATCH v1] Prevent self-join elimination when RTEs' checkAsUser fields differ. SJE didn't consider the possibility that two RTEs referencing the same table have different securityQuals, and might choose to merge them anyway, thereby possibly losing quals that need to be enforced. This is a regression introduced by 2ebf25e7d, since before that we didn't re-generate baserestrictinfo lists from the RTEs' securityQuals after performing SJE. To defend against this, only consider SJE between RTEs with the same checkAsUser values. That solves the problem because the set of applicable RLS policies depends only on the role that is considered to be accessing the table, so that the securityQuals must be equal if the checkAsUser values are. It might also keep us from creating similar bugs if we ever invent other features that depend on the accessing role. And it's a lot cheaper than comparing securityQuals trees themselves would be, not least because we can't sort them so the preliminary sort step wouldn't help. (The first proposed solution was to not perform SJE at all on RTEs with nonempty securityQuals, but that seems rather sad, especially since such cases worked before 2ebf25e7d. Making the restriction depend on checkAsUser seems much less likely to interfere with SJE unnecessarily, since in most cases that'll be the same for all potentially-mergeable RTEs.) The added test cases show that SJE is rejected when necessary, and also demonstrate two quirks of this implementation. One is that if a removed security qual includes an InitPlan, we'll still attach the now-unused InitPlan to the plan. That's because SS_process_sublinks runs before self-join elimination, so the extra InitPlan has already been made. The other quirk is that we won't merge RTEs having zero and nonzero checkAsUser fields, even if the calling user matches the nonzero checkAsUser value so that there is no difference for this user. That's intentional so that SJE doesn't require having to mark the plan as caller-dependent. Reported-by: Yonghwa Lee <underdog@theori.io> Author: Tom Lane <tgl@sss.pgh.pa.us> Discussion: https://postgr.es/m/20260926174457.13.noahmisch@microsoft.com Backpatch-through: 16 --- src/backend/optimizer/plan/analyzejoins.c | 47 ++++++++++++++++------- src/test/regress/expected/rowsecurity.out | 47 ++++++++++++++++++++++- src/test/regress/sql/rowsecurity.sql | 17 +++++++- 3 files changed, 95 insertions(+), 16 deletions(-) diff --git a/src/backend/optimizer/plan/analyzejoins.c b/src/backend/optimizer/plan/analyzejoins.c index 2252185564c..1fafca57004 100644 --- a/src/backend/optimizer/plan/analyzejoins.c +++ b/src/backend/optimizer/plan/analyzejoins.c @@ -37,23 +37,27 @@ #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" /* * Utility structure. A sorting procedure is needed to simplify the search - * of SJE-candidate baserels referencing the same database relation. Having - * collected all baserels from the query jointree, the planner sorts them - * according to the reloid value, groups them with the next pass and attempts - * to remove self-joins. - * - * Preliminary sorting prevents quadratic behavior that can be harmful in the - * case of numerous joins. + * for SJE-candidate baserels, which must reference the same database relation + * with the same reader permissions (checkAsUser value). We require the + * checkAsUser fields to match to ensure that merged RTEs carry the same + * securityQuals; in future this rule might keep us out of trouble with other + * role-based features, too. Having collected all baserels from the jointree, + * remove_self_joins_recurse sorts them according to their reloid and useroid + * values, groups them in another pass and attempts to remove self-joins + * within each group. This preliminary sorting prevents quadratic behavior + * in the case of numerous joins. */ typedef struct { int relid; Oid reloid; + Oid useroid; } SelfJoinCandidate; bool enable_self_join_elimination; @@ -2011,16 +2015,27 @@ remove_self_joins_recurse(PlannerInfo *root, List *joinlist) return removed; /* ... but don't fail to report sub-removals */ /* - * In order to find relations with the same oid we first build an array of - * candidates and then sort it by oid. + * In order to find relations with the same reloid/useroid we first build + * an array of candidates and then sort it by those oids. */ candidates = palloc_array(SelfJoinCandidate, numRels); i = -1; j = 0; while ((i = bms_next_member(relids, i)) >= 0) { + RangeTblEntry *rte = root->simple_rte_array[i]; + candidates[j].relid = i; - candidates[j].reloid = root->simple_rte_array[i]->relid; + candidates[j].reloid = rte->relid; + if (rte->perminfoindex != 0) + { + RTEPermissionInfo *perminfo; + + perminfo = getRTEPermissionInfo(root->parse->rteperminfos, rte); + candidates[j].useroid = perminfo->checkAsUser; + } + else + candidates[j].useroid = InvalidOid; j++; } @@ -2028,7 +2043,7 @@ remove_self_joins_recurse(PlannerInfo *root, List *joinlist) self_join_candidates_cmp); /* - * Iteratively form a group of relation indexes with the same oid and + * Iteratively form a group of relation indexes with the same oids and * launch the routine that detects self-joins in this group. * * We remove considered relations from relids as we scan, so that that set @@ -2037,11 +2052,13 @@ remove_self_joins_recurse(PlannerInfo *root, List *joinlist) i = 0; for (j = 1; j <= numRels; j++) { - if (j == numRels || candidates[j].reloid != candidates[i].reloid) + if (j == numRels || + candidates[j].reloid != candidates[i].reloid || + candidates[j].useroid != candidates[i].useroid) { if (j - i >= 2) { - /* Create a group of relation indexes with the same oid */ + /* Create a group of relation indexes with the same oids */ Relids group = NULL; while (i < j) @@ -2073,7 +2090,7 @@ remove_self_joins_recurse(PlannerInfo *root, List *joinlist) } /* - * Compare self-join candidates by their oids. + * Compare self-join candidates by their reloid and then useroid. */ static int self_join_candidates_cmp(const void *a, const void *b) @@ -2083,6 +2100,8 @@ self_join_candidates_cmp(const void *a, const void *b) if (ca->reloid != cb->reloid) return (ca->reloid < cb->reloid ? -1 : 1); + else if (ca->useroid != cb->useroid) + return (ca->useroid < cb->useroid ? -1 : 1); else return 0; } diff --git a/src/test/regress/expected/rowsecurity.out b/src/test/regress/expected/rowsecurity.out index 00b11544589..72d76405639 100644 --- a/src/test/regress/expected/rowsecurity.out +++ b/src/test/regress/expected/rowsecurity.out @@ -4869,7 +4869,7 @@ DROP USER regress_rls_dob_role2; -- Bug #15708: view + table with RLS should check policies as view owner CREATE TABLE ref_tbl (a int); INSERT INTO ref_tbl VALUES (1); -CREATE TABLE rls_tbl (a int); +CREATE TABLE rls_tbl (a int PRIMARY KEY); INSERT INTO rls_tbl VALUES (10); ALTER TABLE rls_tbl ENABLE ROW LEVEL SECURITY; CREATE POLICY p1 ON rls_tbl USING (EXISTS (SELECT 1 FROM ref_tbl)); @@ -4889,6 +4889,51 @@ SELECT * FROM rls_view; -- OK 10 (1 row) +EXPLAIN (COSTS OFF) -- check that RLS enforcement is actually happening +SELECT * FROM rls_view; + QUERY PLAN +------------------------------------ + Seq Scan on rls_tbl + Filter: (InitPlan exists_1).col1 + InitPlan exists_1 + -> Seq Scan on ref_tbl +(4 rows) + +-- Use the same view+table to test interaction of SJE with RLS +SET enable_self_join_elimination = on; +-- We can do SJE here, although presently an unused InitPlan survives +EXPLAIN (COSTS OFF) +SELECT * FROM rls_view r1, rls_view r2 WHERE r1.a = r2.a; + QUERY PLAN +--------------------------------------- + Seq Scan on rls_tbl + Filter: (InitPlan exists_2).col1 + InitPlan exists_1 + -> Seq Scan on ref_tbl + InitPlan exists_2 + -> Seq Scan on ref_tbl ref_tbl_1 +(6 rows) + +SET SESSION AUTHORIZATION regress_rls_bob; +-- No SJE here, because the two rls_tbl RTEs have different checkAsUser values +EXPLAIN (COSTS OFF) +SELECT * FROM rls_tbl r1, rls_view r2 WHERE r1.a = r2.a; + QUERY PLAN +------------------------------------------------ + Hash Join + Hash Cond: (r1.a = rls_tbl.a) + InitPlan exists_1 + -> Seq Scan on ref_tbl + InitPlan exists_2 + -> Seq Scan on ref_tbl ref_tbl_1 + -> Seq Scan on rls_tbl r1 + Filter: (InitPlan exists_1).col1 + -> Hash + -> Seq Scan on rls_tbl + Filter: (InitPlan exists_2).col1 +(11 rows) + +RESET enable_self_join_elimination; RESET SESSION AUTHORIZATION; DROP VIEW rls_view; DROP TABLE rls_tbl; diff --git a/src/test/regress/sql/rowsecurity.sql b/src/test/regress/sql/rowsecurity.sql index 9e987b4d927..2bdb0c70c5c 100644 --- a/src/test/regress/sql/rowsecurity.sql +++ b/src/test/regress/sql/rowsecurity.sql @@ -2373,7 +2373,7 @@ DROP USER regress_rls_dob_role2; CREATE TABLE ref_tbl (a int); INSERT INTO ref_tbl VALUES (1); -CREATE TABLE rls_tbl (a int); +CREATE TABLE rls_tbl (a int PRIMARY KEY); INSERT INTO rls_tbl VALUES (10); ALTER TABLE rls_tbl ENABLE ROW LEVEL SECURITY; CREATE POLICY p1 ON rls_tbl USING (EXISTS (SELECT 1 FROM ref_tbl)); @@ -2386,9 +2386,24 @@ ALTER VIEW rls_view OWNER TO regress_rls_bob; GRANT SELECT ON rls_view TO regress_rls_alice; SET SESSION AUTHORIZATION regress_rls_alice; + SELECT * FROM ref_tbl; -- Permission denied SELECT * FROM rls_tbl; -- Permission denied SELECT * FROM rls_view; -- OK +EXPLAIN (COSTS OFF) -- check that RLS enforcement is actually happening +SELECT * FROM rls_view; + +-- Use the same view+table to test interaction of SJE with RLS +SET enable_self_join_elimination = on; +-- We can do SJE here, although presently an unused InitPlan survives +EXPLAIN (COSTS OFF) +SELECT * FROM rls_view r1, rls_view r2 WHERE r1.a = r2.a; +SET SESSION AUTHORIZATION regress_rls_bob; +-- No SJE here, because the two rls_tbl RTEs have different checkAsUser values +EXPLAIN (COSTS OFF) +SELECT * FROM rls_tbl r1, rls_view r2 WHERE r1.a = r2.a; + +RESET enable_self_join_elimination; RESET SESSION AUTHORIZATION; DROP VIEW rls_view; -- 2.52.0
^ permalink raw reply [nested|flat] 74+ messages in thread

* Re: remove_useless_joins vs. bug #19560
  2026-07-20 18:52 remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-24 13:38 ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-07-25 16:46   ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-25 20:07     ` Re: remove_useless_joins vs. bug #19560 Thom Brown <thom@linux.com>
  2026-07-25 21:23       ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-26 02:15         ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-26 09:49           ` Re: remove_useless_joins vs. bug #19560 Thom Brown <thom@linux.com>
  2026-07-26 17:33             ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-26 17:35               ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-27 07:07                 ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-07-27 16:33                   ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-27 18:21                     ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-29 06:21                       ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-16 23:58                         ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-26 05:26                           ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-26 17:25                             ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-27 01:57                               ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-27 15:53                                 ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-28 07:29                                   ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-28 13:43                                     ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-09-17 02:51                                       ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-09-17 07:15                                         ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-09-19 14:05                                           ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-09-26 17:44                                             ` Re: remove_useless_joins vs. bug #19560 Noah Misch <noah@leadboat.com>
  2026-09-26 18:05                                               ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-09-26 19:27                                                 ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-09-27 16:32                                                   ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
@ 2026-09-29 14:10                                                     ` Ayush Tiwari <ayushtiwari.slg01@gmail.com>
  2026-09-29 15:11                                                       ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  0 siblings, 1 reply; 74+ messages in thread

From: Ayush Tiwari @ 2026-09-29 14:10 UTC (permalink / raw)
  To: Tom Lane <tgl@sss.pgh.pa.us>; +Cc: Noah Misch <noah@leadboat.com>; Richard Guo <guofenglinux@gmail.com>; Thom Brown <thom@linux.com>; Jacob Brazeal <jacob.brazeal@gmail.com>; pgsql-hackers@lists.postgresql.org; underdog@theori.io

Hi,

On Sun, 27 Sept 2026 at 22:02, Tom Lane <tgl@sss.pgh.pa.us> wrote:
>
> I wrote:
> > Concretely, about like this.  This fixes the given reproducer.
> > I've not put thought into what sort of test cases we might want
> > to add.
>
> Now with test cases, a commit message explaining why do it like
> this, and a bit of additional comment-polishing.

Thanks for the patch.

I went through v1.  Grouping the SJE candidates by checkAsUser
looks right to me, including the unset case.  I didn't spot any
issues.  LGTM.

Regards,
Ayush






^ permalink  raw  reply  [nested|flat] 74+ messages in thread

* Re: remove_useless_joins vs. bug #19560
  2026-07-20 18:52 remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-24 13:38 ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-07-25 16:46   ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-25 20:07     ` Re: remove_useless_joins vs. bug #19560 Thom Brown <thom@linux.com>
  2026-07-25 21:23       ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-26 02:15         ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-26 09:49           ` Re: remove_useless_joins vs. bug #19560 Thom Brown <thom@linux.com>
  2026-07-26 17:33             ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-26 17:35               ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-27 07:07                 ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-07-27 16:33                   ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-27 18:21                     ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-29 06:21                       ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-16 23:58                         ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-26 05:26                           ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-26 17:25                             ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-27 01:57                               ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-27 15:53                                 ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-28 07:29                                   ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-28 13:43                                     ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-09-17 02:51                                       ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-09-17 07:15                                         ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-09-19 14:05                                           ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-09-26 17:44                                             ` Re: remove_useless_joins vs. bug #19560 Noah Misch <noah@leadboat.com>
  2026-09-26 18:05                                               ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-09-26 19:27                                                 ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-09-27 16:32                                                   ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-09-29 14:10                                                     ` Re: remove_useless_joins vs. bug #19560 Ayush Tiwari <ayushtiwari.slg01@gmail.com>
@ 2026-09-29 15:11                                                       ` Tom Lane <tgl@sss.pgh.pa.us>
  0 siblings, 0 replies; 74+ messages in thread

From: Tom Lane @ 2026-09-29 15:11 UTC (permalink / raw)
  To: Ayush Tiwari <ayushtiwari.slg01@gmail.com>; +Cc: Noah Misch <noah@leadboat.com>; Richard Guo <guofenglinux@gmail.com>; Thom Brown <thom@linux.com>; Jacob Brazeal <jacob.brazeal@gmail.com>; pgsql-hackers@lists.postgresql.org; underdog@theori.io

Ayush Tiwari <ayushtiwari.slg01@gmail.com> writes:
> I went through v1.  Grouping the SJE candidates by checkAsUser
> looks right to me, including the unset case.  I didn't spot any
> issues.  LGTM.

Pushed, thanks for looking at it!

			regards, tom lane






^ permalink  raw  reply  [nested|flat] 74+ messages in thread

* Re: remove_useless_joins vs. bug #19560
  2026-07-20 18:52 remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-24 13:38 ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-07-25 16:46   ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-25 20:07     ` Re: remove_useless_joins vs. bug #19560 Thom Brown <thom@linux.com>
  2026-07-25 21:23       ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-26 02:15         ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-26 09:49           ` Re: remove_useless_joins vs. bug #19560 Thom Brown <thom@linux.com>
  2026-07-26 17:33             ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-26 17:35               ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-27 07:07                 ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-07-27 16:33                   ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-27 18:21                     ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-29 06:21                       ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
@ 2026-08-26 07:33                         ` Richard Guo <guofenglinux@gmail.com>
  2026-08-26 14:02                           ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  1 sibling, 1 reply; 74+ messages in thread

From: Richard Guo @ 2026-08-26 07:33 UTC (permalink / raw)
  To: Tom Lane <tgl@sss.pgh.pa.us>; +Cc: Thom Brown <thom@linux.com>; Jacob Brazeal <jacob.brazeal@gmail.com>; pgsql-hackers@lists.postgresql.org

On Wed, Jul 29, 2026 at 3:21 PM Richard Guo <guofenglinux@gmail.com> wrote:
> 4. The commit message claims that "it doesn't seem to result in any
> significant planning-time penalty".  I'm somewhat skeptical of that.

I did some testing of planning time.  Independent removals are fine,
even faster than before: 64 removable joins that each join directly to
t0 plan in 0.57 ms here vs 1.11 ms on master.  They all go in the
first pass, and one extra pass over a single-rel query is cheaper than
the per-removal cleanup the old code did.

Chains of dependent joins are not fine though:

  select t0.id from t0
    left join t1 on t0.nxt = t1.id
    left join t2 on t1.nxt = t2.id
    ...
    left join t64 on t63.nxt = t64.id;

Only t64 can go in the first pass; t63 still looks needed because
attr_needed for t63.nxt includes t64's join, and we only find out
otherwise after the restart.  So each link costs a full pass, and this
plans in 20.9 ms vs 1.98 ms on master.  The gap widens quickly with
the chain length, and views built on views give the same shape.

I think we can fix this without giving up the restart design.  After a
scan has removed something, recompute attr_needed and ph_needed into
temp arrays from the surviving sources (targetlist, the quals in each
rel's baserestrictinfo/joininfo, no-const ECs, PHV expressions,
lateral refs), treating anything whose relids overlap the removed set
as dead, and scan again until nothing more goes.  That's basically
rebuild_*_attr_needed() again, but read-only, and it can only
overestimate what's needed, so a mistake just postpones a removal to
the next restart, and the real derived data is never touched.

Thoughts?

- Richard






^ permalink  raw  reply  [nested|flat] 74+ messages in thread

* Re: remove_useless_joins vs. bug #19560
  2026-07-20 18:52 remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-24 13:38 ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-07-25 16:46   ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-25 20:07     ` Re: remove_useless_joins vs. bug #19560 Thom Brown <thom@linux.com>
  2026-07-25 21:23       ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-26 02:15         ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-26 09:49           ` Re: remove_useless_joins vs. bug #19560 Thom Brown <thom@linux.com>
  2026-07-26 17:33             ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-26 17:35               ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-27 07:07                 ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-07-27 16:33                   ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-27 18:21                     ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-29 06:21                       ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-26 07:33                         ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
@ 2026-08-26 14:02                           ` Tom Lane <tgl@sss.pgh.pa.us>
  2026-08-27 00:51                             ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  0 siblings, 1 reply; 74+ messages in thread

From: Tom Lane @ 2026-08-26 14:02 UTC (permalink / raw)
  To: Richard Guo <guofenglinux@gmail.com>; +Cc: Thom Brown <thom@linux.com>; Jacob Brazeal <jacob.brazeal@gmail.com>; pgsql-hackers@lists.postgresql.org

Richard Guo <guofenglinux@gmail.com> writes:
> I did some testing of planning time.  Independent removals are fine,
> even faster than before: 64 removable joins that each join directly to
> t0 plan in 0.57 ms here vs 1.11 ms on master.  They all go in the
> first pass, and one extra pass over a single-rel query is cheaper than
> the per-removal cleanup the old code did.

Thanks for looking into this!

> Chains of dependent joins are not fine though:

>   select t0.id from t0
>     left join t1 on t0.nxt = t1.id
>     left join t2 on t1.nxt = t2.id
>     ...
>     left join t64 on t63.nxt = t64.id;

> Only t64 can go in the first pass; t63 still looks needed because
> attr_needed for t63.nxt includes t64's join, and we only find out
> otherwise after the restart.  So each link costs a full pass, and this
> plans in 20.9 ms vs 1.98 ms on master.  The gap widens quickly with
> the chain length, and views built on views give the same shape.

I'm skeptical that this example is a deal-breaker, because it seems
quite artificial.  Queries with this many relations would typically
take a long time to plan.  If we're somewhat slower to deal with the
edge case where most of the joins vanish, is anyone really likely to
notice?  So I'm hesitant to add complexity in hopes of making the
edge case faster.  Especially since this is a bug fix that I'm hoping
to back-patch; every dollop of complexity adds risk.

			regards, tom lane






^ permalink  raw  reply  [nested|flat] 74+ messages in thread

* Re: remove_useless_joins vs. bug #19560
  2026-07-20 18:52 remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-24 13:38 ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-07-25 16:46   ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-25 20:07     ` Re: remove_useless_joins vs. bug #19560 Thom Brown <thom@linux.com>
  2026-07-25 21:23       ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-26 02:15         ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-26 09:49           ` Re: remove_useless_joins vs. bug #19560 Thom Brown <thom@linux.com>
  2026-07-26 17:33             ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-26 17:35               ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-27 07:07                 ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-07-27 16:33                   ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-27 18:21                     ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-29 06:21                       ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-26 07:33                         ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-08-26 14:02                           ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
@ 2026-08-27 00:51                             ` Richard Guo <guofenglinux@gmail.com>
  0 siblings, 0 replies; 74+ messages in thread

From: Richard Guo @ 2026-08-27 00:51 UTC (permalink / raw)
  To: Tom Lane <tgl@sss.pgh.pa.us>; +Cc: Thom Brown <thom@linux.com>; Jacob Brazeal <jacob.brazeal@gmail.com>; pgsql-hackers@lists.postgresql.org

On Wed, Aug 26, 2026 at 11:03 PM Tom Lane <tgl@sss.pgh.pa.us> wrote:
> I'm skeptical that this example is a deal-breaker, because it seems
> quite artificial.  Queries with this many relations would typically
> take a long time to plan.  If we're somewhat slower to deal with the
> edge case where most of the joins vanish, is anyone really likely to
> notice?  So I'm hesitant to add complexity in hopes of making the
> edge case faster.  Especially since this is a bug fix that I'm hoping
> to back-patch; every dollop of complexity adds risk.

Fair enough.  Thinking about it more, this regression only happens
when we remove a lot of joins that depend on each other.  In that
case, the query becomes smaller after each restart, so the total
planning time is still much less than planning the query with all
those joins.

Also, I do not like my proposal about recomputing attr_needed very
much.  It computes attr_needed again in another place, which would be
a maintenance burden, especially in stable branches.  So let's not do
it.

- Richard






^ permalink  raw  reply  [nested|flat] 74+ messages in thread

* Re: remove_useless_joins vs. bug #19560
  2026-07-20 18:52 remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-24 13:38 ` Re: remove_useless_joins vs. bug #19560 Richard Guo <guofenglinux@gmail.com>
  2026-07-25 16:46   ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
  2026-07-25 20:07     ` Re: remove_useless_joins vs. bug #19560 Thom Brown <thom@linux.com>
  2026-07-25 21:23       ` Re: remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
@ 2026-07-26 20:34         ` Tom Lane <tgl@sss.pgh.pa.us>
  1 sibling, 0 replies; 74+ messages in thread

From: Tom Lane @ 2026-07-26 20:34 UTC (permalink / raw)
  To: Thom Brown <thom@linux.com>; +Cc: Richard Guo <guofenglinux@gmail.com>; pgsql-hackers@lists.postgresql.org

I wrote:
> As for the speed question, I'd not poked at the details of Claude's
> claim, but I guess I should have.

I asked Claude to explain exactly how it arrived at its numbers,
and the answer is that it missed the problem the first time, partly
through not trying to go higher than N=8.  Full details attached for
the archives' sake, though I think this is now of mostly academic
interest.

			regards, tom lane

Attachments:

  benchmark.tar.gz (application/gzip, 6.3K) download

^ permalink  raw  reply  [nested|flat] 74+ messages in thread


end of thread, other threads:[~2026-10-06 02:04 UTC | newest]

Thread overview: 74+ messages (download: mbox mbox.gz follow: Atom feed)
-- links below jump to the message on this page --
2026-07-20 18:52 remove_useless_joins vs. bug #19560 Tom Lane <tgl@sss.pgh.pa.us>
2026-07-22 07:44 ` Tender Wang <tndrwang@gmail.com>
2026-07-24 13:38 ` Richard Guo <guofenglinux@gmail.com>
2026-07-25 16:46   ` Tom Lane <tgl@sss.pgh.pa.us>
2026-07-25 20:07     ` Thom Brown <thom@linux.com>
2026-07-25 21:23       ` Tom Lane <tgl@sss.pgh.pa.us>
2026-07-26 02:15         ` Tom Lane <tgl@sss.pgh.pa.us>
2026-07-26 04:23           ` Jacob Brazeal <jacob.brazeal@gmail.com>
2026-07-26 04:27             ` Jacob Brazeal <jacob.brazeal@gmail.com>
2026-07-26 09:49           ` Thom Brown <thom@linux.com>
2026-07-26 17:33             ` Tom Lane <tgl@sss.pgh.pa.us>
2026-07-26 17:35               ` Tom Lane <tgl@sss.pgh.pa.us>
2026-07-27 07:07                 ` Richard Guo <guofenglinux@gmail.com>
2026-07-27 16:33                   ` Tom Lane <tgl@sss.pgh.pa.us>
2026-07-27 18:21                     ` Tom Lane <tgl@sss.pgh.pa.us>
2026-07-28 08:58                       ` Tender Wang <tndrwang@gmail.com>
2026-07-28 12:24                         ` Tom Lane <tgl@sss.pgh.pa.us>
2026-07-28 13:03                           ` Tender Wang <tndrwang@gmail.com>
2026-07-29 06:21                       ` Richard Guo <guofenglinux@gmail.com>
2026-08-16 23:58                         ` Tom Lane <tgl@sss.pgh.pa.us>
2026-08-26 05:26                           ` Richard Guo <guofenglinux@gmail.com>
2026-08-26 17:25                             ` Tom Lane <tgl@sss.pgh.pa.us>
2026-08-27 01:57                               ` Richard Guo <guofenglinux@gmail.com>
2026-08-27 05:46                                 ` Richard Guo <guofenglinux@gmail.com>
2026-08-27 15:53                                 ` Tom Lane <tgl@sss.pgh.pa.us>
2026-08-28 07:29                                   ` Richard Guo <guofenglinux@gmail.com>
2026-08-28 13:43                                     ` Tom Lane <tgl@sss.pgh.pa.us>
2026-08-29 03:03                                       ` Tender Wang <tndrwang@gmail.com>
2026-08-29 03:27                                       ` Tom Lane <tgl@sss.pgh.pa.us>
2026-08-29 20:10                                         ` Tom Lane <tgl@sss.pgh.pa.us>
2026-08-30 06:50                                           ` Richard Guo <guofenglinux@gmail.com>
2026-08-30 15:33                                             ` Tom Lane <tgl@sss.pgh.pa.us>
2026-08-30 16:20                                             ` Tom Lane <tgl@sss.pgh.pa.us>
2026-08-31 01:54                                               ` Richard Guo <guofenglinux@gmail.com>
2026-09-03 14:55                                                 ` Tom Lane <tgl@sss.pgh.pa.us>
2026-09-09 08:04                                                   ` Richard Guo <guofenglinux@gmail.com>
2026-09-09 14:54                                                     ` Tom Lane <tgl@sss.pgh.pa.us>
2026-09-10 09:33                                                       ` Richard Guo <guofenglinux@gmail.com>
2026-09-13 17:32                                                         ` Tom Lane <tgl@sss.pgh.pa.us>
2026-09-14 05:10                                                           ` Richard Guo <guofenglinux@gmail.com>
2026-09-15 16:28                                                             ` Fujii Masao <masao.fujii@gmail.com>
2026-09-16 00:38                                                               ` Richard Guo <guofenglinux@gmail.com>
2026-09-16 05:16                                                                 ` Fujii Masao <masao.fujii@gmail.com>
2026-09-16 06:58                                                                   ` Tender Wang <tndrwang@gmail.com>
2026-09-16 07:02                                                                   ` Richard Guo <guofenglinux@gmail.com>
2026-09-16 04:56                                                               ` Richard Guo <guofenglinux@gmail.com>
2026-09-19 13:14                                                                 ` Richard Guo <guofenglinux@gmail.com>
2026-09-25 11:43                                                                   ` Ayush Tiwari <ayushtiwari.slg01@gmail.com>
2026-10-03 18:43                                                                     ` Ayush Tiwari <ayushtiwari.slg01@gmail.com>
2026-10-04 06:14                                                                     ` Richard Guo <guofenglinux@gmail.com>
2026-10-06 02:04                                                                       ` Richard Guo <guofenglinux@gmail.com>
2026-08-31 01:55                                               ` Tender Wang <tndrwang@gmail.com>
2026-08-31 07:32                                                 ` Richard Guo <guofenglinux@gmail.com>
2026-08-31 15:56                                                   ` Tom Lane <tgl@sss.pgh.pa.us>
2026-09-01 02:07                                                     ` Richard Guo <guofenglinux@gmail.com>
2026-09-01 15:35                                                       ` Tom Lane <tgl@sss.pgh.pa.us>
2026-09-02 05:37                                                         ` Richard Guo <guofenglinux@gmail.com>
2026-09-02 03:42                                                       ` Tender Wang <tndrwang@gmail.com>
2026-09-17 02:40                                       ` Richard Guo <guofenglinux@gmail.com>
2026-09-17 02:51                                       ` Tom Lane <tgl@sss.pgh.pa.us>
2026-09-17 07:15                                         ` Richard Guo <guofenglinux@gmail.com>
2026-09-18 19:22                                           ` Haibo Yan <tristan.yim@gmail.com>
2026-09-19 01:45                                             ` Richard Guo <guofenglinux@gmail.com>
2026-09-19 14:05                                           ` Richard Guo <guofenglinux@gmail.com>
2026-09-26 17:44                                             ` Noah Misch <noah@leadboat.com>
2026-09-26 18:05                                               ` Tom Lane <tgl@sss.pgh.pa.us>
2026-09-26 19:27                                                 ` Tom Lane <tgl@sss.pgh.pa.us>
2026-09-27 16:32                                                   ` Tom Lane <tgl@sss.pgh.pa.us>
2026-09-29 14:10                                                     ` Ayush Tiwari <ayushtiwari.slg01@gmail.com>
2026-09-29 15:11                                                       ` Tom Lane <tgl@sss.pgh.pa.us>
2026-08-26 07:33                         ` Richard Guo <guofenglinux@gmail.com>
2026-08-26 14:02                           ` Tom Lane <tgl@sss.pgh.pa.us>
2026-08-27 00:51                             ` Richard Guo <guofenglinux@gmail.com>
2026-07-26 20:34         ` Tom Lane <tgl@sss.pgh.pa.us>

This inbox is served by DDX for PostgreSQL; see mirroring instructions
for how to clone and mirror all data and code used for this inbox