pg.ddx.io pgsql-hackers@postgresql.org mailing list archive
help / color / mirror / Atom feedAllow a prosupport function to be attached to an aggregate
12+ messages / 3 participants
[nested] [flat]
Commits from this thread:
2026-08-23 8aa49d34e9 165aa5040a Allow an aggregate's planner support function to be set via CREATE AGGREGATE.
* Allow a prosupport function to be attached to an aggregate
@ 2026-08-17 06:13 Andrei Lepikhov <lepihov@gmail.com>
2026-08-18 04:56 ` Re: Allow a prosupport function to be attached to an aggregate David Rowley <dgrowleyml@gmail.com>
0 siblings, 1 reply; 12+ messages in thread
From: Andrei Lepikhov @ 2026-08-17 06:13 UTC (permalink / raw)
To: PostgreSQL Hackers <pgsql-hackers@lists.postgresql.org>; David Rowley <dgrowleyml@gmail.com>; +Cc: Corey Huinker <corey.huinker@gmail.com>
Hi,
Commit 42473b3b31 added SupportRequestSimplifyAggref, which the planner issues
for any Aggref whose function names a support function. Nice, but extensions
cannot reach it, because there is no way to attach a support function to an
aggregate:
ALTER FUNCTION pg_catalog.sum(numeric) SUPPORT numeric_support;
ERROR: "pg_catalog.sum" is an aggregate function
CREATE/ALTER aggregate doesn't support this feature at all. This does not look
like a decision about support functions. AlterFunction() rejects an aggregate
for every property it can change, not just for SUPPORT, and the other properties
it covers are ones AggregateCreate() fixes for aggregates anyway. prosupport is
different: nothing else in the catalog determines it, so refusing to set it
leaves the capability simply unreachable rather than merely inconvenient.
Updating pg_proc directly is not an answer. It records no pg_depend entry, so
the support function can then be dropped and leave a dangling OID behind.
My interest is extension-defined optimizations of numeric aggregates [1] or even
more extravagant dumb transformations, like the following (doable for specific
conditions):
SUM(x ORDER BY x) → SUM(x)
SUM(x) FILTER (WHERE true) → SUM(x)
SUM(N) -> N * COUNT(*)
Please find attached a patch adding SUPPORT to CREATE AGGREGATE's option
list and an ALTER AGGREGATE ... SUPPORT form. Both require superuser,
as the equivalent function clauses do, and record a normal dependency.
[1] https://github.com/danolivo/pg_numeric_agg_support
--
regards, Andrei Lepikhov,
pgEdge
Attachments:
v0-0001-Enable-altering-prosupport-function-of-an-aggrega.patch (text/plain, 13.5K) download
From b90baa875491f48568edf7ed7f41b5850a9c289d Mon Sep 17 00:00:00 2001
From: Claude <noreply@anthropic.com>
Date: Sun, 16 Aug 2026 20:18:30 +0000
Subject: [PATCH v0] Enable altering prosupport function of an aggregate
The prosupport has been settable only through CREATE/ALTER FUNCTION,
that rejects aggregates, so an aggregate could
acquire a support function only as a pg_proc.dat entry or direct catalog
update. Extensions should have more convenient way by a DDL command.
Add SUPPORT to CREATE AGGREGATE's option list, and accept it in
ALTER AGGREGATE. ALTER FUNCTION continues to reject them, as it does for
every other property. Setting a support function requires superuser, as
the equivalent function clauses do, and records a normal dependency on
it. CREATE OR REPLACE AGGREGATE without SUPPORT clears it, matching
CREATE OR REPLACE FUNCTION; as for functions, ALTER cannot clear it.
The restriction that SUPPORT is the only alterable property of an
aggregate is enforced by the grammar for ALTER AGGREGATE.
---
doc/src/sgml/ref/alter_aggregate.sgml | 20 ++++++++++++++++++++
doc/src/sgml/ref/create_aggregate.sgml | 21 +++++++++++++++++++++
src/backend/catalog/pg_aggregate.c | 6 ++++--
src/backend/commands/aggregatecmds.c | 11 ++++++++++-
src/backend/commands/functioncmds.c | 20 ++++++++++++++++++--
src/backend/parser/gram.y | 15 ++++++++++++++-
src/backend/tcop/utility.c | 3 +++
src/bin/psql/tab-complete.in.c | 2 +-
src/include/catalog/pg_aggregate.h | 3 ++-
src/include/commands/defrem.h | 1 +
10 files changed, 94 insertions(+), 8 deletions(-)
diff --git a/doc/src/sgml/ref/alter_aggregate.sgml b/doc/src/sgml/ref/alter_aggregate.sgml
index d0a39ba7b5e..4079a6f7a13 100644
--- a/doc/src/sgml/ref/alter_aggregate.sgml
+++ b/doc/src/sgml/ref/alter_aggregate.sgml
@@ -25,6 +25,7 @@ ALTER AGGREGATE <replaceable>name</replaceable> ( <replaceable>aggregate_signatu
ALTER AGGREGATE <replaceable>name</replaceable> ( <replaceable>aggregate_signature</replaceable> )
OWNER TO { <replaceable>new_owner</replaceable> | CURRENT_ROLE | CURRENT_USER | SESSION_USER }
ALTER AGGREGATE <replaceable>name</replaceable> ( <replaceable>aggregate_signature</replaceable> ) SET SCHEMA <replaceable>new_schema</replaceable>
+ALTER AGGREGATE <replaceable>name</replaceable> ( <replaceable>aggregate_signature</replaceable> ) SUPPORT <replaceable>support_function</replaceable>
<phrase>where <replaceable>aggregate_signature</replaceable> is:</phrase>
@@ -53,6 +54,8 @@ ALTER AGGREGATE <replaceable>name</replaceable> ( <replaceable>aggregate_signatu
the owner doesn't do anything you couldn't do by dropping and recreating
the aggregate function. However, a superuser can alter ownership of any
aggregate function anyway.)
+ To set the aggregate function's planner support function, you must be
+ superuser.
</para>
</refsect1>
@@ -133,6 +136,23 @@ ALTER AGGREGATE <replaceable>name</replaceable> ( <replaceable>aggregate_signatu
</para>
</listitem>
</varlistentry>
+
+ <varlistentry>
+ <term><literal>SUPPORT</literal> <replaceable class="parameter">support_function</replaceable></term>
+ <listitem>
+ <para>
+ Set or change the planner support function to use for this aggregate.
+ See <xref linkend="xfunc-optimization"/> for details. You must be
+ superuser to use this option.
+ </para>
+
+ <para>
+ This option cannot be used to remove the support function altogether,
+ since it must name a new support function. Use <command>CREATE OR
+ REPLACE AGGREGATE</command> if you need to do that.
+ </para>
+ </listitem>
+ </varlistentry>
</variablelist>
</refsect1>
diff --git a/doc/src/sgml/ref/create_aggregate.sgml b/doc/src/sgml/ref/create_aggregate.sgml
index 0472ac2e874..b5829091abc 100644
--- a/doc/src/sgml/ref/create_aggregate.sgml
+++ b/doc/src/sgml/ref/create_aggregate.sgml
@@ -42,6 +42,7 @@ CREATE [ OR REPLACE ] AGGREGATE <replaceable class="parameter">name</replaceable
[ , MINITCOND = <replaceable class="parameter">minitial_condition</replaceable> ]
[ , SORTOP = <replaceable class="parameter">sort_operator</replaceable> ]
[ , PARALLEL = { SAFE | RESTRICTED | UNSAFE } ]
+ [ , SUPPORT = <replaceable class="parameter">support_function</replaceable> ]
)
CREATE [ OR REPLACE ] AGGREGATE <replaceable class="parameter">name</replaceable> ( [ [ <replaceable class="parameter">argmode</replaceable> ] [ <replaceable class="parameter">argname</replaceable> ] <replaceable class="parameter">arg_data_type</replaceable> [ , ... ] ]
@@ -54,6 +55,7 @@ CREATE [ OR REPLACE ] AGGREGATE <replaceable class="parameter">name</replaceable
[ , FINALFUNC_MODIFY = { READ_ONLY | SHAREABLE | READ_WRITE } ]
[ , INITCOND = <replaceable class="parameter">initial_condition</replaceable> ]
[ , PARALLEL = { SAFE | RESTRICTED | UNSAFE } ]
+ [ , SUPPORT = <replaceable class="parameter">support_function</replaceable> ]
[ , HYPOTHETICAL ]
)
@@ -644,6 +646,25 @@ SELECT col FROM tab ORDER BY col USING sortop LIMIT 1;
</listitem>
</varlistentry>
+ <varlistentry>
+ <term><literal>SUPPORT =</literal> <replaceable class="parameter">support_function</replaceable></term>
+ <listitem>
+ <para>
+ The name (optionally schema-qualified) of a <firstterm>planner support
+ function</firstterm> to use for this aggregate. See
+ <xref linkend="xfunc-optimization"/> for details.
+ You must be superuser to use this option.
+ </para>
+
+ <para>
+ Note that this is unrelated to the aggregate's transition, final and
+ other helper functions described above, which implement the aggregate
+ itself; a planner support function instead advises the planner about
+ calls to the aggregate.
+ </para>
+ </listitem>
+ </varlistentry>
+
<varlistentry>
<term><literal>HYPOTHETICAL</literal></term>
<listitem>
diff --git a/src/backend/catalog/pg_aggregate.c b/src/backend/catalog/pg_aggregate.c
index 243b952b9cc..9cb28e0e569 100644
--- a/src/backend/catalog/pg_aggregate.c
+++ b/src/backend/catalog/pg_aggregate.c
@@ -30,6 +30,7 @@
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/lsyscache.h"
+#include "utils/regproc.h"
#include "utils/rel.h"
#include "utils/syscache.h"
@@ -74,7 +75,8 @@ AggregateCreate(const char *aggName,
int32 aggmTransSpace,
const char *agginitval,
const char *aggminitval,
- char proparallel)
+ char proparallel,
+ Oid prosupport)
{
Relation aggdesc;
HeapTuple tup;
@@ -639,7 +641,7 @@ AggregateCreate(const char *aggName,
PointerGetDatum(NULL), /* trftypes */
NIL, /* trfoids */
PointerGetDatum(NULL), /* proconfig */
- InvalidOid, /* no prosupport */
+ prosupport, /* planner support function */
1, /* procost */
0); /* prorows */
procOid = myself.objectId;
diff --git a/src/backend/commands/aggregatecmds.c b/src/backend/commands/aggregatecmds.c
index 41b45dc6402..f8e51c1d81c 100644
--- a/src/backend/commands/aggregatecmds.c
+++ b/src/backend/commands/aggregatecmds.c
@@ -82,6 +82,8 @@ DefineAggregate(ParseState *pstate,
char *initval = NULL;
char *minitval = NULL;
char *parallel = NULL;
+ DefElem *supportItem = NULL;
+ Oid prosupport = InvalidOid;
int numArgs;
int numDirectArgs = 0;
oidvector *parameterTypes;
@@ -186,6 +188,8 @@ DefineAggregate(ParseState *pstate,
minitval = defGetString(defel);
else if (strcmp(defel->defname, "parallel") == 0)
parallel = defGetString(defel);
+ else if (strcmp(defel->defname, "support") == 0)
+ supportItem = defel;
else
ereport(WARNING,
(errcode(ERRCODE_SYNTAX_ERROR),
@@ -434,6 +438,10 @@ DefineAggregate(ParseState *pstate,
errmsg("parameter \"parallel\" must be SAFE, RESTRICTED, or UNSAFE")));
}
+ /* interpret_func_support handles the privilege check */
+ if (supportItem)
+ prosupport = interpret_func_support(supportItem);
+
/*
* Most of the argument-checking is done inside of AggregateCreate
*/
@@ -468,7 +476,8 @@ DefineAggregate(ParseState *pstate,
mtransSpace, /* transition space */
initval, /* initial condition */
minitval, /* initial condition */
- proparallel); /* parallel safe? */
+ proparallel, /* parallel safe? */
+ prosupport); /* planner support function */
}
/*
diff --git a/src/backend/commands/functioncmds.c b/src/backend/commands/functioncmds.c
index 3afd762e9dc..3b9bc0b58b4 100644
--- a/src/backend/commands/functioncmds.c
+++ b/src/backend/commands/functioncmds.c
@@ -684,7 +684,12 @@ update_proconfig_value(ArrayType *a, List *set_items)
return a;
}
-static Oid
+/*
+ * Interpret a SUPPORT clause, and return the OID of the named planner
+ * support function. This is shared by CREATE/ALTER FUNCTION and
+ * CREATE/ALTER AGGREGATE; it also enforces the privilege check.
+ */
+Oid
interpret_func_support(DefElem *defel)
{
List *procName = defGetQualifiedName(defel);
@@ -1397,7 +1402,14 @@ AlterFunction(ParseState *pstate, AlterFunctionStmt *stmt)
aclcheck_error(ACLCHECK_NOT_OWNER, stmt->objtype,
NameListToString(stmt->func->objname));
- if (procForm->prokind == PROKIND_AGGREGATE)
+ /*
+ * An aggregate's properties belong to CREATE AGGREGATE, except for the
+ * planner support function, which has no other DDL home. Only ALTER
+ * AGGREGATE can set that, and its grammar admits no other action, as
+ * asserted below.
+ */
+ if (procForm->prokind == PROKIND_AGGREGATE &&
+ stmt->objtype != OBJECT_AGGREGATE)
ereport(ERROR,
(errcode(ERRCODE_WRONG_OBJECT_TYPE),
errmsg("\"%s\" is an aggregate function",
@@ -1425,6 +1437,10 @@ AlterFunction(ParseState *pstate, AlterFunctionStmt *stmt)
elog(ERROR, "option \"%s\" not recognized", defel->defname);
}
+ /* SUPPORT is the only thing the grammar lets us do to an aggregate */
+ Assert(procForm->prokind != PROKIND_AGGREGATE ||
+ (support_item != NULL && list_length(stmt->actions) == 1));
+
if (volatility_item)
procForm->provolatile = interpret_func_volatility(volatility_item);
if (strict_item)
diff --git a/src/backend/parser/gram.y b/src/backend/parser/gram.y
index 17035fb4d15..498c75e4c42 100644
--- a/src/backend/parser/gram.y
+++ b/src/backend/parser/gram.y
@@ -9164,12 +9164,15 @@ table_func_column_list:
;
/*****************************************************************************
- * ALTER FUNCTION / ALTER PROCEDURE / ALTER ROUTINE
+ * ALTER FUNCTION / ALTER PROCEDURE / ALTER ROUTINE / ALTER AGGREGATE
*
* RENAME and OWNER subcommands are already provided by the generic
* ALTER infrastructure, here we just specify alterations that can
* only be applied to functions.
*
+ * For aggregates, SUPPORT is the only alterable property; the rest of an
+ * aggregate's definition belongs to CREATE AGGREGATE.
+ *
*****************************************************************************/
AlterFunctionStmt:
ALTER FUNCTION function_with_argtypes alterfunc_opt_list opt_restrict
@@ -9199,6 +9202,16 @@ AlterFunctionStmt:
n->actions = $4;
$$ = (Node *) n;
}
+ | ALTER AGGREGATE aggregate_with_argtypes SUPPORT any_name
+ {
+ AlterFunctionStmt *n = makeNode(AlterFunctionStmt);
+
+ n->objtype = OBJECT_AGGREGATE;
+ n->func = $3;
+ n->actions = list_make1(makeDefElem("support",
+ (Node *) $5, @4));
+ $$ = (Node *) n;
+ }
;
alterfunc_opt_list:
diff --git a/src/backend/tcop/utility.c b/src/backend/tcop/utility.c
index 4d33fcb5e9d..37dd3d4f8f2 100644
--- a/src/backend/tcop/utility.c
+++ b/src/backend/tcop/utility.c
@@ -2759,6 +2759,9 @@ CreateCommandTag(Node *parsetree)
case OBJECT_ROUTINE:
tag = CMDTAG_ALTER_ROUTINE;
break;
+ case OBJECT_AGGREGATE:
+ tag = CMDTAG_ALTER_AGGREGATE;
+ break;
default:
tag = CMDTAG_UNKNOWN;
}
diff --git a/src/bin/psql/tab-complete.in.c b/src/bin/psql/tab-complete.in.c
index 190fff7ea0e..da849e5b1af 100644
--- a/src/bin/psql/tab-complete.in.c
+++ b/src/bin/psql/tab-complete.in.c
@@ -2244,7 +2244,7 @@ match_previous_words(int pattern_id,
else if (Matches("ALTER", "AGGREGATE", MatchAny, MatchAny))
{
if (ends_with(prev_wd, ')'))
- COMPLETE_WITH("OWNER TO", "RENAME TO", "SET SCHEMA");
+ COMPLETE_WITH("OWNER TO", "RENAME TO", "SET SCHEMA", "SUPPORT");
else
COMPLETE_WITH_FUNCTION_ARG(prev2_wd);
}
diff --git a/src/include/catalog/pg_aggregate.h b/src/include/catalog/pg_aggregate.h
index 2b4f5dae5f2..ccf6377e9ee 100644
--- a/src/include/catalog/pg_aggregate.h
+++ b/src/include/catalog/pg_aggregate.h
@@ -181,6 +181,7 @@ extern ObjectAddress AggregateCreate(const char *aggName,
int32 aggmTransSpace,
const char *agginitval,
const char *aggminitval,
- char proparallel);
+ char proparallel,
+ Oid prosupport);
#endif /* PG_AGGREGATE_H */
diff --git a/src/include/commands/defrem.h b/src/include/commands/defrem.h
index 574f860bdd2..48dadcf1bc7 100644
--- a/src/include/commands/defrem.h
+++ b/src/include/commands/defrem.h
@@ -58,6 +58,7 @@ extern void GetOperatorFromCompareType(Oid opclass, Oid rhstype, CompareType cmp
extern ObjectAddress CreateFunction(ParseState *pstate, CreateFunctionStmt *stmt);
extern void RemoveFunctionById(Oid funcOid);
extern ObjectAddress AlterFunction(ParseState *pstate, AlterFunctionStmt *stmt);
+extern Oid interpret_func_support(DefElem *defel);
extern ObjectAddress CreateCast(CreateCastStmt *stmt);
extern ObjectAddress CreateTransform(CreateTransformStmt *stmt);
extern void IsThereFunctionInNamespace(const char *proname, int pronargs,
--
2.55.0
^ permalink raw reply [nested|flat] 12+ messages in thread
* Re: Allow a prosupport function to be attached to an aggregate
2026-08-17 06:13 Allow a prosupport function to be attached to an aggregate Andrei Lepikhov <lepihov@gmail.com>
@ 2026-08-18 04:56 ` David Rowley <dgrowleyml@gmail.com>
2026-08-18 06:31 ` Re: Allow a prosupport function to be attached to an aggregate Andrei Lepikhov <lepihov@gmail.com>
2026-08-18 14:35 ` Re: Allow a prosupport function to be attached to an aggregate Tom Lane <tgl@sss.pgh.pa.us>
0 siblings, 2 replies; 12+ messages in thread
From: David Rowley @ 2026-08-18 04:56 UTC (permalink / raw)
To: Andrei Lepikhov <lepihov@gmail.com>; +Cc: PostgreSQL Hackers <pgsql-hackers@lists.postgresql.org>; Corey Huinker <corey.huinker@gmail.com>
On Mon, 17 Aug 2026 at 18:13, Andrei Lepikhov <lepihov@gmail.com> wrote:
> Commit 42473b3b31 added SupportRequestSimplifyAggref, which the planner issues
> for any Aggref whose function names a support function. Nice, but extensions
> cannot reach it, because there is no way to attach a support function to an
> aggregate:
>
> ALTER FUNCTION pg_catalog.sum(numeric) SUPPORT numeric_support;
> ERROR: "pg_catalog.sum" is an aggregate function
I failed to realise that there was no way to set that for user-defined
aggregates. Not good. While I do agree that lack of extensibility is
not aligned with the spirit of the project, my current thoughts are
that now is a bit late to add this to v19.
Is delaying this until v20 fine for you?
Or does anyone else feel this is a must-fix for v19?
David
^ permalink raw reply [nested|flat] 12+ messages in thread
* Re: Allow a prosupport function to be attached to an aggregate
2026-08-17 06:13 Allow a prosupport function to be attached to an aggregate Andrei Lepikhov <lepihov@gmail.com>
2026-08-18 04:56 ` Re: Allow a prosupport function to be attached to an aggregate David Rowley <dgrowleyml@gmail.com>
@ 2026-08-18 06:31 ` Andrei Lepikhov <lepihov@gmail.com>
2026-08-18 12:36 ` Re: Allow a prosupport function to be attached to an aggregate Andrei Lepikhov <lepihov@gmail.com>
1 sibling, 1 reply; 12+ messages in thread
From: Andrei Lepikhov @ 2026-08-18 06:31 UTC (permalink / raw)
To: David Rowley <dgrowleyml@gmail.com>; +Cc: PostgreSQL Hackers <pgsql-hackers@lists.postgresql.org>; Corey Huinker <corey.huinker@gmail.com>
On 18/08/2026 06:56, David Rowley wrote:
> On Mon, 17 Aug 2026 at 18:13, Andrei Lepikhov <lepihov@gmail.com> wrote:
>> Commit 42473b3b31 added SupportRequestSimplifyAggref, which the planner issues
>> for any Aggref whose function names a support function. Nice, but extensions
>> cannot reach it, because there is no way to attach a support function to an
>> aggregate:
>>
>> ALTER FUNCTION pg_catalog.sum(numeric) SUPPORT numeric_support;
>> ERROR: "pg_catalog.sum" is an aggregate function
>
> I failed to realise that there was no way to set that for user-defined
> aggregates. Not good. While I do agree that lack of extensibility is
> not aligned with the spirit of the project, my current thoughts are
> that now is a bit late to add this to v19.
>
> Is delaying this until v20 fine for you?
Yes, I can do it manually in pg_catalog for now - rewriting prosupport and
setting the dependency in the pg_depend. There’s no rush - it’s just about
keeping things tidy.
--
regards, Andrei Lepikhov,
pgEdge
^ permalink raw reply [nested|flat] 12+ messages in thread
* Re: Allow a prosupport function to be attached to an aggregate
2026-08-17 06:13 Allow a prosupport function to be attached to an aggregate Andrei Lepikhov <lepihov@gmail.com>
2026-08-18 04:56 ` Re: Allow a prosupport function to be attached to an aggregate David Rowley <dgrowleyml@gmail.com>
2026-08-18 06:31 ` Re: Allow a prosupport function to be attached to an aggregate Andrei Lepikhov <lepihov@gmail.com>
@ 2026-08-18 12:36 ` Andrei Lepikhov <lepihov@gmail.com>
0 siblings, 0 replies; 12+ messages in thread
From: Andrei Lepikhov @ 2026-08-18 12:36 UTC (permalink / raw)
To: David Rowley <dgrowleyml@gmail.com>; +Cc: PostgreSQL Hackers <pgsql-hackers@lists.postgresql.org>; Corey Huinker <corey.huinker@gmail.com>
On 18/08/2026 08:31, Andrei Lepikhov wrote:
> On 18/08/2026 06:56, David Rowley wrote:
>> Is delaying this until v20 fine for you?
> Yes, I can do it manually in pg_catalog for now - rewriting prosupport and
> setting the dependency in the pg_depend. There’s no rush - it’s just about
> keeping things tidy.
However, I noticed that it is not documented yet.
There are also three other prosupport requests that are not documented. A quick
search showed that documentation usually depends on the author, so it makes
sense to add it now.
Since each was introduced at a different time and serves a different purpose, I
suggest we start by documenting SupportRequestSimplifyAggref, as I am more
familiar with it - see the patch in attachment.
--
regards, Andrei Lepikhov,
pgEdge
Attachments:
v0-0001-Document-the-SupportRequestSimplifyAggref-support.patch (text/plain, 1.8K) download
From 08b9a1fdd6ab0ec67ccbe310df0bf0b64854b46c Mon Sep 17 00:00:00 2001
From: "Andrei V. Lepikhov" <lepihov@gmail.com>
Date: Tue, 18 Aug 2026 14:29:50 +0200
Subject: [PATCH v0] Document the SupportRequestSimplifyAggref support request
The request has been in supportnodes.h since 42473b3b312, but
documentation was not updated, so the only description of it is the
header comment.
---
doc/src/sgml/xfunc.sgml | 16 ++++++++++++++++
1 file changed, 16 insertions(+)
diff --git a/doc/src/sgml/xfunc.sgml b/doc/src/sgml/xfunc.sgml
index 2b8a11e7ad0..880edf24588 100644
--- a/doc/src/sgml/xfunc.sgml
+++ b/doc/src/sgml/xfunc.sgml
@@ -4241,6 +4241,22 @@ supportfn(internal) returns internal
normal execution of the target function.
</para>
+ <para>
+ Aggregate function calls can also be simplified during planning. For
+ example, <literal>COUNT(<replaceable>x</replaceable>)</literal> can be
+ replaced by <literal>COUNT(*)</literal>
+ when <replaceable>x</replaceable> is known not to be null. This can be
+ done by a support function that implements
+ the <literal>SupportRequestSimplifyAggref</literal> request type. The
+ support function will be called for each instance of its target aggregate
+ found in a query parse tree. If it finds that the particular call can be
+ replaced, it can build and return a new node, usually another aggregate
+ call, leaving the node it was given unmodified. As with
+ <literal>SupportRequestSimplify</literal>, it is the support function's
+ responsibility that the replacement be equivalent to normal execution of the
+ target aggregate.
+ </para>
+
<para>
For target functions that return <type>boolean</type>, it is often useful to estimate
the fraction of rows that will be selected by a <literal>WHERE</literal> clause using that
--
2.55.0
^ permalink raw reply [nested|flat] 12+ messages in thread
* Re: Allow a prosupport function to be attached to an aggregate
2026-08-17 06:13 Allow a prosupport function to be attached to an aggregate Andrei Lepikhov <lepihov@gmail.com>
2026-08-18 04:56 ` Re: Allow a prosupport function to be attached to an aggregate David Rowley <dgrowleyml@gmail.com>
@ 2026-08-18 14:35 ` Tom Lane <tgl@sss.pgh.pa.us>
2026-08-20 07:23 ` Re: Allow a prosupport function to be attached to an aggregate Andrei Lepikhov <lepihov@gmail.com>
1 sibling, 1 reply; 12+ messages in thread
From: Tom Lane @ 2026-08-18 14:35 UTC (permalink / raw)
To: David Rowley <dgrowleyml@gmail.com>; +Cc: Andrei Lepikhov <lepihov@gmail.com>; PostgreSQL Hackers <pgsql-hackers@lists.postgresql.org>; Corey Huinker <corey.huinker@gmail.com>
David Rowley <dgrowleyml@gmail.com> writes:
> I failed to realise that there was no way to set that for user-defined
> aggregates. Not good. While I do agree that lack of extensibility is
> not aligned with the spirit of the project, my current thoughts are
> that now is a bit late to add this to v19.
> Is delaying this until v20 fine for you?
> Or does anyone else feel this is a must-fix for v19?
That seems quite sad. The entire point of the support-function
mechanism is to allow extensibility, so if an extension cannot use
a support hook we have totally failed at implementing that hook.
(As you yourself remarked in a different context, it's unlikely
we would have implemented SupportRequestSimplifyAggref if the only
possible use-case was COUNT(any).)
So I think it's a must-fix. To put my money where my mouth is,
here's a draft patch. (I could not resist the temptation to
improve compute_common_attribute's existing error message,
which pretty well sucks: it's useless in a context that's not
showing you an accurate error pointer.)
regards, tom lane
Attachments:
v1-allow-alter-aggregate-support.patch (text/x-diff, 8.3K) download
diff --git a/src/backend/commands/functioncmds.c b/src/backend/commands/functioncmds.c
index ba24a708982..ee778502b8a 100644
--- a/src/backend/commands/functioncmds.c
+++ b/src/backend/commands/functioncmds.c
@@ -516,7 +516,7 @@ interpret_function_parameter_list(ParseState *pstate,
*/
static bool
compute_common_attribute(ParseState *pstate,
- bool is_procedure,
+ char prokind,
DefElem *defel,
DefElem **volatility_item,
DefElem **strict_item,
@@ -528,8 +528,13 @@ compute_common_attribute(ParseState *pstate,
DefElem **support_item,
DefElem **parallel_item)
{
+ bool is_aggregate = (prokind == PROKIND_AGGREGATE);
+ bool is_procedure = (prokind == PROKIND_PROCEDURE);
+
if (strcmp(defel->defname, "volatility") == 0)
{
+ if (is_aggregate)
+ goto aggregate_error;
if (is_procedure)
goto procedure_error;
if (*volatility_item)
@@ -539,6 +544,8 @@ compute_common_attribute(ParseState *pstate,
}
else if (strcmp(defel->defname, "strict") == 0)
{
+ if (is_aggregate)
+ goto aggregate_error;
if (is_procedure)
goto procedure_error;
if (*strict_item)
@@ -548,6 +555,8 @@ compute_common_attribute(ParseState *pstate,
}
else if (strcmp(defel->defname, "security") == 0)
{
+ if (is_aggregate)
+ goto aggregate_error;
if (*security_item)
errorConflictingDefElem(defel, pstate);
@@ -555,6 +564,8 @@ compute_common_attribute(ParseState *pstate,
}
else if (strcmp(defel->defname, "leakproof") == 0)
{
+ if (is_aggregate)
+ goto aggregate_error;
if (is_procedure)
goto procedure_error;
if (*leakproof_item)
@@ -564,10 +575,14 @@ compute_common_attribute(ParseState *pstate,
}
else if (strcmp(defel->defname, "set") == 0)
{
+ if (is_aggregate)
+ goto aggregate_error;
*set_items = lappend(*set_items, defel->arg);
}
else if (strcmp(defel->defname, "cost") == 0)
{
+ if (is_aggregate)
+ goto aggregate_error;
if (is_procedure)
goto procedure_error;
if (*cost_item)
@@ -577,6 +592,8 @@ compute_common_attribute(ParseState *pstate,
}
else if (strcmp(defel->defname, "rows") == 0)
{
+ if (is_aggregate)
+ goto aggregate_error;
if (is_procedure)
goto procedure_error;
if (*rows_item)
@@ -595,6 +612,8 @@ compute_common_attribute(ParseState *pstate,
}
else if (strcmp(defel->defname, "parallel") == 0)
{
+ if (is_aggregate)
+ goto aggregate_error;
if (is_procedure)
goto procedure_error;
if (*parallel_item)
@@ -608,10 +627,19 @@ compute_common_attribute(ParseState *pstate,
/* Recognized an option */
return true;
+aggregate_error:
+ ereport(ERROR,
+ (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
+ errmsg("attribute \"%s\" is not allowed for aggregates",
+ defel->defname),
+ parser_errposition(pstate, defel->location)));
+ return false;
+
procedure_error:
ereport(ERROR,
(errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
- errmsg("invalid attribute in procedure definition"),
+ errmsg("attribute \"%s\" is not allowed for procedures",
+ defel->defname),
parser_errposition(pstate, defel->location)));
return false;
}
@@ -730,7 +758,7 @@ interpret_func_support(DefElem *defel)
*/
static void
compute_function_attributes(ParseState *pstate,
- bool is_procedure,
+ char prokind,
List *options,
List **as,
char **language,
@@ -787,15 +815,16 @@ compute_function_attributes(ParseState *pstate,
{
if (windowfunc_item)
errorConflictingDefElem(defel, pstate);
- if (is_procedure)
+ if (prokind == PROKIND_PROCEDURE)
ereport(ERROR,
(errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
- errmsg("invalid attribute in procedure definition"),
+ errmsg("attribute \"%s\" is not allowed for procedures",
+ defel->defname),
parser_errposition(pstate, defel->location)));
windowfunc_item = defel;
}
else if (compute_common_attribute(pstate,
- is_procedure,
+ prokind,
defel,
&volatility_item,
&strict_item,
@@ -1052,6 +1081,7 @@ CreateFunction(ParseState *pstate, CreateFunctionStmt *stmt)
List *trfoids_list = NIL;
ArrayType *trftypes;
Oid requiredResultType;
+ char prokind;
bool isWindowFunc,
isStrict,
security,
@@ -1079,6 +1109,7 @@ CreateFunction(ParseState *pstate, CreateFunctionStmt *stmt)
/* Set default attributes */
as_clause = NIL;
language = NULL;
+ prokind = (stmt->is_procedure ? PROKIND_PROCEDURE : PROKIND_FUNCTION);
isWindowFunc = false;
isStrict = false;
security = false;
@@ -1092,7 +1123,7 @@ CreateFunction(ParseState *pstate, CreateFunctionStmt *stmt)
/* Extract non-default attributes from stmt->options list */
compute_function_attributes(pstate,
- stmt->is_procedure,
+ prokind,
stmt->options,
&as_clause, &language, &transformDefElem,
&isWindowFunc, &volatility,
@@ -1100,6 +1131,16 @@ CreateFunction(ParseState *pstate, CreateFunctionStmt *stmt)
&proconfig, &procost, &prorows,
&prosupport, ¶llel);
+ /*
+ * If we found a WINDOW attribute, change prokind accordingly. Note that
+ * as things stand, we must allow all the same attributes for window
+ * functions as plain functions, since we don't know the difference while
+ * scanning the options list. If that ever needs to change, we'd have to
+ * scan the list twice, the first time just to identify WINDOW.
+ */
+ if (isWindowFunc)
+ prokind = PROKIND_WINDOW;
+
if (!language)
{
if (stmt->sql_body)
@@ -1285,7 +1326,7 @@ CreateFunction(ParseState *pstate, CreateFunctionStmt *stmt)
prosrc_str, /* converted to text later */
probin_str, /* converted to text later */
prosqlbody,
- stmt->is_procedure ? PROKIND_PROCEDURE : (isWindowFunc ? PROKIND_WINDOW : PROKIND_FUNCTION),
+ prokind,
security,
isLeakProof,
isStrict,
@@ -1366,7 +1407,6 @@ AlterFunction(ParseState *pstate, AlterFunctionStmt *stmt)
HeapTuple tup;
Oid funcOid;
Form_pg_proc procForm;
- bool is_procedure;
Relation rel;
ListCell *l;
DefElem *volatility_item = NULL;
@@ -1397,21 +1437,13 @@ AlterFunction(ParseState *pstate, AlterFunctionStmt *stmt)
aclcheck_error(ACLCHECK_NOT_OWNER, stmt->objtype,
NameListToString(stmt->func->objname));
- if (procForm->prokind == PROKIND_AGGREGATE)
- ereport(ERROR,
- (errcode(ERRCODE_WRONG_OBJECT_TYPE),
- errmsg("\"%s\" is an aggregate function",
- NameListToString(stmt->func->objname))));
-
- is_procedure = (procForm->prokind == PROKIND_PROCEDURE);
-
/* Examine requested actions. */
foreach(l, stmt->actions)
{
DefElem *defel = (DefElem *) lfirst(l);
if (compute_common_attribute(pstate,
- is_procedure,
+ procForm->prokind,
defel,
&volatility_item,
&strict_item,
diff --git a/src/test/regress/expected/create_procedure.out b/src/test/regress/expected/create_procedure.out
index f89042cf798..48170c008db 100644
--- a/src/test/regress/expected/create_procedure.out
+++ b/src/test/regress/expected/create_procedure.out
@@ -392,11 +392,11 @@ LINE 1: CALL sum(1);
^
HINT: To call a function, use SELECT.
CREATE PROCEDURE ptestx() LANGUAGE SQL WINDOW AS $$ INSERT INTO cp_test VALUES (1, 'a') $$;
-ERROR: invalid attribute in procedure definition
+ERROR: attribute "window" is not allowed for procedures
LINE 1: CREATE PROCEDURE ptestx() LANGUAGE SQL WINDOW AS $$ INSERT I...
^
CREATE PROCEDURE ptestx() LANGUAGE SQL STRICT AS $$ INSERT INTO cp_test VALUES (1, 'a') $$;
-ERROR: invalid attribute in procedure definition
+ERROR: attribute "strict" is not allowed for procedures
LINE 1: CREATE PROCEDURE ptestx() LANGUAGE SQL STRICT AS $$ INSERT I...
^
CREATE PROCEDURE ptestx(a VARIADIC int[], b OUT int) LANGUAGE SQL
@@ -410,7 +410,7 @@ ERROR: procedure OUT parameters cannot appear after one with a default value
LINE 1: CREATE PROCEDURE ptestx(a int DEFAULT 42, b OUT int) LANGUAG...
^
ALTER PROCEDURE ptest1(text) STRICT;
-ERROR: invalid attribute in procedure definition
+ERROR: attribute "strict" is not allowed for procedures
LINE 1: ALTER PROCEDURE ptest1(text) STRICT;
^
ALTER FUNCTION ptest1(text) VOLATILE; -- error: not a function
^ permalink raw reply [nested|flat] 12+ messages in thread
* Re: Allow a prosupport function to be attached to an aggregate
2026-08-17 06:13 Allow a prosupport function to be attached to an aggregate Andrei Lepikhov <lepihov@gmail.com>
2026-08-18 04:56 ` Re: Allow a prosupport function to be attached to an aggregate David Rowley <dgrowleyml@gmail.com>
2026-08-18 14:35 ` Re: Allow a prosupport function to be attached to an aggregate Tom Lane <tgl@sss.pgh.pa.us>
@ 2026-08-20 07:23 ` Andrei Lepikhov <lepihov@gmail.com>
2026-08-20 19:47 ` Re: Allow a prosupport function to be attached to an aggregate Tom Lane <tgl@sss.pgh.pa.us>
0 siblings, 1 reply; 12+ messages in thread
From: Andrei Lepikhov @ 2026-08-20 07:23 UTC (permalink / raw)
To: Tom Lane <tgl@sss.pgh.pa.us>; David Rowley <dgrowleyml@gmail.com>; +Cc: PostgreSQL Hackers <pgsql-hackers@lists.postgresql.org>; Corey Huinker <corey.huinker@gmail.com>
On 18/8/2026 16:35, Tom Lane wrote:
> David Rowley <dgrowleyml@gmail.com> writes:
> So I think it's a must-fix. To put my money where my mouth is,
> here's a draft patch. (I could not resist the temptation to
> improve compute_common_attribute's existing error message,
> which pretty well sucks: it's useless in a context that's not
> showing you an accurate error pointer.)
Thank you for the patch. I agree that it is the right shape for v19, so
I assembled it into a small series.
- 0001 documents SupportRequestSimplifyAggref. This is the patch I sent
earlier, unchanged.
- 0002 is your patch, plus documentation and regression tests.
The documentation there provides the rationale for why CREATE/ALTER
AGGREGATE should be added in v.20.
Also, I'm not sure why pg_dump/upgrade has not been implemented. So, I
added an 'unsupported' clause into the docs - let's discuss it later or
correct me if such a feature can't be supported at all.
--
regards, Andrei Lepikhov
Attachments: download all (2 files, .tar.gz)
0001-Document-the-SupportRequestSimplifyAggref-support-re.patch (text/plain, 1.9K) download
From 9f7d2e715a707c2d793f5ee99a6d25938ef69090 Mon Sep 17 00:00:00 2001
From: Andrei Lepikhov <lepihov@gmail.com>
Date: Wed, 19 Aug 2026 17:34:13 +0000
Subject: [PATCH 1/2] Document the SupportRequestSimplifyAggref support request
The request has been in supportnodes.h since 42473b3b312, but the
documentation was not updated, so the only description of it is the
header comment.
Author: Andrei Lepikhov <lepihov@gmail.com>
Discussion: https://postgr.es/m/ca4ee281-f75b-445b-b57f-0b560067c1d7@gmail.com
---
doc/src/sgml/xfunc.sgml | 16 ++++++++++++++++
1 file changed, 16 insertions(+)
diff --git a/doc/src/sgml/xfunc.sgml b/doc/src/sgml/xfunc.sgml
index 050e1e50bec..99be010f89f 100644
--- a/doc/src/sgml/xfunc.sgml
+++ b/doc/src/sgml/xfunc.sgml
@@ -4241,6 +4241,22 @@ supportfn(internal) returns internal
normal execution of the target function.
</para>
+ <para>
+ Aggregate function calls can also be simplified during planning. For
+ example, <literal>COUNT(<replaceable>x</replaceable>)</literal> can be
+ replaced by <literal>COUNT(*)</literal>
+ when <replaceable>x</replaceable> is known not to be null. This can be
+ done by a support function that implements
+ the <literal>SupportRequestSimplifyAggref</literal> request type. The
+ support function will be called for each instance of its target aggregate
+ found in a query parse tree. If it finds that the particular call can be
+ replaced, it can build and return a new node, usually another aggregate
+ call, leaving the node it was given unmodified. As with
+ <literal>SupportRequestSimplify</literal>, it is the support function's
+ responsibility that the replacement be equivalent to normal execution of
+ the target aggregate.
+ </para>
+
<para>
For target functions that return <type>boolean</type>, it is often useful to estimate
the fraction of rows that will be selected by a <literal>WHERE</literal> clause using that
--
2.52.0
0002-Allow-a-planner-support-function-to-be-attached-to-a.patch (text/plain, 20.9K) download
From 6ff80e081ef2e853329eda19b2b24f6ef3da96ff Mon Sep 17 00:00:00 2001
From: Andrei Lepikhov <lepihov@gmail.com>
Date: Wed, 19 Aug 2026 17:44:44 +0000
Subject: [PATCH 2/2] Allow a planner support function to be attached to an
aggregate
Commit 42473b3b31 added the SupportRequestSimplifyAggref request, but an
extension had no way to reach it. AlterFunction() rejected every
aggregate, and no other DDL command can set pg_proc.prosupport, so the only
remaining option was a direct catalog update, which records no
dependency. A support hook that an extension cannot use defeats the
purpose of the support function mechanism.
Teach compute_common_attribute() about prokind, rather than a plain
is_procedure flag, so that it can reject each attribute per kind of
routine.
While here, improve the error message for a rejected attribute. The old
wording was useless in a context that shows no accurate error pointer.
pg_dump did not read pg_proc.prosupport for aggregates, so an aggregate
would silently lose its support function during dump and restore, and
during pg_upgrade. Emit a separate ALTER FUNCTION command after CREATE
AGGREGATE, since CREATE AGGREGATE has no SUPPORT clause.
Author: Tom Lane <tgl@sss.pgh.pa.us>
Reported-by: Andrei Lepikhov <lepihov@gmail.com>
Discussion: https://postgr.es/m/8f58c96d-d3c7-4c0f-9898-116f00eeaff6@gmail.com
---
doc/src/sgml/ref/alter_aggregate.sgml | 7 ++
doc/src/sgml/ref/alter_function.sgml | 11 ++-
doc/src/sgml/ref/create_aggregate.sgml | 3 +-
doc/src/sgml/xfunc.sgml | 16 +++++
src/backend/commands/functioncmds.c | 68 ++++++++++++++-----
.../regress/expected/create_procedure.out | 6 +-
src/test/regress/expected/misc_functions.out | 68 +++++++++++++++++++
src/test/regress/regress.c | 40 +++++++++++
src/test/regress/sql/misc_functions.sql | 40 +++++++++++
9 files changed, 236 insertions(+), 23 deletions(-)
diff --git a/doc/src/sgml/ref/alter_aggregate.sgml b/doc/src/sgml/ref/alter_aggregate.sgml
index d0a39ba7b5e..8fedd0e0595 100644
--- a/doc/src/sgml/ref/alter_aggregate.sgml
+++ b/doc/src/sgml/ref/alter_aggregate.sgml
@@ -139,6 +139,13 @@ ALTER AGGREGATE <replaceable>name</replaceable> ( <replaceable>aggregate_signatu
<refsect1>
<title>Notes</title>
+ <para>
+ An aggregate can have a planner support function, but this command does
+ not set it. Use
+ <link linkend="sql-alterfunction"><command>ALTER FUNCTION</command></link>
+ with the <literal>SUPPORT</literal> clause for that.
+ </para>
+
<para>
The recommended syntax for referencing an ordered-set aggregate
is to write <literal>ORDER BY</literal> between the direct and aggregated
diff --git a/doc/src/sgml/ref/alter_function.sgml b/doc/src/sgml/ref/alter_function.sgml
index 8193b17f255..c42c105f0a3 100644
--- a/doc/src/sgml/ref/alter_function.sgml
+++ b/doc/src/sgml/ref/alter_function.sgml
@@ -57,6 +57,14 @@ ALTER FUNCTION <replaceable>name</replaceable> [ ( [ [ <replaceable class="param
function.
</para>
+ <para>
+ The target can also be an aggregate function. In that case
+ <literal>SUPPORT</literal> is the only action that is allowed, because
+ every other property of an aggregate is fixed by
+ <link linkend="sql-createaggregate"><command>CREATE
+ AGGREGATE</command></link>.
+ </para>
+
<para>
You must own the function to use <command>ALTER FUNCTION</command>.
To change a function's schema, you must also have <literal>CREATE</literal>
@@ -269,7 +277,8 @@ ALTER FUNCTION <replaceable>name</replaceable> [ ( [ [ <replaceable class="param
<para>
This option cannot be used to remove the support function altogether,
since it must name a new support function. Use <command>CREATE OR
- REPLACE FUNCTION</command> if you need to do that.
+ REPLACE FUNCTION</command> if you need to do that. For an aggregate,
+ use <command>CREATE OR REPLACE AGGREGATE</command>.
</para>
</listitem>
</varlistentry>
diff --git a/doc/src/sgml/ref/create_aggregate.sgml b/doc/src/sgml/ref/create_aggregate.sgml
index 0472ac2e874..1c538b3ebb3 100644
--- a/doc/src/sgml/ref/create_aggregate.sgml
+++ b/doc/src/sgml/ref/create_aggregate.sgml
@@ -102,7 +102,8 @@ CREATE [ OR REPLACE ] AGGREGATE <replaceable class="parameter">name</replaceable
When replacing an existing definition, the argument types, result type,
and number of direct arguments may not be changed. Also, the new definition
must be of the same kind (ordinary aggregate, ordered-set aggregate, or
- hypothetical-set aggregate) as the old one.
+ hypothetical-set aggregate) as the old one. Replacing an aggregate also
+ resets its planner support function, if it had one.
</para>
<para>
diff --git a/doc/src/sgml/xfunc.sgml b/doc/src/sgml/xfunc.sgml
index 99be010f89f..e0e7b0a9b06 100644
--- a/doc/src/sgml/xfunc.sgml
+++ b/doc/src/sgml/xfunc.sgml
@@ -4184,6 +4184,22 @@ supportfn(internal) returns internal
the <literal>SUPPORT</literal> clause when creating the target function.
</para>
+ <para>
+ An aggregate can also be a target function. Because an aggregate is
+ created by <link linkend="sql-createaggregate"><command>CREATE
+ AGGREGATE</command></link>, which has no <literal>SUPPORT</literal>
+ clause, attach the support function with
+ <link linkend="sql-alterfunction"><command>ALTER FUNCTION</command></link>
+ instead.
+ </para>
+
+ <para>
+ An aggregate's support function is not preserved by
+ <application>pg_dump</application>, and therefore not
+ by <application>pg_upgrade</application> either. Set it again after a
+ restore, or arrange for the owning extension to do so.
+ </para>
+
<para>
The details of the API for planner support functions can be found in
file <filename>src/include/nodes/supportnodes.h</filename> in the
diff --git a/src/backend/commands/functioncmds.c b/src/backend/commands/functioncmds.c
index ba24a708982..ee778502b8a 100644
--- a/src/backend/commands/functioncmds.c
+++ b/src/backend/commands/functioncmds.c
@@ -516,7 +516,7 @@ interpret_function_parameter_list(ParseState *pstate,
*/
static bool
compute_common_attribute(ParseState *pstate,
- bool is_procedure,
+ char prokind,
DefElem *defel,
DefElem **volatility_item,
DefElem **strict_item,
@@ -528,8 +528,13 @@ compute_common_attribute(ParseState *pstate,
DefElem **support_item,
DefElem **parallel_item)
{
+ bool is_aggregate = (prokind == PROKIND_AGGREGATE);
+ bool is_procedure = (prokind == PROKIND_PROCEDURE);
+
if (strcmp(defel->defname, "volatility") == 0)
{
+ if (is_aggregate)
+ goto aggregate_error;
if (is_procedure)
goto procedure_error;
if (*volatility_item)
@@ -539,6 +544,8 @@ compute_common_attribute(ParseState *pstate,
}
else if (strcmp(defel->defname, "strict") == 0)
{
+ if (is_aggregate)
+ goto aggregate_error;
if (is_procedure)
goto procedure_error;
if (*strict_item)
@@ -548,6 +555,8 @@ compute_common_attribute(ParseState *pstate,
}
else if (strcmp(defel->defname, "security") == 0)
{
+ if (is_aggregate)
+ goto aggregate_error;
if (*security_item)
errorConflictingDefElem(defel, pstate);
@@ -555,6 +564,8 @@ compute_common_attribute(ParseState *pstate,
}
else if (strcmp(defel->defname, "leakproof") == 0)
{
+ if (is_aggregate)
+ goto aggregate_error;
if (is_procedure)
goto procedure_error;
if (*leakproof_item)
@@ -564,10 +575,14 @@ compute_common_attribute(ParseState *pstate,
}
else if (strcmp(defel->defname, "set") == 0)
{
+ if (is_aggregate)
+ goto aggregate_error;
*set_items = lappend(*set_items, defel->arg);
}
else if (strcmp(defel->defname, "cost") == 0)
{
+ if (is_aggregate)
+ goto aggregate_error;
if (is_procedure)
goto procedure_error;
if (*cost_item)
@@ -577,6 +592,8 @@ compute_common_attribute(ParseState *pstate,
}
else if (strcmp(defel->defname, "rows") == 0)
{
+ if (is_aggregate)
+ goto aggregate_error;
if (is_procedure)
goto procedure_error;
if (*rows_item)
@@ -595,6 +612,8 @@ compute_common_attribute(ParseState *pstate,
}
else if (strcmp(defel->defname, "parallel") == 0)
{
+ if (is_aggregate)
+ goto aggregate_error;
if (is_procedure)
goto procedure_error;
if (*parallel_item)
@@ -608,10 +627,19 @@ compute_common_attribute(ParseState *pstate,
/* Recognized an option */
return true;
+aggregate_error:
+ ereport(ERROR,
+ (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
+ errmsg("attribute \"%s\" is not allowed for aggregates",
+ defel->defname),
+ parser_errposition(pstate, defel->location)));
+ return false;
+
procedure_error:
ereport(ERROR,
(errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
- errmsg("invalid attribute in procedure definition"),
+ errmsg("attribute \"%s\" is not allowed for procedures",
+ defel->defname),
parser_errposition(pstate, defel->location)));
return false;
}
@@ -730,7 +758,7 @@ interpret_func_support(DefElem *defel)
*/
static void
compute_function_attributes(ParseState *pstate,
- bool is_procedure,
+ char prokind,
List *options,
List **as,
char **language,
@@ -787,15 +815,16 @@ compute_function_attributes(ParseState *pstate,
{
if (windowfunc_item)
errorConflictingDefElem(defel, pstate);
- if (is_procedure)
+ if (prokind == PROKIND_PROCEDURE)
ereport(ERROR,
(errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
- errmsg("invalid attribute in procedure definition"),
+ errmsg("attribute \"%s\" is not allowed for procedures",
+ defel->defname),
parser_errposition(pstate, defel->location)));
windowfunc_item = defel;
}
else if (compute_common_attribute(pstate,
- is_procedure,
+ prokind,
defel,
&volatility_item,
&strict_item,
@@ -1052,6 +1081,7 @@ CreateFunction(ParseState *pstate, CreateFunctionStmt *stmt)
List *trfoids_list = NIL;
ArrayType *trftypes;
Oid requiredResultType;
+ char prokind;
bool isWindowFunc,
isStrict,
security,
@@ -1079,6 +1109,7 @@ CreateFunction(ParseState *pstate, CreateFunctionStmt *stmt)
/* Set default attributes */
as_clause = NIL;
language = NULL;
+ prokind = (stmt->is_procedure ? PROKIND_PROCEDURE : PROKIND_FUNCTION);
isWindowFunc = false;
isStrict = false;
security = false;
@@ -1092,7 +1123,7 @@ CreateFunction(ParseState *pstate, CreateFunctionStmt *stmt)
/* Extract non-default attributes from stmt->options list */
compute_function_attributes(pstate,
- stmt->is_procedure,
+ prokind,
stmt->options,
&as_clause, &language, &transformDefElem,
&isWindowFunc, &volatility,
@@ -1100,6 +1131,16 @@ CreateFunction(ParseState *pstate, CreateFunctionStmt *stmt)
&proconfig, &procost, &prorows,
&prosupport, ¶llel);
+ /*
+ * If we found a WINDOW attribute, change prokind accordingly. Note that
+ * as things stand, we must allow all the same attributes for window
+ * functions as plain functions, since we don't know the difference while
+ * scanning the options list. If that ever needs to change, we'd have to
+ * scan the list twice, the first time just to identify WINDOW.
+ */
+ if (isWindowFunc)
+ prokind = PROKIND_WINDOW;
+
if (!language)
{
if (stmt->sql_body)
@@ -1285,7 +1326,7 @@ CreateFunction(ParseState *pstate, CreateFunctionStmt *stmt)
prosrc_str, /* converted to text later */
probin_str, /* converted to text later */
prosqlbody,
- stmt->is_procedure ? PROKIND_PROCEDURE : (isWindowFunc ? PROKIND_WINDOW : PROKIND_FUNCTION),
+ prokind,
security,
isLeakProof,
isStrict,
@@ -1366,7 +1407,6 @@ AlterFunction(ParseState *pstate, AlterFunctionStmt *stmt)
HeapTuple tup;
Oid funcOid;
Form_pg_proc procForm;
- bool is_procedure;
Relation rel;
ListCell *l;
DefElem *volatility_item = NULL;
@@ -1397,21 +1437,13 @@ AlterFunction(ParseState *pstate, AlterFunctionStmt *stmt)
aclcheck_error(ACLCHECK_NOT_OWNER, stmt->objtype,
NameListToString(stmt->func->objname));
- if (procForm->prokind == PROKIND_AGGREGATE)
- ereport(ERROR,
- (errcode(ERRCODE_WRONG_OBJECT_TYPE),
- errmsg("\"%s\" is an aggregate function",
- NameListToString(stmt->func->objname))));
-
- is_procedure = (procForm->prokind == PROKIND_PROCEDURE);
-
/* Examine requested actions. */
foreach(l, stmt->actions)
{
DefElem *defel = (DefElem *) lfirst(l);
if (compute_common_attribute(pstate,
- is_procedure,
+ procForm->prokind,
defel,
&volatility_item,
&strict_item,
diff --git a/src/test/regress/expected/create_procedure.out b/src/test/regress/expected/create_procedure.out
index f89042cf798..48170c008db 100644
--- a/src/test/regress/expected/create_procedure.out
+++ b/src/test/regress/expected/create_procedure.out
@@ -392,11 +392,11 @@ LINE 1: CALL sum(1);
^
HINT: To call a function, use SELECT.
CREATE PROCEDURE ptestx() LANGUAGE SQL WINDOW AS $$ INSERT INTO cp_test VALUES (1, 'a') $$;
-ERROR: invalid attribute in procedure definition
+ERROR: attribute "window" is not allowed for procedures
LINE 1: CREATE PROCEDURE ptestx() LANGUAGE SQL WINDOW AS $$ INSERT I...
^
CREATE PROCEDURE ptestx() LANGUAGE SQL STRICT AS $$ INSERT INTO cp_test VALUES (1, 'a') $$;
-ERROR: invalid attribute in procedure definition
+ERROR: attribute "strict" is not allowed for procedures
LINE 1: CREATE PROCEDURE ptestx() LANGUAGE SQL STRICT AS $$ INSERT I...
^
CREATE PROCEDURE ptestx(a VARIADIC int[], b OUT int) LANGUAGE SQL
@@ -410,7 +410,7 @@ ERROR: procedure OUT parameters cannot appear after one with a default value
LINE 1: CREATE PROCEDURE ptestx(a int DEFAULT 42, b OUT int) LANGUAG...
^
ALTER PROCEDURE ptest1(text) STRICT;
-ERROR: invalid attribute in procedure definition
+ERROR: attribute "strict" is not allowed for procedures
LINE 1: ALTER PROCEDURE ptest1(text) STRICT;
^
ALTER FUNCTION ptest1(text) VOLATILE; -- error: not a function
diff --git a/src/test/regress/expected/misc_functions.out b/src/test/regress/expected/misc_functions.out
index c3261bff209..5465f206640 100644
--- a/src/test/regress/expected/misc_functions.out
+++ b/src/test/regress/expected/misc_functions.out
@@ -681,6 +681,74 @@ EXPLAIN (COSTS OFF) SELECT * FROM foo_from_bar('f1', 'text_tbl', 'doh!');
(2 rows)
DROP FUNCTION foo_from_bar;
+--
+-- Test adding a support function to an aggregate
+--
+CREATE FUNCTION test_aggref_support(internal)
+ RETURNS internal
+ AS :'regresslib', 'test_aggref_support'
+ LANGUAGE C STRICT;
+-- my_count() counts its input rows in the same way as count(any) does
+CREATE AGGREGATE my_count("any") (
+ SFUNC = int8inc_any, STYPE = int8, INITCOND = '0', PARALLEL = SAFE
+);
+-- SUPPORT is the only attribute an aggregate accepts
+ALTER FUNCTION my_count("any") COST 10;
+ERROR: attribute "cost" is not allowed for aggregates
+LINE 1: ALTER FUNCTION my_count("any") COST 10;
+ ^
+-- Setting the support function records a dependency
+ALTER FUNCTION my_count("any") SUPPORT test_aggref_support;
+DROP FUNCTION test_aggref_support(internal);
+ERROR: cannot drop function test_aggref_support(internal) because other objects depend on it
+DETAIL: function my_count("any") depends on function test_aggref_support(internal)
+HINT: Use DROP ... CASCADE to drop the dependent objects too.
+-- Attach a support function to a built-in aggregate and check that the
+-- planner calls it.
+BEGIN;
+ALTER FUNCTION pg_catalog.count("any") SUPPORT test_aggref_support;
+EXPLAIN (VERBOSE, COSTS OFF) SELECT count(a) FROM generate_series(1,10) AS a;
+ QUERY PLAN
+-----------------------------------------------------
+ Aggregate
+ Output: my_count(a)
+ -> Function Scan on pg_catalog.generate_series a
+ Output: a
+ Function Call: generate_series(1, 10)
+(5 rows)
+
+SELECT count(a) FROM generate_series(1,10) AS a;
+ count
+-------
+ 10
+(1 row)
+
+-- count(*) is a different aggregate, and keeps its own support function
+EXPLAIN (VERBOSE, COSTS OFF) SELECT count(*) FROM generate_series(1,10) AS a;
+ QUERY PLAN
+-----------------------------------------------------
+ Aggregate
+ Output: count(*)
+ -> Function Scan on pg_catalog.generate_series a
+ Output: a
+ Function Call: generate_series(1, 10)
+(5 rows)
+
+ROLLBACK;
+-- After the rollback the built-in support function is in charge again
+EXPLAIN (VERBOSE, COSTS OFF) SELECT count(a) FROM generate_series(1,10) AS a;
+ QUERY PLAN
+-----------------------------------------------------
+ Aggregate
+ Output: count(a)
+ -> Function Scan on pg_catalog.generate_series a
+ Output: a
+ Function Call: generate_series(1, 10)
+(5 rows)
+
+ALTER FUNCTION my_count("any") SUPPORT int8inc_support;
+-- Now we can delete this support function
+DROP FUNCTION test_aggref_support(internal);
-- Test functions for control data
SELECT count(*) > 0 AS ok FROM pg_control_checkpoint();
ok
diff --git a/src/test/regress/regress.c b/src/test/regress/regress.c
index c2975ffc1b0..faaee610a9d 100644
--- a/src/test/regress/regress.c
+++ b/src/test/regress/regress.c
@@ -35,10 +35,12 @@
#include "funcapi.h"
#include "mb/pg_wchar.h"
#include "miscadmin.h"
+#include "nodes/makefuncs.h"
#include "nodes/supportnodes.h"
#include "optimizer/optimizer.h"
#include "optimizer/plancat.h"
#include "parser/parse_coerce.h"
+#include "parser/parse_func.h"
#include "port/atomics.h"
#include "portability/instr_time.h"
#include "postmaster/postmaster.h" /* for MAX_BACKENDS */
@@ -822,6 +824,44 @@ test_support_func(PG_FUNCTION_ARGS)
PG_RETURN_POINTER(ret);
}
+PG_FUNCTION_INFO_V1(test_aggref_support);
+Datum
+test_aggref_support(PG_FUNCTION_ARGS)
+{
+ Node *rawreq = (Node *) PG_GETARG_POINTER(0);
+
+ if (IsA(rawreq, SupportRequestSimplifyAggref))
+ {
+ /*
+ * Replace the target with my_count(), a user aggregate that counts
+ * its input rows in the same way as count(any) does. That's safe as
+ * long as we don't attach this to any other aggregate.
+ */
+ SupportRequestSimplifyAggref *req;
+ Aggref *agg;
+ Aggref *newagg;
+ Oid argtypes[1] = {ANYOID};
+ Oid newfnoid;
+
+ req = (SupportRequestSimplifyAggref *) rawreq;
+ agg = req->aggref;
+
+ newfnoid = LookupFuncName(list_make1(makeString("my_count")),
+ 1, argtypes, true);
+ if (!OidIsValid(newfnoid) || newfnoid == agg->aggfnoid)
+ PG_RETURN_POINTER(NULL);
+
+ /* Build a new Aggref that names my_count, and change nothing else */
+ newagg = makeNode(Aggref);
+ memcpy(newagg, agg, sizeof(Aggref));
+ newagg->aggfnoid = newfnoid;
+
+ PG_RETURN_POINTER(newagg);
+ }
+
+ PG_RETURN_POINTER(NULL);
+}
+
PG_FUNCTION_INFO_V1(test_inline_in_from_support_func);
Datum
test_inline_in_from_support_func(PG_FUNCTION_ARGS)
diff --git a/src/test/regress/sql/misc_functions.sql b/src/test/regress/sql/misc_functions.sql
index 946ee5726cd..9386a388a1b 100644
--- a/src/test/regress/sql/misc_functions.sql
+++ b/src/test/regress/sql/misc_functions.sql
@@ -270,6 +270,46 @@ EXPLAIN (COSTS OFF) SELECT * FROM foo_from_bar('f1', 'text_tbl', 'doh!');
DROP FUNCTION foo_from_bar;
+--
+-- Test adding a support function to an aggregate
+--
+
+CREATE FUNCTION test_aggref_support(internal)
+ RETURNS internal
+ AS :'regresslib', 'test_aggref_support'
+ LANGUAGE C STRICT;
+
+-- my_count() counts its input rows in the same way as count(any) does
+CREATE AGGREGATE my_count("any") (
+ SFUNC = int8inc_any, STYPE = int8, INITCOND = '0', PARALLEL = SAFE
+);
+
+-- SUPPORT is the only attribute an aggregate accepts
+ALTER FUNCTION my_count("any") COST 10;
+
+-- Setting the support function records a dependency
+ALTER FUNCTION my_count("any") SUPPORT test_aggref_support;
+DROP FUNCTION test_aggref_support(internal);
+
+-- Attach a support function to a built-in aggregate and check that the
+-- planner calls it.
+BEGIN;
+ALTER FUNCTION pg_catalog.count("any") SUPPORT test_aggref_support;
+
+EXPLAIN (VERBOSE, COSTS OFF) SELECT count(a) FROM generate_series(1,10) AS a;
+SELECT count(a) FROM generate_series(1,10) AS a;
+
+-- count(*) is a different aggregate, and keeps its own support function
+EXPLAIN (VERBOSE, COSTS OFF) SELECT count(*) FROM generate_series(1,10) AS a;
+ROLLBACK;
+
+-- After the rollback the built-in support function is in charge again
+EXPLAIN (VERBOSE, COSTS OFF) SELECT count(a) FROM generate_series(1,10) AS a;
+
+ALTER FUNCTION my_count("any") SUPPORT int8inc_support;
+-- Now we can delete this support function
+DROP FUNCTION test_aggref_support(internal);
+
-- Test functions for control data
SELECT count(*) > 0 AS ok FROM pg_control_checkpoint();
SELECT count(*) > 0 AS ok FROM pg_control_init();
--
2.52.0
^ permalink raw reply [nested|flat] 12+ messages in thread
* Re: Allow a prosupport function to be attached to an aggregate
2026-08-17 06:13 Allow a prosupport function to be attached to an aggregate Andrei Lepikhov <lepihov@gmail.com>
2026-08-18 04:56 ` Re: Allow a prosupport function to be attached to an aggregate David Rowley <dgrowleyml@gmail.com>
2026-08-18 14:35 ` Re: Allow a prosupport function to be attached to an aggregate Tom Lane <tgl@sss.pgh.pa.us>
2026-08-20 07:23 ` Re: Allow a prosupport function to be attached to an aggregate Andrei Lepikhov <lepihov@gmail.com>
@ 2026-08-20 19:47 ` Tom Lane <tgl@sss.pgh.pa.us>
2026-08-20 20:06 ` Re: Allow a prosupport function to be attached to an aggregate Tom Lane <tgl@sss.pgh.pa.us>
0 siblings, 1 reply; 12+ messages in thread
From: Tom Lane @ 2026-08-20 19:47 UTC (permalink / raw)
To: Andrei Lepikhov <lepihov@gmail.com>; +Cc: David Rowley <dgrowleyml@gmail.com>; PostgreSQL Hackers <pgsql-hackers@lists.postgresql.org>; Corey Huinker <corey.huinker@gmail.com>
Andrei Lepikhov <lepihov@gmail.com> writes:
> Also, I'm not sure why pg_dump/upgrade has not been implemented. So, I
> added an 'unsupported' clause into the docs - let's discuss it later or
> correct me if such a feature can't be supported at all.
Shame on me, I didn't think about that angle.
After reflection I realized that the approach I took in my first patch
is wrong: letting ALTER FUNCTION work on an aggregate is pretty
non-orthogonal, if the only property it can set is SUPPORT. The right
way to do this is to add a SUPPORT option to CREATE AGGREGATE, which
slots nicely into getting pg_dump to handle it. As attached.
One thing I don't quite love about this is that the CREATE AGGREGATE
docs already refer to transfn, finalfn, etc as "support functions",
so that there's a potential for confusion as to what SUPPORT really
means. I considered naming the option something else, but it feels
wrong to not use the same name as in CREATE FUNCTION. Any other
opinions about that?
regards, tom lane
Attachments:
v2-0001-Allow-an-aggregate-s-planner-support-function-to-.patch (text/x-diff, 14.4K) download
From 7adf1cf56e82ddc3959a8cc44d277457ac03febd Mon Sep 17 00:00:00 2001
From: Tom Lane <tgl@sss.pgh.pa.us>
Date: Thu, 20 Aug 2026 15:40:39 -0400
Subject: [PATCH v2] Allow an aggregate's planner support function to be set
via CREATE AGGREGATE.
Commit 42473b3b3 implemented SupportRequestSimplifyAggref, but failed
to think about what infrastructure would be required for an extension
to use that: there is no SQL-level mechanism for attaching a planner
support function to an aggregate. That seems pretty critical for a
feature that's primarily intended to be used by extensions.
To fix, add a SUPPORT clause to CREATE AGGREGATE, and teach pg_dump
(and thereby pg_upgrade) about dumping this aggregate property.
We don't need to touch ALTER AGGREGATE, because it's already the case
that you're supposed to use CREATE OR REPLACE AGGREGATE if you want
to alter any aggregate-specific properties set by CREATE AGGREGATE.
(Maybe at some point we'll think that that policy ought to change,
but I don't think this one feature moves the needle enough.)
Per report from Andrei Lepikhov, who also provided some of the
new documentation text.
Reported-by: Andrei Lepikhov <lepihov@gmail.com>
Author: Tom Lane <tgl@sss.pgh.pa.us>
Reviewed-by: Andrei Lepikhov <lepihov@gmail.com>
Discussion: https://postgr.es/m/8f58c96d-d3c7-4c0f-9898-116f00eeaff6@gmail.com
Backpatch-through: 19
---
doc/src/sgml/ref/alter_aggregate.sgml | 7 ++++++
doc/src/sgml/ref/create_aggregate.sgml | 15 ++++++++++++
doc/src/sgml/xfunc.sgml | 18 +++++++++++++-
src/backend/catalog/pg_aggregate.c | 24 ++++++++++++++++++-
src/backend/commands/aggregatecmds.c | 4 ++++
src/bin/pg_dump/pg_dump.c | 18 ++++++++++++--
src/include/catalog/pg_aggregate.h | 1 +
.../regress/expected/create_aggregate.out | 15 ++++++++++++
src/test/regress/sql/create_aggregate.sql | 8 +++++++
9 files changed, 106 insertions(+), 4 deletions(-)
diff --git a/doc/src/sgml/ref/alter_aggregate.sgml b/doc/src/sgml/ref/alter_aggregate.sgml
index d0a39ba7b5e..cc11e077561 100644
--- a/doc/src/sgml/ref/alter_aggregate.sgml
+++ b/doc/src/sgml/ref/alter_aggregate.sgml
@@ -149,6 +149,13 @@ ALTER AGGREGATE <replaceable>name</replaceable> ( <replaceable>aggregate_signatu
if <literal>VARIADIC "any"</literal> was used in both the direct and
aggregated argument lists, write <literal>VARIADIC "any"</literal> only once.
</para>
+
+ <para>
+ <command>ALTER AGGREGATE</command> deals only with generic properties of
+ an aggregate, such as its name. To change the aggregate-specific
+ properties of an aggregate such as its support functions, replace its
+ definition entirely with <command>CREATE OR REPLACE AGGREGATE</command>.
+ </para>
</refsect1>
<refsect1>
diff --git a/doc/src/sgml/ref/create_aggregate.sgml b/doc/src/sgml/ref/create_aggregate.sgml
index 0472ac2e874..89203d39221 100644
--- a/doc/src/sgml/ref/create_aggregate.sgml
+++ b/doc/src/sgml/ref/create_aggregate.sgml
@@ -41,6 +41,7 @@ CREATE [ OR REPLACE ] AGGREGATE <replaceable class="parameter">name</replaceable
[ , MFINALFUNC_MODIFY = { READ_ONLY | SHAREABLE | READ_WRITE } ]
[ , MINITCOND = <replaceable class="parameter">minitial_condition</replaceable> ]
[ , SORTOP = <replaceable class="parameter">sort_operator</replaceable> ]
+ [ , SUPPORT = <replaceable class="parameter">supportfunc</replaceable> ]
[ , PARALLEL = { SAFE | RESTRICTED | UNSAFE } ]
)
@@ -53,6 +54,7 @@ CREATE [ OR REPLACE ] AGGREGATE <replaceable class="parameter">name</replaceable
[ , FINALFUNC_EXTRA ]
[ , FINALFUNC_MODIFY = { READ_ONLY | SHAREABLE | READ_WRITE } ]
[ , INITCOND = <replaceable class="parameter">initial_condition</replaceable> ]
+ [ , SUPPORT = <replaceable class="parameter">supportfunc</replaceable> ]
[ , PARALLEL = { SAFE | RESTRICTED | UNSAFE } ]
[ , HYPOTHETICAL ]
)
@@ -80,6 +82,7 @@ CREATE [ OR REPLACE ] AGGREGATE <replaceable class="parameter">name</replaceable
[ , MFINALFUNC_MODIFY = { READ_ONLY | SHAREABLE | READ_WRITE } ]
[ , MINITCOND = <replaceable class="parameter">minitial_condition</replaceable> ]
[ , SORTOP = <replaceable class="parameter">sort_operator</replaceable> ]
+ [ , SUPPORT = <replaceable class="parameter">supportfunc</replaceable> ]
)
</synopsis>
</refsynopsisdiv>
@@ -628,6 +631,18 @@ SELECT col FROM tab ORDER BY col USING sortop LIMIT 1;
</listitem>
</varlistentry>
+ <varlistentry>
+ <term><replaceable class="parameter">supportfunc</replaceable></term>
+ <listitem>
+ <para>
+ The name (optionally schema-qualified) of a <firstterm>planner support
+ function</firstterm> to use for this aggregate. See
+ <xref linkend="xfunc-optimization"/> for details.
+ You must be superuser to use this option.
+ </para>
+ </listitem>
+ </varlistentry>
+
<varlistentry>
<term><literal>PARALLEL =</literal> { <literal>SAFE</literal> | <literal>RESTRICTED</literal> | <literal>UNSAFE</literal> }</term>
<listitem>
diff --git a/doc/src/sgml/xfunc.sgml b/doc/src/sgml/xfunc.sgml
index 050e1e50bec..97f3cb625e2 100644
--- a/doc/src/sgml/xfunc.sgml
+++ b/doc/src/sgml/xfunc.sgml
@@ -4167,7 +4167,7 @@ extern PgStat_Kind pgstat_register_kind(PgStat_Kind kind,
<para>
It is also possible to attach a <firstterm>planner support
- function</firstterm> to an SQL-callable function (called
+ function</firstterm> to an SQL-callable function or aggregate (called
its <firstterm>target function</firstterm>), and thereby provide
knowledge about the target function that is too complex to be
represented declaratively. Planner support functions have to be
@@ -4241,6 +4241,22 @@ supportfn(internal) returns internal
normal execution of the target function.
</para>
+ <para>
+ Aggregate function calls can also be simplified during planning. For
+ example, <literal>COUNT(<replaceable>x</replaceable>)</literal> can be
+ replaced by <literal>COUNT(*)</literal>
+ when <replaceable>x</replaceable> is known to not be null. This can be
+ done by a support function that implements
+ the <literal>SupportRequestSimplifyAggref</literal> request type. The
+ support function will be called for each instance of its target aggregate
+ found in a query parse tree. If it finds that the particular call can be
+ replaced, it can build and return a new node, usually another aggregate
+ call, leaving the node it was given unmodified. As with
+ <literal>SupportRequestSimplify</literal>, it is the support function's
+ responsibility that the replacement be equivalent to normal execution of
+ the target aggregate.
+ </para>
+
<para>
For target functions that return <type>boolean</type>, it is often useful to estimate
the fraction of rows that will be selected by a <literal>WHERE</literal> clause using that
diff --git a/src/backend/catalog/pg_aggregate.c b/src/backend/catalog/pg_aggregate.c
index 243b952b9cc..c66ff706f4c 100644
--- a/src/backend/catalog/pg_aggregate.c
+++ b/src/backend/catalog/pg_aggregate.c
@@ -68,6 +68,7 @@ AggregateCreate(const char *aggName,
char finalfnModify,
char mfinalfnModify,
List *aggsortopName,
+ List *aggsupportfuncName,
Oid aggTransType,
int32 aggTransSpace,
Oid aggmTransType,
@@ -92,6 +93,7 @@ AggregateCreate(const char *aggName,
Oid minvtransfn = InvalidOid; /* can be omitted */
Oid mfinalfn = InvalidOid; /* can be omitted */
Oid sortop = InvalidOid; /* can be omitted */
+ Oid supportfn = InvalidOid; /* can be omitted */
Oid *aggArgTypes = parameterTypes->values;
bool mtransIsStrict = false;
Oid rettype;
@@ -581,6 +583,26 @@ AggregateCreate(const char *aggName,
false, -1);
}
+ /*
+ * Validate the planner support function, if present.
+ */
+ if (aggsupportfuncName)
+ {
+ /* signature is always support(internal) returns internal */
+ fnArgs[0] = INTERNALOID;
+
+ supportfn = lookup_agg_function(aggsupportfuncName, 1,
+ fnArgs, InvalidOid,
+ &rettype);
+
+ if (rettype != INTERNALOID)
+ ereport(ERROR,
+ (errcode(ERRCODE_DATATYPE_MISMATCH),
+ errmsg("return type of support function %s is not %s",
+ NameListToString(aggsupportfuncName),
+ format_type_be(INTERNALOID))));
+ }
+
/*
* permission checks on used types
*/
@@ -639,7 +661,7 @@ AggregateCreate(const char *aggName,
PointerGetDatum(NULL), /* trftypes */
NIL, /* trfoids */
PointerGetDatum(NULL), /* proconfig */
- InvalidOid, /* no prosupport */
+ supportfn, /* prosupport */
1, /* procost */
0); /* prorows */
procOid = myself.objectId;
diff --git a/src/backend/commands/aggregatecmds.c b/src/backend/commands/aggregatecmds.c
index 41b45dc6402..d26cfd8081d 100644
--- a/src/backend/commands/aggregatecmds.c
+++ b/src/backend/commands/aggregatecmds.c
@@ -74,6 +74,7 @@ DefineAggregate(ParseState *pstate,
char finalfuncModify = 0;
char mfinalfuncModify = 0;
List *sortoperatorName = NIL;
+ List *supportfuncName = NIL;
TypeName *baseType = NULL;
TypeName *transType = NULL;
TypeName *mtransType = NULL;
@@ -155,6 +156,8 @@ DefineAggregate(ParseState *pstate,
mfinalfuncModify = extractModify(defel);
else if (strcmp(defel->defname, "sortop") == 0)
sortoperatorName = defGetQualifiedName(defel);
+ else if (strcmp(defel->defname, "support") == 0)
+ supportfuncName = defGetQualifiedName(defel);
else if (strcmp(defel->defname, "basetype") == 0)
baseType = defGetTypeName(defel);
else if (strcmp(defel->defname, "hypothetical") == 0)
@@ -462,6 +465,7 @@ DefineAggregate(ParseState *pstate,
finalfuncModify,
mfinalfuncModify,
sortoperatorName, /* sort operator name */
+ supportfuncName, /* planner support func name */
transTypeId, /* transition data type */
transSpace, /* transition space */
mtransTypeId, /* transition data type */
diff --git a/src/bin/pg_dump/pg_dump.c b/src/bin/pg_dump/pg_dump.c
index feed88f9854..db14834e430 100644
--- a/src/bin/pg_dump/pg_dump.c
+++ b/src/bin/pg_dump/pg_dump.c
@@ -15365,6 +15365,7 @@ dumpAgg(Archive *fout, const AggInfo *agginfo)
const char *agginitval;
const char *aggminitval;
const char *proparallel;
+ const char *prosupport;
char defaultfinalmodify;
/* Do nothing if not dumping schema */
@@ -15413,11 +15414,18 @@ dumpAgg(Archive *fout, const AggInfo *agginfo)
if (fout->remoteVersion >= 110000)
appendPQExpBufferStr(query,
"aggfinalmodify,\n"
- "aggmfinalmodify\n");
+ "aggmfinalmodify,\n");
else
appendPQExpBufferStr(query,
"'0' AS aggfinalmodify,\n"
- "'0' AS aggmfinalmodify\n");
+ "'0' AS aggmfinalmodify,\n");
+
+ if (fout->remoteVersion >= 120000)
+ appendPQExpBufferStr(query,
+ "prosupport\n");
+ else
+ appendPQExpBufferStr(query,
+ "'-' AS prosupport\n");
appendPQExpBufferStr(query,
"FROM pg_catalog.pg_aggregate a, pg_catalog.pg_proc p "
@@ -15459,6 +15467,7 @@ dumpAgg(Archive *fout, const AggInfo *agginfo)
agginitval = PQgetvalue(res, 0, i_agginitval);
aggminitval = PQgetvalue(res, 0, i_aggminitval);
proparallel = PQgetvalue(res, 0, PQfnumber(res, "proparallel"));
+ prosupport = PQgetvalue(res, 0, PQfnumber(res, "prosupport"));
{
char *funcargs;
@@ -15587,6 +15596,11 @@ dumpAgg(Archive *fout, const AggInfo *agginfo)
free(aggsortconvop);
}
+ if (strcmp(prosupport, "-") != 0)
+ {
+ appendPQExpBuffer(details, ",\n SUPPORT = %s", prosupport);
+ }
+
if (aggkind == AGGKIND_HYPOTHETICAL)
appendPQExpBufferStr(details, ",\n HYPOTHETICAL");
diff --git a/src/include/catalog/pg_aggregate.h b/src/include/catalog/pg_aggregate.h
index 2b4f5dae5f2..2668b035859 100644
--- a/src/include/catalog/pg_aggregate.h
+++ b/src/include/catalog/pg_aggregate.h
@@ -175,6 +175,7 @@ extern ObjectAddress AggregateCreate(const char *aggName,
char finalfnModify,
char mfinalfnModify,
List *aggsortopName,
+ List *aggsupportfuncName,
Oid aggTransType,
int32 aggTransSpace,
Oid aggmTransType,
diff --git a/src/test/regress/expected/create_aggregate.out b/src/test/regress/expected/create_aggregate.out
index dcf69094237..68062620efa 100644
--- a/src/test/regress/expected/create_aggregate.out
+++ b/src/test/regress/expected/create_aggregate.out
@@ -30,12 +30,27 @@ CREATE AGGREGATE oldcnt (
-- aggregate that only cares about null/nonnull input
CREATE AGGREGATE newcnt ("any") (
sfunc = int8inc_any, stype = int8,
+ support = int8inc_support,
initcond = '0'
);
COMMENT ON AGGREGATE nosuchagg (*) IS 'should fail';
ERROR: aggregate nosuchagg(*) does not exist
COMMENT ON AGGREGATE newcnt (*) IS 'an agg(*) comment';
COMMENT ON AGGREGATE newcnt ("any") IS 'an agg(any) comment';
+-- verify that newcnt's support function enables run-condition optimization
+EXPLAIN (COSTS OFF)
+SELECT * FROM
+ (SELECT newcnt(ten) OVER (RANGE BETWEEN CURRENT ROW AND CURRENT ROW) c
+ FROM tenk1) t
+WHERE c = 1;
+ QUERY PLAN
+-------------------------------------------------------------
+ WindowAgg
+ Window: w1 AS (RANGE BETWEEN CURRENT ROW AND CURRENT ROW)
+ Run Condition: (newcnt(tenk1.ten) OVER w1 = 1)
+ -> Seq Scan on tenk1
+(4 rows)
+
-- multi-argument aggregate
create function sum3(int8,int8,int8) returns int8 as
'select $1 + $2 + $3' language sql strict immutable;
diff --git a/src/test/regress/sql/create_aggregate.sql b/src/test/regress/sql/create_aggregate.sql
index d4b4036fd7d..6b88b9735af 100644
--- a/src/test/regress/sql/create_aggregate.sql
+++ b/src/test/regress/sql/create_aggregate.sql
@@ -35,6 +35,7 @@ CREATE AGGREGATE oldcnt (
-- aggregate that only cares about null/nonnull input
CREATE AGGREGATE newcnt ("any") (
sfunc = int8inc_any, stype = int8,
+ support = int8inc_support,
initcond = '0'
);
@@ -42,6 +43,13 @@ COMMENT ON AGGREGATE nosuchagg (*) IS 'should fail';
COMMENT ON AGGREGATE newcnt (*) IS 'an agg(*) comment';
COMMENT ON AGGREGATE newcnt ("any") IS 'an agg(any) comment';
+-- verify that newcnt's support function enables run-condition optimization
+EXPLAIN (COSTS OFF)
+SELECT * FROM
+ (SELECT newcnt(ten) OVER (RANGE BETWEEN CURRENT ROW AND CURRENT ROW) c
+ FROM tenk1) t
+WHERE c = 1;
+
-- multi-argument aggregate
create function sum3(int8,int8,int8) returns int8 as
'select $1 + $2 + $3' language sql strict immutable;
--
2.52.0
^ permalink raw reply [nested|flat] 12+ messages in thread
* Re: Allow a prosupport function to be attached to an aggregate
2026-08-17 06:13 Allow a prosupport function to be attached to an aggregate Andrei Lepikhov <lepihov@gmail.com>
2026-08-18 04:56 ` Re: Allow a prosupport function to be attached to an aggregate David Rowley <dgrowleyml@gmail.com>
2026-08-18 14:35 ` Re: Allow a prosupport function to be attached to an aggregate Tom Lane <tgl@sss.pgh.pa.us>
2026-08-20 07:23 ` Re: Allow a prosupport function to be attached to an aggregate Andrei Lepikhov <lepihov@gmail.com>
2026-08-20 19:47 ` Re: Allow a prosupport function to be attached to an aggregate Tom Lane <tgl@sss.pgh.pa.us>
@ 2026-08-20 20:06 ` Tom Lane <tgl@sss.pgh.pa.us>
2026-08-21 15:06 ` Re: Allow a prosupport function to be attached to an aggregate Andrei Lepikhov <lepihov@gmail.com>
0 siblings, 1 reply; 12+ messages in thread
From: Tom Lane @ 2026-08-20 20:06 UTC (permalink / raw)
To: Andrei Lepikhov <lepihov@gmail.com>; +Cc: David Rowley <dgrowleyml@gmail.com>; PostgreSQL Hackers <pgsql-hackers@lists.postgresql.org>; Corey Huinker <corey.huinker@gmail.com>
I wrote:
> After reflection I realized that the approach I took in my first patch
> is wrong: letting ALTER FUNCTION work on an aggregate is pretty
> non-orthogonal, if the only property it can set is SUPPORT. The right
> way to do this is to add a SUPPORT option to CREATE AGGREGATE, which
> slots nicely into getting pg_dump to handle it. As attached.
Grumble ... for some reason I was thinking that ProcedureCreate would
handle checking for superuser when specifying a support function,
but it doesn't; AggregateCreate must do that. v3 attached contains
just that one addition.
regards, tom lane
Attachments:
v3-0001-Allow-an-aggregate-s-planner-support-function-to-.patch (text/x-diff, 14.6K) download
From af5b492e92239da03d791427d2bf31657fc92e79 Mon Sep 17 00:00:00 2001
From: Tom Lane <tgl@sss.pgh.pa.us>
Date: Thu, 20 Aug 2026 16:03:13 -0400
Subject: [PATCH v3] Allow an aggregate's planner support function to be set
via CREATE AGGREGATE.
Commit 42473b3b3 implemented SupportRequestSimplifyAggref, but failed
to think about what infrastructure would be required for an extension
to use that: there is no SQL-level mechanism for attaching a planner
support function to an aggregate. That seems pretty critical for a
feature that's primarily intended to be used by extensions.
To fix, add a SUPPORT clause to CREATE AGGREGATE, and teach pg_dump
(and thereby pg_upgrade) about dumping this aggregate property.
We don't need to touch ALTER AGGREGATE, because it's already the case
that you're supposed to use CREATE OR REPLACE AGGREGATE if you want
to alter any aggregate-specific properties set by CREATE AGGREGATE.
(Maybe at some point we'll think that that policy ought to change,
but I don't think this one feature moves the needle enough.)
Per report from Andrei Lepikhov, who also provided some of the
new documentation text.
Reported-by: Andrei Lepikhov <lepihov@gmail.com>
Author: Tom Lane <tgl@sss.pgh.pa.us>
Reviewed-by: Andrei Lepikhov <lepihov@gmail.com>
Discussion: https://postgr.es/m/8f58c96d-d3c7-4c0f-9898-116f00eeaff6@gmail.com
Backpatch-through: 19
---
doc/src/sgml/ref/alter_aggregate.sgml | 7 ++++
doc/src/sgml/ref/create_aggregate.sgml | 15 +++++++++
doc/src/sgml/xfunc.sgml | 18 +++++++++-
src/backend/catalog/pg_aggregate.c | 33 ++++++++++++++++++-
src/backend/commands/aggregatecmds.c | 4 +++
src/bin/pg_dump/pg_dump.c | 18 ++++++++--
src/include/catalog/pg_aggregate.h | 1 +
.../regress/expected/create_aggregate.out | 15 +++++++++
src/test/regress/sql/create_aggregate.sql | 8 +++++
9 files changed, 115 insertions(+), 4 deletions(-)
diff --git a/doc/src/sgml/ref/alter_aggregate.sgml b/doc/src/sgml/ref/alter_aggregate.sgml
index d0a39ba7b5e..cc11e077561 100644
--- a/doc/src/sgml/ref/alter_aggregate.sgml
+++ b/doc/src/sgml/ref/alter_aggregate.sgml
@@ -149,6 +149,13 @@ ALTER AGGREGATE <replaceable>name</replaceable> ( <replaceable>aggregate_signatu
if <literal>VARIADIC "any"</literal> was used in both the direct and
aggregated argument lists, write <literal>VARIADIC "any"</literal> only once.
</para>
+
+ <para>
+ <command>ALTER AGGREGATE</command> deals only with generic properties of
+ an aggregate, such as its name. To change the aggregate-specific
+ properties of an aggregate such as its support functions, replace its
+ definition entirely with <command>CREATE OR REPLACE AGGREGATE</command>.
+ </para>
</refsect1>
<refsect1>
diff --git a/doc/src/sgml/ref/create_aggregate.sgml b/doc/src/sgml/ref/create_aggregate.sgml
index 0472ac2e874..89203d39221 100644
--- a/doc/src/sgml/ref/create_aggregate.sgml
+++ b/doc/src/sgml/ref/create_aggregate.sgml
@@ -41,6 +41,7 @@ CREATE [ OR REPLACE ] AGGREGATE <replaceable class="parameter">name</replaceable
[ , MFINALFUNC_MODIFY = { READ_ONLY | SHAREABLE | READ_WRITE } ]
[ , MINITCOND = <replaceable class="parameter">minitial_condition</replaceable> ]
[ , SORTOP = <replaceable class="parameter">sort_operator</replaceable> ]
+ [ , SUPPORT = <replaceable class="parameter">supportfunc</replaceable> ]
[ , PARALLEL = { SAFE | RESTRICTED | UNSAFE } ]
)
@@ -53,6 +54,7 @@ CREATE [ OR REPLACE ] AGGREGATE <replaceable class="parameter">name</replaceable
[ , FINALFUNC_EXTRA ]
[ , FINALFUNC_MODIFY = { READ_ONLY | SHAREABLE | READ_WRITE } ]
[ , INITCOND = <replaceable class="parameter">initial_condition</replaceable> ]
+ [ , SUPPORT = <replaceable class="parameter">supportfunc</replaceable> ]
[ , PARALLEL = { SAFE | RESTRICTED | UNSAFE } ]
[ , HYPOTHETICAL ]
)
@@ -80,6 +82,7 @@ CREATE [ OR REPLACE ] AGGREGATE <replaceable class="parameter">name</replaceable
[ , MFINALFUNC_MODIFY = { READ_ONLY | SHAREABLE | READ_WRITE } ]
[ , MINITCOND = <replaceable class="parameter">minitial_condition</replaceable> ]
[ , SORTOP = <replaceable class="parameter">sort_operator</replaceable> ]
+ [ , SUPPORT = <replaceable class="parameter">supportfunc</replaceable> ]
)
</synopsis>
</refsynopsisdiv>
@@ -628,6 +631,18 @@ SELECT col FROM tab ORDER BY col USING sortop LIMIT 1;
</listitem>
</varlistentry>
+ <varlistentry>
+ <term><replaceable class="parameter">supportfunc</replaceable></term>
+ <listitem>
+ <para>
+ The name (optionally schema-qualified) of a <firstterm>planner support
+ function</firstterm> to use for this aggregate. See
+ <xref linkend="xfunc-optimization"/> for details.
+ You must be superuser to use this option.
+ </para>
+ </listitem>
+ </varlistentry>
+
<varlistentry>
<term><literal>PARALLEL =</literal> { <literal>SAFE</literal> | <literal>RESTRICTED</literal> | <literal>UNSAFE</literal> }</term>
<listitem>
diff --git a/doc/src/sgml/xfunc.sgml b/doc/src/sgml/xfunc.sgml
index 050e1e50bec..97f3cb625e2 100644
--- a/doc/src/sgml/xfunc.sgml
+++ b/doc/src/sgml/xfunc.sgml
@@ -4167,7 +4167,7 @@ extern PgStat_Kind pgstat_register_kind(PgStat_Kind kind,
<para>
It is also possible to attach a <firstterm>planner support
- function</firstterm> to an SQL-callable function (called
+ function</firstterm> to an SQL-callable function or aggregate (called
its <firstterm>target function</firstterm>), and thereby provide
knowledge about the target function that is too complex to be
represented declaratively. Planner support functions have to be
@@ -4241,6 +4241,22 @@ supportfn(internal) returns internal
normal execution of the target function.
</para>
+ <para>
+ Aggregate function calls can also be simplified during planning. For
+ example, <literal>COUNT(<replaceable>x</replaceable>)</literal> can be
+ replaced by <literal>COUNT(*)</literal>
+ when <replaceable>x</replaceable> is known to not be null. This can be
+ done by a support function that implements
+ the <literal>SupportRequestSimplifyAggref</literal> request type. The
+ support function will be called for each instance of its target aggregate
+ found in a query parse tree. If it finds that the particular call can be
+ replaced, it can build and return a new node, usually another aggregate
+ call, leaving the node it was given unmodified. As with
+ <literal>SupportRequestSimplify</literal>, it is the support function's
+ responsibility that the replacement be equivalent to normal execution of
+ the target aggregate.
+ </para>
+
<para>
For target functions that return <type>boolean</type>, it is often useful to estimate
the fraction of rows that will be selected by a <literal>WHERE</literal> clause using that
diff --git a/src/backend/catalog/pg_aggregate.c b/src/backend/catalog/pg_aggregate.c
index 243b952b9cc..4d98a7584ae 100644
--- a/src/backend/catalog/pg_aggregate.c
+++ b/src/backend/catalog/pg_aggregate.c
@@ -68,6 +68,7 @@ AggregateCreate(const char *aggName,
char finalfnModify,
char mfinalfnModify,
List *aggsortopName,
+ List *aggsupportfuncName,
Oid aggTransType,
int32 aggTransSpace,
Oid aggmTransType,
@@ -92,6 +93,7 @@ AggregateCreate(const char *aggName,
Oid minvtransfn = InvalidOid; /* can be omitted */
Oid mfinalfn = InvalidOid; /* can be omitted */
Oid sortop = InvalidOid; /* can be omitted */
+ Oid supportfn = InvalidOid; /* can be omitted */
Oid *aggArgTypes = parameterTypes->values;
bool mtransIsStrict = false;
Oid rettype;
@@ -581,6 +583,35 @@ AggregateCreate(const char *aggName,
false, -1);
}
+ /*
+ * Validate the planner support function, if present.
+ */
+ if (aggsupportfuncName)
+ {
+ /* signature is always support(internal) returns internal */
+ fnArgs[0] = INTERNALOID;
+
+ supportfn = lookup_agg_function(aggsupportfuncName, 1,
+ fnArgs, InvalidOid,
+ &rettype);
+
+ if (rettype != INTERNALOID)
+ ereport(ERROR,
+ (errcode(ERRCODE_DATATYPE_MISMATCH),
+ errmsg("return type of support function %s is not %s",
+ NameListToString(aggsupportfuncName),
+ format_type_be(INTERNALOID))));
+
+ /*
+ * Specifying a support function requires superuser, same as in CREATE
+ * FUNCTION.
+ */
+ if (!superuser())
+ ereport(ERROR,
+ (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
+ errmsg("must be superuser to specify a support function")));
+ }
+
/*
* permission checks on used types
*/
@@ -639,7 +670,7 @@ AggregateCreate(const char *aggName,
PointerGetDatum(NULL), /* trftypes */
NIL, /* trfoids */
PointerGetDatum(NULL), /* proconfig */
- InvalidOid, /* no prosupport */
+ supportfn, /* prosupport */
1, /* procost */
0); /* prorows */
procOid = myself.objectId;
diff --git a/src/backend/commands/aggregatecmds.c b/src/backend/commands/aggregatecmds.c
index 41b45dc6402..d26cfd8081d 100644
--- a/src/backend/commands/aggregatecmds.c
+++ b/src/backend/commands/aggregatecmds.c
@@ -74,6 +74,7 @@ DefineAggregate(ParseState *pstate,
char finalfuncModify = 0;
char mfinalfuncModify = 0;
List *sortoperatorName = NIL;
+ List *supportfuncName = NIL;
TypeName *baseType = NULL;
TypeName *transType = NULL;
TypeName *mtransType = NULL;
@@ -155,6 +156,8 @@ DefineAggregate(ParseState *pstate,
mfinalfuncModify = extractModify(defel);
else if (strcmp(defel->defname, "sortop") == 0)
sortoperatorName = defGetQualifiedName(defel);
+ else if (strcmp(defel->defname, "support") == 0)
+ supportfuncName = defGetQualifiedName(defel);
else if (strcmp(defel->defname, "basetype") == 0)
baseType = defGetTypeName(defel);
else if (strcmp(defel->defname, "hypothetical") == 0)
@@ -462,6 +465,7 @@ DefineAggregate(ParseState *pstate,
finalfuncModify,
mfinalfuncModify,
sortoperatorName, /* sort operator name */
+ supportfuncName, /* planner support func name */
transTypeId, /* transition data type */
transSpace, /* transition space */
mtransTypeId, /* transition data type */
diff --git a/src/bin/pg_dump/pg_dump.c b/src/bin/pg_dump/pg_dump.c
index feed88f9854..db14834e430 100644
--- a/src/bin/pg_dump/pg_dump.c
+++ b/src/bin/pg_dump/pg_dump.c
@@ -15365,6 +15365,7 @@ dumpAgg(Archive *fout, const AggInfo *agginfo)
const char *agginitval;
const char *aggminitval;
const char *proparallel;
+ const char *prosupport;
char defaultfinalmodify;
/* Do nothing if not dumping schema */
@@ -15413,11 +15414,18 @@ dumpAgg(Archive *fout, const AggInfo *agginfo)
if (fout->remoteVersion >= 110000)
appendPQExpBufferStr(query,
"aggfinalmodify,\n"
- "aggmfinalmodify\n");
+ "aggmfinalmodify,\n");
else
appendPQExpBufferStr(query,
"'0' AS aggfinalmodify,\n"
- "'0' AS aggmfinalmodify\n");
+ "'0' AS aggmfinalmodify,\n");
+
+ if (fout->remoteVersion >= 120000)
+ appendPQExpBufferStr(query,
+ "prosupport\n");
+ else
+ appendPQExpBufferStr(query,
+ "'-' AS prosupport\n");
appendPQExpBufferStr(query,
"FROM pg_catalog.pg_aggregate a, pg_catalog.pg_proc p "
@@ -15459,6 +15467,7 @@ dumpAgg(Archive *fout, const AggInfo *agginfo)
agginitval = PQgetvalue(res, 0, i_agginitval);
aggminitval = PQgetvalue(res, 0, i_aggminitval);
proparallel = PQgetvalue(res, 0, PQfnumber(res, "proparallel"));
+ prosupport = PQgetvalue(res, 0, PQfnumber(res, "prosupport"));
{
char *funcargs;
@@ -15587,6 +15596,11 @@ dumpAgg(Archive *fout, const AggInfo *agginfo)
free(aggsortconvop);
}
+ if (strcmp(prosupport, "-") != 0)
+ {
+ appendPQExpBuffer(details, ",\n SUPPORT = %s", prosupport);
+ }
+
if (aggkind == AGGKIND_HYPOTHETICAL)
appendPQExpBufferStr(details, ",\n HYPOTHETICAL");
diff --git a/src/include/catalog/pg_aggregate.h b/src/include/catalog/pg_aggregate.h
index 2b4f5dae5f2..2668b035859 100644
--- a/src/include/catalog/pg_aggregate.h
+++ b/src/include/catalog/pg_aggregate.h
@@ -175,6 +175,7 @@ extern ObjectAddress AggregateCreate(const char *aggName,
char finalfnModify,
char mfinalfnModify,
List *aggsortopName,
+ List *aggsupportfuncName,
Oid aggTransType,
int32 aggTransSpace,
Oid aggmTransType,
diff --git a/src/test/regress/expected/create_aggregate.out b/src/test/regress/expected/create_aggregate.out
index dcf69094237..68062620efa 100644
--- a/src/test/regress/expected/create_aggregate.out
+++ b/src/test/regress/expected/create_aggregate.out
@@ -30,12 +30,27 @@ CREATE AGGREGATE oldcnt (
-- aggregate that only cares about null/nonnull input
CREATE AGGREGATE newcnt ("any") (
sfunc = int8inc_any, stype = int8,
+ support = int8inc_support,
initcond = '0'
);
COMMENT ON AGGREGATE nosuchagg (*) IS 'should fail';
ERROR: aggregate nosuchagg(*) does not exist
COMMENT ON AGGREGATE newcnt (*) IS 'an agg(*) comment';
COMMENT ON AGGREGATE newcnt ("any") IS 'an agg(any) comment';
+-- verify that newcnt's support function enables run-condition optimization
+EXPLAIN (COSTS OFF)
+SELECT * FROM
+ (SELECT newcnt(ten) OVER (RANGE BETWEEN CURRENT ROW AND CURRENT ROW) c
+ FROM tenk1) t
+WHERE c = 1;
+ QUERY PLAN
+-------------------------------------------------------------
+ WindowAgg
+ Window: w1 AS (RANGE BETWEEN CURRENT ROW AND CURRENT ROW)
+ Run Condition: (newcnt(tenk1.ten) OVER w1 = 1)
+ -> Seq Scan on tenk1
+(4 rows)
+
-- multi-argument aggregate
create function sum3(int8,int8,int8) returns int8 as
'select $1 + $2 + $3' language sql strict immutable;
diff --git a/src/test/regress/sql/create_aggregate.sql b/src/test/regress/sql/create_aggregate.sql
index d4b4036fd7d..6b88b9735af 100644
--- a/src/test/regress/sql/create_aggregate.sql
+++ b/src/test/regress/sql/create_aggregate.sql
@@ -35,6 +35,7 @@ CREATE AGGREGATE oldcnt (
-- aggregate that only cares about null/nonnull input
CREATE AGGREGATE newcnt ("any") (
sfunc = int8inc_any, stype = int8,
+ support = int8inc_support,
initcond = '0'
);
@@ -42,6 +43,13 @@ COMMENT ON AGGREGATE nosuchagg (*) IS 'should fail';
COMMENT ON AGGREGATE newcnt (*) IS 'an agg(*) comment';
COMMENT ON AGGREGATE newcnt ("any") IS 'an agg(any) comment';
+-- verify that newcnt's support function enables run-condition optimization
+EXPLAIN (COSTS OFF)
+SELECT * FROM
+ (SELECT newcnt(ten) OVER (RANGE BETWEEN CURRENT ROW AND CURRENT ROW) c
+ FROM tenk1) t
+WHERE c = 1;
+
-- multi-argument aggregate
create function sum3(int8,int8,int8) returns int8 as
'select $1 + $2 + $3' language sql strict immutable;
--
2.52.0
^ permalink raw reply [nested|flat] 12+ messages in thread
* Re: Allow a prosupport function to be attached to an aggregate
2026-08-17 06:13 Allow a prosupport function to be attached to an aggregate Andrei Lepikhov <lepihov@gmail.com>
2026-08-18 04:56 ` Re: Allow a prosupport function to be attached to an aggregate David Rowley <dgrowleyml@gmail.com>
2026-08-18 14:35 ` Re: Allow a prosupport function to be attached to an aggregate Tom Lane <tgl@sss.pgh.pa.us>
2026-08-20 07:23 ` Re: Allow a prosupport function to be attached to an aggregate Andrei Lepikhov <lepihov@gmail.com>
2026-08-20 19:47 ` Re: Allow a prosupport function to be attached to an aggregate Tom Lane <tgl@sss.pgh.pa.us>
2026-08-20 20:06 ` Re: Allow a prosupport function to be attached to an aggregate Tom Lane <tgl@sss.pgh.pa.us>
@ 2026-08-21 15:06 ` Andrei Lepikhov <lepihov@gmail.com>
2026-08-21 15:20 ` Re: Allow a prosupport function to be attached to an aggregate Tom Lane <tgl@sss.pgh.pa.us>
0 siblings, 1 reply; 12+ messages in thread
From: Andrei Lepikhov @ 2026-08-21 15:06 UTC (permalink / raw)
To: Tom Lane <tgl@sss.pgh.pa.us>; +Cc: David Rowley <dgrowleyml@gmail.com>; PostgreSQL Hackers <pgsql-hackers@lists.postgresql.org>; Corey Huinker <corey.huinker@gmail.com>
On 20/08/2026 22:06, Tom Lane wrote:
> I wrote:
>> After reflection I realized that the approach I took in my first patch
>> is wrong: letting ALTER FUNCTION work on an aggregate is pretty
>> non-orthogonal, if the only property it can set is SUPPORT. The right
>> way to do this is to add a SUPPORT option to CREATE AGGREGATE, which
>> slots nicely into getting pg_dump to handle it. As attached.
>
> Grumble ... for some reason I was thinking that ProcedureCreate would
> handle checking for superuser when specifying a support function,
> but it doesn't; AggregateCreate must do that. v3 attached contains
> just that one addition.
Thanks. For aggregates that an extension defines itself, this is clearly the
right approach, and the pg_dump part is exactly what v0 was missing.
It does leave out the case I started with, though: attaching a support function
to an existing aggregate. What I want to optimise is the built-in functions like
sum(), avg(), and similar ones, because those are what users actually use. With
only CREATE OR REPLACE AGGREGATE available, an extension would have to restate
the whole definition of pg_catalog.sum(numeric), including sfunc, combinefunc,
and so on, and keep that copy updated with every major release. Even worse,
CREATE OR REPLACE in an extension script should record an extension dependency,
so pg_catalog.sum would become a member of the extension and DROP EXTENSION
would try to drop it.
ALTER AGGREGATE ... SUPPORT avoids both problems, and for this use case it does
not need anything from pg_dump. The statement is part of the extension script,
so CREATE EXTENSION replays it on restore. That is why v0 had both forms. Could
we commit your patch now and add the ALTER form as well, in v20 if it is too
late for v19?
Also, I am not sure I understand the reason for not exporting
interpret_func_support(), as v0 did, instead of repeating the lookup,
return-type, and superuser checks.
> One thing I don't quite love about this is that the CREATE AGGREGATE
> docs already refer to transfn, finalfn, etc as "support functions",
In v0, I just added a paragraph to the create_aggregate.sgml:
"Note that this is unrelated to the aggregate's transition, final and other
helper functions described above, which implement the aggregate itself; a
planner support function instead advises the planner about calls to the aggregate."
I think this should be enough.
--
regards, Andrei Lepikhov,
pgEdge
^ permalink raw reply [nested|flat] 12+ messages in thread
* Re: Allow a prosupport function to be attached to an aggregate
2026-08-17 06:13 Allow a prosupport function to be attached to an aggregate Andrei Lepikhov <lepihov@gmail.com>
2026-08-18 04:56 ` Re: Allow a prosupport function to be attached to an aggregate David Rowley <dgrowleyml@gmail.com>
2026-08-18 14:35 ` Re: Allow a prosupport function to be attached to an aggregate Tom Lane <tgl@sss.pgh.pa.us>
2026-08-20 07:23 ` Re: Allow a prosupport function to be attached to an aggregate Andrei Lepikhov <lepihov@gmail.com>
2026-08-20 19:47 ` Re: Allow a prosupport function to be attached to an aggregate Tom Lane <tgl@sss.pgh.pa.us>
2026-08-20 20:06 ` Re: Allow a prosupport function to be attached to an aggregate Tom Lane <tgl@sss.pgh.pa.us>
2026-08-21 15:06 ` Re: Allow a prosupport function to be attached to an aggregate Andrei Lepikhov <lepihov@gmail.com>
@ 2026-08-21 15:20 ` Tom Lane <tgl@sss.pgh.pa.us>
2026-08-22 20:33 ` Re: Allow a prosupport function to be attached to an aggregate Andrei Lepikhov <lepihov@gmail.com>
0 siblings, 1 reply; 12+ messages in thread
From: Tom Lane @ 2026-08-21 15:20 UTC (permalink / raw)
To: Andrei Lepikhov <lepihov@gmail.com>; +Cc: David Rowley <dgrowleyml@gmail.com>; PostgreSQL Hackers <pgsql-hackers@lists.postgresql.org>; Corey Huinker <corey.huinker@gmail.com>
Andrei Lepikhov <lepihov@gmail.com> writes:
> Thanks. For aggregates that an extension defines itself, this is clearly the
> right approach, and the pg_dump part is exactly what v0 was missing.
> It does leave out the case I started with, though: attaching a support function
> to an existing aggregate.
How so? The expectation is that you'd issue CREATE OR REPLACE
AGGREGATE. It is a bit tedious to have to re-specify all the
existing properties, but that's the way previous extensions of
aggregate options have been handled. I don't feel that this one
new feature is a big enough deal to redesign that (especially
not this late in beta).
> What I want to optimise is the built-in functions like
> sum(), avg(), and similar ones, because those are what users
> actually use.
For those, wouldn't we just modify the initial contents of pg_proc?
> With
> only CREATE OR REPLACE AGGREGATE available, an extension would have to restate
> the whole definition of pg_catalog.sum(numeric), including sfunc, combinefunc,
> and so on, and keep that copy updated with every major release.
I'm not particularly on board with this goal: I think letting
extensions modify built-in aggregates is fraught with all sorts
of issues. (To name only one, there's no way for multiple
extensions to each attach new behaviors to the same aggregate.)
I'm certainly not going to risk putting in half-considered
support for such a thing at this stage of the release cycle.
There's enough risk in adding what I proposed yesterday.
regards, tom lane
^ permalink raw reply [nested|flat] 12+ messages in thread
* Re: Allow a prosupport function to be attached to an aggregate
2026-08-17 06:13 Allow a prosupport function to be attached to an aggregate Andrei Lepikhov <lepihov@gmail.com>
2026-08-18 04:56 ` Re: Allow a prosupport function to be attached to an aggregate David Rowley <dgrowleyml@gmail.com>
2026-08-18 14:35 ` Re: Allow a prosupport function to be attached to an aggregate Tom Lane <tgl@sss.pgh.pa.us>
2026-08-20 07:23 ` Re: Allow a prosupport function to be attached to an aggregate Andrei Lepikhov <lepihov@gmail.com>
2026-08-20 19:47 ` Re: Allow a prosupport function to be attached to an aggregate Tom Lane <tgl@sss.pgh.pa.us>
2026-08-20 20:06 ` Re: Allow a prosupport function to be attached to an aggregate Tom Lane <tgl@sss.pgh.pa.us>
2026-08-21 15:06 ` Re: Allow a prosupport function to be attached to an aggregate Andrei Lepikhov <lepihov@gmail.com>
2026-08-21 15:20 ` Re: Allow a prosupport function to be attached to an aggregate Tom Lane <tgl@sss.pgh.pa.us>
@ 2026-08-22 20:33 ` Andrei Lepikhov <lepihov@gmail.com>
2026-08-23 16:55 ` Re: Allow a prosupport function to be attached to an aggregate Tom Lane <tgl@sss.pgh.pa.us>
0 siblings, 1 reply; 12+ messages in thread
From: Andrei Lepikhov @ 2026-08-22 20:33 UTC (permalink / raw)
To: Tom Lane <tgl@sss.pgh.pa.us>; +Cc: David Rowley <dgrowleyml@gmail.com>; PostgreSQL Hackers <pgsql-hackers@lists.postgresql.org>; Corey Huinker <corey.huinker@gmail.com>
On 21/08/2026 17:20, Tom Lane wrote:
> Andrei Lepikhov <lepihov@gmail.com> writes:>
>> What I want to optimise is the built-in functions like
>> sum(), avg(), and similar ones, because those are what users
>> actually use.
>
> For those, wouldn't we just modify the initial contents of pg_proc?
For the trivial ones, yes, and that is a fair point. sum(x) FILTER (WHERE true)
-> sum(x) holds unconditionally; sum(x ORDER BY x) -> sum(x) holds for the exact
types, though not for float, where the order is part of the result. They would
also make a decent worked example of an aggregate support function - AFAICS
int8inc_support is still the only in-core user of SupportRequestSimplifyAggref.
Other optimisations of built-in aggregates in my pocket are an OLAP
specialisation and would be pure overhead for other workloads. I doubt it makes
sense to put a sum(numeric(N,M)) variant into core when it only pays off in a
database whose numeric columns carry a typmod.
>> With
>> only CREATE OR REPLACE AGGREGATE available, an extension would have to restate
>> the whole definition of pg_catalog.sum(numeric), including sfunc, combinefunc,
>> and so on, and keep that copy updated with every major release.
>
> I'm not particularly on board with this goal: I think letting
> extensions modify built-in aggregates is fraught with all sorts
> of issues. (To name only one, there's no way for multiple
> extensions to each attach new behaviors to the same aggregate.)
Agreed as far as it goes, though the limitation is neither new nor specific to
aggregates: prosupport is a single regproc column, so ALTER FUNCTION ... SUPPORT
on a plain function is already last-one-wins. Whether a shared object should
accept support functions from third parties at all is a fair question, and a
larger one than this patch. So, with more evidence of practical need, we can
return to it later.
In my experience that is what applications ask for. An extension also back-ports
the optimisation to already-released majors, which is a large part of why we
write one. In the meantime we will do it by rewriting prosupport directly and
adding the pg_depend entry - the only way I know to attach such an optimisation
without touching the application.
> I'm certainly not going to risk putting in half-considered
> support for such a thing at this stage of the release cycle.
> There's enough risk in adding what I proposed yesterday.
No objection. It closes the case the thread started from and the pg_dump part is
what v0 was missing.
--
regards, Andrei Lepikhov,
pgEdge
^ permalink raw reply [nested|flat] 12+ messages in thread
* Re: Allow a prosupport function to be attached to an aggregate
2026-08-17 06:13 Allow a prosupport function to be attached to an aggregate Andrei Lepikhov <lepihov@gmail.com>
2026-08-18 04:56 ` Re: Allow a prosupport function to be attached to an aggregate David Rowley <dgrowleyml@gmail.com>
2026-08-18 14:35 ` Re: Allow a prosupport function to be attached to an aggregate Tom Lane <tgl@sss.pgh.pa.us>
2026-08-20 07:23 ` Re: Allow a prosupport function to be attached to an aggregate Andrei Lepikhov <lepihov@gmail.com>
2026-08-20 19:47 ` Re: Allow a prosupport function to be attached to an aggregate Tom Lane <tgl@sss.pgh.pa.us>
2026-08-20 20:06 ` Re: Allow a prosupport function to be attached to an aggregate Tom Lane <tgl@sss.pgh.pa.us>
2026-08-21 15:06 ` Re: Allow a prosupport function to be attached to an aggregate Andrei Lepikhov <lepihov@gmail.com>
2026-08-21 15:20 ` Re: Allow a prosupport function to be attached to an aggregate Tom Lane <tgl@sss.pgh.pa.us>
2026-08-22 20:33 ` Re: Allow a prosupport function to be attached to an aggregate Andrei Lepikhov <lepihov@gmail.com>
@ 2026-08-23 16:55 ` Tom Lane <tgl@sss.pgh.pa.us>
0 siblings, 0 replies; 12+ messages in thread
From: Tom Lane @ 2026-08-23 16:55 UTC (permalink / raw)
To: Andrei Lepikhov <lepihov@gmail.com>; +Cc: David Rowley <dgrowleyml@gmail.com>; PostgreSQL Hackers <pgsql-hackers@lists.postgresql.org>; Corey Huinker <corey.huinker@gmail.com>
Andrei Lepikhov <lepihov@gmail.com> writes:
> On 21/08/2026 17:20, Tom Lane wrote:
>> I'm certainly not going to risk putting in half-considered
>> support for such a thing at this stage of the release cycle.
>> There's enough risk in adding what I proposed yesterday.
> No objection. It closes the case the thread started from and the pg_dump part is
> what v0 was missing.
OK, pushed v3 then.
regards, tom lane
^ permalink raw reply [nested|flat] 12+ messages in thread
end of thread, other threads:[~2026-08-23 16:55 UTC | newest]
Thread overview: 12+ messages (download: mbox mbox.gz follow: Atom feed)
-- links below jump to the message on this page --
2026-08-17 06:13 Allow a prosupport function to be attached to an aggregate Andrei Lepikhov <lepihov@gmail.com>
2026-08-18 04:56 ` David Rowley <dgrowleyml@gmail.com>
2026-08-18 06:31 ` Andrei Lepikhov <lepihov@gmail.com>
2026-08-18 12:36 ` Andrei Lepikhov <lepihov@gmail.com>
2026-08-18 14:35 ` Tom Lane <tgl@sss.pgh.pa.us>
2026-08-20 07:23 ` Andrei Lepikhov <lepihov@gmail.com>
2026-08-20 19:47 ` Tom Lane <tgl@sss.pgh.pa.us>
2026-08-20 20:06 ` Tom Lane <tgl@sss.pgh.pa.us>
2026-08-21 15:06 ` Andrei Lepikhov <lepihov@gmail.com>
2026-08-21 15:20 ` Tom Lane <tgl@sss.pgh.pa.us>
2026-08-22 20:33 ` Andrei Lepikhov <lepihov@gmail.com>
2026-08-23 16:55 ` Tom Lane <tgl@sss.pgh.pa.us>
This inbox is served by DDX for PostgreSQL; see mirroring instructions
for how to clone and mirror all data and code used for this inbox