From: Tom Lane <tgl@sss.pgh.pa.us>
To: pgsql-committers@lists.postgresql.org
Subject: pgsql: Fix SEARCH/CYCLE when the recursive term has resjunk columns.
Date: Fri, 20 Nov 2026 16:52:33 +0000
Message-ID: <E1xURqi-00000000XUg-0hC7@gemulon.postgresql.org> (raw)
Fix SEARCH/CYCLE when the recursive term has resjunk columns.
rewriteSearchAndCycle() appended the extra SEARCH/CYCLE columns to
the end of the recursive term's targetlist. If that targetlist had
resjunk entries, for example a window function's ORDER BY column or a
GROUP BY column that is not selected, the new columns landed after
them. That breaks the expectation that resjunk entries come last, and
the column names added to the wrapping subquery then pointed at the
wrong entries. Depending on the query, this caused errors such as
"could not find replacement targetlist entry" or "attribute N of type
record has wrong type", an assertion failure in assert-enabled builds,
or silently wrong results.
Fix by detaching any resjunk entries before adding the new columns and
re-attaching them afterwards with renumbered resnos. Sort/group
clauses reference targetlist entries via ressortgroupref, not resno,
so renumbering them is safe.
The non-recursive term is not affected, since it is wrapped in a new
subquery without modifying its targetlist.
Bug: #19922
Reported-by: Robins Tharakan <tharakan@gmail.com>
Diagnosed-by: Tom Lane <tgl@sss.pgh.pa.us>
Author: Nitin Motiani <nitinmotiani@google.com>
Reviewed-by: Tom Lane <tgl@sss.pgh.pa.us>
Discussion: https://postgr.es/m/19922-a0d338245d361a4c@postgresql.org
Backpatch-through: 15
Branch
------
REL_15_STABLE
Details
-------
https://git.postgresql.org/pg/commitdiff/0f8e93fab91ea2efe1410b52e31edbefefb074c8
Modified Files
--------------
src/backend/rewrite/rewriteSearchCycle.c | 42 ++++++++++++++++++++++++++++++--
src/test/regress/expected/with.out | 40 ++++++++++++++++++++++++++++++
src/test/regress/sql/with.sql | 23 +++++++++++++++++
3 files changed, 103 insertions(+), 2 deletions(-)
Reply instructions:
You may reply publicly to this message via plain-text email
using any one of the following methods:
* Reply to all the recipients from your mail client; the link fills in
the headers below: reply via email
Some clients, webmail especially, drop In-Reply-To and References from
a link, and the reply then starts a new thread: use the mbox below.
To: pgsql-committers@postgresql.org
Cc: tgl@sss.pgh.pa.us
Subject: Re: pgsql: Fix SEARCH/CYCLE when the recursive term has resjunk columns.
In-Reply-To: <E1xURqi-00000000XUg-0hC7@gemulon.postgresql.org>
References: <E1xURqi-00000000XUg-0hC7@gemulon.postgresql.org>
* Save the following mbox file, import it into your mail client,
and reply-to-all from there: mbox
This inbox is served by DDX for PostgreSQL; see mirroring instructions
for how to clone and mirror all data and code used for this inbox