public inbox for [email protected]  
help / color / mirror / Atom feed
From: Tom Lane <[email protected]>
To: jian he <[email protected]>
Cc: [email protected]
Subject: Re: Making jsonb_agg() faster
Date: Fri, 15 Aug 2025 18:40:29 -0400
Message-ID: <[email protected]> (raw)
In-Reply-To: <CACJufxGHLYtvOAB7uA59C9Lz+rDPta5Egiii-B5opsZbw6eDDQ@mail.gmail.com>
References: <[email protected]>
	<CACJufxHuE-P0s1PxiRja26ZMjKUZiCAgWa1jedswo94SFzjXMg@mail.gmail.com>
	<[email protected]>
	<CACJufxGHLYtvOAB7uA59C9Lz+rDPta5Egiii-B5opsZbw6eDDQ@mail.gmail.com>

jian he <[email protected]> writes:
> about 0002:
> jsonb_agg_finalfn
>     /*
>      * The final function can be called more than once, so we must not change
>      * the stored JsonbValue data structure.  Fortunately, the WJB_END_ARRAY
>      * action will only change fields in the JsonbInState struct itself, so we
>      * can simply invoke pushJsonbValue on a local copy of that.
>      */
> I don't understand the above comments.
> If I add another ``pushJsonbValue(&result, WJB_END_ARRAY, NULL);``
> then it will cause segmentation fault, that means we can not call
> WJB_END_ARRAY action twice.

No, but so what?  We're not doing that twice here.

> in finalize_aggregate:
> there is no foreach loop within
> ```if (OidIsValid(peragg->finalfn_oid))```
> Overall, I can not come up with a case where the final function is
> called more than once.

If memory serves, the issue arises when the aggregate is used as a
window function.  If the frame definition allows, the operation will
proceed like "accumulate a row into the transition state, call the
finalfn to get the aggregate's result at this row, accumulate another
row into the transition state, call the finalfn to get the aggregate's
result at that row, accumulate another row, yadda yadda".  So in this
example, the point is not about calling the finalfn more than once per
row, but that it mustn't damage the transition state in case we choose
to accumulate more data.

There are also cases where multiple finalfns can be called on the
same transition state, although that requires aggregates that share a
transfn, and I don't think jsonb_agg shares its transfn with anything
else.

See the discussion of FINALFUNC_MODIFY in the CREATE AGGREGATE man
page for more details.

			regards, tom lane





view thread (25+ messages)  latest in thread

reply

Reply instructions:

You may reply publicly to this message via plain-text email
using any one of the following methods:

* Reply to all the recipients using the --to and --cc options:
  reply via email

  To: [email protected]
  Cc: [email protected], [email protected], [email protected]
  Subject: Re: Making jsonb_agg() faster
  In-Reply-To: <[email protected]>

* Save the following mbox file, import it into your mail client,
  and reply-to-all from there: mbox

This inbox is served by agora; see mirroring instructions
for how to clone and mirror all data and code used for this inbox