In ExecInitModifyTable, don't scribble on the source plan.
authorTom Lane <tgl@sss.pgh.pa.us>
Thu, 22 May 2025 18:28:51 +0000 (14:28 -0400)
committerTom Lane <tgl@sss.pgh.pa.us>
Thu, 22 May 2025 18:28:51 +0000 (14:28 -0400)
commitd376ab570ef95f2eae13a77cbd9ba21383f195f7
tree64ed0a6de3a4904c2dc1b317c4c134e925e3af5d
parentf24605e2dc1687917766f43775f0dcde2cf678a0
In ExecInitModifyTable, don't scribble on the source plan.

The code carelessly modified mtstate->ps.plan->targetlist,
which it's not supposed to do.  Fortunately, there's not
really any need to do that because the planner already
set up a perfectly acceptable targetlist for the plan node.
We just need to remove the erroneous assignments and update some
relevant comments.

As it happens, the erroneous assignments caused the targetlist to
point to a different part of the source plan tree, so that there
isn't really a risk of the pointer becoming dangling after executor
termination.  The only visible effect of this change we can find is
that EXPLAIN will show upper references to the ModifyTable's output
expressions using different variables.  Formerly it showed Vars from
the first target relation that survived executor-startup pruning.
Now it always shows such references using the first relation appearing
in the planner output, independently of what happens during executor
pruning.  On the whole that seems like a good thing.

Also make a small tweak in ExplainPreScanNode to ensure that the first
relation will receive a refname assignment in set_rtable_names, even
if it got pruned at startup.  Previously the Vars might be shown
without any table qualification, which is confusing in a multi-table
query.

I considered back-patching this, but since the bug doesn't seem to
have any really terrible consequences in existing branches, it
seems better to not change their EXPLAIN output.  It's not too late
for v18 though, especially since v18 already made other changes in
the EXPLAIN output for these cases.

Reported-by: Tom Lane <tgl@sss.pgh.pa.us>
Author: Andres Freund <andres@anarazel.de>
Co-authored-by: Tom Lane <tgl@sss.pgh.pa.us>
Discussion: https://postgr.es/m/213261.1747611093@sss.pgh.pa.us
src/backend/commands/explain.c
src/backend/executor/nodeModifyTable.c
src/backend/optimizer/plan/setrefs.c
src/test/regress/expected/partition_prune.out
src/test/regress/sql/partition_prune.sql