Subject: pgsql: Build whole-row Vars the same way during parsing and planning.

From: Tom Lane <[email-masked]>
Date: Wed, 12 Mar 2025 15:48:05 +0000

Build whole-row Vars the same way during parsing and planning.

makeWholeRowVar() has different rules for constructing a
whole-row Var depending on the kind of RTE it's representing.
This turns out to be problematic because the rewriter and planner
can convert view RTEs and set-returning-function RTEs into
subquery RTEs; so a whole-row Var made during planning might
look different from one made by the parser.  In isolation this
doesn't cause any problem, but if a query contains Vars made
both ways for the same varno, there are cross-checks in the
executor that will complain.  This manifests for UPDATE, DELETE,
and MERGE queries that use whole-row table references.

To fix, we need makeWholeRowVar() to produce the same result
from an inlined RTE as it would have for the original.  For
an inlined view, we can use RangeTblEntry.relid to detect
that this had been a view RTE.  For inlined SRFs, make a
data structure definition change akin to commit 47bb9db75,
and say that we won't clear RangeTblEntry.functions until
the end of planning.  That allows makeWholeRowVar() to
repeat what it would have done with the unmodified RTE.

Reported-by: Duncan Sands <[email-masked]>
Reported-by: Dean Rasheed <[email-masked]>
Diagnosed-by: Tender Wang <[email-masked]>
Author: Tom Lane <[email-masked]>
Reviewed-by: Dean Rasheed <[email-masked]>
Discussion: https://postgr.es/m/[email-masked]
Backpatch-through: 13

Branch
------
REL_15_STABLE

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

Modified Files
--------------
src/backend/nodes/makefuncs.c             | 51 +++++++++++++++++++++++++--
src/backend/optimizer/prep/prepjointree.c | 10 ++++--
src/test/regress/expected/returning.out   | 57 +++++++++++++++++++++++++++++++
src/test/regress/sql/returning.sql        | 24 +++++++++++++
4 files changed, 138 insertions(+), 4 deletions(-)