forked from ClickHouse/ClickHouse
-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathInterpreterSelectQuery.cpp
More file actions
3363 lines (2851 loc) · 146 KB
/
InterpreterSelectQuery.cpp
File metadata and controls
3363 lines (2851 loc) · 146 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
#include <Access/AccessControl.h>
#include <DataTypes/DataTypeAggregateFunction.h>
#include <DataTypes/DataTypeInterval.h>
#include <Parsers/ASTFunction.h>
#include <Parsers/ASTIdentifier.h>
#include <Parsers/ASTLiteral.h>
#include <Parsers/ASTOrderByElement.h>
#include <Parsers/ASTInterpolateElement.h>
#include <Parsers/ASTSelectWithUnionQuery.h>
#include <Parsers/ASTSelectIntersectExceptQuery.h>
#include <Parsers/ASTTablesInSelectQuery.h>
#include <Parsers/ExpressionListParsers.h>
#include <Parsers/parseQuery.h>
#include <Access/Common/AccessFlags.h>
#include <Access/ContextAccess.h>
#include <AggregateFunctions/AggregateFunctionCount.h>
#include <DataTypes/DataTypeNullable.h>
#include <Interpreters/ApplyWithAliasVisitor.h>
#include <Interpreters/ApplyWithSubqueryVisitor.h>
#include <Interpreters/InterpreterFactory.h>
#include <Interpreters/InterpreterSelectQuery.h>
#include <Interpreters/InterpreterSelectWithUnionQuery.h>
#include <Interpreters/InterpreterSetQuery.h>
#include <Interpreters/ExpressionActions.h>
#include <Interpreters/evaluateConstantExpression.h>
#include <Interpreters/convertFieldToType.h>
#include <Interpreters/addTypeConversionToAST.h>
#include <Interpreters/ExpressionAnalyzer.h>
#include <Interpreters/getTableExpressions.h>
#include <Interpreters/JoinToSubqueryTransformVisitor.h>
#include <Interpreters/CrossToInnerJoinVisitor.h>
#include <Interpreters/TableJoin.h>
#include <Interpreters/JoinedTables.h>
#include <Interpreters/OpenTelemetrySpanLog.h>
#include <Interpreters/QueryAliasesVisitor.h>
#include <Interpreters/QueryLog.h>
#include <Interpreters/replaceAliasColumnsInQuery.h>
#include <Interpreters/RewriteCountDistinctVisitor.h>
#include <Interpreters/RewriteUniqToCountVisitor.h>
#include <Interpreters/getCustomKeyFilterForParallelReplicas.h>
#include <QueryPipeline/Pipe.h>
#include <Processors/QueryPlan/AggregatingStep.h>
#include <Processors/QueryPlan/ArrayJoinStep.h>
#include <Processors/QueryPlan/CreateSetAndFilterOnTheFlyStep.h>
#include <Processors/QueryPlan/CreatingSetsStep.h>
#include <Processors/QueryPlan/CubeStep.h>
#include <Processors/QueryPlan/DistinctStep.h>
#include <Processors/QueryPlan/ExpressionStep.h>
#include <Processors/QueryPlan/ExtremesStep.h>
#include <Processors/QueryPlan/FillingStep.h>
#include <Processors/QueryPlan/FilterStep.h>
#include <Processors/QueryPlan/JoinStep.h>
#include <Processors/QueryPlan/LimitByStep.h>
#include <Processors/QueryPlan/LimitStep.h>
#include <Processors/QueryPlan/SortingStep.h>
#include <Processors/QueryPlan/MergingAggregatedStep.h>
#include <Processors/QueryPlan/OffsetStep.h>
#include <Processors/QueryPlan/QueryPlan.h>
#include <Processors/QueryPlan/ReadFromPreparedSource.h>
#include <Processors/QueryPlan/ReadNothingStep.h>
#include <Processors/QueryPlan/RollupStep.h>
#include <Processors/QueryPlan/TotalsHavingStep.h>
#include <Processors/QueryPlan/WindowStep.h>
#include <Processors/QueryPlan/Optimizations/QueryPlanOptimizationSettings.h>
#include <Processors/Sources/NullSource.h>
#include <Processors/Sources/SourceFromSingleChunk.h>
#include <Processors/Transforms/AggregatingTransform.h>
#include <Processors/Transforms/FilterTransform.h>
#include <QueryPipeline/QueryPipelineBuilder.h>
#include <Storages/MergeTree/MergeTreeWhereOptimizer.h>
#include <Storages/StorageDistributed.h>
#include <Storages/StorageMerge.h>
#include <Storages/StorageValues.h>
#include <Storages/StorageView.h>
#include <Storages/ReadInOrderOptimizer.h>
#include <Columns/Collator.h>
#include <Columns/ColumnAggregateFunction.h>
#include <Core/ColumnNumbers.h>
#include <Core/Field.h>
#include <Core/ProtocolDefines.h>
#include <Core/Settings.h>
#include <Core/ServerSettings.h>
#include <Interpreters/Aggregator.h>
#include <Interpreters/ArrayJoinAction.h>
#include <Interpreters/HashTablesStatistics.h>
#include <Interpreters/IJoin.h>
#include <QueryPipeline/SizeLimits.h>
#include <base/map.h>
#include <Common/FieldVisitorToString.h>
#include <Common/FieldAccurateComparison.h>
#include <Common/NaNUtils.h>
#include <Common/ProfileEvents.h>
#include <Common/checkStackSize.h>
#include <Common/quoteString.h>
#include <Common/scope_guard_safe.h>
#include <Common/typeid_cast.h>
namespace ProfileEvents
{
extern const Event SelectQueriesWithSubqueries;
extern const Event QueriesWithSubqueries;
}
namespace DB
{
namespace Setting
{
extern const SettingsMap additional_table_filters;
extern const SettingsUInt64 aggregation_in_order_max_block_bytes;
extern const SettingsUInt64 aggregation_memory_efficient_merge_threads;
extern const SettingsUInt64 allow_experimental_parallel_reading_from_replicas;
extern const SettingsBool allow_experimental_query_deduplication;
extern const SettingsBool async_socket_for_remote;
extern const SettingsBool collect_hash_table_stats_during_aggregation;
extern const SettingsBool compile_sort_description;
extern const SettingsBool count_distinct_optimization;
extern const SettingsUInt64 cross_to_inner_join_rewrite;
extern const SettingsOverflowMode distinct_overflow_mode;
extern const SettingsBool distributed_aggregation_memory_efficient;
extern const SettingsBool empty_result_for_aggregation_by_constant_keys_on_empty_set;
extern const SettingsBool empty_result_for_aggregation_by_empty_set;
extern const SettingsBool enable_global_with_statement;
extern const SettingsBool enable_memory_bound_merging_of_aggregation_results;
extern const SettingsBool exact_rows_before_limit;
extern const SettingsBool enable_unaligned_array_join;
extern const SettingsBool extremes;
extern const SettingsBool final;
extern const SettingsBool force_aggregation_in_order;
extern const SettingsUInt64 group_by_two_level_threshold;
extern const SettingsUInt64 group_by_two_level_threshold_bytes;
extern const SettingsBool group_by_use_nulls;
extern const SettingsSeconds lock_acquire_timeout;
extern const SettingsUInt64 max_analyze_depth;
extern const SettingsUInt64 max_block_size;
extern const SettingsUInt64 max_bytes_in_distinct;
extern const SettingsUInt64 max_columns_to_read;
extern const SettingsUInt64 max_distributed_connections;
extern const SettingsNonZeroUInt64 max_parallel_replicas;
extern const SettingsUInt64 max_parser_backtracks;
extern const SettingsUInt64 max_parser_depth;
extern const SettingsUInt64 max_query_size;
extern const SettingsUInt64 max_result_bytes;
extern const SettingsUInt64 max_result_rows;
extern const SettingsUInt64 max_rows_in_distinct;
extern const SettingsUInt64 max_rows_in_set_to_optimize_join;
extern const SettingsUInt64 max_rows_to_read;
extern const SettingsUInt64 max_size_to_preallocate_for_aggregation;
extern const SettingsFloat max_streams_to_max_threads_ratio;
extern const SettingsUInt64 max_subquery_depth;
extern const SettingsMaxThreads max_threads;
extern const SettingsUInt64 min_count_to_compile_sort_description;
extern const SettingsBool multiple_joins_try_to_keep_original_names;
extern const SettingsBool optimize_aggregation_in_order;
extern const SettingsBool optimize_move_to_prewhere;
extern const SettingsBool optimize_move_to_prewhere_if_final;
extern const SettingsBool optimize_uniq_to_count;
extern const SettingsUInt64 parallel_replicas_count;
extern const SettingsString parallel_replicas_custom_key;
extern const SettingsParallelReplicasMode parallel_replicas_mode;
extern const SettingsUInt64 parallel_replicas_custom_key_range_lower;
extern const SettingsUInt64 parallel_replicas_custom_key_range_upper;
extern const SettingsBool parallel_replicas_for_non_replicated_merge_tree;
extern const SettingsUInt64 parallel_replicas_min_number_of_rows_per_replica;
extern const SettingsUInt64 parallel_replica_offset;
extern const SettingsBool query_plan_enable_optimizations;
extern const SettingsBool query_plan_enable_multithreading_after_window_functions;
extern const SettingsBool query_plan_optimize_prewhere;
extern const SettingsBool throw_on_unsupported_query_inside_transaction;
extern const SettingsFloat totals_auto_threshold;
extern const SettingsTotalsMode totals_mode;
extern const SettingsBool use_concurrency_control;
extern const SettingsBool use_with_fill_by_sorting_prefix;
extern const SettingsFloat min_hit_rate_to_use_consecutive_keys_optimization;
extern const SettingsUInt64 max_rows_to_group_by;
extern const SettingsOverflowModeGroupBy group_by_overflow_mode;
extern const SettingsUInt64 max_bytes_before_external_group_by;
extern const SettingsDouble max_bytes_ratio_before_external_group_by;
extern const SettingsUInt64 min_free_disk_space_for_temporary_data;
extern const SettingsBool compile_aggregate_expressions;
extern const SettingsUInt64 min_count_to_compile_aggregate_expression;
extern const SettingsBool enable_software_prefetch_in_aggregation;
extern const SettingsBool optimize_group_by_constant_keys;
}
namespace ServerSetting
{
extern const ServerSettingsUInt64 max_entries_for_hash_table_stats;
}
static UInt64 getLimitUIntValue(const ASTPtr & node, const ContextPtr & context, const std::string & expr);
namespace ErrorCodes
{
extern const int TOO_DEEP_SUBQUERIES;
extern const int SAMPLING_NOT_SUPPORTED;
extern const int ILLEGAL_FINAL;
extern const int ILLEGAL_PREWHERE;
extern const int TOO_MANY_COLUMNS;
extern const int LOGICAL_ERROR;
extern const int NOT_IMPLEMENTED;
extern const int PARAMETER_OUT_OF_BOUND;
extern const int INVALID_LIMIT_EXPRESSION;
extern const int INVALID_WITH_FILL_EXPRESSION;
extern const int ACCESS_DENIED;
extern const int UNKNOWN_IDENTIFIER;
extern const int BAD_ARGUMENTS;
extern const int SUPPORT_IS_DISABLED;
}
/// Assumes `storage` is set and the table filter (row-level security) is not empty.
FilterDAGInfoPtr generateFilterActions(
const StorageID & table_id,
const ASTPtr & row_policy_filter_expression,
const ContextPtr & context,
const StoragePtr & storage,
const StorageSnapshotPtr & storage_snapshot,
const StorageMetadataPtr & metadata_snapshot,
Names & prerequisite_columns,
PreparedSetsPtr prepared_sets)
try
{
auto filter_info = std::make_shared<FilterDAGInfo>();
const auto & db_name = table_id.getDatabaseName();
const auto & table_name = table_id.getTableName();
/// TODO: implement some AST builders for this kind of stuff
ASTPtr query_ast = std::make_shared<ASTSelectQuery>();
auto * select_ast = query_ast->as<ASTSelectQuery>();
select_ast->setExpression(ASTSelectQuery::Expression::SELECT, std::make_shared<ASTExpressionList>());
auto expr_list = select_ast->select();
/// The first column is our filter expression.
/// the row_policy_filter_expression should be cloned, because it may be changed by TreeRewriter.
/// which make it possible an invalid expression, although it may be valid in whole select.
expr_list->children.push_back(row_policy_filter_expression->clone());
/// Keep columns that are required after the filter actions.
for (const auto & column_str : prerequisite_columns)
{
ParserExpression expr_parser;
/// We should add back quotes around column name as it can contain dots.
expr_list->children.push_back(parseQuery(
expr_parser,
backQuoteIfNeed(column_str),
0,
context->getSettingsRef()[Setting::max_parser_depth],
context->getSettingsRef()[Setting::max_parser_backtracks]));
}
select_ast->setExpression(ASTSelectQuery::Expression::TABLES, std::make_shared<ASTTablesInSelectQuery>());
auto tables = select_ast->tables();
auto tables_elem = std::make_shared<ASTTablesInSelectQueryElement>();
auto table_expr = std::make_shared<ASTTableExpression>();
tables->children.push_back(tables_elem);
tables_elem->table_expression = table_expr;
tables_elem->children.push_back(table_expr);
table_expr->database_and_table_name = std::make_shared<ASTTableIdentifier>(db_name, table_name);
table_expr->children.push_back(table_expr->database_and_table_name);
/// Using separate expression analyzer to prevent any possible alias injection
auto syntax_result = TreeRewriter(context).analyzeSelect(query_ast, TreeRewriterResult({}, storage, storage_snapshot));
SelectQueryExpressionAnalyzer analyzer(query_ast, syntax_result, context, metadata_snapshot, {}, false, {}, prepared_sets);
filter_info->actions = std::move(analyzer.simpleSelectActions()->dag);
filter_info->column_name = expr_list->children.at(0)->getColumnName();
filter_info->actions.removeUnusedActions(NameSet{filter_info->column_name});
for (const auto * node : filter_info->actions.getInputs())
filter_info->actions.getOutputs().push_back(node);
auto required_columns_from_filter = filter_info->actions.getRequiredColumns();
for (const auto & column : required_columns_from_filter)
{
if (prerequisite_columns.end() == std::find(prerequisite_columns.begin(), prerequisite_columns.end(), column.name))
prerequisite_columns.push_back(column.name);
}
return filter_info;
}
catch (Exception & e)
{
e.addMessage("While applying a row policy (see system.row_policies)");
throw;
}
InterpreterSelectQuery::InterpreterSelectQuery(
const ASTPtr & query_ptr_,
const ContextPtr & context_,
const SelectQueryOptions & options_,
const Names & required_result_column_names_)
: InterpreterSelectQuery(query_ptr_, context_, std::nullopt, nullptr, options_, required_result_column_names_)
{}
InterpreterSelectQuery::InterpreterSelectQuery(
const ASTPtr & query_ptr_,
const ContextMutablePtr & context_,
const SelectQueryOptions & options_,
const Names & required_result_column_names_)
: InterpreterSelectQuery(query_ptr_, context_, std::nullopt, nullptr, options_, required_result_column_names_)
{}
InterpreterSelectQuery::InterpreterSelectQuery(
const ASTPtr & query_ptr_,
const ContextPtr & context_,
Pipe input_pipe_,
const SelectQueryOptions & options_)
: InterpreterSelectQuery(query_ptr_, context_, std::move(input_pipe_), nullptr, options_.copy().noSubquery())
{}
InterpreterSelectQuery::InterpreterSelectQuery(
const ASTPtr & query_ptr_,
const ContextPtr & context_,
const StoragePtr & storage_,
const StorageMetadataPtr & metadata_snapshot_,
const SelectQueryOptions & options_)
: InterpreterSelectQuery(query_ptr_, context_, std::nullopt, storage_, options_.copy().noSubquery(), {}, metadata_snapshot_)
{}
InterpreterSelectQuery::InterpreterSelectQuery(
const ASTPtr & query_ptr_,
const ContextPtr & context_,
const SelectQueryOptions & options_,
PreparedSetsPtr prepared_sets_)
: InterpreterSelectQuery(query_ptr_, context_, std::nullopt, nullptr, options_, {}, {}, prepared_sets_)
{}
InterpreterSelectQuery::~InterpreterSelectQuery() = default;
namespace
{
/** There are no limits on the maximum size of the result for the subquery.
* Since the result of the query is not the result of the entire query.
*/
ContextPtr getSubqueryContext(const ContextPtr & context)
{
auto subquery_context = Context::createCopy(context);
Settings subquery_settings = context->getSettingsCopy();
subquery_settings[Setting::max_result_rows] = 0;
subquery_settings[Setting::max_result_bytes] = 0;
/// The calculation of extremes does not make sense and is not necessary (if you do it, then the extremes of the subquery can be taken for whole query).
subquery_settings[Setting::extremes] = false;
subquery_context->setSettings(subquery_settings);
return subquery_context;
}
void rewriteMultipleJoins(ASTPtr & query, const TablesWithColumns & tables, const String & database, const Settings & settings)
{
ASTSelectQuery & select = query->as<ASTSelectQuery &>();
Aliases aliases;
if (ASTPtr with = select.with())
QueryAliasesNoSubqueriesVisitor(aliases).visit(with);
QueryAliasesNoSubqueriesVisitor(aliases).visit(select.select());
CrossToInnerJoinVisitor::Data cross_to_inner{tables, aliases, database};
cross_to_inner.cross_to_inner_join_rewrite = static_cast<UInt8>(std::min<UInt64>(settings[Setting::cross_to_inner_join_rewrite], 2));
CrossToInnerJoinVisitor(cross_to_inner).visit(query);
JoinToSubqueryTransformVisitor::Data join_to_subs_data{tables, aliases};
join_to_subs_data.try_to_keep_original_names = settings[Setting::multiple_joins_try_to_keep_original_names];
JoinToSubqueryTransformVisitor(join_to_subs_data).visit(query);
}
/// Checks that the current user has the SELECT privilege.
void checkAccessRightsForSelect(
const ContextPtr & context,
const StorageID & table_id,
const StorageMetadataPtr & table_metadata,
const TreeRewriterResult & syntax_analyzer_result)
{
if (!syntax_analyzer_result.has_explicit_columns && table_metadata && !table_metadata->getColumns().empty())
{
/// For a trivial query like "SELECT count() FROM table" access is granted if at least
/// one column is accessible.
/// In this case just checking access for `required_columns` doesn't work correctly
/// because `required_columns` will contain the name of a column of minimum size (see TreeRewriterResult::collectUsedColumns())
/// which is probably not the same column as the column the current user has access to.
auto access = context->getAccess();
for (const auto & column : table_metadata->getColumns())
{
if (access->isGranted(AccessType::SELECT, table_id.database_name, table_id.table_name, column.name))
return;
}
throw Exception(
ErrorCodes::ACCESS_DENIED,
"{}: Not enough privileges. To execute this query, it's necessary to have the grant SELECT for at least one column on {}",
context->getUserName(),
table_id.getFullTableName());
}
/// General check.
context->checkAccess(AccessType::SELECT, table_id, syntax_analyzer_result.requiredSourceColumnsForAccessCheck());
}
ASTPtr parseAdditionalFilterConditionForTable(
const Map & additional_table_filters,
const DatabaseAndTableWithAlias & target,
const Context & context)
{
for (const auto & additional_filter : additional_table_filters)
{
const auto & tuple = additional_filter.safeGet<Tuple>();
const auto & table = tuple.at(0).safeGet<String>();
const auto & filter = tuple.at(1).safeGet<String>();
if (table == target.alias ||
(table == target.table && context.getCurrentDatabase() == target.database) ||
(table == target.database + '.' + target.table))
{
/// Try to parse expression
ParserExpression parser;
const auto & settings = context.getSettingsRef();
return parseQuery(
parser,
filter.data(),
filter.data() + filter.size(),
"additional filter",
settings[Setting::max_query_size],
settings[Setting::max_parser_depth],
settings[Setting::max_parser_backtracks]);
}
}
return nullptr;
}
/// Returns true if we should ignore quotas and limits for a specified table in the system database.
bool shouldIgnoreQuotaAndLimits(const StorageID & table_id)
{
if (table_id.database_name == DatabaseCatalog::SYSTEM_DATABASE)
{
static const boost::container::flat_set<String> tables_ignoring_quota{"quotas", "quota_limits", "quota_usage", "quotas_usage", "one"};
if (tables_ignoring_quota.count(table_id.table_name))
return true;
}
return false;
}
GroupingSetsParamsList getAggregatorGroupingSetsParams(const NamesAndTypesLists & aggregation_keys_list, const Names & all_keys)
{
GroupingSetsParamsList result;
for (const auto & aggregation_keys : aggregation_keys_list)
{
NameSet keys;
for (const auto & key : aggregation_keys)
keys.insert(key.name);
Names missing_keys;
for (const auto & key : all_keys)
if (!keys.contains(key))
missing_keys.push_back(key);
result.emplace_back(aggregation_keys.getNames(), std::move(missing_keys));
}
return result;
}
}
InterpreterSelectQuery::InterpreterSelectQuery(
const ASTPtr & query_ptr_,
const ContextPtr & context_,
std::optional<Pipe> input_pipe_,
const StoragePtr & storage_,
const SelectQueryOptions & options_,
const Names & required_result_column_names,
const StorageMetadataPtr & metadata_snapshot_,
PreparedSetsPtr prepared_sets_)
: InterpreterSelectQuery(
query_ptr_,
Context::createCopy(context_),
std::move(input_pipe_),
storage_,
options_,
required_result_column_names,
metadata_snapshot_,
prepared_sets_)
{}
InterpreterSelectQuery::InterpreterSelectQuery(
const ASTPtr & query_ptr_,
const ContextMutablePtr & context_,
std::optional<Pipe> input_pipe_,
const StoragePtr & storage_,
const SelectQueryOptions & options_,
const Names & required_result_column_names,
const StorageMetadataPtr & metadata_snapshot_,
PreparedSetsPtr prepared_sets_)
/// NOTE: the query almost always should be cloned because it will be modified during analysis.
: IInterpreterUnionOrSelectQuery(options_.modify_inplace ? query_ptr_ : query_ptr_->clone(), context_, options_)
, storage(storage_)
, input_pipe(std::move(input_pipe_))
, log(getLogger("InterpreterSelectQuery"))
, metadata_snapshot(metadata_snapshot_)
, prepared_sets(prepared_sets_)
{
checkStackSize();
if (!prepared_sets)
prepared_sets = std::make_shared<PreparedSets>();
query_info.is_internal = options.is_internal;
initSettings();
const Settings & settings = context->getSettingsRef();
if (settings[Setting::max_subquery_depth] && options.subquery_depth > settings[Setting::max_subquery_depth])
throw Exception(ErrorCodes::TOO_DEEP_SUBQUERIES, "Too deep subqueries. Maximum: {}", settings[Setting::max_subquery_depth].toString());
bool has_input = input_pipe != std::nullopt;
if (input_pipe)
{
/// Read from prepared input.
source_header = input_pipe->getHeader();
}
// Only propagate WITH elements to subqueries if we're not a subquery
if (!options.is_subquery)
{
if (context->getSettingsRef()[Setting::enable_global_with_statement])
ApplyWithAliasVisitor::visit(query_ptr);
ApplyWithSubqueryVisitor(context).visit(query_ptr);
}
query_info.query = query_ptr->clone();
if (settings[Setting::count_distinct_optimization])
{
RewriteCountDistinctFunctionMatcher::Data data_rewrite_countdistinct;
RewriteCountDistinctFunctionVisitor(data_rewrite_countdistinct).visit(query_ptr);
}
if (settings[Setting::optimize_uniq_to_count])
{
RewriteUniqToCountMatcher::Data data_rewrite_uniq_count;
RewriteUniqToCountVisitor(data_rewrite_uniq_count).visit(query_ptr);
}
JoinedTables joined_tables(getSubqueryContext(context), getSelectQuery(), options.with_all_cols, options_.is_create_parameterized_view);
bool got_storage_from_query = false;
if (!has_input && !storage)
{
storage = joined_tables.getLeftTableStorage();
// Mark uses_view_source if the returned storage is the same as the one saved in viewSource
uses_view_source |= storage && storage == context->getViewSource();
got_storage_from_query = true;
}
if (storage)
{
if (storage->hasExternalDynamicMetadata())
{
storage->updateExternalDynamicMetadata(context);
metadata_snapshot = storage->getInMemoryMetadataPtr();
}
table_lock = storage->lockForShare(context->getInitialQueryId(), context->getSettingsRef()[Setting::lock_acquire_timeout]);
table_id = storage->getStorageID();
if (!metadata_snapshot)
metadata_snapshot = storage->getInMemoryMetadataPtr();
if (options.only_analyze)
storage_snapshot = storage->getStorageSnapshotWithoutData(metadata_snapshot, context);
else
storage_snapshot = storage->getStorageSnapshotForQuery(metadata_snapshot, query_ptr, context);
}
if (has_input || !joined_tables.resolveTables())
joined_tables.makeFakeTable(storage, metadata_snapshot, source_header);
if (context->getCurrentTransaction() && context->getSettingsRef()[Setting::throw_on_unsupported_query_inside_transaction])
{
if (storage)
checkStorageSupportsTransactionsIfNeeded(storage, context, /* is_readonly_query */ true);
for (const auto & table : joined_tables.tablesWithColumns())
{
if (table.table.table.empty())
continue;
auto maybe_storage = DatabaseCatalog::instance().tryGetTable({table.table.database, table.table.table}, context);
if (!maybe_storage)
continue;
checkStorageSupportsTransactionsIfNeeded(maybe_storage, context, /* is_readonly_query */ true);
}
}
/// Check support for JOIN for parallel replicas with custom key
if (joined_tables.tablesCount() > 1 && !settings[Setting::parallel_replicas_custom_key].value.empty())
{
LOG_DEBUG(log, "JOINs are not supported with parallel_replicas_custom_key. Query will be executed without using them.");
context->setSetting("parallel_replicas_custom_key", String{""});
}
/// Check support for FINAL for parallel replicas
bool is_query_with_final = isQueryWithFinal(query_info);
if (is_query_with_final && context->canUseTaskBasedParallelReplicas())
{
if (settings[Setting::allow_experimental_parallel_reading_from_replicas] == 1)
{
LOG_DEBUG(log, "FINAL modifier is not supported with parallel replicas. Query will be executed without using them.");
context->setSetting("allow_experimental_parallel_reading_from_replicas", Field(0));
}
else if (settings[Setting::allow_experimental_parallel_reading_from_replicas] >= 2)
{
throw Exception(ErrorCodes::SUPPORT_IS_DISABLED, "FINAL modifier is not supported with parallel replicas");
}
}
/// Check support for parallel replicas for non-replicated storage (plain MergeTree)
bool is_plain_merge_tree = storage && storage->isMergeTree() && !storage->supportsReplication();
if (is_plain_merge_tree && settings[Setting::allow_experimental_parallel_reading_from_replicas] > 0
&& !settings[Setting::parallel_replicas_for_non_replicated_merge_tree])
{
if (settings[Setting::allow_experimental_parallel_reading_from_replicas] == 1)
{
LOG_DEBUG(log, "To use parallel replicas with plain MergeTree tables please enable setting `parallel_replicas_for_non_replicated_merge_tree`. For now query will be executed without using them.");
context->setSetting("allow_experimental_parallel_reading_from_replicas", Field(0));
}
else if (settings[Setting::allow_experimental_parallel_reading_from_replicas] >= 2)
{
throw Exception(ErrorCodes::SUPPORT_IS_DISABLED, "To use parallel replicas with plain MergeTree tables please enable setting `parallel_replicas_for_non_replicated_merge_tree`");
}
}
/// Rewrite JOINs
if (!has_input && joined_tables.tablesCount() > 1)
{
rewriteMultipleJoins(query_ptr, joined_tables.tablesWithColumns(), context->getCurrentDatabase(), context->getSettingsRef());
joined_tables.reset(getSelectQuery());
joined_tables.resolveTables();
if (auto view_source = context->getViewSource())
{
// If we are using a virtual block view to replace a table and that table is used
// inside the JOIN then we need to update uses_view_source accordingly so we avoid propagating scalars that we can't cache
const auto & storage_values = static_cast<const StorageValues &>(*view_source);
auto tmp_table_id = storage_values.getStorageID();
for (const auto & t : joined_tables.tablesWithColumns())
uses_view_source |= (t.table.database == tmp_table_id.database_name && t.table.table == tmp_table_id.table_name);
}
if (storage && joined_tables.isLeftTableSubquery())
{
/// Rewritten with subquery. Free storage locks here.
storage = nullptr;
table_lock.reset();
table_id = StorageID::createEmpty();
metadata_snapshot = nullptr;
storage_snapshot = nullptr;
}
}
if (!has_input)
{
interpreter_subquery = joined_tables.makeLeftTableSubquery(options.subquery());
if (interpreter_subquery)
{
source_header = interpreter_subquery->getSampleBlock();
uses_view_source |= interpreter_subquery->usesViewSource();
}
}
joined_tables.rewriteDistributedInAndJoins(query_ptr);
max_streams = settings[Setting::max_threads];
ASTSelectQuery & query = getSelectQuery();
std::shared_ptr<TableJoin> table_join = joined_tables.makeTableJoin(query);
if (storage)
row_policy_filter = context->getRowPolicyFilter(table_id.getDatabaseName(), table_id.getTableName(), RowPolicyFilterType::SELECT_FILTER);
StorageView * view = nullptr;
if (storage)
view = dynamic_cast<StorageView *>(storage.get());
if (!settings[Setting::additional_table_filters].value.empty() && storage && !joined_tables.tablesWithColumns().empty())
query_info.additional_filter_ast = parseAdditionalFilterConditionForTable(
settings[Setting::additional_table_filters], joined_tables.tablesWithColumns().front().table, *context);
ASTPtr parallel_replicas_custom_filter_ast = nullptr;
if (storage && context->canUseParallelReplicasCustomKey() && !joined_tables.tablesWithColumns().empty())
{
if (settings[Setting::parallel_replicas_count] > 1)
{
if (auto custom_key_ast = parseCustomKeyForTable(settings[Setting::parallel_replicas_custom_key], *context))
{
LOG_TRACE(log, "Processing query on a replica using custom_key '{}'", settings[Setting::parallel_replicas_custom_key].value);
parallel_replicas_custom_filter_ast = getCustomKeyFilterForParallelReplica(
settings[Setting::parallel_replicas_count],
settings[Setting::parallel_replica_offset],
std::move(custom_key_ast),
{settings[Setting::parallel_replicas_mode],
settings[Setting::parallel_replicas_custom_key_range_lower],
settings[Setting::parallel_replicas_custom_key_range_upper]},
storage->getInMemoryMetadataPtr()->columns,
context);
}
else if (settings[Setting::parallel_replica_offset] > 0)
{
throw Exception(
ErrorCodes::BAD_ARGUMENTS,
"Parallel replicas processing with custom_key has been requested "
"(setting 'max_parallel_replicas') but the table does not have custom_key defined for it "
"or it's invalid (settings `parallel_replicas_custom_key`)");
}
}
/// We disable prefer_localhost_replica because if one of the replicas is local it will create a single local plan
/// instead of executing the query with multiple replicas
/// We can enable this setting again for custom key parallel replicas when we can generate a plan that will use both a
/// local plan and remote replicas
else if (auto * distributed = dynamic_cast<StorageDistributed *>(storage.get());
distributed && context->canUseParallelReplicasCustomKeyForCluster(*distributed->getCluster()))
{
context->setSetting("distributed_group_by_no_merge", 2);
context->setSetting("prefer_localhost_replica", Field(0));
}
else if (
storage->isMergeTree() && (storage->supportsReplication() || settings[Setting::parallel_replicas_for_non_replicated_merge_tree])
&& context->getClientInfo().distributed_depth == 0
&& context->canUseParallelReplicasCustomKeyForCluster(*context->getClusterForParallelReplicas()))
{
context->setSetting("prefer_localhost_replica", Field(0));
}
}
if (autoFinalOnQuery(query))
{
query.setFinal();
}
auto analyze = [&] (bool try_move_to_prewhere)
{
/// Allow push down and other optimizations for VIEW: replace with subquery and rewrite it.
ASTPtr view_table;
if (view)
{
query_info.is_parameterized_view = view->isParameterizedView();
StorageView::replaceWithSubquery(getSelectQuery(), view_table, metadata_snapshot, view->isParameterizedView());
}
syntax_analyzer_result = TreeRewriter(context).analyzeSelect(
query_ptr,
TreeRewriterResult(source_header.getNamesAndTypesList(), storage, storage_snapshot),
options,
joined_tables.tablesWithColumns(),
required_result_column_names,
table_join);
query_info.syntax_analyzer_result = syntax_analyzer_result;
context->setDistributed(syntax_analyzer_result->is_remote_storage);
if (storage && !query.final() && storage->needRewriteQueryWithFinal(syntax_analyzer_result->requiredSourceColumns()))
query.setFinal();
if (view)
{
/// Restore original view name. Save rewritten subquery for future usage in StorageView.
query_info.view_query = StorageView::restoreViewName(getSelectQuery(), view_table);
view = nullptr;
}
if (try_move_to_prewhere
&& storage && storage->canMoveConditionsToPrewhere()
&& query.where() && !query.prewhere()
&& !query.hasJoin()) /// Join may produce rows with nulls or default values, it's difficult to analyze if they affected or not.
{
/// PREWHERE optimization: transfer some condition from WHERE to PREWHERE if enabled and viable
if (const auto & column_sizes = storage->getColumnSizes(); !column_sizes.empty())
{
/// Extract column compressed sizes.
std::unordered_map<std::string, UInt64> column_compressed_sizes;
for (const auto & [name, sizes] : column_sizes)
column_compressed_sizes[name] = sizes.data_compressed;
SelectQueryInfo current_info;
current_info.query = query_ptr;
current_info.syntax_analyzer_result = syntax_analyzer_result;
Names queried_columns = syntax_analyzer_result->requiredSourceColumns();
const auto & supported_prewhere_columns = storage->supportedPrewhereColumns();
MergeTreeWhereOptimizer where_optimizer{
std::move(column_compressed_sizes),
metadata_snapshot,
storage->getConditionSelectivityEstimatorByPredicate(storage_snapshot, nullptr, context),
queried_columns,
supported_prewhere_columns,
log};
where_optimizer.optimize(current_info, context);
}
}
if (query.prewhere() && query.where())
{
/// Filter block in WHERE instead to get better performance
query.setExpression(
ASTSelectQuery::Expression::WHERE, makeASTFunction("and", query.prewhere()->clone(), query.where()->clone()));
}
query_analyzer = std::make_unique<SelectQueryExpressionAnalyzer>(
query_ptr,
syntax_analyzer_result,
context,
metadata_snapshot,
required_result_column_names,
!options.only_analyze,
options,
prepared_sets);
if (!options.only_analyze)
{
if (query.sampleSize() && (input_pipe || !storage || !storage->supportsSampling()))
{
if (storage)
throw Exception(
ErrorCodes::SAMPLING_NOT_SUPPORTED,
"Storage {} doesn't support sampling",
storage->getStorageID().getNameForLogs());
throw Exception(
ErrorCodes::SAMPLING_NOT_SUPPORTED, "Illegal SAMPLE: sampling is only allowed with the table engines that support it");
}
if (query.final() && (input_pipe || !storage || !storage->supportsFinal()))
{
if (!input_pipe && storage)
throw Exception(ErrorCodes::ILLEGAL_FINAL, "Storage {} doesn't support FINAL", storage->getName());
throw Exception(ErrorCodes::ILLEGAL_FINAL, "Illegal FINAL");
}
if (query.prewhere() && (input_pipe || !storage || !storage->supportsPrewhere()))
{
if (!input_pipe && storage)
throw Exception(ErrorCodes::ILLEGAL_PREWHERE, "Storage {} doesn't support PREWHERE", storage->getName());
throw Exception(ErrorCodes::ILLEGAL_PREWHERE, "Illegal PREWHERE");
}
/// Save the new temporary tables in the query context
for (const auto & it : query_analyzer->getExternalTables())
if (!context->tryResolveStorageID({"", it.first}, Context::ResolveExternal))
context->addExternalTable(it.first, std::move(*it.second));
}
if (!options.only_analyze || options.modify_inplace)
{
if (syntax_analyzer_result->rewrite_subqueries)
{
/// remake interpreter_subquery when PredicateOptimizer rewrites subqueries and main table is subquery
interpreter_subquery = joined_tables.makeLeftTableSubquery(options.subquery());
}
}
if (interpreter_subquery)
{
/// If there is an aggregation in the outer query, WITH TOTALS is ignored in the subquery.
if (query_analyzer->hasAggregation())
interpreter_subquery->ignoreWithTotals();
uses_view_source |= interpreter_subquery->usesViewSource();
}
required_columns = syntax_analyzer_result->requiredSourceColumns();
if (storage)
{
query_info.filter_asts.clear();
/// Fix source_header for filter actions.
if (row_policy_filter && !row_policy_filter->empty())
{
row_policy_info = generateFilterActions(
table_id, row_policy_filter->expression, context, storage, storage_snapshot, metadata_snapshot, required_columns,
prepared_sets);
query_info.filter_asts.push_back(row_policy_filter->expression);
}
if (query_info.additional_filter_ast)
{
additional_filter_info = generateFilterActions(
table_id, query_info.additional_filter_ast, context, storage, storage_snapshot, metadata_snapshot, required_columns,
prepared_sets);
additional_filter_info->do_remove_column = true;
query_info.filter_asts.push_back(query_info.additional_filter_ast);
}
if (parallel_replicas_custom_filter_ast)
{
parallel_replicas_custom_filter_info = generateFilterActions(
table_id, parallel_replicas_custom_filter_ast, context, storage, storage_snapshot, metadata_snapshot, required_columns,
prepared_sets);
parallel_replicas_custom_filter_info->do_remove_column = true;
query_info.filter_asts.push_back(parallel_replicas_custom_filter_ast);
}
source_header = storage_snapshot->getSampleBlockForColumns(required_columns);
}
/// Calculate structure of the result.
result_header = getSampleBlockImpl();
};
/// This is a hack to make sure we reanalyze if GlobalSubqueriesVisitor changed allow_experimental_parallel_reading_from_replicas
/// inside the query context (because it doesn't have write access to the main context)
UInt64 parallel_replicas_before_analysis
= context->hasQueryContext() ? context->getQueryContext()->getSettingsRef()[Setting::allow_experimental_parallel_reading_from_replicas] : 0;
/// Conditionally support AST-based PREWHERE optimization.
analyze(shouldMoveToPrewhere() && (!settings[Setting::query_plan_optimize_prewhere] || !settings[Setting::query_plan_enable_optimizations]));
bool need_analyze_again = false;
bool can_analyze_again = false;
if (context->hasQueryContext())
{
/// As this query can't be executed with parallel replicas, we must reanalyze it
if (context->getQueryContext()->getSettingsRef()[Setting::allow_experimental_parallel_reading_from_replicas]
!= parallel_replicas_before_analysis)
{
context->setSetting("allow_experimental_parallel_reading_from_replicas", Field(0));
context->setSetting("max_parallel_replicas", UInt64{1});
need_analyze_again = true;
}
/// Check number of calls of 'analyze' function.
/// If it is too big, we will not analyze the query again not to have exponential blowup.
std::atomic<size_t> & current_query_analyze_count = context->getQueryContext()->kitchen_sink.analyze_counter;
++current_query_analyze_count;
can_analyze_again = settings[Setting::max_analyze_depth] == 0 || current_query_analyze_count < settings[Setting::max_analyze_depth];
}
if (can_analyze_again && (analysis_result.prewhere_constant_filter_description.always_false ||
analysis_result.prewhere_constant_filter_description.always_true))
{
if (analysis_result.prewhere_constant_filter_description.always_true)
query.setExpression(ASTSelectQuery::Expression::PREWHERE, {});
else
query.setExpression(ASTSelectQuery::Expression::PREWHERE, std::make_shared<ASTLiteral>(0u));
need_analyze_again = true;
}
if (can_analyze_again && (analysis_result.where_constant_filter_description.always_false ||
analysis_result.where_constant_filter_description.always_true))
{
if (analysis_result.where_constant_filter_description.always_true)
query.setExpression(ASTSelectQuery::Expression::WHERE, {});
else
query.setExpression(ASTSelectQuery::Expression::WHERE, std::make_shared<ASTLiteral>(0u));
need_analyze_again = true;
}
if (can_analyze_again)
need_analyze_again |= adjustParallelReplicasAfterAnalysis();
if (need_analyze_again)
{
size_t current_query_analyze_count = context->getQueryContext()->kitchen_sink.analyze_counter.load();
LOG_TRACE(log, "Running 'analyze' second time (current analyze depth: {})", current_query_analyze_count);
/// Reuse already built sets for multiple passes of analysis
prepared_sets = query_analyzer->getPreparedSets();
/// Do not try move conditions to PREWHERE for the second time.
/// Otherwise, we won't be able to fallback from inefficient PREWHERE to WHERE later.
analyze(/* try_move_to_prewhere = */ false);
}
/// If there is no WHERE, filter blocks as usual
if (query.prewhere() && !query.where())
analysis_result.prewhere_info->need_filter = true;
if (table_id && got_storage_from_query && !joined_tables.isLeftTableFunction() && !options.ignore_access_check)
{
/// The current user should have the SELECT privilege. If this table_id is for a table
/// function we don't check access rights here because in this case they have been already
/// checked in ITableFunction::execute().
checkAccessRightsForSelect(context, table_id, metadata_snapshot, *syntax_analyzer_result);