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. Back-patch to v16, as with commit 2ebf25e7d. Reported-by: Tender Wang <[email protected]> Author: Richard Guo <[email protected]> Reviewed-by: Tom Lane <[email protected]> Discussion: https://postgr.es/m/CAHewXN=kwgaxv537mktsybyobgdhhyjvdjjmxxzemmpwe_z...@mail.gmail.com Backpatch-through: 16 Branch ------ REL_17_STABLE Details ------- https://git.postgresql.org/pg/commitdiff/ccb7d9dba1c3705c544ddee129f2dec677920a03 Modified Files -------------- src/backend/optimizer/plan/initsplan.c | 15 ++-- src/backend/optimizer/plan/planner.c | 90 ++++++++++++++++++++ src/backend/optimizer/plan/subselect.c | 12 +-- src/backend/optimizer/util/clauses.c | 35 ++++---- src/backend/optimizer/util/var.c | 33 ++++++-- src/test/regress/expected/join.out | 145 +++++++++++++++++++++++++++++++++ src/test/regress/sql/join.sql | 47 +++++++++++ src/tools/pgindent/typedefs.list | 1 + 8 files changed, 344 insertions(+), 34 deletions(-)
