pgsql: Fix stale copies of PHVs in subqueries

From: Richard Guo <rguo(at)postgresql(dot)org>
To: pgsql-committers(at)lists(dot)postgresql(dot)org
Subject: pgsql: Fix stale copies of PHVs in subqueries
Date: 2026-09-14 03:31:59
Message-ID: E1x5xQF-00000000EAa-1Tvf@gemulon.postgresql.org
Views: Whole Thread | Raw Message | Download mbox | Resend email
Thread:
Lists: pgsql-committers

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 <tndrwang(at)gmail(dot)com>
Author: Richard Guo <guofenglinux(at)gmail(dot)com>
Reviewed-by: Tom Lane <tgl(at)sss(dot)pgh(dot)pa(dot)us>
Discussion: https://postgr.es/m/CAHewXN=kWGAXV537mKtSyBYobGdHhYJVDJJMXXZEmmPWE_zaPw@mail.gmail.com
Backpatch-through: 16

Branch
------
REL_19_STABLE

Details
-------
https://git.postgresql.org/pg/commitdiff/2d48d0f153dc86c71a1ab80c5252ab35bb1d84b7

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(-)

Browse pgsql-committers by date

  From Date Subject
Next Message Amit Kapila 2026-09-14 04:15:40 pgsql: Disallow SET UNLOGGED for tables in a publication's EXCEPT claus
Previous Message Michael Paquier 2026-09-14 03:07:38 pgsql: Check that a promoted standby keeps its 8-byte OID counter