Fix EXPLAIN failure when deparsing SQL/JSON aggregates If an expression containing an aggregate is evaluated above the plan node that computes the aggregate, as happens with window functions or with expressions postponed to above the final sort, setrefs.c replaces the Aggref or WindowFunc with a Var referencing the lower node's output. For SQL/JSON aggregates such as JSON_ARRAYAGG and JSON_OBJECTAGG, deparsing the containing JsonConstructorExpr then failed with "invalid JsonConstructorExpr underlying node type", since get_json_agg_constructor() did not expect a Var there.
Fix by resolving the Var back to the underlying Aggref or WindowFunc and deparsing the constructor as if the aggregate were computed at the current node. The JsonConstructorExpr retains the RETURNING clause and the ABSENT/NULL ON NULL and WITH UNIQUE options, and the arguments come from the resolved aggregate, so the original JSON aggregate syntax is reproduced in full. This mirrors how get_agg_expr() already looks through such a Var when deparsing a combining aggregate. Reported-by: Thom Brown <[email protected]> Author: Richard Guo <[email protected]> Discussion: https://postgr.es/m/CAA-aLv5QYTaMOk=qhv6cgwceehetzv8yjvwz_rh+yvzcuch...@mail.gmail.com Backpatch-through: 16 Branch ------ REL_16_STABLE Details ------- https://git.postgresql.org/pg/commitdiff/485527190a97f7eb57a1ce28e140d9e5f3f60f0a Modified Files -------------- src/backend/utils/adt/ruleutils.c | 32 ++++++++++++ src/test/regress/expected/sqljson.out | 98 +++++++++++++++++++++++++++++++++++ src/test/regress/sql/sqljson.sql | 41 +++++++++++++++ 3 files changed, 171 insertions(+)
