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 protected]>
Author: Tom Lane <[email protected]>
Reviewed-by: Richard Guo <[email protected]>
Discussion: 
https://postgr.es/m/ca+-gibjcg_vjcq3hwtm0sls3_tuz6q9rkv8+pe2yjrdh4o4...@mail.gmail.com
Backpatch-through: 18

Branch
------
REL_18_STABLE

Details
-------
https://git.postgresql.org/pg/commitdiff/c2c1962a64b547412c88fa2728e4fa35e65f4c90

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(-)

Reply via email to