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_17_STABLE

Details
-------
https://git.postgresql.org/pg/commitdiff/2a3ac15548c6318a33e954b9858284bc05e62bc8

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

Reply via email to