Properly handling aggregate in nested function call

From: Matt Magoffin <postgresql(dot)org(at)msqr(dot)us>
To: pgsql-general(at)lists(dot)postgresql(dot)org
Subject: Properly handling aggregate in nested function call
Date: 2021-12-13 21:12:31
Message-ID: 0005FD8A-0FBE-4D53-BBDE-7242A4DC525C@msqr.us
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

I am working on a C aggregate function that returns a numeric[] result. If I execute the aggregate and return the results directly in my SQL, I get the expected results. For example:

SELECT vec_agg_mean(nums) FROM measurements;
NOTICE: avg 0 = 1.23000000000000000000
NOTICE: avg 1 = 1.9700000000000000
NOTICE: avg 2 = 3.7000000000000000
vec_agg_mean
----------------------------------------------------------------
{1.23000000000000000000,1.9700000000000000,3.7000000000000000}
(1 row)

The NOTICE logs are are there to help me verify the computed result in the aggregate final function, and they essentially do

DatumGetCString(DirectFunctionCall1(numeric_out, datum))

However if I nest the aggregate inside something, such as unnest(), I get what appear to be just memory addresses:

SELECT unnest(vec_agg_mean(nums)) FROM measurements;
NOTICE: avg 0 = 1.23000000000000000000
NOTICE: avg 1 = 1.9700000000000000
NOTICE: avg 2 = 3.7000000000000000
unnest
----------------
94674302945040
94674302945052
94674302945064
(3 rows)

You can see the NOTICE logs are still the same. Passing the aggregate result to any other function seems to expose the problem, for example:

SELECT ARRAY[vec_agg_mean(nums)]::numeric[] FROM measurements;
NOTICE: avg 0 = 1.23000000000000000000
NOTICE: avg 1 = 1.9700000000000000
NOTICE: avg 2 = 3.7000000000000000
array
--------------------------------------------------
{{94674302928624,94674302928636,94674302928648}}
(1 row)

Any ideas what I’m doing wrong here? The source is available here:

https://github.com/SolarNetwork/aggs_for_vecs/blob/9e742cdc32a113268fd3c1f928c8ac724acec9f5/vec_agg_mean.c <https://github.com/SolarNetwork/aggs_for_vecs/blob/9e742cdc32a113268fd3c1f928c8ac724acec9f5/vec_agg_mean.c>

Cheers,
Matt Magoffin

Responses

Browse pgsql-general by date

  From Date Subject
Next Message Bryn Llewellyn 2021-12-13 21:15:38 Re: Why can't I have a "language sql" anonymous block?
Previous Message Tom Lane 2021-12-13 20:53:37 Re: Why can't I have a "language sql" anonymous block?