pgsql: Fix incorrect targetlist in dummy UNIONs

From: David Rowley <drowley(at)postgresql(dot)org>
To: pgsql-committers(at)lists(dot)postgresql(dot)org
Subject: pgsql: Fix incorrect targetlist in dummy UNIONs
Date: 2025-10-07 01:15:28
Message-ID: E1v5wIa-000QS3-06@gemulon.postgresql.org
Views: Whole Thread | Raw Message | Download mbox | Resend email
Thread:
Lists: pgsql-committers

Fix incorrect targetlist in dummy UNIONs

The prior code, added in 03d40e4b5 attempted to use the targetlist of the
first UNION child when all UNION children were proven as dummy rels.
That's not going to work when some operation atop of the Result node must
find target entries within the Result's targetlist. This could have been
something as simple as trying to sort the results of the UNION operation,
which would lead to:

ERROR: could not find pathkey item to sort

Instead, use the top-level UNION's targetlist and fix the varnos in
setrefs.c. Because set operation targetlists always use varno==0, we
can rewrite those to become varno==1, i.e. use the Vars from the first
UNION child. This does result in showing Vars from relations that are
not present in the final plan, but that's no different to what we see
when normal base relations are proven dummy.

Without this fix it would be possible to see the following error in
EXPLAIN VERBOSE when all UNION inputs were proven empty.

ERROR: bogus varno: 0

Author: David Rowley <dgrowleyml(at)gmail(dot)com>
Discussion: https://postgr.es/m/CAApHDvrUASy9sfULMEsM2udvZJP6AoBRCZvHYXYxZTy2tX9FYw@mail.gmail.com

Branch
------
master

Details
-------
https://git.postgresql.org/pg/commitdiff/928df067d1e6ca5b747722d32c79bc3efa891a32

Modified Files
--------------
src/backend/optimizer/plan/setrefs.c | 27 +++++++++++++++++++++++----
src/backend/optimizer/prep/prepunion.c | 1 -
src/test/regress/expected/union.out | 18 +++++++++++-------
src/test/regress/sql/union.sql | 3 ++-
4 files changed, 36 insertions(+), 13 deletions(-)

Browse pgsql-committers by date

  From Date Subject
Next Message David Rowley 2025-10-07 04:18:32 pgsql: Teach planner to short-circuit EXCEPT/INTERSECT with dummy input
Previous Message Masahiko Sawada 2025-10-06 21:03:20 pgsql: Avoid unnecessary GinFormTuple() calls for incompressible postin