-
Notifications
You must be signed in to change notification settings - Fork 6.5k
/
Planner.cpp
1705 lines (1451 loc) · 72.9 KB
/
Planner.cpp
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
#include <Planner/Planner.h>
#include <Core/ProtocolDefines.h>
#include <Common/logger_useful.h>
#include <Common/ProfileEvents.h>
#include <Columns/ColumnSet.h>
#include <DataTypes/DataTypeString.h>
#include <Functions/FunctionFactory.h>
#include <Functions/CastOverloadResolver.h>
#include <Functions/indexHint.h>
#include <QueryPipeline/Pipe.h>
#include <Processors/Sources/SourceFromSingleChunk.h>
#include <Processors/QueryPlan/QueryPlan.h>
#include <Processors/QueryPlan/ExpressionStep.h>
#include <Processors/QueryPlan/Optimizations/QueryPlanOptimizationSettings.h>
#include <Processors/QueryPlan/FilterStep.h>
#include <Processors/QueryPlan/UnionStep.h>
#include <Processors/QueryPlan/DistinctStep.h>
#include <Processors/QueryPlan/IntersectOrExceptStep.h>
#include <Processors/QueryPlan/CreatingSetsStep.h>
#include <Processors/QueryPlan/AggregatingStep.h>
#include <Processors/QueryPlan/MergingAggregatedStep.h>
#include <Processors/QueryPlan/SortingStep.h>
#include <Processors/QueryPlan/FillingStep.h>
#include <Processors/QueryPlan/LimitStep.h>
#include <Processors/QueryPlan/OffsetStep.h>
#include <Processors/QueryPlan/ExtremesStep.h>
#include <Processors/QueryPlan/TotalsHavingStep.h>
#include <Processors/QueryPlan/RollupStep.h>
#include <Processors/QueryPlan/CubeStep.h>
#include <Processors/QueryPlan/LimitByStep.h>
#include <Processors/QueryPlan/WindowStep.h>
#include <Processors/QueryPlan/ReadNothingStep.h>
#include <QueryPipeline/QueryPipelineBuilder.h>
#include <Interpreters/Context.h>
#include <Interpreters/StorageID.h>
#include <Storages/ColumnsDescription.h>
#include <Storages/IStorage.h>
#include <Storages/MergeTree/MergeTreeData.h>
#include <Storages/SelectQueryInfo.h>
#include <Storages/StorageDistributed.h>
#include <Storages/StorageDummy.h>
#include <Analyzer/Utils.h>
#include <Analyzer/ColumnNode.h>
#include <Analyzer/ConstantNode.h>
#include <Analyzer/FunctionNode.h>
#include <Analyzer/SortNode.h>
#include <Analyzer/InterpolateNode.h>
#include <Analyzer/WindowNode.h>
#include <Analyzer/TableNode.h>
#include <Analyzer/TableFunctionNode.h>
#include <Analyzer/QueryNode.h>
#include <Analyzer/UnionNode.h>
#include <Analyzer/JoinNode.h>
#include <Analyzer/ArrayJoinNode.h>
#include <Analyzer/QueryTreeBuilder.h>
#include <Analyzer/QueryTreePassManager.h>
#include <Analyzer/AggregationUtils.h>
#include <Analyzer/WindowFunctionsUtils.h>
#include <Planner/Utils.h>
#include <Planner/PlannerContext.h>
#include <Planner/PlannerActionsVisitor.h>
#include <Planner/PlannerJoins.h>
#include <Planner/PlannerAggregation.h>
#include <Planner/PlannerSorting.h>
#include <Planner/PlannerWindowFunctions.h>
#include <Planner/ActionsChain.h>
#include <Planner/CollectSets.h>
#include <Planner/CollectTableExpressionData.h>
#include <Planner/PlannerJoinTree.h>
#include <Planner/PlannerExpressionAnalysis.h>
#include <Planner/CollectColumnIdentifiers.h>
#include <Planner/PlannerQueryProcessingInfo.h>
namespace ProfileEvents
{
extern const Event SelectQueriesWithSubqueries;
extern const Event QueriesWithSubqueries;
}
namespace DB
{
namespace ErrorCodes
{
extern const int UNSUPPORTED_METHOD;
extern const int LOGICAL_ERROR;
extern const int BAD_ARGUMENTS;
extern const int TOO_DEEP_SUBQUERIES;
extern const int NOT_IMPLEMENTED;
extern const int SUPPORT_IS_DISABLED;
}
/** ClickHouse query planner.
*
* TODO: Support projections.
* TODO: Support trivial count using partition predicates.
* TODO: Support trivial count for table functions.
* TODO: Support indexes for IN function.
*/
namespace
{
/** Check that table and table function table expressions from planner context support transactions.
*
* There is precondition that table expression data for table expression nodes is collected in planner context.
*/
void checkStoragesSupportTransactions(const PlannerContextPtr & planner_context)
{
const auto & query_context = planner_context->getQueryContext();
if (!query_context->getSettingsRef().throw_on_unsupported_query_inside_transaction)
return;
if (!query_context->getCurrentTransaction())
return;
for (const auto & [table_expression, _] : planner_context->getTableExpressionNodeToData())
{
StoragePtr storage;
if (auto * table_node = table_expression->as<TableNode>())
storage = table_node->getStorage();
else if (auto * table_function_node = table_expression->as<TableFunctionNode>())
storage = table_function_node->getStorage();
if (storage && !storage->supportsTransactions())
throw Exception(ErrorCodes::NOT_IMPLEMENTED,
"Storage {} (table {}) does not support transactions",
storage->getName(),
storage->getStorageID().getNameForLogs());
}
}
/** Storages can rely that filters that for storage will be available for analysis before
* getQueryProcessingStage method will be called.
*
* StorageDistributed skip unused shards optimization relies on this.
* Parallel replicas estimation relies on this too.
*
* To collect filters that will be applied to specific table in case we have JOINs requires
* to run query plan optimization pipeline.
*
* Algorithm:
* 1. Replace all table expressions in query tree with dummy tables.
* 2. Build query plan.
* 3. Optimize query plan.
* 4. Extract filters from ReadFromDummy query plan steps from query plan leaf nodes.
*/
void collectFiltersForAnalysis(const QueryTreeNodePtr & query_tree, const PlannerContextPtr & planner_context)
{
bool collect_filters = false;
const auto & query_context = planner_context->getQueryContext();
const auto & settings = query_context->getSettingsRef();
bool parallel_replicas_estimation_enabled
= query_context->canUseParallelReplicasOnInitiator() && settings.parallel_replicas_min_number_of_rows_per_replica > 0;
for (auto & [table_expression, table_expression_data] : planner_context->getTableExpressionNodeToData())
{
auto * table_node = table_expression->as<TableNode>();
auto * table_function_node = table_expression->as<TableFunctionNode>();
if (!table_node && !table_function_node)
continue;
const auto & storage = table_node ? table_node->getStorage() : table_function_node->getStorage();
if (typeid_cast<const StorageDistributed *>(storage.get())
|| (parallel_replicas_estimation_enabled && std::dynamic_pointer_cast<MergeTreeData>(storage)))
{
collect_filters = true;
break;
}
}
if (!collect_filters)
return;
ResultReplacementMap replacement_map;
auto updated_query_tree = replaceTableExpressionsWithDummyTables(query_tree, planner_context->getQueryContext(), &replacement_map);
std::unordered_map<const IStorage *, TableExpressionData *> dummy_storage_to_table_expression_data;
for (auto & [from_table_expression, dummy_table_expression] : replacement_map)
{
auto * dummy_storage = dummy_table_expression->as<TableNode &>().getStorage().get();
auto * table_expression_data = &planner_context->getTableExpressionDataOrThrow(from_table_expression);
dummy_storage_to_table_expression_data.emplace(dummy_storage, table_expression_data);
}
SelectQueryOptions select_query_options;
Planner planner(updated_query_tree, select_query_options);
planner.buildQueryPlanIfNeeded();
auto & result_query_plan = planner.getQueryPlan();
auto optimization_settings = QueryPlanOptimizationSettings::fromContext(query_context);
result_query_plan.optimize(optimization_settings);
std::vector<QueryPlan::Node *> nodes_to_process;
nodes_to_process.push_back(result_query_plan.getRootNode());
while (!nodes_to_process.empty())
{
const auto * node_to_process = nodes_to_process.back();
nodes_to_process.pop_back();
nodes_to_process.insert(nodes_to_process.end(), node_to_process->children.begin(), node_to_process->children.end());
auto * read_from_dummy = typeid_cast<ReadFromDummy *>(node_to_process->step.get());
if (!read_from_dummy)
continue;
auto filter_actions = ActionsDAG::buildFilterActionsDAG(read_from_dummy->getFilterNodes().nodes, {}, query_context);
auto & table_expression_data = dummy_storage_to_table_expression_data.at(&read_from_dummy->getStorage());
table_expression_data->setFilterActions(std::move(filter_actions));
}
}
/// Extend lifetime of query context, storages, and table locks
void extendQueryContextAndStoragesLifetime(QueryPlan & query_plan, const PlannerContextPtr & planner_context)
{
query_plan.addInterpreterContext(planner_context->getQueryContext());
for (const auto & [table_expression, _] : planner_context->getTableExpressionNodeToData())
{
if (auto * table_node = table_expression->as<TableNode>())
{
query_plan.addStorageHolder(table_node->getStorage());
query_plan.addTableLock(table_node->getStorageLock());
}
else if (auto * table_function_node = table_expression->as<TableFunctionNode>())
{
query_plan.addStorageHolder(table_function_node->getStorage());
}
}
}
class QueryAnalysisResult
{
public:
QueryAnalysisResult(const QueryTreeNodePtr & query_tree,
const PlannerQueryProcessingInfo & query_processing_info,
const PlannerContextPtr & planner_context)
{
const auto & query_node = query_tree->as<QueryNode &>();
const auto & query_context = planner_context->getQueryContext();
const auto & settings = query_context->getSettingsRef();
aggregate_overflow_row = query_node.isGroupByWithTotals() && settings.max_rows_to_group_by
&& settings.group_by_overflow_mode == OverflowMode::ANY && settings.totals_mode != TotalsMode::AFTER_HAVING_EXCLUSIVE;
aggregate_final = query_processing_info.getToStage() > QueryProcessingStage::WithMergeableState
&& !query_node.isGroupByWithTotals() && !query_node.isGroupByWithRollup() && !query_node.isGroupByWithCube();
aggregation_with_rollup_or_cube_or_grouping_sets = query_node.isGroupByWithRollup() || query_node.isGroupByWithCube() ||
query_node.isGroupByWithGroupingSets();
aggregation_should_produce_results_in_order_of_bucket_number = query_processing_info.getToStage() == QueryProcessingStage::WithMergeableState &&
settings.distributed_aggregation_memory_efficient;
query_has_array_join_in_join_tree = queryHasArrayJoinInJoinTree(query_tree);
query_has_with_totals_in_any_subquery_in_join_tree = queryHasWithTotalsInAnySubqueryInJoinTree(query_tree);
sort_description = extractSortDescription(query_node.getOrderByNode(), *planner_context);
if (query_node.hasLimit())
{
/// Constness of limit is validated during query analysis stage
limit_length = query_node.getLimit()->as<ConstantNode &>().getValue().safeGet<UInt64>();
if (query_node.hasOffset() && limit_length)
{
/// Constness of offset is validated during query analysis stage
limit_offset = query_node.getOffset()->as<ConstantNode &>().getValue().safeGet<UInt64>();
}
}
else if (query_node.hasOffset())
{
/// Constness of offset is validated during query analysis stage
limit_offset = query_node.getOffset()->as<ConstantNode &>().getValue().safeGet<UInt64>();
}
/// Partial sort can be done if there is LIMIT, but no DISTINCT, LIMIT WITH TIES, LIMIT BY, ARRAY JOIN
if (limit_length != 0 &&
!query_node.isDistinct() &&
!query_node.isLimitWithTies() &&
!query_node.hasLimitBy() &&
!query_has_array_join_in_join_tree &&
limit_length <= std::numeric_limits<UInt64>::max() - limit_offset)
{
partial_sorting_limit = limit_length + limit_offset;
}
}
bool aggregate_overflow_row = false;
bool aggregate_final = false;
bool aggregation_with_rollup_or_cube_or_grouping_sets = false;
bool aggregation_should_produce_results_in_order_of_bucket_number = false;
bool query_has_array_join_in_join_tree = false;
bool query_has_with_totals_in_any_subquery_in_join_tree = false;
SortDescription sort_description;
UInt64 limit_length = 0;
UInt64 limit_offset = 0;
UInt64 partial_sorting_limit = 0;
};
void addExpressionStep(QueryPlan & query_plan,
const ActionsDAGPtr & expression_actions,
const std::string & step_description,
std::vector<ActionsDAGPtr> & result_actions_to_execute)
{
result_actions_to_execute.push_back(expression_actions);
auto expression_step = std::make_unique<ExpressionStep>(query_plan.getCurrentDataStream(), expression_actions);
expression_step->setStepDescription(step_description);
query_plan.addStep(std::move(expression_step));
}
void addFilterStep(QueryPlan & query_plan,
const FilterAnalysisResult & filter_analysis_result,
const std::string & step_description,
std::vector<ActionsDAGPtr> & result_actions_to_execute)
{
result_actions_to_execute.push_back(filter_analysis_result.filter_actions);
auto where_step = std::make_unique<FilterStep>(query_plan.getCurrentDataStream(),
filter_analysis_result.filter_actions,
filter_analysis_result.filter_column_name,
filter_analysis_result.remove_filter_column);
where_step->setStepDescription(step_description);
query_plan.addStep(std::move(where_step));
}
Aggregator::Params getAggregatorParams(const PlannerContextPtr & planner_context,
const AggregationAnalysisResult & aggregation_analysis_result,
const QueryAnalysisResult & query_analysis_result,
const SelectQueryInfo & select_query_info,
bool aggregate_descriptions_remove_arguments = false)
{
const auto & query_context = planner_context->getQueryContext();
const Settings & settings = query_context->getSettingsRef();
const auto stats_collecting_params = Aggregator::Params::StatsCollectingParams(
select_query_info.query,
settings.collect_hash_table_stats_during_aggregation,
settings.max_entries_for_hash_table_stats,
settings.max_size_to_preallocate_for_aggregation);
auto aggregate_descriptions = aggregation_analysis_result.aggregate_descriptions;
if (aggregate_descriptions_remove_arguments)
{
for (auto & aggregate_description : aggregate_descriptions)
aggregate_description.argument_names.clear();
}
Aggregator::Params aggregator_params = Aggregator::Params(
aggregation_analysis_result.aggregation_keys,
aggregate_descriptions,
query_analysis_result.aggregate_overflow_row,
settings.max_rows_to_group_by,
settings.group_by_overflow_mode,
settings.group_by_two_level_threshold,
settings.group_by_two_level_threshold_bytes,
settings.max_bytes_before_external_group_by,
settings.empty_result_for_aggregation_by_empty_set
|| (settings.empty_result_for_aggregation_by_constant_keys_on_empty_set && aggregation_analysis_result.aggregation_keys.empty()
&& aggregation_analysis_result.group_by_with_constant_keys),
query_context->getTempDataOnDisk(),
settings.max_threads,
settings.min_free_disk_space_for_temporary_data,
settings.compile_aggregate_expressions,
settings.min_count_to_compile_aggregate_expression,
settings.max_block_size,
settings.enable_software_prefetch_in_aggregation,
/* only_merge */ false,
settings.optimize_group_by_constant_keys,
settings.min_hit_rate_to_use_consecutive_keys_optimization,
stats_collecting_params);
return aggregator_params;
}
SortDescription getSortDescriptionFromNames(const Names & names)
{
SortDescription order_descr;
order_descr.reserve(names.size());
for (const auto & name : names)
order_descr.emplace_back(name, 1, 1);
return order_descr;
}
void addAggregationStep(QueryPlan & query_plan,
const AggregationAnalysisResult & aggregation_analysis_result,
const QueryAnalysisResult & query_analysis_result,
const PlannerContextPtr & planner_context,
const SelectQueryInfo & select_query_info)
{
const Settings & settings = planner_context->getQueryContext()->getSettingsRef();
auto aggregator_params = getAggregatorParams(planner_context, aggregation_analysis_result, query_analysis_result, select_query_info);
SortDescription sort_description_for_merging;
SortDescription group_by_sort_description;
if (settings.force_aggregation_in_order)
{
group_by_sort_description = getSortDescriptionFromNames(aggregation_analysis_result.aggregation_keys);
sort_description_for_merging = group_by_sort_description;
}
auto merge_threads = settings.max_threads;
auto temporary_data_merge_threads = settings.aggregation_memory_efficient_merge_threads
? static_cast<size_t>(settings.aggregation_memory_efficient_merge_threads)
: static_cast<size_t>(settings.max_threads);
bool storage_has_evenly_distributed_read = false;
const auto & table_expression_node_to_data = planner_context->getTableExpressionNodeToData();
if (table_expression_node_to_data.size() == 1)
{
auto it = table_expression_node_to_data.begin();
const auto & table_expression_node = it->first;
if (const auto * table_node = table_expression_node->as<TableNode>())
storage_has_evenly_distributed_read = table_node->getStorage()->hasEvenlyDistributedRead();
else if (const auto * table_function_node = table_expression_node->as<TableFunctionNode>())
storage_has_evenly_distributed_read = table_function_node->getStorageOrThrow()->hasEvenlyDistributedRead();
}
auto aggregating_step = std::make_unique<AggregatingStep>(
query_plan.getCurrentDataStream(),
aggregator_params,
aggregation_analysis_result.grouping_sets_parameters_list,
query_analysis_result.aggregate_final,
settings.max_block_size,
settings.aggregation_in_order_max_block_bytes,
merge_threads,
temporary_data_merge_threads,
storage_has_evenly_distributed_read,
settings.group_by_use_nulls,
std::move(sort_description_for_merging),
std::move(group_by_sort_description),
query_analysis_result.aggregation_should_produce_results_in_order_of_bucket_number,
settings.enable_memory_bound_merging_of_aggregation_results,
settings.force_aggregation_in_order);
query_plan.addStep(std::move(aggregating_step));
}
void addMergingAggregatedStep(QueryPlan & query_plan,
const AggregationAnalysisResult & aggregation_analysis_result,
const QueryAnalysisResult & query_analysis_result,
const PlannerContextPtr & planner_context)
{
const auto & query_context = planner_context->getQueryContext();
const auto & settings = query_context->getSettingsRef();
/** There are two modes of distributed aggregation.
*
* 1. In different threads read from the remote servers blocks.
* Save all the blocks in the RAM. Merge blocks.
* If the aggregation is two-level - parallelize to the number of buckets.
*
* 2. In one thread, read blocks from different servers in order.
* RAM stores only one block from each server.
* If the aggregation is a two-level aggregation, we consistently merge the blocks of each next level.
*
* The second option consumes less memory (up to 256 times less)
* in the case of two-level aggregation, which is used for large results after GROUP BY,
* but it can work more slowly.
*/
auto keys = aggregation_analysis_result.aggregation_keys;
if (!aggregation_analysis_result.grouping_sets_parameters_list.empty())
keys.insert(keys.begin(), "__grouping_set");
Aggregator::Params params(keys,
aggregation_analysis_result.aggregate_descriptions,
query_analysis_result.aggregate_overflow_row,
settings.max_threads,
settings.max_block_size,
settings.min_hit_rate_to_use_consecutive_keys_optimization);
bool is_remote_storage = false;
bool parallel_replicas_from_merge_tree = false;
const auto & table_expression_node_to_data = planner_context->getTableExpressionNodeToData();
if (table_expression_node_to_data.size() == 1)
{
auto it = table_expression_node_to_data.begin();
is_remote_storage = it->second.isRemote();
parallel_replicas_from_merge_tree = it->second.isMergeTree() && query_context->canUseParallelReplicasOnInitiator();
}
SortDescription group_by_sort_description;
auto merging_aggregated = std::make_unique<MergingAggregatedStep>(
query_plan.getCurrentDataStream(),
params,
query_analysis_result.aggregate_final,
/// Grouping sets don't work with distributed_aggregation_memory_efficient enabled (#43989)
settings.distributed_aggregation_memory_efficient && (is_remote_storage || parallel_replicas_from_merge_tree) && !query_analysis_result.aggregation_with_rollup_or_cube_or_grouping_sets,
settings.max_threads,
settings.aggregation_memory_efficient_merge_threads,
query_analysis_result.aggregation_should_produce_results_in_order_of_bucket_number,
settings.max_block_size,
settings.aggregation_in_order_max_block_bytes,
std::move(group_by_sort_description),
settings.enable_memory_bound_merging_of_aggregation_results);
query_plan.addStep(std::move(merging_aggregated));
}
void addTotalsHavingStep(QueryPlan & query_plan,
const PlannerExpressionsAnalysisResult & expression_analysis_result,
const QueryAnalysisResult & query_analysis_result,
const PlannerContextPtr & planner_context,
const QueryNode & query_node,
std::vector<ActionsDAGPtr> & result_actions_to_execute)
{
const auto & query_context = planner_context->getQueryContext();
const auto & settings = query_context->getSettingsRef();
const auto & aggregation_analysis_result = expression_analysis_result.getAggregation();
const auto & having_analysis_result = expression_analysis_result.getHaving();
bool need_finalize = !query_node.isGroupByWithRollup() && !query_node.isGroupByWithCube();
if (having_analysis_result.filter_actions)
result_actions_to_execute.push_back(having_analysis_result.filter_actions);
auto totals_having_step = std::make_unique<TotalsHavingStep>(
query_plan.getCurrentDataStream(),
aggregation_analysis_result.aggregate_descriptions,
query_analysis_result.aggregate_overflow_row,
having_analysis_result.filter_actions,
having_analysis_result.filter_column_name,
having_analysis_result.remove_filter_column,
settings.totals_mode,
settings.totals_auto_threshold,
need_finalize);
query_plan.addStep(std::move(totals_having_step));
}
void addCubeOrRollupStepIfNeeded(QueryPlan & query_plan,
const AggregationAnalysisResult & aggregation_analysis_result,
const QueryAnalysisResult & query_analysis_result,
const PlannerContextPtr & planner_context,
const SelectQueryInfo & select_query_info,
const QueryNode & query_node)
{
if (!query_node.isGroupByWithCube() && !query_node.isGroupByWithRollup())
return;
const auto & query_context = planner_context->getQueryContext();
const auto & settings = query_context->getSettingsRef();
auto aggregator_params = getAggregatorParams(planner_context,
aggregation_analysis_result,
query_analysis_result,
select_query_info,
true /*aggregate_descriptions_remove_arguments*/);
if (query_node.isGroupByWithRollup())
{
auto rollup_step = std::make_unique<RollupStep>(
query_plan.getCurrentDataStream(), std::move(aggregator_params), true /*final*/, settings.group_by_use_nulls);
query_plan.addStep(std::move(rollup_step));
}
else if (query_node.isGroupByWithCube())
{
auto cube_step = std::make_unique<CubeStep>(
query_plan.getCurrentDataStream(), std::move(aggregator_params), true /*final*/, settings.group_by_use_nulls);
query_plan.addStep(std::move(cube_step));
}
}
void addDistinctStep(QueryPlan & query_plan,
const QueryAnalysisResult & query_analysis_result,
const PlannerContextPtr & planner_context,
const Names & column_names,
const QueryNode & query_node,
bool before_order,
bool pre_distinct)
{
const Settings & settings = planner_context->getQueryContext()->getSettingsRef();
UInt64 limit_offset = query_analysis_result.limit_offset;
UInt64 limit_length = query_analysis_result.limit_length;
UInt64 limit_hint_for_distinct = 0;
/** If after this stage of DISTINCT
* 1. ORDER BY is not executed.
* 2. There is no LIMIT BY.
* Then you can get no more than limit_length + limit_offset of different rows.
*/
if ((!query_node.hasOrderBy() || !before_order) && !query_node.hasLimitBy())
{
if (limit_length <= std::numeric_limits<UInt64>::max() - limit_offset)
limit_hint_for_distinct = limit_length + limit_offset;
}
SizeLimits limits(settings.max_rows_in_distinct, settings.max_bytes_in_distinct, settings.distinct_overflow_mode);
auto distinct_step = std::make_unique<DistinctStep>(
query_plan.getCurrentDataStream(),
limits,
limit_hint_for_distinct,
column_names,
pre_distinct,
settings.optimize_distinct_in_order);
distinct_step->setStepDescription(pre_distinct ? "Preliminary DISTINCT" : "DISTINCT");
query_plan.addStep(std::move(distinct_step));
}
void addSortingStep(QueryPlan & query_plan,
const QueryAnalysisResult & query_analysis_result,
const PlannerContextPtr & planner_context)
{
const auto & sort_description = query_analysis_result.sort_description;
const auto & query_context = planner_context->getQueryContext();
const Settings & settings = query_context->getSettingsRef();
SortingStep::Settings sort_settings(*query_context);
auto sorting_step = std::make_unique<SortingStep>(
query_plan.getCurrentDataStream(),
sort_description,
query_analysis_result.partial_sorting_limit,
sort_settings,
settings.optimize_sorting_by_input_stream_properties);
sorting_step->setStepDescription("Sorting for ORDER BY");
query_plan.addStep(std::move(sorting_step));
}
void addMergeSortingStep(QueryPlan & query_plan,
const QueryAnalysisResult & query_analysis_result,
const PlannerContextPtr & planner_context,
const std::string & description)
{
const auto & query_context = planner_context->getQueryContext();
const auto & settings = query_context->getSettingsRef();
const auto & sort_description = query_analysis_result.sort_description;
const auto max_block_size = settings.max_block_size;
auto merging_sorted = std::make_unique<SortingStep>(query_plan.getCurrentDataStream(),
sort_description,
max_block_size,
query_analysis_result.partial_sorting_limit,
settings.exact_rows_before_limit);
merging_sorted->setStepDescription("Merge sorted streams " + description);
query_plan.addStep(std::move(merging_sorted));
}
void addWithFillStepIfNeeded(QueryPlan & query_plan,
const QueryAnalysisResult & query_analysis_result,
const PlannerContextPtr & planner_context,
const QueryNode & query_node)
{
const auto & sort_description = query_analysis_result.sort_description;
NameSet column_names_with_fill;
SortDescription fill_description;
for (const auto & description : sort_description)
{
if (description.with_fill)
{
fill_description.push_back(description);
column_names_with_fill.insert(description.column_name);
}
}
if (fill_description.empty())
return;
InterpolateDescriptionPtr interpolate_description;
if (query_node.hasInterpolate())
{
auto interpolate_actions_dag = std::make_shared<ActionsDAG>();
auto query_plan_columns = query_plan.getCurrentDataStream().header.getColumnsWithTypeAndName();
for (auto & query_plan_column : query_plan_columns)
{
/// INTERPOLATE actions dag input columns must be non constant
query_plan_column.column = nullptr;
interpolate_actions_dag->addInput(query_plan_column);
}
auto & interpolate_list_node = query_node.getInterpolate()->as<ListNode &>();
auto & interpolate_list_nodes = interpolate_list_node.getNodes();
if (interpolate_list_nodes.empty())
{
for (const auto * input_node : interpolate_actions_dag->getInputs())
{
if (column_names_with_fill.contains(input_node->result_name))
continue;
interpolate_actions_dag->getOutputs().push_back(input_node);
}
}
else
{
for (auto & interpolate_node : interpolate_list_nodes)
{
auto & interpolate_node_typed = interpolate_node->as<InterpolateNode &>();
PlannerActionsVisitor planner_actions_visitor(planner_context);
auto expression_to_interpolate_expression_nodes = planner_actions_visitor.visit(interpolate_actions_dag,
interpolate_node_typed.getExpression());
if (expression_to_interpolate_expression_nodes.size() != 1)
throw Exception(ErrorCodes::BAD_ARGUMENTS, "Expression to interpolate expected to have single action node");
auto interpolate_expression_nodes = planner_actions_visitor.visit(interpolate_actions_dag,
interpolate_node_typed.getInterpolateExpression());
if (interpolate_expression_nodes.size() != 1)
throw Exception(ErrorCodes::BAD_ARGUMENTS, "Interpolate expression expected to have single action node");
const auto * expression_to_interpolate = expression_to_interpolate_expression_nodes[0];
const auto & expression_to_interpolate_name = expression_to_interpolate->result_name;
const auto * interpolate_expression = interpolate_expression_nodes[0];
if (!interpolate_expression->result_type->equals(*expression_to_interpolate->result_type))
{
interpolate_expression = &interpolate_actions_dag->addCast(*interpolate_expression,
expression_to_interpolate->result_type,
interpolate_expression->result_name);
}
const auto * alias_node = &interpolate_actions_dag->addAlias(*interpolate_expression, expression_to_interpolate_name);
interpolate_actions_dag->getOutputs().push_back(alias_node);
}
interpolate_actions_dag->removeUnusedActions();
}
Aliases empty_aliases;
interpolate_description = std::make_shared<InterpolateDescription>(std::move(interpolate_actions_dag), empty_aliases);
}
const auto & query_context = planner_context->getQueryContext();
const Settings & settings = query_context->getSettingsRef();
auto filling_step = std::make_unique<FillingStep>(
query_plan.getCurrentDataStream(),
sort_description,
std::move(fill_description),
interpolate_description,
settings.use_with_fill_by_sorting_prefix);
query_plan.addStep(std::move(filling_step));
}
void addLimitByStep(QueryPlan & query_plan,
const LimitByAnalysisResult & limit_by_analysis_result,
const QueryNode & query_node)
{
/// Constness of LIMIT BY limit is validated during query analysis stage
UInt64 limit_by_limit = query_node.getLimitByLimit()->as<ConstantNode &>().getValue().safeGet<UInt64>();
UInt64 limit_by_offset = 0;
if (query_node.hasLimitByOffset())
{
/// Constness of LIMIT BY offset is validated during query analysis stage
limit_by_offset = query_node.getLimitByOffset()->as<ConstantNode &>().getValue().safeGet<UInt64>();
}
auto limit_by_step = std::make_unique<LimitByStep>(query_plan.getCurrentDataStream(),
limit_by_limit,
limit_by_offset,
limit_by_analysis_result.limit_by_column_names);
query_plan.addStep(std::move(limit_by_step));
}
void addPreliminaryLimitStep(QueryPlan & query_plan,
const QueryAnalysisResult & query_analysis_result,
const PlannerContextPtr & planner_context,
bool do_not_skip_offset)
{
UInt64 limit_offset = query_analysis_result.limit_offset;
UInt64 limit_length = query_analysis_result.limit_length;
if (do_not_skip_offset)
{
if (limit_length > std::numeric_limits<UInt64>::max() - limit_offset)
return;
limit_length += limit_offset;
limit_offset = 0;
}
const auto & query_context = planner_context->getQueryContext();
const Settings & settings = query_context->getSettingsRef();
auto limit = std::make_unique<LimitStep>(query_plan.getCurrentDataStream(), limit_length, limit_offset, settings.exact_rows_before_limit);
limit->setStepDescription(do_not_skip_offset ? "preliminary LIMIT (with OFFSET)" : "preliminary LIMIT (without OFFSET)");
query_plan.addStep(std::move(limit));
}
bool addPreliminaryLimitOptimizationStepIfNeeded(QueryPlan & query_plan,
const QueryAnalysisResult & query_analysis_result,
const PlannerContextPtr planner_context,
const PlannerQueryProcessingInfo & query_processing_info,
const QueryTreeNodePtr & query_tree)
{
const auto & query_node = query_tree->as<QueryNode &>();
const auto & query_context = planner_context->getQueryContext();
const auto & settings = query_context->getSettingsRef();
const auto & sort_description = query_analysis_result.sort_description;
bool has_withfill = false;
for (const auto & desc : sort_description)
{
if (desc.with_fill)
{
has_withfill = true;
break;
}
}
bool apply_limit = query_processing_info.getToStage() != QueryProcessingStage::WithMergeableStateAfterAggregation;
bool apply_prelimit = apply_limit &&
query_node.hasLimit() &&
!query_node.isLimitWithTies() &&
!query_node.isGroupByWithTotals() &&
!query_analysis_result.query_has_with_totals_in_any_subquery_in_join_tree &&
!query_analysis_result.query_has_array_join_in_join_tree &&
!query_node.isDistinct() &&
!query_node.hasLimitBy() &&
!settings.extremes &&
!has_withfill;
bool apply_offset = query_processing_info.getToStage() != QueryProcessingStage::WithMergeableStateAfterAggregationAndLimit;
if (apply_prelimit)
{
addPreliminaryLimitStep(query_plan, query_analysis_result, planner_context, /* do_not_skip_offset= */!apply_offset);
return true;
}
return false;
}
/** For distributed query processing, add preliminary sort or distinct or limit
* for first stage of query processing on shard, if there is no GROUP BY, HAVING,
* WINDOW functions.
*/
void addPreliminarySortOrDistinctOrLimitStepsIfNeeded(QueryPlan & query_plan,
const PlannerExpressionsAnalysisResult & expressions_analysis_result,
const QueryAnalysisResult & query_analysis_result,
const PlannerContextPtr & planner_context,
const PlannerQueryProcessingInfo & query_processing_info,
const QueryTreeNodePtr & query_tree,
std::vector<ActionsDAGPtr> & result_actions_to_execute)
{
const auto & query_node = query_tree->as<QueryNode &>();
if (query_processing_info.isSecondStage() ||
expressions_analysis_result.hasAggregation() ||
expressions_analysis_result.hasHaving() ||
expressions_analysis_result.hasWindow())
return;
if (expressions_analysis_result.hasSort())
addSortingStep(query_plan, query_analysis_result, planner_context);
/** For DISTINCT step, pre_distinct = false, because if we have limit and distinct,
* we need to merge streams to one and calculate overall distinct.
* Otherwise we can take several equal values from different streams
* according to limit and skip some distinct values.
*/
if (query_node.hasLimit() && query_node.isDistinct())
{
addDistinctStep(query_plan,
query_analysis_result,
planner_context,
expressions_analysis_result.getProjection().projection_column_names,
query_node,
false /*before_order*/,
false /*pre_distinct*/);
}
if (expressions_analysis_result.hasLimitBy())
{
const auto & limit_by_analysis_result = expressions_analysis_result.getLimitBy();
addExpressionStep(query_plan, limit_by_analysis_result.before_limit_by_actions, "Before LIMIT BY", result_actions_to_execute);
addLimitByStep(query_plan, limit_by_analysis_result, query_node);
}
if (query_node.hasLimit())
addPreliminaryLimitStep(query_plan, query_analysis_result, planner_context, true /*do_not_skip_offset*/);
}
void addWindowSteps(QueryPlan & query_plan,
const PlannerContextPtr & planner_context,
const WindowAnalysisResult & window_analysis_result)
{
const auto & query_context = planner_context->getQueryContext();
const auto & settings = query_context->getSettingsRef();
auto window_descriptions = window_analysis_result.window_descriptions;
sortWindowDescriptions(window_descriptions);
size_t window_descriptions_size = window_descriptions.size();
for (size_t i = 0; i < window_descriptions_size; ++i)
{
const auto & window_description = window_descriptions[i];
/** We don't need to sort again if the input from previous window already
* has suitable sorting. Also don't create sort steps when there are no
* columns to sort by, because the sort nodes are confused by this. It
* happens in case of `over ()`.
* Even if full_sort_description of both windows match, in case of different
* partitioning we need to add a SortingStep to reshuffle data in the streams.
*/
bool need_sort = !window_description.full_sort_description.empty();
if (need_sort && i != 0)
{
need_sort = !sortDescriptionIsPrefix(window_description.full_sort_description, window_descriptions[i - 1].full_sort_description)
|| (settings.max_threads != 1 && window_description.partition_by.size() != window_descriptions[i - 1].partition_by.size());
}
if (need_sort)
{
SortingStep::Settings sort_settings(*query_context);
auto sorting_step = std::make_unique<SortingStep>(
query_plan.getCurrentDataStream(),
window_description.full_sort_description,
window_description.partition_by,
0 /*limit*/,
sort_settings,
settings.optimize_sorting_by_input_stream_properties);
sorting_step->setStepDescription("Sorting for window '" + window_description.window_name + "'");
query_plan.addStep(std::move(sorting_step));
}
// Fan out streams only for the last window to preserve the ordering between windows,
// and WindowTransform works on single stream anyway.
const bool streams_fan_out = settings.query_plan_enable_multithreading_after_window_functions && ((i + 1) == window_descriptions_size);
auto window_step
= std::make_unique<WindowStep>(query_plan.getCurrentDataStream(), window_description, window_description.window_functions, streams_fan_out);
window_step->setStepDescription("Window step for window '" + window_description.window_name + "'");
query_plan.addStep(std::move(window_step));
}
}
void addLimitStep(QueryPlan & query_plan,
const QueryAnalysisResult & query_analysis_result,
const PlannerContextPtr & planner_context,
const QueryNode & query_node)
{
const auto & query_context = planner_context->getQueryContext();
const auto & settings = query_context->getSettingsRef();
bool always_read_till_end = settings.exact_rows_before_limit;
bool limit_with_ties = query_node.isLimitWithTies();
/** Special cases:
*
* 1. If there is WITH TOTALS and there is no ORDER BY, then read the data to the end,
* otherwise TOTALS is counted according to incomplete data.
*
* 2. If there is no WITH TOTALS and there is a subquery in FROM, and there is WITH TOTALS on one of the levels,
* then when using LIMIT, you should read the data to the end, rather than cancel the query earlier,
* because if you cancel the query, we will not get `totals` data from the remote server.
*/
if (query_node.isGroupByWithTotals() && !query_node.hasOrderBy())
always_read_till_end = true;
if (!query_node.isGroupByWithTotals() && query_analysis_result.query_has_with_totals_in_any_subquery_in_join_tree)
always_read_till_end = true;
SortDescription limit_with_ties_sort_description;
if (query_node.isLimitWithTies())
{
/// Validated during parser stage
if (!query_node.hasOrderBy())
throw Exception(ErrorCodes::LOGICAL_ERROR, "LIMIT WITH TIES without ORDER BY");
limit_with_ties_sort_description = query_analysis_result.sort_description;
}
UInt64 limit_length = query_analysis_result.limit_length;
UInt64 limit_offset = query_analysis_result.limit_offset;
auto limit = std::make_unique<LimitStep>(
query_plan.getCurrentDataStream(),
limit_length,
limit_offset,
always_read_till_end,
limit_with_ties,
limit_with_ties_sort_description);
if (limit_with_ties)
limit->setStepDescription("LIMIT WITH TIES");
query_plan.addStep(std::move(limit));
}
void addExtremesStepIfNeeded(QueryPlan & query_plan, const PlannerContextPtr & planner_context)