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
------
master

Details
-------
https://git.postgresql.org/pg/commitdiff/e28cf96e9351152760a24ccb55f3f66c26961294

Modified Files
--------------
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           |  33 +++++-
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, 360 insertions(+), 68 deletions(-)

Reply via email to