Fix accidental ignoring of subsequent keys in Sort nodes

91e9e89dc (v15) changed nodeSort.c to allow the slightly more efficient
Datum sort method to be used when the Sort node was only outputting a
single column.  That commit mistakenly failed to consider additional
sort keys.

This wasn't trivial to hit as adding more sort keys on another column
would add a resjunk target entry, so Datum sort wouldn't be used.  Hitting
this required all sort keys to be on the only output column, and then you
might think that subsequent sort keys *could* be ignored in that case, but
the collation for subsequent keys might differ from the first, and if the
first sort key had a nondeterministic collation, ignoring subsequent keys
isn't correct.

Ordinary ORDER BY queries were not affected by this as repeating the same
column in the ORDER BY clause with different collations would lead to
additional redundant target entries and would have failed the one-column
requirement to enable the Datum sort optimization.  The only known case
where problems could occur was sorting for the presorted aggregate
optimization added in 1349d2790 (v16).

A query such as the following would trigger this issue if the "x" column
was defined with a nondeterministic collation as the presorted input
would arrive at the aggregate only presorted by 'x' (using its
nondeterministic collation), rather than 'x, x COLLATE "C"':

SELECT count(DISTINCT x COLLATE "C") FROM t GROUP BY x;

This could lead to COUNT(DISTINCT) returning a count higher than the actual
number of distinct values according to the "C" collation.

Fix this by only using the Datum sort optimization when there's 1 output
column and 1 sort key, rather than just checking for 1 output column.

Reported-by: Nidal FAKIH <[email protected]>
Author: David Rowley <[email protected]>
Discussion: 
https://postgr.es/m/[email protected]
Backpatch-through: 15

Branch
------
REL_15_STABLE

Details
-------
https://git.postgresql.org/pg/commitdiff/6e860511622a8f6894ae9294280b584cd98e3fdb

Modified Files
--------------
src/backend/executor/nodeSort.c | 11 ++++++++---
1 file changed, 8 insertions(+), 3 deletions(-)

Reply via email to