forked from ClickHouse/ClickHouse
-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathPlannerActionsVisitor.cpp
More file actions
1348 lines (1098 loc) · 55.9 KB
/
PlannerActionsVisitor.cpp
File metadata and controls
1348 lines (1098 loc) · 55.9 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 <utility>
#include <ranges>
#include <Planner/PlannerActionsVisitor.h>
#include <AggregateFunctions/WindowFunction.h>
#include <Analyzer/ColumnNode.h>
#include <Analyzer/ConstantNode.h>
#include <Analyzer/FunctionNode.h>
#include <Analyzer/LambdaNode.h>
#include <Analyzer/QueryNode.h>
#include <Analyzer/SetUtils.h>
#include <Analyzer/SortNode.h>
#include <Analyzer/UnionNode.h>
#include <Analyzer/Utils.h>
#include <Analyzer/WindowNode.h>
#include <DataTypes/DataTypeSet.h>
#include <DataTypes/DataTypeString.h>
#include <DataTypes/DataTypeTuple.h>
#include <DataTypes/FieldToDataType.h>
#include <Common/FieldVisitorToString.h>
#include <Common/quoteString.h>
#include <Columns/ColumnSet.h>
#include <Columns/ColumnConst.h>
#include <Functions/FunctionsMiscellaneous.h>
#include <Functions/FunctionFactory.h>
#include <Functions/indexHint.h>
#include <Interpreters/ExpressionActionsSettings.h>
#include <Interpreters/ClientInfo.h>
#include <Interpreters/Context.h>
#include <Interpreters/Set.h>
#include <Planner/PlannerContext.h>
#include <Planner/PlannerCorrelatedSubqueries.h>
#include <Planner/TableExpressionData.h>
#include <Planner/Utils.h>
#include <Core/Settings.h>
#include <fmt/format.h>
namespace DB
{
namespace Setting
{
extern const SettingsBool enable_named_columns_in_function_tuple;
extern const SettingsBool transform_null_in;
extern const SettingsInt64 optimize_const_name_size;
}
namespace ErrorCodes
{
extern const int UNSUPPORTED_METHOD;
extern const int LOGICAL_ERROR;
extern const int BAD_ARGUMENTS;
extern const int INCORRECT_QUERY;
}
namespace
{
/* Calculates Action node name for ConstantNode.
*
* If converting to AST will add a '_CAST' function call,
* the result action name will also include it.
*/
String calculateActionNodeNameWithCastIfNeeded(const ConstantNode & constant_node, Int64 optimize_const_name_size)
{
const auto & [name, type] = constant_node.getValueNameAndType({.optimize_const_name_size = optimize_const_name_size});
bool requires_cast_call = constant_node.hasSourceExpression() || ConstantNode::requiresCastCall(type, constant_node.getResultType());
WriteBufferFromOwnString buffer;
if (requires_cast_call)
buffer << "_CAST(";
buffer << name << "_" << constant_node.getResultType()->getName();
if (requires_cast_call)
{
/// Projection name for constants is <value>_<type> so for _cast(1, 'String') we will have _cast(1_Uint8, 'String'_String)
buffer << ", '" << constant_node.getResultType()->getName() << "'_String)";
}
return buffer.str();
}
String tryExtractAliasMarkerIdFromSecondArgument(const QueryTreeNodePtr & argument)
{
if (const auto * second_argument_constant = argument->as<ConstantNode>();
second_argument_constant && isString(second_argument_constant->getResultType()))
{
return second_argument_constant->getValue().safeGet<String>();
}
return {};
}
class ActionNodeNameHelper
{
public:
ActionNodeNameHelper(QueryTreeNodeToName & node_to_name_,
const PlannerContext & planner_context_,
bool use_column_identifier_as_action_node_name_)
: node_to_name(node_to_name_)
, planner_context(planner_context_)
, use_column_identifier_as_action_node_name(use_column_identifier_as_action_node_name_)
{
}
String calculateActionNodeName(const QueryTreeNodePtr & node)
{
auto it = node_to_name.find(node);
if (it != node_to_name.end())
return it->second;
String result;
auto node_type = node->getNodeType();
switch (node_type)
{
case QueryTreeNodeType::COLUMN:
{
const ColumnIdentifier * column_identifier = nullptr;
if (use_column_identifier_as_action_node_name)
column_identifier = planner_context.getColumnNodeIdentifierOrNull(node);
if (column_identifier)
{
result = *column_identifier;
}
else
{
const auto & column_node = node->as<ColumnNode &>();
result = column_node.getColumnName();
}
break;
}
case QueryTreeNodeType::CONSTANT:
{
const auto & constant_node = node->as<ConstantNode &>();
/* To ensure that headers match during distributed query we need to simulate action node naming on
* secondary servers. If we don't do that headers will mismatch due to constant folding.
*
* +--------+
* -----------------| Server |----------------
* / +--------+ \
* / \
* v v
* +-----------+ +-----------+
* | Initiator | ------ | Secondary |------
* +-----------+ / +-----------+ \
* | / \
* | / \
* v / \
* +---------------+ v v
* | Wrap in _CAST | +----------------------------+ +----------------------+
* | if needed | | Constant folded from _CAST | | Constant folded from |
* +---------------+ +----------------------------+ | another expression |
* | +----------------------+
* v |
* +----------------------------+ v
* | Name ConstantNode the same | +--------------------------+
* | as on initiator server | | Generate action name for |
* | (wrap in _CAST if needed) | | original expression |
* +----------------------------+ +--------------------------+
*/
if (planner_context.isASTLevelOptimizationAllowed())
{
result = calculateActionNodeNameWithCastIfNeeded(constant_node, planner_context.getQueryContext()->getSettingsRef()[Setting::optimize_const_name_size]);
}
else
{
// Need to check if constant folded from QueryNode until https://github.com/ClickHouse/ClickHouse/issues/60847 is fixed.
if (constant_node.hasSourceExpression() && constant_node.getSourceExpression()->getNodeType() != QueryTreeNodeType::QUERY)
{
if (constant_node.receivedFromInitiatorServer())
result = calculateActionNodeNameWithCastIfNeeded(constant_node, planner_context.getQueryContext()->getSettingsRef()[Setting::optimize_const_name_size]);
else
result = calculateActionNodeName(constant_node.getSourceExpression());
}
else
result = calculateConstantActionNodeName(constant_node, planner_context.getQueryContext()->getSettingsRef()[Setting::optimize_const_name_size]);
}
break;
}
case QueryTreeNodeType::FUNCTION:
{
const auto & function_node = node->as<FunctionNode &>();
if (function_node.getFunctionName() == "__aliasMarker")
{
/// Perform sanity check, because user may call this function with unexpected arguments
const auto & function_argument_nodes = function_node.getArguments().getNodes();
if (function_argument_nodes.size() != 2)
throw Exception(ErrorCodes::BAD_ARGUMENTS, "Function __aliasMarker expects 2 arguments");
result = tryExtractAliasMarkerIdFromSecondArgument(function_argument_nodes.at(1));
if (result.empty())
result = calculateActionNodeName(function_argument_nodes.at(0));
/// Empty node name is not allowed and leads to logical errors
if (result.empty())
throw Exception(ErrorCodes::BAD_ARGUMENTS, "Function __aliasMarker is internal and should not be used directly");
break;
}
else if (function_node.getFunctionName() == "__actionName")
{
/// Perform sanity check, because user may call this function with unexpected arguments
const auto & function_argument_nodes = function_node.getArguments().getNodes();
if (function_argument_nodes.size() == 2)
{
if (const auto * second_argument = function_argument_nodes.at(1)->as<ConstantNode>())
result = fieldToString(second_argument->getValue());
}
/// Empty node name is not allowed and leads to logical errors
if (result.empty())
throw Exception(ErrorCodes::BAD_ARGUMENTS, "Function __actionName is internal nad should not be used directly");
break;
}
else if (function_node.getFunctionName() == "exists")
{
const auto & arguments = function_node.getArguments().getNodes();
chassert(arguments.size() == 1);
const auto & exists_argument = arguments.front();
chassert(exists_argument != nullptr);
const auto & table_alias = exists_argument->getAlias();
chassert(!table_alias.empty());
result = fmt::format("exists({})", table_alias);
break;
}
else if (function_node.getFunctionName() == "__getScalar")
{
const auto & arguments = function_node.getArguments().getNodes();
chassert(arguments.size() == 1);
const auto & argument = arguments.front();
chassert(argument != nullptr);
auto * argument_node = argument->as<ConstantNode>();
chassert(argument_node != nullptr);
chassert(isString(argument_node->getResultType()));
result = fmt::format("__getScalar('{}'_String)", argument_node->getValue().safeGet<String>());
break;
}
if (planner_context.getQueryContext()->getSettingsRef()[Setting::enable_named_columns_in_function_tuple])
{
/// Function "tuple" which generates named tuple should use argument aliases to construct its name.
if (function_node.getFunctionName() == "tuple")
{
if (const DataTypeTuple * type_tuple = typeid_cast<const DataTypeTuple *>(function_node.getResultType().get()))
{
if (type_tuple->hasExplicitNames())
{
const auto & names = type_tuple->getElementNames();
size_t size = names.size();
WriteBufferFromOwnString s;
s << "tuple(";
for (size_t i = 0; i < size; ++i)
{
if (i != 0)
s << ", ";
s << backQuoteIfNeed(names[i]);
}
s << ")";
result = s.str();
break;
}
}
}
}
String in_function_second_argument_node_name;
if (isNameOfInFunction(function_node.getFunctionName()))
{
const auto & in_first_argument_node = function_node.getArguments().getNodes().at(0);
const auto & in_second_argument_node = function_node.getArguments().getNodes().at(1);
in_function_second_argument_node_name = PlannerContext::createSetKey(in_first_argument_node->getResultType(), in_second_argument_node);
}
WriteBufferFromOwnString buffer;
buffer << function_node.getFunctionName();
const auto & function_parameters_nodes = function_node.getParameters().getNodes();
if (!function_parameters_nodes.empty())
{
buffer << '(';
size_t function_parameters_nodes_size = function_parameters_nodes.size();
for (size_t i = 0; i < function_parameters_nodes_size; ++i)
{
const auto & function_parameter_node = function_parameters_nodes[i];
buffer << calculateActionNodeName(function_parameter_node);
if (i + 1 != function_parameters_nodes_size)
buffer << ", ";
}
buffer << ')';
}
const auto & function_arguments_nodes = function_node.getArguments().getNodes();
String function_argument_name;
buffer << '(';
size_t function_arguments_nodes_size = function_arguments_nodes.size();
for (size_t i = 0; i < function_arguments_nodes_size; ++i)
{
if (i == 1 && !in_function_second_argument_node_name.empty())
{
function_argument_name = in_function_second_argument_node_name;
}
else
{
const auto & function_argument_node = function_arguments_nodes[i];
function_argument_name = calculateActionNodeName(function_argument_node);
}
buffer << function_argument_name;
if (i + 1 != function_arguments_nodes_size)
buffer << ", ";
}
buffer << ')';
if (function_node.isWindowFunction())
{
buffer << " OVER (";
buffer << calculateWindowNodeActionName(node, function_node.getWindowNode());
buffer << ')';
}
result = buffer.str();
break;
}
case QueryTreeNodeType::LAMBDA:
{
/// Initially, the action name was `"__lambda_" + toString(node->getTreeHash());`.
/// This is not a good idea because:
/// * hash is different on initiator and shard if the default database is changed in cluster
/// * hash is reliable only within one node; any change will break queries in between versions
///
/// Now, we calculate execution name as (names + types) for lambda arguments + action name (expression)
/// and this should be more reliable (as long as we trust the calculation of action name for functions)
WriteBufferFromOwnString buffer;
const auto & lambda_node = node->as<LambdaNode &>();
const auto & lambda_arguments_nodes = lambda_node.getArguments().getNodes();
size_t lambda_arguments_nodes_size = lambda_arguments_nodes.size();
for (size_t i = 0; i < lambda_arguments_nodes_size; ++i)
{
const auto & lambda_argument_node = lambda_arguments_nodes[i];
buffer << calculateActionNodeName(lambda_argument_node);
buffer << ' ';
buffer << lambda_argument_node->as<ColumnNode &>().getResultType()->getName();
if (i + 1 != lambda_arguments_nodes_size)
buffer << ", ";
}
buffer << " -> " << calculateActionNodeName(lambda_node.getExpression());
result = buffer.str();
break;
}
case QueryTreeNodeType::QUERY:
{
auto & query_node = node->as<QueryNode &>();
if (query_node.isCorrelated())
result = query_node.getAlias();
else
throw Exception(
ErrorCodes::LOGICAL_ERROR,
"Only correlated QueryNode can be used as action query tree node, but got {}",
node->formatASTForErrorMessage());
break;
}
default:
{
throw Exception(ErrorCodes::LOGICAL_ERROR, "Invalid action query tree node {} (node_type: {})", node->formatASTForErrorMessage(), static_cast<int>(node_type));
}
}
node_to_name.emplace(node, result);
return result;
}
static String calculateConstantActionNodeName(const Field & constant_literal, const DataTypePtr & constant_type)
{
auto constant_name = applyVisitor(FieldVisitorToString(), constant_literal);
return constant_name + "_" + constant_type->getName();
}
static String calculateConstantActionNodeName(const Field & constant_literal)
{
return calculateConstantActionNodeName(constant_literal, applyVisitor(FieldToDataType(), constant_literal));
}
static String calculateConstantActionNodeName(const ConstantNode & constant_node, Int64 optimize_const_name_size)
{
const auto & [name, type] = constant_node.getValueNameAndType({.optimize_const_name_size = optimize_const_name_size});
return name + "_" + constant_node.getResultType()->getName();
}
String calculateWindowNodeActionName(const QueryTreeNodePtr & function_nodew_node_, const QueryTreeNodePtr & window_node_)
{
const auto & function_node = function_nodew_node_->as<const FunctionNode&>();
const auto & window_node = window_node_->as<const WindowNode &>();
WriteBufferFromOwnString buffer;
if (window_node.hasPartitionBy())
{
buffer << "PARTITION BY ";
const auto & partition_by_nodes = window_node.getPartitionBy().getNodes();
size_t partition_by_nodes_size = partition_by_nodes.size();
for (size_t i = 0; i < partition_by_nodes_size; ++i)
{
const auto & partition_by_node = partition_by_nodes[i];
buffer << calculateActionNodeName(partition_by_node);
if (i + 1 != partition_by_nodes_size)
buffer << ", ";
}
}
if (window_node.hasOrderBy())
{
if (window_node.hasPartitionBy())
buffer << ' ';
buffer << "ORDER BY ";
const auto & order_by_nodes = window_node.getOrderBy().getNodes();
size_t order_by_nodes_size = order_by_nodes.size();
for (size_t i = 0; i < order_by_nodes_size; ++i)
{
auto & sort_node = order_by_nodes[i]->as<SortNode &>();
buffer << calculateActionNodeName(sort_node.getExpression());
auto sort_direction = sort_node.getSortDirection();
buffer << (sort_direction == SortDirection::ASCENDING ? " ASC" : " DESC");
auto nulls_sort_direction = sort_node.getNullsSortDirection();
if (nulls_sort_direction)
buffer << " NULLS " << (nulls_sort_direction == sort_direction ? "LAST" : "FIRST");
if (auto collator = sort_node.getCollator())
buffer << " COLLATE " << collator->getLocale();
if (sort_node.withFill())
{
buffer << " WITH FILL";
if (sort_node.hasFillFrom())
buffer << " FROM " << calculateActionNodeName(sort_node.getFillFrom());
if (sort_node.hasFillTo())
buffer << " TO " << calculateActionNodeName(sort_node.getFillTo());
if (sort_node.hasFillStep())
buffer << " STEP " << calculateActionNodeName(sort_node.getFillStep());
if (sort_node.hasFillStaleness())
buffer << " STALENESS " << calculateActionNodeName(sort_node.getFillStaleness());
}
if (i + 1 != order_by_nodes_size)
buffer << ", ";
}
}
auto window_frame_opt = extractWindowFrame(function_node);
if (window_frame_opt)
{
auto & window_frame = *window_frame_opt;
if (window_node.hasPartitionBy() || window_node.hasOrderBy())
buffer << ' ';
window_frame.toString(buffer);
}
return buffer.str();
}
private:
std::unordered_map<QueryTreeNodePtr, std::string> & node_to_name;
const PlannerContext & planner_context;
bool use_column_identifier_as_action_node_name = true;
};
class ActionsScopeNode
{
public:
explicit ActionsScopeNode(ActionsDAG & actions_dag_, QueryTreeNodePtr scope_node_)
: actions_dag(actions_dag_)
, scope_node(std::move(scope_node_))
{
for (const auto & node : actions_dag.getNodes())
node_name_to_node[node.result_name] = &node;
}
ActionsScopeNode(const ActionsScopeNode &) = delete;
ActionsScopeNode(ActionsScopeNode &&) = default;
ActionsScopeNode & operator=(const ActionsScopeNode &) = delete;
ActionsScopeNode & operator=(ActionsScopeNode &&) = delete;
const QueryTreeNodePtr & getScopeNode() const
{
return scope_node;
}
[[maybe_unused]] bool containsNode(const std::string & node_name)
{
return node_name_to_node.contains(node_name);
}
[[maybe_unused]] bool containsInputNode(const std::string & node_name)
{
const auto * node = tryGetNode(node_name);
if (node && node->type == ActionsDAG::ActionType::INPUT)
return true;
return false;
}
[[maybe_unused]] const ActionsDAG::Node * tryGetNode(const std::string & node_name)
{
auto it = node_name_to_node.find(node_name);
if (it == node_name_to_node.end())
return {};
return it->second;
}
const ActionsDAG::Node * getNodeOrThrow(const std::string & node_name)
{
auto it = node_name_to_node.find(node_name);
if (it == node_name_to_node.end())
throw Exception(ErrorCodes::LOGICAL_ERROR,
"No node with name {}. There are only nodes {}",
node_name,
actions_dag.dumpNames());
return it->second;
}
const ActionsDAG::Node * addInputColumnIfNecessary(const std::string & node_name, const DataTypePtr & column_type)
{
auto it = node_name_to_node.find(node_name);
if (it != node_name_to_node.end())
return it->second;
const auto * node = &actions_dag.addInput(node_name, column_type);
node_name_to_node[node->result_name] = node;
return node;
}
const ActionsDAG::Node * addPlaceholderColumnIfNecessary(const std::string & node_name, const DataTypePtr & column_type)
{
auto it = node_name_to_node.find(node_name);
if (it != node_name_to_node.end())
return it->second;
const auto * node = &actions_dag.addPlaceholder(node_name, column_type);
node_name_to_node[node->result_name] = node;
return node;
}
const ActionsDAG::Node * addInputConstantColumnIfNecessary(const std::string & node_name, const ColumnWithTypeAndName & column)
{
auto it = node_name_to_node.find(node_name);
if (it != node_name_to_node.end())
return it->second;
const auto * node = &actions_dag.addInput(column);
node_name_to_node[node->result_name] = node;
return node;
}
const ActionsDAG::Node * addConstantIfNecessary(const std::string & node_name, const ColumnWithTypeAndName & column, bool is_deterministic)
{
auto it = node_name_to_node.find(node_name);
if (it != node_name_to_node.end())
{
/// It is possible that ActionsDAG already has an input with the same name as constant.
/// In this case, prefer constant to input.
/// Constatns affect function return type, which should be consistent with QueryTree.
/// Query example:
/// SELECT materialize(toLowCardinality('b')) || 'a' FROM remote('127.0.0.{1,2}', system, one) GROUP BY 'a'
bool materialized_input = it->second->type == ActionsDAG::ActionType::INPUT && !it->second->column;
if (!materialized_input)
return it->second;
}
const auto * node = &actions_dag.addColumn(column, is_deterministic);
node_name_to_node[node->result_name] = node;
return node;
}
template <typename FunctionOrOverloadResolver>
const ActionsDAG::Node * addFunctionIfNecessary(const std::string & node_name, ActionsDAG::NodeRawConstPtrs children, const FunctionOrOverloadResolver & function)
{
auto it = node_name_to_node.find(node_name);
if (it != node_name_to_node.end())
return it->second;
const auto * node = &actions_dag.addFunction(function, children, node_name);
node_name_to_node[node->result_name] = node;
return node;
}
const ActionsDAG::Node * addArrayJoinIfNecessary(const std::string & node_name, const ActionsDAG::Node * child)
{
auto it = node_name_to_node.find(node_name);
if (it != node_name_to_node.end())
return it->second;
const auto * node = &actions_dag.addArrayJoin(*child, node_name);
node_name_to_node[node->result_name] = node;
return node;
}
const ActionsDAG::Node * addAliasIfNecessary(const std::string & node_name, const ActionsDAG::Node * child)
{
auto it = node_name_to_node.find(node_name);
if (it != node_name_to_node.end())
return it->second;
const auto * node = &actions_dag.addAlias(*child, node_name);
node_name_to_node[node->result_name] = node;
return node;
}
private:
std::unordered_map<std::string_view, const ActionsDAG::Node *> node_name_to_node;
ActionsDAG & actions_dag;
QueryTreeNodePtr scope_node;
};
class PlannerActionsVisitorImpl
{
public:
PlannerActionsVisitorImpl(
ActionsDAG & actions_dag,
const PlannerContextPtr & planner_context_,
const ColumnNodePtrWithHashSet & correlated_columns_set_,
bool use_column_identifier_as_action_node_name_);
std::pair<ActionsDAG::NodeRawConstPtrs, CorrelatedSubtrees> visit(QueryTreeNodePtr expression_node);
private:
class Levels
{
public:
explicit Levels(size_t level) { set(level); }
void set(size_t level)
{
check(level);
if (level)
mask |= (uint64_t(1) << (level - 1));
}
void reset(size_t level)
{
check(level);
if (level)
mask &= ~(uint64_t(1) << (level - 1));
}
void add(Levels levels) { mask |= levels.mask; }
size_t max() const { return 64 - getLeadingZeroBits(mask); }
private:
uint64_t mask = 0;
void check(size_t level)
{
if (level > 64)
throw Exception(ErrorCodes::INCORRECT_QUERY, "Maximum lambda depth exceeded. Maximum 64.");
}
};
using NodeNameAndNodeMinLevel = std::pair<std::string, Levels>;
NodeNameAndNodeMinLevel visitImpl(QueryTreeNodePtr node);
NodeNameAndNodeMinLevel visitColumn(const QueryTreeNodePtr & node);
NodeNameAndNodeMinLevel visitCorrelatedColumn(const ColumnNodePtr & node);
NodeNameAndNodeMinLevel visitConstant(const QueryTreeNodePtr & node, const std::string & override_column_name = {});
NodeNameAndNodeMinLevel visitLambda(const QueryTreeNodePtr & node);
NodeNameAndNodeMinLevel makeSetForInFunction(const QueryTreeNodePtr & node);
NodeNameAndNodeMinLevel visitIndexHintFunction(const QueryTreeNodePtr & node);
NodeNameAndNodeMinLevel visitExistsFunction(const QueryTreeNodePtr & node);
NodeNameAndNodeMinLevel visitFunction(const QueryTreeNodePtr & node);
NodeNameAndNodeMinLevel visitQuery(const QueryTreeNodePtr & node);
std::vector<ActionsScopeNode> actions_stack;
std::unordered_map<QueryTreeNodePtr, std::string> node_to_node_name;
CorrelatedSubtrees correlated_subtrees;
const PlannerContextPtr planner_context;
const ColumnNodePtrWithHashSet & correlated_columns_set;
ActionNodeNameHelper action_node_name_helper;
bool use_column_identifier_as_action_node_name;
};
PlannerActionsVisitorImpl::PlannerActionsVisitorImpl(
ActionsDAG & actions_dag,
const PlannerContextPtr & planner_context_,
const ColumnNodePtrWithHashSet & correlated_columns_set_,
bool use_column_identifier_as_action_node_name_
)
: planner_context(planner_context_)
, correlated_columns_set(correlated_columns_set_)
, action_node_name_helper(node_to_node_name, *planner_context, use_column_identifier_as_action_node_name_)
, use_column_identifier_as_action_node_name(use_column_identifier_as_action_node_name_)
{
actions_stack.emplace_back(actions_dag, nullptr);
}
std::pair<ActionsDAG::NodeRawConstPtrs, CorrelatedSubtrees> PlannerActionsVisitorImpl::visit(QueryTreeNodePtr expression_node)
{
ActionsDAG::NodeRawConstPtrs result;
if (auto * expression_list_node = expression_node->as<ListNode>())
{
for (auto & node : expression_list_node->getNodes())
{
auto [node_name, _] = visitImpl(node);
result.push_back(actions_stack.front().getNodeOrThrow(node_name));
}
}
else
{
auto [node_name, _] = visitImpl(expression_node);
result.push_back(actions_stack.front().getNodeOrThrow(node_name));
}
return std::make_pair(result, correlated_subtrees);
}
PlannerActionsVisitorImpl::NodeNameAndNodeMinLevel PlannerActionsVisitorImpl::visitImpl(QueryTreeNodePtr node)
{
auto node_type = node->getNodeType();
switch (node_type)
{
case QueryTreeNodeType::COLUMN:
return visitColumn(node);
case QueryTreeNodeType::CONSTANT:
return visitConstant(node);
case QueryTreeNodeType::FUNCTION:
return visitFunction(node);
case QueryTreeNodeType::QUERY:
return visitQuery(node);
default:
throw Exception(ErrorCodes::UNSUPPORTED_METHOD,
"Expected column, constant, function. Actual {} with type: {}",
node->formatASTForErrorMessage(), node_type);
}
}
PlannerActionsVisitorImpl::NodeNameAndNodeMinLevel PlannerActionsVisitorImpl::visitColumn(const QueryTreeNodePtr & node)
{
const auto & column_node = node->as<ColumnNode &>();
const auto & column_node_ptr = static_pointer_cast<ColumnNode>(node);
if (correlated_columns_set.contains(column_node_ptr))
return visitCorrelatedColumn(column_node_ptr);
auto column_node_name = action_node_name_helper.calculateActionNodeName(node);
if (column_node.hasExpression())
{
auto expression = column_node.getExpression();
/// In case of constant expression, prefer constant value from QueryTree vs. re-calculating the expression.
/// It is possible that during the execution of distributed queries
/// source columns from constant expression are removed, so that the attempt to recalculate it fails.
if (expression->getNodeType() == QueryTreeNodeType::CONSTANT)
return visitConstant(expression, column_node_name);
else if (!use_column_identifier_as_action_node_name)
return visitImpl(expression);
}
Int64 actions_stack_size = static_cast<Int64>(actions_stack.size() - 1);
for (Int64 i = actions_stack_size; i >= 0; --i)
{
actions_stack[i].addInputColumnIfNecessary(column_node_name, column_node.getColumnType());
auto column_source = column_node.getColumnSourceOrNull();
if (column_source &&
column_source->getNodeType() == QueryTreeNodeType::LAMBDA &&
actions_stack[i].getScopeNode().get() == column_source.get())
{
return {column_node_name, Levels(i)};
}
}
return {column_node_name, Levels(0)};
}
PlannerActionsVisitorImpl::NodeNameAndNodeMinLevel PlannerActionsVisitorImpl::visitCorrelatedColumn(const ColumnNodePtr & node)
{
auto column_node_name = action_node_name_helper.calculateActionNodeName(node);
for (auto & action_scope_node : actions_stack)
action_scope_node.addPlaceholderColumnIfNecessary(column_node_name, node->getColumnType());
return {column_node_name, Levels(0)};
}
PlannerActionsVisitorImpl::NodeNameAndNodeMinLevel PlannerActionsVisitorImpl::visitConstant(const QueryTreeNodePtr & node, const std::string & override_column_name)
{
const auto & constant_node = node->as<ConstantNode &>();
const auto & constant_type = constant_node.getResultType();
auto constant_node_name = !override_column_name.empty() ? override_column_name : [&]()
{
/* To ensure that headers match during distributed query we need to simulate action node naming on
* secondary servers. If we don't do that headers will mismatch due to constant folding.
*
* +--------+
* -----------------| Server |----------------
* / +--------+ \
* / \
* v v
* +-----------+ +-----------+
* | Initiator | ------ | Secondary |------
* +-----------+ / +-----------+ \
* | / \
* | / \
* v / \
* +---------------+ v v
* | Wrap in _CAST | +----------------------------+ +----------------------+
* | if needed | | Constant folded from _CAST | | Constant folded from |
* +---------------+ +----------------------------+ | another expression |
* | +----------------------+
* v |
* +----------------------------+ v
* | Name ConstantNode the same | +--------------------------+
* | as on initiator server | | Generate action name for |
* | (wrap in _CAST if needed) | | original expression |
* +----------------------------+ +--------------------------+
*/
if (planner_context->isASTLevelOptimizationAllowed())
{
return calculateActionNodeNameWithCastIfNeeded(constant_node, planner_context->getQueryContext()->getSettingsRef()[Setting::optimize_const_name_size]);
}
// Need to check if constant folded from QueryNode until https://github.com/ClickHouse/ClickHouse/issues/60847 is fixed.
if (constant_node.hasSourceExpression() && constant_node.getSourceExpression()->getNodeType() != QueryTreeNodeType::QUERY)
{
if (constant_node.receivedFromInitiatorServer())
return calculateActionNodeNameWithCastIfNeeded(constant_node, planner_context->getQueryContext()->getSettingsRef()[Setting::optimize_const_name_size]);
return action_node_name_helper.calculateActionNodeName(constant_node.getSourceExpression());
}
return calculateConstantActionNodeName(constant_node, planner_context->getQueryContext()->getSettingsRef()[Setting::optimize_const_name_size]);
}();
ColumnWithTypeAndName column;
column.name = constant_node_name;
column.type = constant_type;
column.column = constant_node.getColumn();
actions_stack[0].addConstantIfNecessary(constant_node_name, column, constant_node.isDeterministic());
size_t actions_stack_size = actions_stack.size();
for (size_t i = 1; i < actions_stack_size; ++i)
{
auto & actions_stack_node = actions_stack[i];
actions_stack_node.addInputConstantColumnIfNecessary(constant_node_name, column);
}
return {constant_node_name, Levels(0)};
}
PlannerActionsVisitorImpl::NodeNameAndNodeMinLevel PlannerActionsVisitorImpl::visitLambda(const QueryTreeNodePtr & node)
{
auto & lambda_node = node->as<LambdaNode &>();
auto result_type = lambda_node.getResultType();
if (!result_type)
throw Exception(ErrorCodes::LOGICAL_ERROR,
"Lambda {} is not resolved during query analysis",
lambda_node.formatASTForErrorMessage());
auto & lambda_arguments_nodes = lambda_node.getArguments().getNodes();
size_t lambda_arguments_nodes_size = lambda_arguments_nodes.size();
NamesAndTypesList lambda_arguments_names_and_types;
for (size_t i = 0; i < lambda_arguments_nodes_size; ++i)
{
const auto & lambda_argument_name = lambda_node.getArgumentNames().at(i);
auto lambda_argument_type = lambda_arguments_nodes[i]->getResultType();
lambda_arguments_names_and_types.emplace_back(lambda_argument_name, std::move(lambda_argument_type));
}
ActionsDAG lambda_actions_dag;
actions_stack.emplace_back(lambda_actions_dag, node);
auto [lambda_expression_node_name, levels] = visitImpl(lambda_node.getExpression());
lambda_actions_dag.getOutputs().push_back(actions_stack.back().getNodeOrThrow(lambda_expression_node_name));
lambda_actions_dag.removeUnusedActions(Names(1, lambda_expression_node_name));
Names captured_column_names;
ActionsDAG::NodeRawConstPtrs lambda_children;
Names required_column_names = lambda_actions_dag.getRequiredColumnsNames();
actions_stack.pop_back();
levels.reset(actions_stack.size());
size_t level = levels.max();
const auto & lambda_argument_names = lambda_node.getArgumentNames();
for (const auto & required_column_name : required_column_names)
{
auto it = std::find(lambda_argument_names.begin(), lambda_argument_names.end(), required_column_name);
if (it == lambda_argument_names.end())
{
lambda_children.push_back(actions_stack[level].getNodeOrThrow(required_column_name));
captured_column_names.push_back(required_column_name);
}
}
auto expression_actions_settings = ExpressionActionsSettings(planner_context->getQueryContext(), CompileExpressions::yes);
auto lambda_node_name = calculateActionNodeName(node, *planner_context);
auto function_capture = std::make_shared<FunctionCaptureOverloadResolver>(
std::move(lambda_actions_dag), expression_actions_settings, captured_column_names, lambda_arguments_names_and_types, lambda_node.getExpression()->getResultType(), lambda_expression_node_name, true);
// TODO: Pass IFunctionBase here not FunctionCaptureOverloadResolver.
const auto * actions_node = actions_stack[level].addFunctionIfNecessary(lambda_node_name, std::move(lambda_children), function_capture);
if (!result_type->equals(*actions_node->result_type))
throw Exception(ErrorCodes::LOGICAL_ERROR,
"Lambda resolved type {} is not equal to type from actions DAG {}",
result_type, actions_node->result_type);
size_t actions_stack_size = actions_stack.size();
for (size_t i = level + 1; i < actions_stack_size; ++i)
{
auto & actions_stack_node = actions_stack[i];
actions_stack_node.addInputColumnIfNecessary(lambda_node_name, result_type);
}
return {lambda_node_name, levels};
}
PlannerActionsVisitorImpl::NodeNameAndNodeMinLevel PlannerActionsVisitorImpl::makeSetForInFunction(const QueryTreeNodePtr & node)
{
const auto & function_node = node->as<FunctionNode &>();
auto in_first_argument = function_node.getArguments().getNodes().at(0);
auto in_second_argument = function_node.getArguments().getNodes().at(1);
DataTypes set_element_types;
auto in_second_argument_node_type = in_second_argument->getNodeType();
bool subquery_or_table =
in_second_argument_node_type == QueryTreeNodeType::QUERY ||
in_second_argument_node_type == QueryTreeNodeType::UNION ||
in_second_argument_node_type == QueryTreeNodeType::TABLE;
bool in_second_is_deterministic = false;