Subject: pgsql: Don't flatten join alias Vars that are stored within a GROUP RTE

From: Tom Lane <[email-masked]>
Date: Fri, 27 Feb 2026 17:54:11 +0000

Don't flatten join alias Vars that are stored within a GROUP RTE.

The RTE's groupexprs list is used for deparsing views, and for that
usage it must contain the original alias Vars; else we can get
incorrect SQL output.  But since commit 247dea89f,
parseCheckAggregates put the GROUP BY expressions through
flatten_join_alias_vars before building the RTE_GROUP RTE.
Changing the order of operations there is enough to fix it.

This patch unfortunately can do nothing for already-created views:
if they use a coding pattern that is subject to the bug, they will
deparse incorrectly and hence present a dump/reload hazard in the
future.  The only fix is to recreate the view from the original SQL.
But the trouble cases seem to be quite narrow.  AFAICT the output
was only wrong for "SELECT ... t1 LEFT JOIN t2 USING (x) GROUP BY x"
where t1.x and t2.x were not of identical data types and t1.x was
the side that required an implicit coercion.  If there was no hidden
coercion, or if the join was plain, RIGHT, or FULL, the deparsed
output was uglier than intended but not functionally wrong.

Reported-by: Swirl Smog Dowry <[email-masked]>
Author: Tom Lane <[email-masked]>
Reviewed-by: Richard Guo <[email-masked]>
Discussion: https://postgr.es/m/[email-masked]
Backpatch-through: 18

Branch
------
master

Details
-------
https://git.postgresql.org/pg/commitdiff/98616ac18b49ac9f84a96177d8a7822f34904183

Modified Files
--------------
src/backend/parser/parse_agg.c           | 36 +++++++++++++++++---------------
src/test/regress/expected/aggregates.out | 13 ++++++++++++
src/test/regress/sql/aggregates.sql      |  6 ++++++
3 files changed, 38 insertions(+), 17 deletions(-)