forked from apache/cloudberry
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcdbgroupingpaths.c
More file actions
2809 lines (2509 loc) · 82.6 KB
/
cdbgroupingpaths.c
File metadata and controls
2809 lines (2509 loc) · 82.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*-------------------------------------------------------------------------
*
* cdbgroupingpaths.c
* Routines to aid in planning grouping queries for parallel
* execution. This is, essentially, an extension of the file
* optimizer/plan/planner.c, although some functions are not
* externalized.
*
*
* The general shape of the generated plan is similar to the parallel
* aggregation plans in upstream:
*
* Finalize Aggregate [3]
* Motion [2]
* Partial Aggregate [1]
*
* but there are many different variants of this basic shape:
*
* [1] The Partial stage can be sorted or hashed. Furthermore,
* the sorted Agg can be construct from sorting the cheapest input Path,
* or from pre-sorted Paths.
*
* [2] The partial results need to be gathered for the second stage.
* For plain aggregation, with no GROUP BY, the results need to be
* gathered to a single node. With GROUP BY, they can be redistributed
* according to the GROUP BY columns.
*
* [3] Like the first tage, the second stage can likewise be sorted or hashed.
*
*
* Things get more complicated if any of the aggregates have DISTINCT
* arguments, also known as DQAs or Distinct-Qualified Aggregates. If there
* is only one DQA, and the input path happens to be collocated with the
* DISTINCT argument, then we can proceed with a two-stage path like above.
* But otherwise, three stages and possibly TupleSplit node is needed. See
* add_single_dqa_hash_agg_path() and add_multi_dqas_hash_agg_path() for
* details.
*
* Portions Copyright (c) 2019-Present VMware, Inc. or its affiliates.
*
* IDENTIFICATION
* src/backend/cdb/cdbgroupingpaths.c
*
*-------------------------------------------------------------------------
*/
#include "postgres.h"
#include "access/htup_details.h"
#include "catalog/pg_type.h"
#include "cdb/cdbgroup.h"
#include "cdb/cdbgroupingpaths.h"
#include "cdb/cdbhash.h"
#include "cdb/cdbpath.h"
#include "cdb/cdbpathlocus.h"
#include "cdb/cdbutil.h"
#include "cdb/cdbvars.h"
#include "foreign/fdwapi.h"
#include "nodes/makefuncs.h"
#include "nodes/nodeFuncs.h"
#include "optimizer/clauses.h"
#include "optimizer/cost.h"
#include "optimizer/optimizer.h"
#include "optimizer/pathnode.h"
#include "optimizer/paths.h"
#include "optimizer/prep.h"
#include "optimizer/tlist.h"
#include "parser/parse_clause.h"
#include "parser/parse_oper.h"
#include "utils/guc.h"
#include "utils/lsyscache.h"
#include "utils/selfuncs.h"
typedef enum
{
INVALID_DQA = -1,
SINGLE_DQA, /* only one unique DQA expr */
MULTI_DQAS, /* multiple DQA exprs */
SINGLE_DQA_WITHAGG, /* only one unique DQA expr with agg */
MULTI_DQAS_WITHAGG/* mixed DQA and normal aggregate */
} DQAType;
/*
* For convenience, we collect various inputs and intermediate planning results
* in this struct, instead of passing a dozen arguments to all subroutines.
*/
typedef struct
{
/* From the Query */
bool hasAggs;
List *groupClause; /* a list of SortGroupClause's */
List *groupingSets; /* a list of GroupingSet's if present */
List *group_tles;
/* Inputs from the caller */
List *havingQual; /* qualifications applied to groups */
PathTarget *target; /* targetlist of final aggregated result */
bool can_sort;
bool can_hash;
double dNumGroupsTotal; /* total number of groups in the result, across all QEs */
const AggClauseCosts *agg_costs;
const AggClauseCosts *agg_partial_costs;
const AggClauseCosts *agg_final_costs;
List *rollups;
List *new_rollups;
AggStrategy strat;
PathTarget *partial_grouping_target; /* targetlist of partially aggregated result */
List *final_groupClause; /* SortGroupClause for final grouping */
List *final_group_tles;
Index gsetid_sortref;
/*
* Pathkeys representing GROUP BY.
*
* 'partial_needed_pathkeys' represents a sort order that's needed for
* doing a sorted GroupAggregate in the first
* stage. 'partial_sort_pathkey' is normally the same, but in case of
* DISTINCT ON and ORDER BY it can include extra columns that are presentt
* in the ORDER BY but not in DISTINCT ON. The idea is the needed_pathkeys
* are sufficient to perform the grouping, but if we have to sort the
* input, we sort using sort_pathkeys. By including the extra columns in
* the Sort we can avoid sorting the data again later to satisfy the ORDER
* BY.
*
* 'final_needed_pathkeys' is the sort order needed to perform the 2nd
* stage by sorted GroupAggregate. In normal GROUP BY it is the same as
* 'partial_needed_pathkeys', but if there are GROUPING SETS,
* 'final_needed_pathkeys' includes the internal GROUPINGSET_ID()
* expression, used to distinguish the rolled up rows. And
* 'final_sort_pathkeys' is the same, but might include extra ORDER BY
* columns.
*
*/
List *partial_needed_pathkeys;
List *partial_sort_pathkeys;
List *final_needed_pathkeys;
List *final_sort_pathkeys;
DQAType type;
/*
* partial_rel holds the partially aggregated results from the first stage.
*/
RelOptInfo *partial_rel;
/* is a DISTINCT?*/
bool is_distinct;
} cdb_agg_planning_context;
typedef struct
{
DQAType type;
PathTarget *final_target; /* finalize agg tlist */
PathTarget *partial_target; /* partial agg tlist */
PathTarget *tup_split_target; /* AggExprId + subpath_proj_target */
PathTarget *input_proj_target; /* input tuple tlist + DQA expr */
List *dqa_group_clause; /* DQA exprs + group by clause for remove duplication */
List *dqa_expr_lst; /* DQAExpr list */
double dNumDistinctGroups; /* # of distinct combinations of GROUP BY and DISTINCT exprs */
} cdb_multi_dqas_info;
static void create_two_stage_paths(PlannerInfo *root, cdb_agg_planning_context *ctx,
RelOptInfo *input_rel, RelOptInfo *output_rel, List *partial_pathlist);
static List *get_all_rollup_groupclauses(List *rollups);
static Index add_gsetid_tlist(List *tlist);
static SortGroupClause *create_gsetid_groupclause(Index groupref);
static List *strip_gsetid_from_pathkeys(Index gsetid_sortref, List *pathkeys);
static void add_first_stage_group_agg_path(PlannerInfo *root,
Path *path,
bool is_sorted,
cdb_agg_planning_context *ctx);
static void add_first_stage_hash_agg_path(PlannerInfo *root,
Path *path,
cdb_agg_planning_context *ctx);
static void add_second_stage_group_agg_path(PlannerInfo *root,
Path *path,
bool is_sorted,
cdb_agg_planning_context *ctx,
RelOptInfo *output_rel,
bool is_partial);
static void add_second_stage_hash_agg_path(PlannerInfo *root,
Path *path,
cdb_agg_planning_context *ctx,
RelOptInfo *output_rel,
bool is_partial);
static void add_single_dqa_hash_agg_path(PlannerInfo *root,
Path *path,
cdb_agg_planning_context *ctx,
RelOptInfo *output_rel,
PathTarget *input_target,
List *dqa_group_clause,
double dNumDistinctGroups);
static void add_single_mixed_dqa_hash_agg_path(PlannerInfo *root,
Path *path,
cdb_agg_planning_context *ctx,
RelOptInfo *output_rel,
PathTarget *input_target,
List *dqa_group_clause);
static void
add_multi_dqas_hash_agg_path(PlannerInfo *root,
Path *path,
cdb_agg_planning_context *ctx,
RelOptInfo *output_rel,
cdb_multi_dqas_info *info);
static void
fetch_single_dqa_info(PlannerInfo *root,
Path *path,
cdb_agg_planning_context *ctx,
cdb_multi_dqas_info *info);
static void
fetch_multi_dqas_info(PlannerInfo *root,
Path *path,
cdb_agg_planning_context *ctx,
cdb_multi_dqas_info *info);
static DQAType
recognize_dqa_type(cdb_agg_planning_context *ctx);
static PathTarget *
strip_aggdistinct(PathTarget *target);
static void add_first_stage_group_agg_partial_path(PlannerInfo *root,
Path *path,
bool is_sorted,
cdb_agg_planning_context *ctx);
/*
* cdb_create_multistage_grouping_paths
*
* This is basically an extension of the function create_grouping_paths() from
* planner.c. It creates two- and three-stage Paths to implement aggregates
* and/or GROUP BY.
*
* The caller already constructed Paths for one-stage plans, we are only
* concerned about more complicated multi-stage plans here.
*/
void
cdb_create_multistage_grouping_paths(PlannerInfo *root,
RelOptInfo *input_rel,
RelOptInfo *output_rel,
PathTarget *target,
PathTarget *partial_grouping_target,
List *havingQual,
double dNumGroupsTotal,
const AggClauseCosts *agg_costs,
const AggClauseCosts *agg_partial_costs,
const AggClauseCosts *agg_final_costs,
List *rollups,
List *new_rollups,
AggStrategy strat,
List *partial_pathlist)
{
Query *parse = root->parse;
Path *cheapest_path = input_rel->cheapest_total_path;
bool has_ordered_aggs = root->numPureOrderedAggs > 0;
cdb_agg_planning_context ctx;
bool can_sort;
bool can_hash;
/* The caller should've checked these already */
Assert(parse->hasAggs || parse->groupClause);
/*
* This prohibition could be relaxed if we tracked missing combine
* functions per DQA and were willing to plan some DQAs as single and
* some as multiple phases. Not currently, however.
*/
Assert(!root->hasNonCombine && !root->hasNonSerialAggs);
Assert(root->config->gp_enable_multiphase_agg);
/*
* Ordered aggregates need to run the transition function on the
* values in sorted order, which in turn translates into single phase
* aggregation.
*/
if (has_ordered_aggs)
return;
/*
* We are currently unwilling to redistribute a gathered intermediate
* across the cluster. This might change one day.
*/
if (!CdbPathLocus_IsPartitioned(cheapest_path->locus))
return;
/*
* Is the input hashable / sortable? This is largely the same logic as in
* upstream create_grouping_paths(), but we can do hashing in limited ways
* even if there are DISTINCT aggs or grouping sets.
*/
can_sort = grouping_is_sortable(parse->groupClause);
can_hash = (parse->groupClause != NIL &&
root->numPureOrderedAggs == 0 &&
grouping_is_hashable(parse->groupClause));
/*
* Prepare a struct to hold the arguments and intermediate results
* across subroutines.
*/
memset(&ctx, 0, sizeof(ctx));
ctx.is_distinct = false;
ctx.can_sort = can_sort;
ctx.can_hash = can_hash;
ctx.target = target;
ctx.dNumGroupsTotal = dNumGroupsTotal;
ctx.agg_costs = agg_costs;
ctx.agg_partial_costs = agg_partial_costs;
ctx.agg_final_costs = agg_final_costs;
ctx.rollups = rollups;
ctx.new_rollups = new_rollups;
ctx.strat = strat;
ctx.hasAggs = parse->hasAggs;
ctx.groupClause = parse->groupClause;
ctx.groupingSets = parse->groupingSets;
ctx.havingQual = havingQual;
ctx.partial_rel = fetch_upper_rel(root, UPPERREL_CDB_FIRST_STAGE_GROUP_AGG, NULL);
ctx.partial_rel->fdwroutine = input_rel->fdwroutine;
ctx.partial_rel->serverid = input_rel->serverid;
ctx.partial_rel->segSeverids = input_rel->segSeverids;
ctx.partial_rel->userid = input_rel->userid;
ctx.partial_rel->exec_location = input_rel->exec_location;
ctx.partial_rel->num_segments = input_rel->num_segments;
/* create a partial rel similar to make_grouping_rel() */
if (IS_OTHER_REL(input_rel))
{
ctx.partial_rel = fetch_upper_rel(root, UPPERREL_CDB_FIRST_STAGE_GROUP_AGG,
input_rel->relids);
ctx.partial_rel->reloptkind = RELOPT_OTHER_UPPER_REL;
}
else
{
ctx.partial_rel = fetch_upper_rel(root, UPPERREL_CDB_FIRST_STAGE_GROUP_AGG,
NULL);
}
ctx.partial_needed_pathkeys = root->group_pathkeys;
ctx.partial_sort_pathkeys = root->group_pathkeys;
/*
* CBDB parallel: Set consider_parallel for costs comparison.
* Else 2-stage agg with lower costs may lose to 1-stage agg.
*/
ctx.partial_rel->consider_parallel = output_rel->consider_parallel;
ctx.group_tles = get_common_group_tles(target,
parse->groupClause,
ctx.rollups);
/*
* For twostage grouping sets, we perform grouping sets aggregation in
* partial stage and normal aggregation in final stage.
*
* With this method, there is a problem, i.e., in the final stage of
* aggregation, we don't have a way to distinguish which tuple comes from
* which grouping set, which is needed for merging the partial results.
*
* For instance, suppose we have a table t(c1, c2, c3) containing one row
* (1, NULL, 3), and we are selecting agg(c3) group by grouping sets
* ((c1,c2), (c1)). Then there would be two tuples as partial results for
* that row, both are (1, NULL, agg(3)), one is from group by (c1,c2) and
* one is from group by (c1). If we cannot tell that the two tuples are
* from two different grouping sets, we will merge them incorrectly.
*
* So we add a hidden column 'GROUPINGSET_ID', representing grouping set
* id, to the targetlist of Partial Aggregate node, as well as to the sort
* keys and group keys for Finalize Aggregate node. So only tuples coming
* from the same grouping set can get merged in the final stage of
* aggregation. Note that we need to keep 'GROUPINGSET_ID' at the head of
* sort keys in final stage to ensure correctness.
*
* Below is a plan to illustrate this idea:
*
* # explain (costs off, verbose)
* select c1, c2, c3, avg(c3) from gstest group by grouping sets((c1,c2),(c1),(c2,c3));
* QUERY PLAN
* ---------------------------------------------------------------------------
* Finalize GroupAggregate
* Output: c1, c2, c3, avg(c3)
* Group Key: (GROUPINGSET_ID()), gstest.c1, gstest.c2, gstest.c3
* -> Sort
* Output: c1, c2, c3, (PARTIAL avg(c3)), (GROUPINGSET_ID())
* Sort Key: (GROUPINGSET_ID()), gstest.c1, gstest.c2, gstest.c3
* -> Gather Motion 3:1 (slice1; segments: 3)
* Output: c1, c2, c3, (PARTIAL avg(c3)), (GROUPINGSET_ID())
* -> Partial GroupAggregate
* Output: c1, c2, c3, PARTIAL avg(c3), GROUPINGSET_ID()
* Group Key: gstest.c1, gstest.c2
* Group Key: gstest.c1
* Sort Key: gstest.c2, gstest.c3
* Group Key: gstest.c2, gstest.c3
* -> Sort
* Output: c1, c2, c3
* Sort Key: gstest.c1, gstest.c2
* -> Seq Scan on public.gstest
* Output: c1, c2, c3
* Optimizer: Postgres query optimizer
* (20 rows)
*
* Here, we prepare a target list and a corresponding list of SortGroupClauses
* for the result of the Partial Aggregate stage.
*/
if (parse->groupingSets)
{
GroupingSetId *gsetid;
List *grouping_sets_tlist;
SortGroupClause *gsetcl;
List *gcls;
List *tlist;
gsetid = makeNode(GroupingSetId);
grouping_sets_tlist = copyObject(root->processed_tlist);
ctx.gsetid_sortref = add_gsetid_tlist(grouping_sets_tlist);
gsetcl = create_gsetid_groupclause(ctx.gsetid_sortref);
ctx.final_groupClause = lappend(copyObject(parse->groupClause), gsetcl);
ctx.partial_grouping_target = copyObject(partial_grouping_target);
if (!list_member(ctx.partial_grouping_target->exprs, gsetid))
add_column_to_pathtarget(ctx.partial_grouping_target,
(Expr *) gsetid, ctx.gsetid_sortref);
gcls = get_all_rollup_groupclauses(rollups);
gcls = lappend(gcls, gsetcl);
tlist = make_tlist_from_pathtarget(ctx.partial_grouping_target);
/*
* The input to the final stage will be sorted by this. It includes the
* GROUPINGSET_ID() column.
*/
ctx.final_needed_pathkeys = make_pathkeys_for_sortclauses(root, gcls, tlist);
}
else
{
ctx.partial_grouping_target = partial_grouping_target;
ctx.final_groupClause = parse->groupClause;
ctx.final_needed_pathkeys = root->group_pathkeys;
ctx.gsetid_sortref = 0;
}
ctx.final_sort_pathkeys = ctx.final_needed_pathkeys;
ctx.final_group_tles = get_common_group_tles(ctx.partial_grouping_target,
ctx.final_groupClause,
NIL);
ctx.partial_rel->reltarget = ctx.partial_grouping_target;
/*
* All set, generate the two-stage paths.
*/
create_two_stage_paths(root, &ctx, input_rel, output_rel, partial_pathlist);
/*
* Aggregates with DISTINCT arguments are more complicated, and are not
* handled by create_two_stage_paths() (except for the case of a single
* DQA that happens to be collocated with the input, see
* add_first_stage_group_agg_path()). Consider ways to implement them,
* too.
*/
if ((can_hash || parse->groupClause == NIL) &&
!parse->groupingSets &&
list_length(agg_costs->distinctAggrefs) > 0)
{
/*
* Try possible plans for DISTINCT-qualified aggregate.
*/
cdb_multi_dqas_info info = {};
DQAType type = recognize_dqa_type(&ctx);
switch (type)
{
case SINGLE_DQA:
{
fetch_single_dqa_info(root, cheapest_path, &ctx, &info);
add_single_dqa_hash_agg_path(root,
cheapest_path,
&ctx,
output_rel,
info.input_proj_target,
info.dqa_group_clause,
info.dNumDistinctGroups);
}
break;
case SINGLE_DQA_WITHAGG:
{
fetch_single_dqa_info(root, cheapest_path, &ctx, &info);
add_single_mixed_dqa_hash_agg_path(root,
cheapest_path,
&ctx,
output_rel,
info.input_proj_target,
info.dqa_group_clause);
}
break;
case MULTI_DQAS:
{
fetch_multi_dqas_info(root, cheapest_path, &ctx, &info);
/*
* GPDB_14_MERGE_FIXME: We have done some copy job in
* make_partial_grouping_target, so that the agg references
* in plan is actually different from
* agg_partial_costs->distinctAggrefs. And it has to be
* different since we need to compute and set agg_expr_id for
* tuple split cases.
* However, we need to push multi dqa's filter to tuplesplit
* to get the correct result. And thus we need to remove the
* filter in aggref referenced by the plan.
*
* It's not that trivial to fix it perfectly. By manually
* removing the origin plan's aggfilter can work around
* this problem. We'll look at it again later.
*/
ListCell *lc;
foreach(lc, root->agginfos)
{
AggInfo *agginfo = (AggInfo *) lfirst(lc);
Aggref *aggref = agginfo->representative_aggref;
if (aggref->aggdistinct != NIL)
aggref->aggfilter = NULL;
}
add_multi_dqas_hash_agg_path(root,
cheapest_path,
&ctx,
output_rel,
&info);
}
break;
case MULTI_DQAS_WITHAGG:
break;
default:
break;
}
}
}
/*
* cdb_create_twostage_distinct_paths
*
* Alternative entry point for DISTINCT planning.
*
* This is basically an extension of the function create_distinct_paths() in
* planner.c. It creates two-stage Aggregate Paths to implement DISTINCT.
* The caller already constructed a Paths for one-stage plans.
*
* 'input_rel' is usually the result of query_planner(), but it can also be
* the result of windowing and/or GROUP BY planning, if the query contains
* both DISTINCT and GROUP BY/windowing.
*/
void
cdb_create_twostage_distinct_paths(PlannerInfo *root,
RelOptInfo *input_rel,
RelOptInfo *output_rel,
PathTarget *target,
double dNumGroupsTotal)
{
Query *parse = root->parse;
Path *cheapest_path = input_rel->cheapest_total_path;
AggClauseCosts zero_agg_costs;
cdb_agg_planning_context ctx;
bool allow_sort;
bool allow_hash;
/*
* We are currently unwilling to redistribute a gathered intermediate
* across the cluster. This might change one day.
*/
if (!CdbPathLocus_IsPartitioned(cheapest_path->locus))
return;
/*
* Is the input hashable / sortable?
*/
allow_sort = grouping_is_sortable(parse->distinctClause);
if (parse->hasDistinctOn || !enable_hashagg)
allow_hash = false; /* policy-based decision not to hash */
else if (!grouping_is_hashable(parse->distinctClause))
allow_hash = false;
else
allow_hash = true;
/* Set up a dummy AggClauseCosts struct. There are no aggregates. */
memset(&zero_agg_costs, 0, sizeof(zero_agg_costs));
memset(&ctx, 0, sizeof(ctx));
ctx.is_distinct = true;
ctx.can_sort = allow_sort;
ctx.can_hash = allow_hash;
ctx.target = target;
ctx.partial_grouping_target = target;
ctx.dNumGroupsTotal = dNumGroupsTotal;
ctx.agg_costs = &zero_agg_costs;
ctx.agg_partial_costs = &zero_agg_costs;
ctx.agg_final_costs = &zero_agg_costs;
ctx.rollups = NIL;
ctx.partial_rel = fetch_upper_rel(root, UPPERREL_CDB_FIRST_STAGE_DISTINCT, NULL);
/*
* CBDB parallel: Set consider_parallel for costs comparison.
* Else 2-stage agg with lower costs may lose to 1-stage agg.
*/
ctx.partial_rel->consider_parallel = output_rel->consider_parallel;
/*
* Set up these fields to look like a query with a GROUP BY on all the
* DISTINCT columns. No HAVING or aggregates; the DISTINCT processing happens
* logically after grouping and aggregation, so those have already been
* handled in the grouping stage.
*/
ctx.hasAggs = false;
ctx.groupingSets = NIL;
ctx.havingQual = NULL;
ctx.groupClause = parse->distinctClause;
ctx.group_tles = get_common_group_tles(target, parse->distinctClause, NIL);
ctx.final_groupClause = ctx.groupClause;
ctx.final_group_tles = ctx.group_tles;
ctx.gsetid_sortref = 0;
if (ctx.can_sort)
{
/*
* First, if we have any adequately-presorted paths, just stick a
* Unique node on those. Then consider doing an explicit sort of the
* cheapest input path and Unique'ing that.
*
* When we have DISTINCT ON, we must sort by the more rigorous of
* DISTINCT and ORDER BY, else it won't have the desired behavior.
* Also, if we do have to do an explicit sort, we might as well use
* the more rigorous ordering to avoid a second sort later. (Note
* that the parser will have ensured that one clause is a prefix of
* the other.)
*/
if (parse->hasDistinctOn &&
list_length(root->distinct_pathkeys) <
list_length(root->sort_pathkeys))
ctx.partial_needed_pathkeys = root->sort_pathkeys;
else
ctx.partial_needed_pathkeys = root->distinct_pathkeys;
/* For explicit-sort case, always use the more rigorous clause */
if (list_length(root->distinct_pathkeys) <
list_length(root->sort_pathkeys))
{
ctx.partial_sort_pathkeys = root->sort_pathkeys;
/* Assert checks that parser didn't mess up... */
Assert(pathkeys_contained_in(root->distinct_pathkeys,
ctx.partial_sort_pathkeys));
}
else
ctx.partial_sort_pathkeys = root->distinct_pathkeys;
ctx.final_needed_pathkeys = ctx.partial_needed_pathkeys;
ctx.final_sort_pathkeys = ctx.partial_sort_pathkeys;
}
/*
* All set, generate the two-stage paths.
*/
create_two_stage_paths(root, &ctx, input_rel, output_rel, input_rel->partial_pathlist);
}
/*
* Guts of GROUP BY and DISTINCT planning.
*/
static void
create_two_stage_paths(PlannerInfo *root, cdb_agg_planning_context *ctx,
RelOptInfo *input_rel, RelOptInfo *output_rel, List *partial_pathlist)
{
Path *cheapest_path = input_rel->cheapest_total_path;
Path *cheapest_partial_path = partial_pathlist ? (Path *) linitial(partial_pathlist) : NULL;
/*
* Consider ways to do the first Aggregate stage.
*
* The first stage's output is Partially Aggregated. The paths are
* collected to the ctx->partial_rel, by calling add_path().
* These partially aggregated paths are considered
* more like MPP paths in Greenplum in general.
*
* First consider sorted Aggregate paths.
*/
if (ctx->can_sort)
{
ListCell *lc;
foreach(lc, input_rel->pathlist)
{
Path *path = (Path *) lfirst(lc);
bool is_sorted;
/*
* If the input is neatly distributed along the GROUP BY columns,
* there's no point in a two-stage plan. The code in planner.c
* already created the straightforward one-stage plan.
*/
if (cdbpathlocus_collocates_tlist(root, path->locus, ctx->group_tles))
continue;
/*
* Consider input paths that are already sorted, and the one with
* the lowest total cost.
*/
is_sorted = pathkeys_contained_in(ctx->partial_needed_pathkeys,
path->pathkeys);
if (path == cheapest_path || is_sorted)
add_first_stage_group_agg_path(root, path, is_sorted, ctx);
}
if (ctx->is_distinct && partial_pathlist)
{
foreach(lc, partial_pathlist)
{
Path *path = (Path *) lfirst(lc);
bool is_sorted;
if (cdbpathlocus_collocates_tlist(root, path->locus, ctx->group_tles))
continue;
is_sorted = pathkeys_contained_in(ctx->partial_needed_pathkeys,
path->pathkeys);
if (path == cheapest_partial_path|| is_sorted)
add_first_stage_group_agg_partial_path(root, path, is_sorted, ctx);
}
}
}
/*
* Consider Hash Aggregate over the cheapest input path.
*
* Hashing is not possible with DQAs.
*/
if (ctx->can_hash &&
list_length(ctx->agg_costs->distinctAggrefs) == 0)
{
/*
* If the input is neatly distributed along the GROUP BY columns,
* there's no point in a two-stage plan. The code in planner.c already
* created the straightforward one-stage plan.
*/
if (!cdbpathlocus_collocates_tlist(root, cheapest_path->locus, ctx->group_tles))
add_first_stage_hash_agg_path(root, cheapest_path, ctx);
}
if (partial_pathlist)
{
ListCell *lc;
foreach (lc, partial_pathlist)
{
Path *path = (Path *)lfirst(lc);
if (cdbpathlocus_collocates_tlist(root, path->locus, ctx->group_tles))
continue;
if (ctx->is_distinct && ctx->can_hash)
{
double dNumGroups = estimate_num_groups_on_segment(ctx->dNumGroupsTotal,
path->rows,
path->locus);
path = (Path *) create_agg_path(root,
ctx->partial_rel,
path,
ctx->partial_grouping_target,
AGG_HASHED,
ctx->hasAggs ? AGGSPLIT_INITIAL_SERIAL : AGGSPLIT_SIMPLE,
parallel_query_use_streaming_hashagg, /* streaming */
ctx->groupClause,
NIL,
ctx->agg_partial_costs,
dNumGroups);
}
add_partial_path(ctx->partial_rel, path);
}
}
if (ctx->partial_rel->fdwroutine &&
ctx->partial_rel->fdwroutine->GetForeignUpperPaths &&
ctx->partial_rel->segSeverids)
{
GroupPathExtraData extra;
FdwRoutine *fdwroutine = ctx->partial_rel->fdwroutine;
ListCell *lc;
extra.patype = PARTITIONWISE_AGGREGATE_NONE;
extra.havingQual = NULL;
foreach(lc, ctx->partial_rel->reltarget->exprs)
{
Expr *expr;
expr = lfirst(lc);
if (IsA(expr, Aggref))
((Aggref*)expr)->aggsplit = AGGSPLIT_SIMPLE;
}
fdwroutine->GetForeignUpperPaths(root, UPPERREL_GROUP_AGG, input_rel,
ctx->partial_rel, &extra);
}
/*
* We now have partially aggregated paths in ctx->partial_rel. Consider
* different ways of performing the Finalize Aggregate stage.
*/
if (ctx->partial_rel->pathlist)
{
Path *cheapest_first_stage_path;
set_cheapest(ctx->partial_rel);
cheapest_first_stage_path = ctx->partial_rel->cheapest_total_path;
if (!IsA(cheapest_first_stage_path, ForeignPath))
{
ListCell *lc;
foreach(lc, ctx->partial_rel->reltarget->exprs)
{
Expr *expr;
expr = lfirst(lc);
if (IsA(expr, Aggref))
((Aggref*)expr)->aggsplit = AGGSPLIT_INITIAL_SERIAL;
}
}
if (ctx->can_sort)
{
ListCell *lc;
foreach(lc, ctx->partial_rel->pathlist)
{
Path *path = (Path *) lfirst(lc);
bool is_sorted;
/*
* In two-stage GROUPING SETS paths, the second stage's grouping
* will include GROUPINGSET_ID(), which is not included in
* root->pathkeys. The first stage's sort order does not include
* that, so we know it's not sorted.
*/
if (!root->parse->groupingSets)
is_sorted = pathkeys_contained_in(ctx->final_needed_pathkeys,
path->pathkeys);
else
is_sorted = false;
if (path == cheapest_first_stage_path || is_sorted)
{
add_second_stage_group_agg_path(root, path, is_sorted,
ctx, output_rel, false);
}
}
}
if (ctx->can_hash && list_length(ctx->agg_costs->distinctAggrefs) == 0)
{
add_second_stage_hash_agg_path(root, cheapest_first_stage_path,
ctx, output_rel, false);
}
}
/*
* Same like above, but for partial paths in partital_rel,
* that's parallel agg with multiple workers.
*/
if (ctx->partial_rel->partial_pathlist)
{
Path *cheapest_first_stage_path;
cheapest_first_stage_path = linitial(ctx->partial_rel->partial_pathlist);
if (ctx->can_sort)
{
ListCell *lc;
foreach(lc, ctx->partial_rel->partial_pathlist)
{
Path *path = (Path *) lfirst(lc);
bool is_sorted;
/*
* In two-stage GROUPING SETS paths, the second stage's grouping
* will include GROUPINGSET_ID(), which is not included in
* root->pathkeys. The first stage's sort order does not include
* that, so we know it's not sorted.
*/
if (!root->parse->groupingSets)
is_sorted = pathkeys_contained_in(ctx->final_needed_pathkeys,
path->pathkeys);
else
is_sorted = false;
if (path == cheapest_first_stage_path || is_sorted)
{
add_second_stage_group_agg_path(root, path, is_sorted,
ctx, output_rel, true);
}
}
}
if (ctx->can_hash && list_length(ctx->agg_costs->distinctAggrefs) == 0)
{
add_second_stage_hash_agg_path(root, cheapest_first_stage_path,
ctx, output_rel, true);
}
}
}
/*
* Add a TargetEntry node of type GroupingSetId to the tlist.
* Return its ressortgroupref.
*/
static Index
add_gsetid_tlist(List *tlist)
{
TargetEntry *tle;
GroupingSetId *gsetid;
ListCell *lc;
foreach(lc, tlist)
{
tle = lfirst_node(TargetEntry, lc);
if (IsA(tle->expr, GroupingSetId))
elog(ERROR, "GROUPINGSET_ID already exists in tlist");
}
gsetid = makeNode(GroupingSetId);
tle = makeTargetEntry((Expr *)gsetid, list_length(tlist) + 1,
"GROUPINGSET_ID", true);
assignSortGroupRef(tle, tlist);
tlist = lappend(tlist, tle);
return tle->ressortgroupref;
}
/*
* Add a SortGroupClause node to the groupClause representing the GroupingSetId.
* Note we insert the new node to the head of groupClause.
*/
static SortGroupClause *
create_gsetid_groupclause(Index groupref)
{
SortGroupClause *gc;
Oid sortop;
Oid eqop;
bool hashable;
get_sort_group_operators(INT4OID,
false, true, false,
&sortop, &eqop, NULL,
&hashable);
gc = makeNode(SortGroupClause);
gc->tleSortGroupRef = groupref;
gc->eqop = eqop;
gc->sortop = sortop;
gc->nulls_first = false;
gc->hashable = hashable;
return gc;
}
static List *
strip_gsetid_from_pathkeys(Index gsetid_sortref, List *pathkeys)
{
ListCell *lc;
List *new_pathkeys;
if (gsetid_sortref == 0)
return pathkeys;
new_pathkeys = NIL;
foreach(lc, pathkeys)
{
PathKey *pathkey = lfirst(lc);
EquivalenceClass *eclass = pathkey->pk_eclass;
if (eclass->ec_sortref == gsetid_sortref)
{
/*
* The GROUPINGSETID_EXPR() should be the last pathkey. But just in
* case it's not, any columns after it won't be in right order i
* we remove it from the middle.
*/
break;
}
new_pathkeys = lappend(new_pathkeys, pathkey);
}
return new_pathkeys;