Fix crash with single-input aggregates with multiple sort keys

An aggregate's ORDER BY can list the same sort key more than once with
different sort operators, and transformDistinctClause() copies such
items into the DISTINCT list.  So an aggregate with a single input can
have several sort keys and several DISTINCT columns.

nodeAgg.c and execExpr.c mistakenly only checked the number of inputs
when deciding if a Datum sort was possible.  That check must also
consider the number of sort keys.

Fix by using the Datum sort only for a single input with a single sort
key.

Also for v16+, fix crash in pre-sorted aggregate code where the uniqslot
was only created when the number of inputs for a DISTINCT aggregate was
above 1.  The uniqslot is required when there are multiple DISTINCT
columns, and an ORDER BY clause may cause more than one of these to exist
when there's only a single input column.

Author: Ayush Tiwari <[email protected]>
Reviewed-by: David Rowley <[email protected]>
Discussion: 
https://postgr.es/m/cajtyswxmuo5qzsy_az+86mty2xdbdw_7ub3c4fjwpfacvd_...@mail.gmail.com
Backpatch-through: 14

Branch
------
REL_15_STABLE

Details
-------
https://git.postgresql.org/pg/commitdiff/21a53865fb5a199fc7f234a9f9fce5608a39e581

Modified Files
--------------
src/backend/executor/execExpr.c          | 10 ++++++----
src/backend/executor/nodeAgg.c           | 22 ++++++++++++++--------
src/test/regress/expected/aggregates.out | 17 +++++++++++++++++
src/test/regress/sql/aggregates.sql      |  9 +++++++++
4 files changed, 46 insertions(+), 12 deletions(-)

Reply via email to