Skip to content

Commit 9154ede

Browse files
committed
Strip off ORDER BY/DISTINCT aggregate pathkeys in create_agg_path
1349d27 added code to adjust the PlannerInfo.group_pathkeys so that ORDER BY / DISTINCT aggregate functions could obtain pre-sorted inputs to allow faster execution. That commit forgot to adjust the pathkeys in create_agg_path(). Some code in there assumed that it was always fine to make the AggPath's pathkeys the same as its subpath's. That seems to have been ok up until 1349d27, but since that commit adds pathkeys for columns which are within the aggregate function, those columns won't be available above the aggregate node. This can result in "could not find pathkey item to sort" during create_plan(). The fix here is to strip off the additional pathkeys added by adjust_group_pathkeys_for_groupagg(). It seems that the pathkeys here will only ever be group_pathkeys, so all we need to do is check if the length of the pathkey list is longer than the num_groupby_pathkeys and get rid of the additional ones only if we see extras. Reported-by: Justin Pryzby Reviewed-by: Richard Guo Discussion: https://postgr.es/m/ZQhYYRhUxpW3PSf9%40telsasoft.com Backpatch-through: 16, where 1349d27 was introduced
1 parent 3ed98ed commit 9154ede

File tree

1 file changed

+17
-1
lines changed

1 file changed

+17
-1
lines changed

src/backend/optimizer/util/pathnode.c

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3127,10 +3127,26 @@ create_agg_path(PlannerInfo *root,
31273127
pathnode->path.parallel_safe = rel->consider_parallel &&
31283128
subpath->parallel_safe;
31293129
pathnode->path.parallel_workers = subpath->parallel_workers;
3130+
31303131
if (aggstrategy == AGG_SORTED)
3131-
pathnode->path.pathkeys = subpath->pathkeys; /* preserves order */
3132+
{
3133+
/*
3134+
* Attempt to preserve the order of the subpath. Additional pathkeys
3135+
* may have been added in adjust_group_pathkeys_for_groupagg() to
3136+
* support ORDER BY / DISTINCT aggregates. Pathkeys added there
3137+
* belong to columns within the aggregate function, so we must strip
3138+
* these additional pathkeys off as those columns are unavailable
3139+
* above the aggregate node.
3140+
*/
3141+
if (list_length(subpath->pathkeys) > root->num_groupby_pathkeys)
3142+
pathnode->path.pathkeys = list_copy_head(subpath->pathkeys,
3143+
root->num_groupby_pathkeys);
3144+
else
3145+
pathnode->path.pathkeys = subpath->pathkeys; /* preserves order */
3146+
}
31323147
else
31333148
pathnode->path.pathkeys = NIL; /* output is unordered */
3149+
31343150
pathnode->subpath = subpath;
31353151

31363152
pathnode->aggstrategy = aggstrategy;

0 commit comments

Comments
 (0)