pgsql: Fix unsafe RTE_GROUP removal in simplify_EXISTS_query

From: Richard Guo <rguo(at)postgresql(dot)org>
To: pgsql-committers(at)lists(dot)postgresql(dot)org
Subject: pgsql: Fix unsafe RTE_GROUP removal in simplify_EXISTS_query
Date: 2026-02-25 02:16:28
Message-ID: E1vv4Rw-0012Rq-0g@gemulon.postgresql.org
Views: Whole Thread | Raw Message | Download mbox | Resend email
Thread:
Lists: pgsql-committers

Fix unsafe RTE_GROUP removal in simplify_EXISTS_query

When simplify_EXISTS_query removes the GROUP BY clauses from an EXISTS
subquery, it previously deleted the RTE_GROUP RTE directly from the
subquery's range table.

This approach is dangerous because deleting an RTE from the middle of
the rtable list shifts the index of any subsequent RTE, which can
silently corrupt any Var nodes in the query tree that reference those
later relations. (Currently, this direct removal has not caused
problems because the RTE_GROUP RTE happens to always be the last entry
in the rtable list. However, relying on that is extremely fragile and
seems like trouble waiting to happen.)

Instead of deleting the RTE_GROUP RTE, this patch converts it in-place
to be RTE_RESULT type and clears its groupexprs list. This preserves
the length and indexing of the rtable list, ensuring all Var
references remain intact.

Reported-by: Tom Lane <tgl(at)sss(dot)pgh(dot)pa(dot)us>
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/3472344.1771858107@sss.pgh.pa.us
Backpatch-through: 18

Branch
------
REL_18_STABLE

Details
-------
https://git.postgresql.org/pg/commitdiff/1c7358099cbe77bc622bc817ec4e9d919ca91fcf

Modified Files
--------------
src/backend/optimizer/plan/subselect.c | 34 +++++++++++++++++-----------------
1 file changed, 17 insertions(+), 17 deletions(-)

Browse pgsql-committers by date

  From Date Subject
Next Message Álvaro Herrera 2026-02-25 10:27:48 Re: pgsql: libpq: Grease the protocol by default
Previous Message Andrew Dunstan 2026-02-25 02:06:57 Re: pgsql: libpq: Grease the protocol by default