pgsql: Fix EXPLAIN failure when deparsing SQL/JSON aggregates

From: Richard Guo <rguo(at)postgresql(dot)org>
To: pgsql-committers(at)lists(dot)postgresql(dot)org
Subject: pgsql: Fix EXPLAIN failure when deparsing SQL/JSON aggregates
Date: 2026-07-07 23:51:50
Message-ID: E1whFZt-0004GA-2f@gemulon.postgresql.org
Views: Whole Thread | Raw Message | Download mbox | Resend email
Thread:
Lists: pgsql-committers

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 <thom(at)linux(dot)com>
Author: Richard Guo <guofenglinux(at)gmail(dot)com>
Discussion: https://postgr.es/m/CAA-aLv5QYTaMOk=Qhv6cgwceeHETZV8YJvWZ_rH+yVZCuchATA@mail.gmail.com
Backpatch-through: 16

Branch
------
REL_19_STABLE

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

Modified Files
--------------
src/backend/utils/adt/ruleutils.c | 32 +++++++++++
src/test/regress/expected/sqljson.out | 101 ++++++++++++++++++++++++++++++++++
src/test/regress/sql/sqljson.sql | 41 ++++++++++++++
3 files changed, 174 insertions(+)

Browse pgsql-committers by date

  From Date Subject
Next Message Fujii Masao 2026-07-08 00:06:09 pgsql: doc: Fix typo in rule-system view example
Previous Message Jeff Davis 2026-07-07 22:34:23 pgsql: unicode_case.c: change API to signal UTF8 decoding error.