forked from ClickHouse/ClickHouse
-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathQueryAnalyzer.cpp
More file actions
5148 lines (4330 loc) · 235 KB
/
QueryAnalyzer.cpp
File metadata and controls
5148 lines (4330 loc) · 235 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 <Analyzer/Utils.h>
#include <Analyzer/SetUtils.h>
#include <Analyzer/AggregationUtils.h>
#include <Analyzer/WindowFunctionsUtils.h>
#include <Analyzer/ValidationUtils.h>
#include <Analyzer/HashUtils.h>
#include <Analyzer/IdentifierNode.h>
#include <Analyzer/MatcherNode.h>
#include <Analyzer/ColumnTransformers.h>
#include <Analyzer/ConstantNode.h>
#include <Analyzer/ColumnNode.h>
#include <Analyzer/FunctionNode.h>
#include <Analyzer/LambdaNode.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/ArrayJoinNode.h>
#include <Analyzer/JoinNode.h>
#include <Analyzer/UnionNode.h>
#include <Analyzer/QueryTreeBuilder.h>
#include <Analyzer/RecursiveCTE.h>
#include <Analyzer/QueryTreePassManager.h>
#include <Analyzer/Resolve/CorrelatedColumnsCollector.h>
#include <Analyzer/Resolve/IdentifierResolveScope.h>
#include <Analyzer/Resolve/QueryAnalyzer.h>
#include <Analyzer/Resolve/QueryExpressionsAliasVisitor.h>
#include <Analyzer/Resolve/ReplaceColumnsVisitor.h>
#include <Analyzer/Resolve/TableExpressionsAliasVisitor.h>
#include <Analyzer/Resolve/TableFunctionsWithClusterAlternativesVisitor.h>
#include <Analyzer/Resolve/TypoCorrection.h>
#include <Common/FieldVisitorToString.h>
#include <Common/quoteString.h>
#include <Core/Settings.h>
#include <DataTypes/DataTypesNumber.h>
#include <DataTypes/DataTypeTuple.h>
#include <DataTypes/DataTypeArray.h>
#include <DataTypes/DataTypeMap.h>
#include <DataTypes/getLeastSupertype.h>
#include <Functions/FunctionFactory.h>
#include <Functions/IFunctionAdaptors.h>
#include <Functions/UserDefined/UserDefinedExecutableFunctionFactory.h>
#include <Functions/UserDefined/UserDefinedSQLFunctionFactory.h>
#include <Formats/FormatFactory.h>
#include <Interpreters/convertFieldToType.h>
#include <TableFunctions/TableFunctionFactory.h>
#include <Storages/IStorage.h>
#include <base/Decimal_fwd.h>
#include <base/types.h>
#include <boost/algorithm/string/predicate.hpp>
#include <ranges>
namespace DB
{
namespace Setting
{
extern const SettingsBool aggregate_functions_null_for_empty;
extern const SettingsBool analyzer_compatibility_join_using_top_level_identifier;
extern const SettingsBool asterisk_include_alias_columns;
extern const SettingsBool asterisk_include_materialized_columns;
extern const SettingsString count_distinct_implementation;
extern const SettingsBool enable_global_with_statement;
extern const SettingsBool enable_scopes_for_with_statement;
extern const SettingsBool enable_order_by_all;
extern const SettingsBool enable_positional_arguments;
extern const SettingsBool joined_subquery_requires_alias;
extern const SettingsUInt64 max_expanded_ast_elements;
extern const SettingsUInt64 max_subquery_depth;
extern const SettingsBool prefer_column_name_to_alias;
extern const SettingsBool rewrite_count_distinct_if_with_count_distinct_implementation;
extern const SettingsBool single_join_prefer_left_table;
extern const SettingsUInt64 use_structure_from_insertion_table_in_table_functions;
extern const SettingsBool allow_suspicious_types_in_group_by;
extern const SettingsBool allow_suspicious_types_in_order_by;
extern const SettingsBool allow_experimental_correlated_subqueries;
extern const SettingsString implicit_table_at_top_level;
}
namespace ErrorCodes
{
extern const int UNSUPPORTED_METHOD;
extern const int UNKNOWN_IDENTIFIER;
extern const int UNKNOWN_FUNCTION;
extern const int LOGICAL_ERROR;
extern const int BAD_ARGUMENTS;
extern const int ILLEGAL_TYPE_OF_ARGUMENT;
extern const int MULTIPLE_EXPRESSIONS_FOR_ALIAS;
extern const int TYPE_MISMATCH;
extern const int INVALID_WITH_FILL_EXPRESSION;
extern const int INVALID_LIMIT_EXPRESSION;
extern const int EMPTY_LIST_OF_COLUMNS_QUERIED;
extern const int TOO_DEEP_SUBQUERIES;
extern const int ILLEGAL_FINAL;
extern const int SAMPLING_NOT_SUPPORTED;
extern const int NO_COMMON_TYPE;
extern const int NOT_IMPLEMENTED;
extern const int ALIAS_REQUIRED;
extern const int NUMBER_OF_ARGUMENTS_DOESNT_MATCH;
extern const int UNKNOWN_TABLE;
extern const int ILLEGAL_COLUMN;
extern const int NUMBER_OF_COLUMNS_DOESNT_MATCH;
extern const int UNEXPECTED_EXPRESSION;
extern const int SYNTAX_ERROR;
}
QueryAnalyzer::QueryAnalyzer(bool only_analyze_)
: identifier_resolver(node_to_projection_name)
, only_analyze(only_analyze_)
{}
QueryAnalyzer::~QueryAnalyzer() = default;
void QueryAnalyzer::resolve(QueryTreeNodePtr & node, const QueryTreeNodePtr & table_expression, ContextPtr context)
{
IdentifierResolveScope & scope = createIdentifierResolveScope(node, /*parent_scope=*/ nullptr);
if (!scope.context)
scope.context = context;
auto node_type = node->getNodeType();
switch (node_type)
{
case QueryTreeNodeType::QUERY:
{
if (table_expression)
throw Exception(ErrorCodes::LOGICAL_ERROR,
"For query analysis table expression must be empty");
resolveQuery(node, scope);
break;
}
case QueryTreeNodeType::UNION:
{
if (table_expression)
throw Exception(ErrorCodes::LOGICAL_ERROR,
"For union analysis table expression must be empty");
resolveUnion(node, scope);
break;
}
case QueryTreeNodeType::IDENTIFIER:
[[fallthrough]];
case QueryTreeNodeType::CONSTANT:
[[fallthrough]];
case QueryTreeNodeType::COLUMN:
[[fallthrough]];
case QueryTreeNodeType::FUNCTION:
[[fallthrough]];
case QueryTreeNodeType::LIST:
{
if (table_expression)
{
scope.expression_join_tree_node = table_expression;
scope.registered_table_expression_nodes.insert(table_expression);
validateTableExpressionModifiers(scope.expression_join_tree_node, scope);
initializeTableExpressionData(scope.expression_join_tree_node, scope);
}
if (node_type == QueryTreeNodeType::LIST)
{
QueryExpressionsAliasVisitor visitor(scope.aliases);
visitor.visit(node);
resolveExpressionNodeList(node, scope, false /*allow_lambda_expression*/, false /*allow_table_expression*/);
}
else
resolveExpressionNode(node, scope, false /*allow_lambda_expression*/, false /*allow_table_expression*/);
break;
}
case QueryTreeNodeType::TABLE_FUNCTION:
{
QueryExpressionsAliasVisitor expressions_alias_visitor(scope.aliases);
resolveTableFunction(node, scope, expressions_alias_visitor, false /*nested_table_function*/);
break;
}
default:
{
throw Exception(ErrorCodes::BAD_ARGUMENTS,
"Node {} with type {} is not supported by query analyzer. "
"Supported nodes are query, union, identifier, constant, column, function, list.",
node->formatASTForErrorMessage(),
node->getNodeTypeName());
}
}
validateCorrelatedSubqueries(node);
}
void QueryAnalyzer::resolveConstantExpression(QueryTreeNodePtr & node, const QueryTreeNodePtr & table_expression, ContextPtr context)
{
IdentifierResolveScope & scope = createIdentifierResolveScope(node, /*parent_scope=*/ nullptr);
if (!scope.context)
scope.context = context;
auto node_type = node->getNodeType();
if (node_type == QueryTreeNodeType::QUERY || node_type == QueryTreeNodeType::UNION)
{
evaluateScalarSubqueryIfNeeded(node, scope);
return;
}
if (table_expression)
{
scope.expression_join_tree_node = table_expression;
scope.registered_table_expression_nodes.insert(table_expression);
validateTableExpressionModifiers(scope.expression_join_tree_node, scope);
initializeTableExpressionData(scope.expression_join_tree_node, scope);
}
if (node_type == QueryTreeNodeType::LIST)
resolveExpressionNodeList(node, scope, false /*allow_lambda_expression*/, false /*allow_table_expression*/);
else
resolveExpressionNode(node, scope, false /*allow_lambda_expression*/, false /*allow_table_expression*/);
validateCorrelatedSubqueries(node);
}
bool isFromJoinTree(const IQueryTreeNode * node_source, const IQueryTreeNode * tree_node)
{
if (node_source == tree_node)
return true;
std::stack<const IQueryTreeNode *> stack;
stack.push(tree_node);
while (!stack.empty())
{
const auto * current = stack.top();
stack.pop();
if (node_source == current)
return true;
if (const auto * child_join_node = current->as<JoinNode>())
{
stack.push(child_join_node->getLeftTableExpression().get());
stack.push(child_join_node->getRightTableExpression().get());
}
if (const auto * child_join_node = current->as<CrossJoinNode>())
{
stack.push_range(child_join_node->getTableExpressions() | std::views::transform(&QueryTreeNodePtr::get));
}
}
return false;
}
std::optional<JoinTableSide> QueryAnalyzer::getColumnSideFromJoinTree(const QueryTreeNodePtr & resolved_identifier, const JoinNode & join_node)
{
if (resolved_identifier->getNodeType() == QueryTreeNodeType::CONSTANT)
return {};
if (resolved_identifier->getNodeType() == QueryTreeNodeType::FUNCTION)
{
const auto & resolved_function = resolved_identifier->as<FunctionNode &>();
const auto & argument_nodes = resolved_function.getArguments().getNodes();
std::optional<JoinTableSide> result;
for (const auto & argument_node : argument_nodes)
{
auto table_side = getColumnSideFromJoinTree(argument_node, join_node);
if (table_side && result && *table_side != *result)
return {};
result = table_side;
}
return result;
}
const auto * column_src = resolved_identifier->as<ColumnNode &>().getColumnSource().get();
if (isFromJoinTree(column_src, join_node.getLeftTableExpression().get()))
return JoinTableSide::Left;
if (isFromJoinTree(column_src, join_node.getRightTableExpression().get()))
return JoinTableSide::Right;
return {};
}
IdentifierResolveScope & QueryAnalyzer::createIdentifierResolveScope(const QueryTreeNodePtr & scope_node, IdentifierResolveScope * parent_scope)
{
auto [it, _] = node_to_scope_map.emplace(scope_node, IdentifierResolveScope{scope_node, parent_scope});
return it->second;
}
ProjectionName QueryAnalyzer::calculateFunctionProjectionName(const QueryTreeNodePtr & function_node, const ProjectionNames & parameters_projection_names,
const ProjectionNames & arguments_projection_names)
{
const auto & function_node_typed = function_node->as<FunctionNode &>();
const auto & function_node_name = function_node_typed.getFunctionName();
bool is_array_function = function_node_name == "array";
bool is_tuple_function = function_node_name == "tuple";
WriteBufferFromOwnString buffer;
if (!is_array_function && !is_tuple_function)
buffer << function_node_name;
if (!parameters_projection_names.empty())
{
buffer << '(';
size_t function_parameters_projection_names_size = parameters_projection_names.size();
for (size_t i = 0; i < function_parameters_projection_names_size; ++i)
{
buffer << parameters_projection_names[i];
if (i + 1 != function_parameters_projection_names_size)
buffer << ", ";
}
buffer << ')';
}
char open_bracket = '(';
char close_bracket = ')';
if (is_array_function)
{
open_bracket = '[';
close_bracket = ']';
}
buffer << open_bracket;
size_t function_arguments_projection_names_size = arguments_projection_names.size();
for (size_t i = 0; i < function_arguments_projection_names_size; ++i)
{
buffer << arguments_projection_names[i];
if (i + 1 != function_arguments_projection_names_size)
buffer << ", ";
}
buffer << close_bracket;
return buffer.str();
}
ProjectionName QueryAnalyzer::calculateWindowProjectionName(const QueryTreeNodePtr & window_node,
const QueryTreeNodePtr & parent_window_node,
const String & parent_window_name,
const ProjectionNames & partition_by_projection_names,
const ProjectionNames & order_by_projection_names,
const ProjectionName & frame_begin_offset_projection_name,
const ProjectionName & frame_end_offset_projection_name)
{
const auto & window_node_typed = window_node->as<WindowNode &>();
const auto & window_frame = window_node_typed.getWindowFrame();
bool parent_window_node_has_partition_by = false;
bool parent_window_node_has_order_by = false;
if (parent_window_node)
{
const auto & parent_window_node_typed = parent_window_node->as<WindowNode &>();
parent_window_node_has_partition_by = parent_window_node_typed.hasPartitionBy();
parent_window_node_has_order_by = parent_window_node_typed.hasOrderBy();
}
WriteBufferFromOwnString buffer;
if (!parent_window_name.empty())
buffer << parent_window_name;
if (!partition_by_projection_names.empty() && !parent_window_node_has_partition_by)
{
if (!parent_window_name.empty())
buffer << ' ';
buffer << "PARTITION BY ";
size_t partition_by_projection_names_size = partition_by_projection_names.size();
for (size_t i = 0; i < partition_by_projection_names_size; ++i)
{
buffer << partition_by_projection_names[i];
if (i + 1 != partition_by_projection_names_size)
buffer << ", ";
}
}
if (!order_by_projection_names.empty() && !parent_window_node_has_order_by)
{
if (!partition_by_projection_names.empty() || !parent_window_name.empty())
buffer << ' ';
buffer << "ORDER BY ";
size_t order_by_projection_names_size = order_by_projection_names.size();
for (size_t i = 0; i < order_by_projection_names_size; ++i)
{
buffer << order_by_projection_names[i];
if (i + 1 != order_by_projection_names_size)
buffer << ", ";
}
}
if (!window_frame.is_default)
{
if (!partition_by_projection_names.empty() || !order_by_projection_names.empty() || !parent_window_name.empty())
buffer << ' ';
buffer << window_frame.type << " BETWEEN ";
if (window_frame.begin_type == WindowFrame::BoundaryType::Current)
{
buffer << "CURRENT ROW";
}
else if (window_frame.begin_type == WindowFrame::BoundaryType::Unbounded)
{
buffer << "UNBOUNDED";
buffer << " " << (window_frame.begin_preceding ? "PRECEDING" : "FOLLOWING");
}
else
{
buffer << frame_begin_offset_projection_name;
buffer << " " << (window_frame.begin_preceding ? "PRECEDING" : "FOLLOWING");
}
buffer << " AND ";
if (window_frame.end_type == WindowFrame::BoundaryType::Current)
{
buffer << "CURRENT ROW";
}
else if (window_frame.end_type == WindowFrame::BoundaryType::Unbounded)
{
buffer << "UNBOUNDED";
buffer << " " << (window_frame.end_preceding ? "PRECEDING" : "FOLLOWING");
}
else
{
buffer << frame_end_offset_projection_name;
buffer << " " << (window_frame.end_preceding ? "PRECEDING" : "FOLLOWING");
}
}
return buffer.str();
}
ProjectionName QueryAnalyzer::calculateSortColumnProjectionName(
const QueryTreeNodePtr & sort_column_node,
const ProjectionName & sort_expression_projection_name,
const ProjectionName & fill_from_expression_projection_name,
const ProjectionName & fill_to_expression_projection_name,
const ProjectionName & fill_step_expression_projection_name,
const ProjectionName & fill_staleness_expression_projection_name)
{
auto & sort_node_typed = sort_column_node->as<SortNode &>();
WriteBufferFromOwnString sort_column_projection_name_buffer;
sort_column_projection_name_buffer << sort_expression_projection_name;
auto sort_direction = sort_node_typed.getSortDirection();
sort_column_projection_name_buffer << (sort_direction == SortDirection::ASCENDING ? " ASC" : " DESC");
auto nulls_sort_direction = sort_node_typed.getNullsSortDirection();
if (nulls_sort_direction)
sort_column_projection_name_buffer << " NULLS " << (nulls_sort_direction == sort_direction ? "LAST" : "FIRST");
if (auto collator = sort_node_typed.getCollator())
sort_column_projection_name_buffer << " COLLATE " << collator->getLocale();
if (sort_node_typed.withFill())
{
sort_column_projection_name_buffer << " WITH FILL";
if (sort_node_typed.hasFillFrom())
sort_column_projection_name_buffer << " FROM " << fill_from_expression_projection_name;
if (sort_node_typed.hasFillTo())
sort_column_projection_name_buffer << " TO " << fill_to_expression_projection_name;
if (sort_node_typed.hasFillStep())
sort_column_projection_name_buffer << " STEP " << fill_step_expression_projection_name;
if (sort_node_typed.hasFillStaleness())
sort_column_projection_name_buffer << " STALENESS " << fill_staleness_expression_projection_name;
}
return sort_column_projection_name_buffer.str();
}
/** Try to get lambda node from sql user defined functions if sql user defined function with function name exists.
* Returns lambda node if function exists, nullptr otherwise.
*/
QueryTreeNodePtr QueryAnalyzer::tryGetLambdaFromSQLUserDefinedFunctions(const std::string & function_name, ContextPtr context)
{
auto user_defined_function = UserDefinedSQLFunctionFactory::instance().tryGet(function_name);
if (!user_defined_function)
return {};
auto it = function_name_to_user_defined_lambda.find(function_name);
if (it != function_name_to_user_defined_lambda.end())
return it->second;
const auto & create_function_query = user_defined_function->as<ASTCreateFunctionQuery>();
auto result_node = buildQueryTree(create_function_query->function_core, context);
if (result_node->getNodeType() != QueryTreeNodeType::LAMBDA)
throw Exception(ErrorCodes::LOGICAL_ERROR,
"SQL user defined function {} must represent lambda expression. Actual: {}",
function_name,
create_function_query->function_core->formatForErrorMessage());
function_name_to_user_defined_lambda.emplace(function_name, result_node);
return result_node;
}
void QueryAnalyzer::mergeWindowWithParentWindow(const QueryTreeNodePtr & window_node, const QueryTreeNodePtr & parent_window_node, IdentifierResolveScope & scope)
{
auto & window_node_typed = window_node->as<WindowNode &>();
auto parent_window_name = window_node_typed.getParentWindowName();
auto & parent_window_node_typed = parent_window_node->as<WindowNode &>();
/** If an existing_window_name is specified it must refer to an earlier
* entry in the WINDOW list; the new window copies its partitioning clause
* from that entry, as well as its ordering clause if any. In this case
* the new window cannot specify its own PARTITION BY clause, and it can
* specify ORDER BY only if the copied window does not have one. The new
* window always uses its own frame clause; the copied window must not
* specify a frame clause.
* https://www.postgresql.org/docs/current/sql-select.html
*/
if (window_node_typed.hasPartitionBy())
{
throw Exception(ErrorCodes::BAD_ARGUMENTS,
"Derived window definition '{}' is not allowed to override PARTITION BY. In scope {}",
window_node_typed.formatASTForErrorMessage(),
scope.scope_node->formatASTForErrorMessage());
}
if (window_node_typed.hasOrderBy() && parent_window_node_typed.hasOrderBy())
{
throw Exception(ErrorCodes::BAD_ARGUMENTS,
"Derived window definition '{}' is not allowed to override a non-empty ORDER BY. In scope {}",
window_node_typed.formatASTForErrorMessage(),
scope.scope_node->formatASTForErrorMessage());
}
if (!parent_window_node_typed.getWindowFrame().is_default)
{
throw Exception(ErrorCodes::BAD_ARGUMENTS,
"Parent window '{}' is not allowed to define a frame: while processing derived window definition '{}'. In scope {}",
parent_window_name,
window_node_typed.formatASTForErrorMessage(),
scope.scope_node->formatASTForErrorMessage());
}
window_node_typed.getPartitionByNode() = parent_window_node_typed.getPartitionBy().clone();
if (parent_window_node_typed.hasOrderBy())
window_node_typed.getOrderByNode() = parent_window_node_typed.getOrderBy().clone();
}
/** Replace nodes in node list with positional arguments.
*
* Example: SELECT id, value FROM test_table GROUP BY 1, 2;
* Example: SELECT id, value FROM test_table ORDER BY 1, 2;
* Example: SELECT id, value FROM test_table LIMIT 5 BY 1, 2;
*/
void QueryAnalyzer::replaceNodesWithPositionalArguments(QueryTreeNodePtr & node_list, const QueryTreeNodes & projection_nodes, IdentifierResolveScope & scope)
{
const auto & settings = scope.context->getSettingsRef();
if (!settings[Setting::enable_positional_arguments] || scope.context->getClientInfo().query_kind != ClientInfo::QueryKind::INITIAL_QUERY)
return;
auto & node_list_typed = node_list->as<ListNode &>();
for (auto & node : node_list_typed.getNodes())
{
auto * node_to_replace = &node;
if (auto * sort_node = node->as<SortNode>())
node_to_replace = &sort_node->getExpression();
auto * constant_node = (*node_to_replace)->as<ConstantNode>();
if (!constant_node
|| (constant_node->getValue().getType() != Field::Types::UInt64
&& constant_node->getValue().getType() != Field::Types::Int64))
continue;
UInt64 pos;
if (constant_node->getValue().getType() == Field::Types::UInt64)
{
pos = constant_node->getValue().safeGet<UInt64>();
}
else // Int64
{
auto value = constant_node->getValue().safeGet<Int64>();
if (value > 0)
pos = value;
else
{
if (value < -static_cast<Int64>(projection_nodes.size()))
throw Exception(
ErrorCodes::BAD_ARGUMENTS,
"Negative positional argument number {} is out of bounds. Expected in range [-{}, -1]. In scope {}",
value,
projection_nodes.size(),
scope.scope_node->formatASTForErrorMessage());
pos = projection_nodes.size() + value + 1;
}
}
if (!pos || pos > projection_nodes.size())
throw Exception(
ErrorCodes::BAD_ARGUMENTS,
"Positional argument number {} is out of bounds. Expected in range [1, {}]. In scope {}",
pos,
projection_nodes.size(),
scope.scope_node->formatASTForErrorMessage());
--pos;
*node_to_replace = projection_nodes[pos]->clone();
if (auto it = resolved_expressions.find(projection_nodes[pos]); it != resolved_expressions.end())
{
resolved_expressions[*node_to_replace] = it->second;
}
}
}
void QueryAnalyzer::convertLimitOffsetExpression(QueryTreeNodePtr & expression_node, const String & expression_description, IdentifierResolveScope & scope)
{
const auto * limit_offset_constant_node = expression_node->as<ConstantNode>();
if (!limit_offset_constant_node || !isNativeNumber(removeNullable(limit_offset_constant_node->getResultType())))
throw Exception(ErrorCodes::INVALID_LIMIT_EXPRESSION,
"{} expression must be constant with numeric type. Actual: {}. In scope {}",
expression_description,
expression_node->formatASTForErrorMessage(),
scope.scope_node->formatASTForErrorMessage());
// We support limit in the range [INT64_MIN, UINT64_MAX] for integral limit or (0, 1) for fractional limit
// Consider the nonnegative limit case first as they are more common
{
Field converted_value = convertFieldToType(limit_offset_constant_node->getValue(), DataTypeUInt64());
if (!converted_value.isNull())
{
auto result_constant_node = std::make_shared<ConstantNode>(std::move(converted_value), std::make_shared<DataTypeUInt64>());
result_constant_node->getSourceExpression() = limit_offset_constant_node->getSourceExpression();
expression_node = std::move(result_constant_node);
return;
}
}
// If we are here, then the number is either negative or outside the supported range or float
// Consider the negative limit value case
{
Field converted_value = convertFieldToType(limit_offset_constant_node->getValue(), DataTypeInt64());
if (!converted_value.isNull())
{
auto result_constant_node = std::make_shared<ConstantNode>(std::move(converted_value), std::make_shared<DataTypeInt64>());
result_constant_node->getSourceExpression() = limit_offset_constant_node->getSourceExpression();
expression_node = std::move(result_constant_node);
return;
}
}
{
Field converted_value = convertFieldToType(limit_offset_constant_node->getValue(), DataTypeFloat64());
if (!converted_value.isNull())
{
auto value = converted_value.safeGet<Float64>();
if (value < 1 && value > 0)
{
auto result_constant_node = std::make_shared<ConstantNode>(Field(value), std::make_shared<DataTypeFloat64>());
result_constant_node->getSourceExpression() = limit_offset_constant_node->getSourceExpression();
expression_node = std::move(result_constant_node);
return;
}
}
}
throw Exception(ErrorCodes::INVALID_LIMIT_EXPRESSION,
"The value {} of {} expression is not representable as UInt64 or Int64 or Float64 in the range (0, 1)",
applyVisitor(FieldVisitorToString(), limit_offset_constant_node->getValue()) , expression_description);
}
void QueryAnalyzer::validateTableExpressionModifiers(const QueryTreeNodePtr & table_expression_node, IdentifierResolveScope & scope)
{
auto * table_node = table_expression_node->as<TableNode>();
auto * table_function_node = table_expression_node->as<TableFunctionNode>();
auto * query_node = table_expression_node->as<QueryNode>();
auto * union_node = table_expression_node->as<UnionNode>();
if (!table_node && !table_function_node && !query_node && !union_node)
throw Exception(ErrorCodes::LOGICAL_ERROR,
"Unexpected table expression. Expected table, table function, query or union node. Table node: {}, scope node: {}",
table_expression_node->formatASTForErrorMessage(),
scope.scope_node->formatASTForErrorMessage());
if (table_node || table_function_node)
{
auto table_expression_modifiers = table_node ? table_node->getTableExpressionModifiers() : table_function_node->getTableExpressionModifiers();
if (table_expression_modifiers.has_value())
{
const auto & storage = table_node ? table_node->getStorage() : table_function_node->getStorage();
if (table_expression_modifiers->hasFinal() && !storage->supportsFinal())
throw Exception(ErrorCodes::ILLEGAL_FINAL,
"Storage {} doesn't support FINAL",
storage->getName());
if (table_expression_modifiers->hasSampleSizeRatio() && !storage->supportsSampling())
throw Exception(ErrorCodes::SAMPLING_NOT_SUPPORTED,
"Storage {} doesn't support sampling",
storage->getStorageID().getFullNameNotQuoted());
}
}
}
void QueryAnalyzer::validateJoinTableExpressionWithoutAlias(const QueryTreeNodePtr & join_node, const QueryTreeNodePtr & table_expression_node, IdentifierResolveScope & scope)
{
if (!scope.context->getSettingsRef()[Setting::joined_subquery_requires_alias])
return;
bool table_expression_has_alias = table_expression_node->hasAlias();
if (table_expression_has_alias)
return;
if (const auto * join = join_node->as<const JoinNode>(); join && join->getKind() == JoinKind::Paste)
return;
auto * query_node = table_expression_node->as<QueryNode>();
auto * union_node = table_expression_node->as<UnionNode>();
if ((query_node && !query_node->getCTEName().empty()) || (union_node && !union_node->getCTEName().empty()))
return;
auto table_expression_node_type = table_expression_node->getNodeType();
if (table_expression_node_type == QueryTreeNodeType::TABLE_FUNCTION ||
table_expression_node_type == QueryTreeNodeType::QUERY ||
table_expression_node_type == QueryTreeNodeType::UNION)
throw Exception(ErrorCodes::ALIAS_REQUIRED,
"JOIN {} no alias for subquery or table function {}. "
"In scope {} (set joined_subquery_requires_alias = 0 to disable restriction)",
join_node->formatASTForErrorMessage(),
table_expression_node->formatASTForErrorMessage(),
scope.scope_node->formatASTForErrorMessage());
}
std::pair<bool, UInt64> QueryAnalyzer::recursivelyCollectMaxOrdinaryExpressions(QueryTreeNodePtr & node, QueryTreeNodes & into)
{
checkStackSize();
if (node->as<ColumnNode>())
{
into.push_back(node);
return {false, 1};
}
auto * function = node->as<FunctionNode>();
if (!function)
return {false, 0};
// We don't need to have GROUPING under GROUP BY ALL, so we treat GROUPING
// as an aggregate function for GROUP BY ALL expansion
if (function->isAggregateFunction() || function->isWindowFunction() || Poco::icompare(function->getFunctionName(), "grouping") == 0)
return {true, 0};
UInt64 pushed_children = 0;
bool has_aggregate = false;
for (auto & child : function->getArguments().getNodes())
{
auto [child_has_aggregate, child_pushed_children] = recursivelyCollectMaxOrdinaryExpressions(child, into);
has_aggregate |= child_has_aggregate;
pushed_children += child_pushed_children;
}
/// The current function is not aggregate function and there is no aggregate function in its arguments,
/// so use the current function to replace its arguments
if (!has_aggregate)
{
for (UInt64 i = 0; i < pushed_children; i++)
into.pop_back();
into.push_back(node);
pushed_children = 1;
}
return {has_aggregate, pushed_children};
}
/** Expand GROUP BY ALL by extracting all the SELECT-ed expressions that are not aggregate functions.
*
* For a special case that if there is a function having both aggregate functions and other fields as its arguments,
* the `GROUP BY` keys will contain the maximum non-aggregate fields we can extract from it.
*
* Example:
* SELECT substring(a, 4, 2), substring(substring(a, 1, 2), 1, count(b)) FROM t GROUP BY ALL
* will expand as
* SELECT substring(a, 4, 2), substring(substring(a, 1, 2), 1, count(b)) FROM t GROUP BY substring(a, 4, 2), substring(a, 1, 2)
*/
void QueryAnalyzer::expandGroupByAll(QueryNode & query_tree_node_typed)
{
if (!query_tree_node_typed.isGroupByAll())
return;
auto & group_by_nodes = query_tree_node_typed.getGroupBy().getNodes();
auto & projection_list = query_tree_node_typed.getProjection();
for (auto & node : projection_list.getNodes())
recursivelyCollectMaxOrdinaryExpressions(node, group_by_nodes);
query_tree_node_typed.setIsGroupByAll(false);
}
void QueryAnalyzer::expandOrderByAll(QueryNode & query_tree_node_typed, const Settings & settings)
{
if (!settings[Setting::enable_order_by_all] || !query_tree_node_typed.isOrderByAll())
return;
auto * all_node = query_tree_node_typed.getOrderBy().getNodes()[0]->as<SortNode>();
if (!all_node)
throw Exception(ErrorCodes::LOGICAL_ERROR, "Select analyze for not sort node.");
auto & projection_nodes = query_tree_node_typed.getProjection().getNodes();
auto list_node = std::make_shared<ListNode>();
list_node->getNodes().reserve(projection_nodes.size());
for (auto & node : projection_nodes)
{
/// Detect and reject ambiguous statements:
/// E.g. for a table with columns "all", "a", "b":
/// - SELECT all, a, b ORDER BY all; -- should we sort by all columns in SELECT or by column "all"?
/// - SELECT a, b AS all ORDER BY all; -- like before but "all" as alias
/// - SELECT func(...) AS all ORDER BY all; -- like before but "all" as function
/// - SELECT a, b ORDER BY all; -- tricky in other way: does the user want to sort by columns in SELECT clause or by not SELECTed column "all"?
auto resolved_expression_it = resolved_expressions.find(node);
if (resolved_expression_it != resolved_expressions.end())
{
auto projection_names = resolved_expression_it->second;
if (projection_names.size() != 1)
throw Exception(ErrorCodes::LOGICAL_ERROR,
"Expression nodes list expected 1 projection names. Actual: {}",
projection_names.size());
if (boost::iequals(projection_names[0], "all"))
throw Exception(ErrorCodes::UNEXPECTED_EXPRESSION,
"Cannot use ORDER BY ALL to sort a column with name 'all', please disable setting `enable_order_by_all` and try again");
}
auto sort_node = std::make_shared<SortNode>(node, all_node->getSortDirection(), all_node->getNullsSortDirection());
list_node->getNodes().push_back(sort_node);
}
query_tree_node_typed.getOrderByNode() = list_node;
query_tree_node_typed.setIsOrderByAll(false);
}
void QueryAnalyzer::expandLimitByAll(QueryNode & query_tree_node_typed)
{
if (!query_tree_node_typed.isLimitByAll())
return;
if (!query_tree_node_typed.hasLimitByLimit())
{
throw Exception(ErrorCodes::SYNTAX_ERROR,
"LIMIT BY ALL requires a limit expression. Use LIMIT n BY ALL");
}
auto & limit_by_nodes = query_tree_node_typed.getLimitBy().getNodes();
auto & projection_nodes = query_tree_node_typed.getProjection().getNodes();
limit_by_nodes.clear();
limit_by_nodes.reserve(projection_nodes.size());
for (auto & projection_node : projection_nodes)
{
if (hasAggregateFunctionNodes(projection_node))
continue;
limit_by_nodes.push_back(projection_node->clone());
}
if (limit_by_nodes.empty())
{
throw Exception(ErrorCodes::SYNTAX_ERROR,
"LIMIT BY ALL requires at least one non-aggregate expression in SELECT");
}
query_tree_node_typed.setIsLimitByAll(false);
}
std::string QueryAnalyzer::rewriteAggregateFunctionNameIfNeeded(
const std::string & aggregate_function_name, NullsAction action, const ContextPtr & context)
{
std::string result_aggregate_function_name = aggregate_function_name;
auto aggregate_function_name_lowercase = Poco::toLower(aggregate_function_name);
const auto & settings = context->getSettingsRef();
if (aggregate_function_name_lowercase == "countdistinct")
{
result_aggregate_function_name = settings[Setting::count_distinct_implementation];
}
else if (
aggregate_function_name_lowercase == "countifdistinct"
|| (settings[Setting::rewrite_count_distinct_if_with_count_distinct_implementation]
&& aggregate_function_name_lowercase == "countdistinctif"))
{
result_aggregate_function_name = settings[Setting::count_distinct_implementation];
result_aggregate_function_name += "If";
}
else if (aggregate_function_name_lowercase.ends_with("ifdistinct"))
{
/// Replace aggregateFunctionIfDistinct into aggregateFunctionDistinctIf to make execution more optimal
size_t prefix_length = result_aggregate_function_name.size() - strlen("ifdistinct");
result_aggregate_function_name = result_aggregate_function_name.substr(0, prefix_length) + "DistinctIf";
}
bool need_add_or_null = settings[Setting::aggregate_functions_null_for_empty] && !result_aggregate_function_name.ends_with("OrNull");
if (need_add_or_null)
{
auto properties = AggregateFunctionFactory::instance().tryGetProperties(result_aggregate_function_name, action);
if (!properties->returns_default_when_only_null)
result_aggregate_function_name += "OrNull";
}
/** Move -OrNull suffix ahead, this should execute after add -OrNull suffix.
* Used to rewrite aggregate functions with -OrNull suffix in some cases.
* Example: sumIfOrNull.
* Result: sumOrNullIf.
*/
if (result_aggregate_function_name.ends_with("OrNull"))
{
auto function_properies = AggregateFunctionFactory::instance().tryGetProperties(result_aggregate_function_name, action);
if (function_properies && !function_properies->returns_default_when_only_null)
{
size_t function_name_size = result_aggregate_function_name.size();
static constexpr std::array<std::string_view, 4> suffixes_to_replace = {"MergeState", "Merge", "State", "If"};
for (const auto & suffix : suffixes_to_replace)
{
auto suffix_string_value = String(suffix);
auto suffix_to_check = suffix_string_value + "OrNull";
if (!result_aggregate_function_name.ends_with(suffix_to_check))
continue;
result_aggregate_function_name = result_aggregate_function_name.substr(0, function_name_size - suffix_to_check.size());
result_aggregate_function_name += "OrNull";
result_aggregate_function_name += suffix_string_value;
break;
}
}
}
return result_aggregate_function_name;
}
/// Resolve identifier functions implementation
/** Resolve identifier from scope aliases.
*
* Resolve strategy:
* 1. Try to find identifier first part in the corresponding alias table.
* 2. If alias is registered in current expressions that are in resolve process and if top expression is not part of bottom expression with the same alias subtree
* it may be cyclic aliases.
* In that case return nullptr and allow to continue identifier resolution in other places.
* TODO: If following identifier resolution fails throw an CYCLIC_ALIASES exception.
*
* This is special scenario where identifier has name the same as alias name in one of its parent expressions including itself.
* In such case we cannot resolve identifier from aliases because of recursion. It is client responsibility to register and deregister alias
* names during expressions resolve.
*
* Below cases should work:
* Example:
* SELECT id AS id FROM test_table;
* SELECT value.value1 AS value FROM test_table;
* SELECT (id + 1) AS id FROM test_table;
* SELECT (1 + (1 + id)) AS id FROM test_table;
*
* Below cases should throw cyclic aliases exception:
* SELECT (id + b) AS id, id as b FROM test_table;
* SELECT (1 + b + 1 + id) AS id, b as c, id as b FROM test_table;
*
* 3. Depending on IdentifierLookupContext select IdentifierResolveScope to resolve aliased expression.
* 4. Clone query tree of aliased expression (do not clone table expression from join tree).
* 5. Resolve the node. It is important in case of compound expressions.
* Example: SELECT value.a, cast('(1)', 'Tuple(a UInt64)') AS value;