forked from ClickHouse/ClickHouse
-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathStorageDistributed.cpp
More file actions
2782 lines (2311 loc) · 113 KB
/
StorageDistributed.cpp
File metadata and controls
2782 lines (2311 loc) · 113 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 <Storages/StorageDistributed.h>
#include <Databases/IDatabase.h>
#include <Disks/IDisk.h>
#include <QueryPipeline/RemoteQueryExecutor.h>
#include <DataTypes/DataTypeFactory.h>
#include <DataTypes/DataTypeLowCardinality.h>
#include <DataTypes/DataTypeUUID.h>
#include <DataTypes/DataTypesNumber.h>
#include <DataTypes/DataTypeString.h>
#include <DataTypes/NestedUtils.h>
#include <Disks/IVolume.h>
#include <Storages/Distributed/DistributedSettings.h>
#include <Storages/Distributed/DistributedSink.h>
#include <Storages/StorageFactory.h>
#include <Storages/AlterCommands.h>
#include <Storages/getStructureOfRemoteTable.h>
#include <Storages/checkAndGetLiteralArgument.h>
#include <Storages/StorageDummy.h>
#include <Storages/removeGroupingFunctionSpecializations.h>
#include <Storages/MergeTree/MergeTreeData.h>
#include <Columns/ColumnConst.h>
#include <Common/CurrentMetrics.h>
#include <Common/Macros.h>
#include <Common/ProfileEvents.h>
#include <Common/escapeForFileName.h>
#include <Common/formatReadable.h>
#include <Common/quoteString.h>
#include <Common/randomSeed.h>
#include <Common/threadPoolCallbackRunner.h>
#include <Common/typeid_cast.h>
#include <Common/setThreadName.h>
#include <Parsers/ASTAsterisk.h>
#include <Parsers/ASTExpressionList.h>
#include <Parsers/ASTFunction.h>
#include <Interpreters/evaluateConstantExpression.h>
#include <Parsers/ASTIdentifier.h>
#include <Parsers/ASTInsertQuery.h>
#include <Parsers/ASTLiteral.h>
#include <Parsers/ASTSelectQuery.h>
#include <Parsers/ASTSelectWithUnionQuery.h>
#include <Parsers/IAST.h>
#include <Parsers/IdentifierQuotingStyle.h>
#include <Parsers/parseQuery.h>
#include <Analyzer/ColumnNode.h>
#include <Analyzer/ConstantNode.h>
#include <Analyzer/FunctionNode.h>
#include <Analyzer/TableNode.h>
#include <Analyzer/TableFunctionNode.h>
#include <Analyzer/QueryNode.h>
#include <Analyzer/JoinNode.h>
#include <Analyzer/QueryTreeBuilder.h>
#include <Analyzer/Passes/QueryAnalysisPass.h>
#include <Analyzer/InDepthQueryTreeVisitor.h>
#include <Analyzer/WindowFunctionsUtils.h>
#include <Analyzer/Utils.h>
#include <Planner/Planner.h>
#include <Planner/Utils.h>
#include <Interpreters/ApplyWithSubqueryVisitor.h>
#include <Interpreters/ApplyWithAliasVisitor.h>
#include <Interpreters/ClusterProxy/SelectStreamFactory.h>
#include <Interpreters/ClusterProxy/executeQuery.h>
#include <Interpreters/Cluster.h>
#include <Interpreters/ExpressionAnalyzer.h>
#include <Interpreters/ExpressionActions.h>
#include <Interpreters/InterpreterSelectQuery.h>
#include <Interpreters/InterpreterSelectQueryAnalyzer.h>
#include <Interpreters/InterpreterInsertQuery.h>
#include <Interpreters/JoinedTables.h>
#include <Interpreters/AddDefaultDatabaseVisitor.h>
#include <Interpreters/TreeRewriter.h>
#include <Interpreters/Context.h>
#include <Interpreters/createBlockSelector.h>
#include <Interpreters/evaluateConstantExpression.h>
#include <Interpreters/getClusterName.h>
#include <Interpreters/RequiredSourceColumnsVisitor.h>
#include <Interpreters/getHeaderForProcessingStage.h>
#include <TableFunctions/TableFunctionView.h>
#include <TableFunctions/TableFunctionFactory.h>
#include <Storages/StorageTableFunction.h>
#include <Storages/buildQueryTreeForShard.h>
#include <Storages/IStorageCluster.h>
#include <Processors/Executors/PushingPipelineExecutor.h>
#include <Processors/Executors/CompletedPipelineExecutor.h>
#include <Processors/QueryPlan/QueryPlan.h>
#include <Processors/QueryPlan/ReadFromPreparedSource.h>
#include <Processors/QueryPlan/ExpressionStep.h>
#include <Processors/QueryPlan/Optimizations/actionsDAGUtils.h>
#include <Processors/QueryPlan/Optimizations/QueryPlanOptimizationSettings.h>
#include <Processors/Sources/NullSource.h>
#include <Processors/Sources/RemoteSource.h>
#include <Processors/Sinks/EmptySink.h>
#include <Core/Names.h>
#include <Core/Settings.h>
#include <Core/SettingsEnums.h>
#include <IO/ReadHelpers.h>
#include <IO/WriteBufferFromString.h>
#include <IO/Operators.h>
#include <IO/ConnectionTimeouts.h>
#include <base/range.h>
#include <memory>
#include <filesystem>
#include <cassert>
#include <boost/algorithm/string/find_iterator.hpp>
#include <boost/algorithm/string/finder.hpp>
#include <fmt/ranges.h>
namespace fs = std::filesystem;
namespace
{
const UInt64 FORCE_OPTIMIZE_SKIP_UNUSED_SHARDS_HAS_SHARDING_KEY = 1;
const UInt64 FORCE_OPTIMIZE_SKIP_UNUSED_SHARDS_ALWAYS = 2;
const UInt64 DISTRIBUTED_GROUP_BY_NO_MERGE_AFTER_AGGREGATION = 2;
const UInt64 PARALLEL_DISTRIBUTED_INSERT_SELECT_ALL = 2;
}
namespace ProfileEvents
{
extern const Event DistributedRejectedInserts;
extern const Event DistributedDelayedInserts;
extern const Event DistributedDelayedInsertsMilliseconds;
}
namespace CurrentMetrics
{
extern const Metric StorageDistributedThreads;
extern const Metric StorageDistributedThreadsActive;
extern const Metric StorageDistributedThreadsScheduled;
}
namespace DB
{
namespace
{
void replaceCurrentDatabaseFunction(ASTPtr & ast, const ContextPtr & context)
{
if (!ast)
return;
if (auto * func = ast->as<ASTFunction>())
{
if (func->name == "currentDatabase")
{
ast = evaluateConstantExpressionForDatabaseName(ast, context);
return;
}
}
for (auto & child : ast->children)
replaceCurrentDatabaseFunction(child, context);
}
}
namespace Setting
{
extern const SettingsBool allow_experimental_analyzer;
extern const SettingsBool allow_nondeterministic_optimize_skip_unused_shards;
extern const SettingsBool async_socket_for_remote;
extern const SettingsBool async_query_sending_for_remote;
extern const SettingsBool distributed_background_insert_batch;
extern const SettingsUInt64 distributed_background_insert_timeout;
extern const SettingsMilliseconds distributed_background_insert_sleep_time_ms;
extern const SettingsMilliseconds distributed_background_insert_max_sleep_time_ms;
extern const SettingsBool distributed_background_insert_split_batch_on_failure;
extern const SettingsUInt64 distributed_group_by_no_merge;
extern const SettingsBool distributed_foreground_insert;
extern const SettingsUInt64 distributed_push_down_limit;
extern const SettingsBool extremes;
extern const SettingsUInt64 force_optimize_skip_unused_shards;
extern const SettingsBool insert_allow_materialized_columns;
extern const SettingsBool insert_distributed_one_random_shard;
extern const SettingsUInt64 insert_shard_id;
extern const SettingsSeconds lock_acquire_timeout;
extern const SettingsUInt64 max_distributed_depth;
extern const SettingsNonZeroUInt64 max_parallel_replicas;
extern const SettingsBool optimize_distributed_group_by_sharding_key;
extern const SettingsBool optimize_skip_unused_shards;
extern const SettingsUInt64 optimize_skip_unused_shards_limit;
extern const SettingsUInt64 parallel_distributed_insert_select;
extern const SettingsBool prefer_localhost_replica;
extern const SettingsUInt64 allow_experimental_parallel_reading_from_replicas;
extern const SettingsBool prefer_global_in_and_join;
extern const SettingsBool enable_global_with_statement;
extern const SettingsBool allow_experimental_hybrid_table;
extern const SettingsBool enable_alias_marker;
}
namespace DistributedSetting
{
extern const DistributedSettingsUInt64 background_insert_batch;
extern const DistributedSettingsMilliseconds background_insert_max_sleep_time_ms;
extern const DistributedSettingsMilliseconds background_insert_sleep_time_ms;
extern const DistributedSettingsUInt64 background_insert_split_batch_on_failure;
extern const DistributedSettingsUInt64 bytes_to_delay_insert;
extern const DistributedSettingsUInt64 bytes_to_throw_insert;
extern const DistributedSettingsBool flush_on_detach;
extern const DistributedSettingsUInt64 max_delay_to_insert;
}
namespace ErrorCodes
{
extern const int LOGICAL_ERROR;
extern const int NOT_IMPLEMENTED;
extern const int STORAGE_REQUIRES_PARAMETER;
extern const int BAD_ARGUMENTS;
extern const int UNKNOWN_DATABASE;
extern const int UNKNOWN_TABLE;
extern const int NUMBER_OF_ARGUMENTS_DOESNT_MATCH;
extern const int INCORRECT_NUMBER_OF_COLUMNS;
extern const int INFINITE_LOOP;
extern const int TYPE_MISMATCH;
extern const int TOO_MANY_ROWS;
extern const int UNABLE_TO_SKIP_UNUSED_SHARDS;
extern const int INVALID_SHARD_ID;
extern const int ALTER_OF_COLUMN_IS_FORBIDDEN;
extern const int DISTRIBUTED_TOO_MANY_PENDING_BYTES;
extern const int ARGUMENT_OUT_OF_BOUND;
extern const int TOO_LARGE_DISTRIBUTED_DEPTH;
extern const int SUPPORT_IS_DISABLED;
}
namespace ActionLocks
{
extern const StorageActionBlockType DistributedSend;
}
namespace
{
/// Calculate maximum number in file names in directory and all subdirectories.
/// To ensure global order of data blocks yet to be sent across server restarts.
UInt64 getMaximumFileNumber(const std::string & dir_path)
{
UInt64 res = 0;
std::filesystem::recursive_directory_iterator begin(dir_path);
std::filesystem::recursive_directory_iterator end;
for (auto it = begin; it != end; ++it)
{
const auto & file_path = it->path();
if (!std::filesystem::is_regular_file(*it) || !endsWith(file_path.filename().string(), ".bin"))
continue;
UInt64 num = 0;
try
{
num = parse<UInt64>(file_path.filename().stem().string());
}
catch (Exception & e)
{
e.addMessage("Unexpected file name " + file_path.filename().string() + " found at " + file_path.parent_path().string() + ", should have numeric base name.");
throw;
}
res = std::max(num, res);
}
return res;
}
std::string makeFormattedListOfShards(const ClusterPtr & cluster)
{
WriteBufferFromOwnString buf;
bool head = true;
buf << "[";
for (const auto & shard_info : cluster->getShardsInfo())
{
(head ? buf : buf << ", ") << shard_info.shard_num;
head = false;
}
buf << "]";
return buf.str();
}
ExpressionActionsPtr buildShardingKeyExpression(const ASTPtr & sharding_key, ContextPtr context, const NamesAndTypesList & columns, bool project)
{
ASTPtr query = sharding_key;
auto syntax_result = TreeRewriter(context).analyze(query, columns);
return ExpressionAnalyzer(query, syntax_result, context).getActions(project);
}
void checkShardingKeyExistsAndIsNumeric(const ASTPtr & sharding_key_ast, ContextPtr context, const NamesAndTypesList & columns)
{
if (!sharding_key_ast)
return;
auto sharding_expr = buildShardingKeyExpression(sharding_key_ast, context, columns, true);
const Block & block = sharding_expr->getSampleBlock();
if (block.columns() != 1)
throw Exception(ErrorCodes::INCORRECT_NUMBER_OF_COLUMNS, "Sharding expression must return exactly one column");
auto type = block.getByPosition(0).type;
if (!type->isValueRepresentedByInteger())
throw Exception(ErrorCodes::TYPE_MISMATCH, "Sharding expression has type {}, but should be one of integer type",
type->getName());
}
bool isExpressionActionsDeterministic(const ExpressionActionsPtr & actions)
{
for (const auto & action : actions->getActions())
{
if (action.node->type != ActionsDAG::ActionType::FUNCTION)
continue;
if (!action.node->function_base->isDeterministic())
return false;
}
return true;
}
class ReplacingConstantExpressionsMatcher
{
public:
using Data = Block;
static bool needChildVisit(ASTPtr &, const ASTPtr &)
{
return true;
}
static void visit(ASTPtr & node, Block & block_with_constants)
{
if (!node->as<ASTFunction>())
return;
std::string name = node->getColumnName();
if (block_with_constants.has(name))
{
const auto & result = block_with_constants.getByName(name);
if (!isColumnConst(*result.column))
return;
node = make_intrusive<ASTLiteral>(assert_cast<const ColumnConst &>(*result.column).getField());
}
}
};
void replaceConstantExpressions(
ASTPtr & node,
ContextPtr context,
const NamesAndTypesList & columns,
ConstStoragePtr storage,
const StorageSnapshotPtr & storage_snapshot)
{
auto syntax_result = TreeRewriter(context).analyze(node, columns, storage, storage_snapshot);
Block block_with_constants = KeyCondition::getBlockWithConstants(node, syntax_result, context);
InDepthNodeVisitor<ReplacingConstantExpressionsMatcher, true> visitor(block_with_constants);
visitor.visit(node);
}
size_t getClusterQueriedNodes(const Settings & settings, const ClusterPtr & cluster)
{
size_t num_local_shards = cluster->getLocalShardCount();
size_t num_remote_shards = cluster->getRemoteShardCount();
UInt64 max_parallel_replicas = settings[Setting::allow_experimental_parallel_reading_from_replicas]
? settings[Setting::max_parallel_replicas] : 1;
return (num_remote_shards + num_local_shards) * max_parallel_replicas;
}
}
/// For destruction of std::unique_ptr of type that is incomplete in class definition.
StorageDistributed::~StorageDistributed() = default;
VirtualColumnsDescription StorageDistributed::createVirtuals()
{
/// NOTE: This is weird.
/// Most of these virtual columns are part of MergeTree
/// tables info. But Distributed is general-purpose engine.
StorageInMemoryMetadata metadata;
auto desc = MergeTreeData::createVirtuals(metadata);
desc.addEphemeral("_shard_num", std::make_shared<DataTypeUInt32>(), "Deprecated. Use function shardNum instead");
/// Add virtual columns from table with Merge engine.
desc.addEphemeral("_database", std::make_shared<DataTypeLowCardinality>(std::make_shared<DataTypeString>()), "The name of database which the row comes from");
desc.addEphemeral("_table", std::make_shared<DataTypeLowCardinality>(std::make_shared<DataTypeString>()), "The name of table which the row comes from");
return desc;
}
StorageDistributed::StorageDistributed(
const StorageID & id_,
const ColumnsDescription & columns_,
const ConstraintsDescription & constraints_,
const String & comment,
const String & remote_database_,
const String & remote_table_,
const String & cluster_name_,
ContextPtr context_,
const ASTPtr & sharding_key_,
const String & storage_policy_name_,
const String & relative_data_path_,
const DistributedSettings & distributed_settings_,
LoadingStrictnessLevel mode,
ClusterPtr owned_cluster_,
ASTPtr remote_table_function_ptr_,
bool is_remote_function_)
: IStorage(id_)
, WithContext(context_->getGlobalContext())
, remote_database(remote_database_)
, remote_table(remote_table_)
, remote_table_function_ptr(remote_table_function_ptr_)
, remote_storage(remote_table_function_ptr ? StorageID::createEmpty() : StorageID{remote_database, remote_table})
, log(getLogger("StorageDistributed (" + id_.table_name + ")"))
, owned_cluster(std::move(owned_cluster_))
, cluster_name(getContext()->getMacros()->expand(cluster_name_))
, has_sharding_key(sharding_key_)
, sharding_key(sharding_key_)
, relative_data_path(relative_data_path_)
, distributed_settings(std::make_unique<DistributedSettings>(distributed_settings_))
, rng(randomSeed())
, is_remote_function(is_remote_function_)
{
if (!(*distributed_settings)[DistributedSetting::flush_on_detach] && (*distributed_settings)[DistributedSetting::background_insert_batch])
throw Exception(ErrorCodes::BAD_ARGUMENTS, "Settings flush_on_detach=0 and background_insert_batch=1 are incompatible");
StorageInMemoryMetadata storage_metadata;
if (columns_.empty())
{
StorageID id = StorageID::createEmpty();
id.table_name = remote_table;
id.database_name = remote_database;
storage_metadata.setColumns(getStructureOfRemoteTable(*getCluster(), id, getContext(), remote_table_function_ptr));
}
else
storage_metadata.setColumns(columns_);
storage_metadata.setConstraints(constraints_);
storage_metadata.setComment(comment);
setInMemoryMetadata(storage_metadata);
setVirtuals(createVirtuals());
if (sharding_key_)
{
sharding_key_expr = buildShardingKeyExpression(sharding_key_, getContext(), storage_metadata.getColumns().getAllPhysical(), false);
sharding_key_column_name = sharding_key_->getColumnName();
sharding_key_is_deterministic = isExpressionActionsDeterministic(sharding_key_expr);
}
if (!relative_data_path.empty())
{
storage_policy = getContext()->getStoragePolicy(storage_policy_name_);
data_volume = storage_policy->getVolume(0);
if (storage_policy->getVolumes().size() > 1)
LOG_WARNING(log, "Storage policy for Distributed table has multiple volumes. "
"Only {} volume will be used to store data. Other will be ignored.", data_volume->getName());
}
/// Sanity check. Skip check if the table is already created to allow the server to start.
if (mode <= LoadingStrictnessLevel::CREATE)
{
if (remote_database.empty() && !remote_table_function_ptr && !getCluster()->maybeCrossReplication())
LOG_WARNING(log, "Name of remote database is empty. Default database will be used implicitly.");
size_t num_local_shards = getCluster()->getLocalShardCount();
if (num_local_shards && (remote_database.empty() || remote_database == id_.database_name) && remote_table == id_.table_name)
throw Exception(ErrorCodes::INFINITE_LOOP, "Distributed table {} looks at itself", id_.table_name);
}
initializeFromDisk();
}
QueryProcessingStage::Enum StorageDistributed::getQueryProcessingStage(
ContextPtr local_context,
QueryProcessingStage::Enum to_stage,
const StorageSnapshotPtr & storage_snapshot,
SelectQueryInfo & query_info) const
{
const auto & settings = local_context->getSettingsRef();
ClusterPtr cluster = getCluster();
size_t nodes = getClusterQueriedNodes(settings, cluster);
query_info.cluster = cluster;
if (!local_context->canUseParallelReplicasCustomKeyForCluster(*cluster))
{
if (nodes > 1 && settings[Setting::optimize_skip_unused_shards])
{
/// Always calculate optimized cluster here, to avoid conditions during read()
/// (Anyway it will be calculated in the read())
auto syntax_analyzer_result = query_info.syntax_analyzer_result;
ClusterPtr optimized_cluster = getOptimizedCluster(local_context, storage_snapshot, query_info, syntax_analyzer_result);
if (optimized_cluster)
{
LOG_DEBUG(log, "Skipping irrelevant shards - the query will be sent to the following shards of the cluster (shard numbers): {}",
makeFormattedListOfShards(optimized_cluster));
cluster = optimized_cluster;
query_info.optimized_cluster = cluster;
nodes = getClusterQueriedNodes(settings, cluster);
}
else
{
LOG_DEBUG(log, "Unable to figure out irrelevant shards from WHERE/PREWHERE clauses - the query will be sent to all shards of the cluster{}",
has_sharding_key ? "" : " (no sharding key)");
}
}
}
if (settings[Setting::distributed_group_by_no_merge])
{
if (settings[Setting::distributed_group_by_no_merge] == DISTRIBUTED_GROUP_BY_NO_MERGE_AFTER_AGGREGATION)
{
if (settings[Setting::distributed_push_down_limit])
return QueryProcessingStage::WithMergeableStateAfterAggregationAndLimit;
return QueryProcessingStage::WithMergeableStateAfterAggregation;
}
/// NOTE: distributed_group_by_no_merge=1 does not respect distributed_push_down_limit
/// (since in this case queries processed separately and the initiator is just a proxy in this case).
if (to_stage != QueryProcessingStage::Complete)
throw Exception(
ErrorCodes::LOGICAL_ERROR, "Queries with distributed_group_by_no_merge=1 should be processed to Complete stage");
return QueryProcessingStage::Complete;
}
/// Nested distributed query cannot return Complete stage,
/// since the parent query need to aggregate the results after.
if (to_stage == QueryProcessingStage::WithMergeableState)
return QueryProcessingStage::WithMergeableState;
// TODO: check logic
if (!segments.empty())
nodes += segments.size();
/// If there is only one node, the query can be fully processed by the
/// shard, initiator will work as a proxy only.
if (nodes == 1)
{
/// In case the query was processed to
/// WithMergeableStateAfterAggregation/WithMergeableStateAfterAggregationAndLimit
/// (which are greater the Complete stage)
/// we cannot return Complete (will break aliases and similar),
/// relevant for Distributed over Distributed
return std::max(to_stage, QueryProcessingStage::Complete);
}
if (nodes == 0)
{
/// In case of 0 shards, the query should be processed fully on the initiator,
/// since we need to apply aggregations.
/// That's why we need to return FetchColumns.
return QueryProcessingStage::FetchColumns;
}
std::optional<QueryProcessingStage::Enum> optimized_stage;
if (settings[Setting::allow_experimental_analyzer])
optimized_stage = getOptimizedQueryProcessingStageAnalyzer(query_info, settings);
else
optimized_stage = getOptimizedQueryProcessingStage(query_info, settings);
if (optimized_stage)
{
if (*optimized_stage == QueryProcessingStage::Complete)
return std::min(to_stage, *optimized_stage);
return *optimized_stage;
}
return QueryProcessingStage::WithMergeableState;
}
/// Reuses the logic of isPartitionKeySuitsGroupByKey in useDataParallelAggregation.cpp
/// Will skip merging step in the initial server when the following conditions are met:
/// 1. Sharding key columns should be a subset of expression columns.
/// 2. Sharding key expression is a deterministic function of col1, ..., coln and expression key is injective functions of these col1, ..., coln.
/// 3. If the expression contains non-injective function, return false.
bool StorageDistributed::isShardingKeySuitsQueryTreeNodeExpression(
const QueryTreeNodePtr & expr, const SelectQueryInfo & query_info) const
{
if (!segments.empty())
return false;
ColumnsWithTypeAndName empty_input_columns;
ColumnNodePtrWithHashSet empty_correlated_columns_set;
// When comparing sharding key expressions, we need to ignore table qualifiers in column names
// because the sharding key is defined without table qualifiers, but the query expression
// may have internal table aliases (e.g. __table1.id). Setting use_column_identifier_as_action_node_name=false
// makes the DAG builder use plain column names without table qualifiers.
auto [expression_dag, correlated_subtrees] = buildActionsDAGFromExpressionNode(
expr,
empty_input_columns,
query_info.planner_context,
empty_correlated_columns_set,
false /* use_column_identifier_as_action_node_name */);
correlated_subtrees.assertEmpty("in sharding key expression");
if (expression_dag.hasArrayJoin() || expression_dag.hasStatefulFunctions() || expression_dag.hasNonDeterministic())
return false;
const auto & expr_key_required_columns = expression_dag.getRequiredColumnsNames();
const auto & sharding_key_dag = sharding_key_expr->getActionsDAG();
for (const auto & col : sharding_key_dag.getRequiredColumnsNames())
{
if (std::ranges::find(expr_key_required_columns, col) == expr_key_required_columns.end())
return false;
}
auto irreducibe_nodes = removeInjectiveFunctionsFromResultsRecursively(expression_dag);
for (const auto & node : irreducibe_nodes)
{
if (node->type == ActionsDAG::ActionType::FUNCTION && !isInjectiveFunction(node))
{
return false;
}
}
const auto matches = matchTrees(expression_dag.getOutputs(), sharding_key_dag);
return allOutputsDependsOnlyOnAllowedNodes(sharding_key_dag, irreducibe_nodes, matches);
}
// TODO: support additional segments
std::optional<QueryProcessingStage::Enum> StorageDistributed::getOptimizedQueryProcessingStageAnalyzer(const SelectQueryInfo & query_info, const Settings & settings) const
{
bool optimize_sharding_key_aggregation = settings[Setting::optimize_skip_unused_shards] && settings[Setting::optimize_distributed_group_by_sharding_key]
&& has_sharding_key && (settings[Setting::allow_nondeterministic_optimize_skip_unused_shards] || sharding_key_is_deterministic);
QueryProcessingStage::Enum default_stage = QueryProcessingStage::WithMergeableStateAfterAggregation;
if (settings[Setting::distributed_push_down_limit])
default_stage = QueryProcessingStage::WithMergeableStateAfterAggregationAndLimit;
const auto & query_node = query_info.query_tree->as<const QueryNode &>();
// GROUP BY qualifiers
// - TODO: WITH TOTALS can be implemented
// - TODO: WITH ROLLUP can be implemented (I guess)
if (query_node.isGroupByWithTotals() || query_node.isGroupByWithRollup() || query_node.isGroupByWithCube())
return {};
// Window functions are not supported.
if (hasWindowFunctionNodes(query_info.query_tree))
return {};
// TODO: extremes support can be implemented
if (settings[Setting::extremes])
return {};
// DISTINCT
if (query_node.isDistinct())
{
if (!optimize_sharding_key_aggregation || !isShardingKeySuitsQueryTreeNodeExpression(query_node.getProjectionNode(), query_info))
return {};
}
// GROUP BY
if (query_info.has_aggregates || query_node.hasGroupBy())
{
if (!optimize_sharding_key_aggregation || !query_node.hasGroupBy() || query_node.isGroupByWithGroupingSets() || !isShardingKeySuitsQueryTreeNodeExpression(query_node.getGroupByNode(), query_info))
return {};
}
// LIMIT BY
if (query_node.hasLimitBy())
{
if (!optimize_sharding_key_aggregation || !isShardingKeySuitsQueryTreeNodeExpression(query_node.getLimitByNode(), query_info))
return {};
}
// ORDER BY
if (query_node.hasOrderBy())
return default_stage;
// LIMIT
// OFFSET
if (query_node.hasLimit() || query_node.hasOffset())
return default_stage;
// Only simple SELECT FROM GROUP BY sharding_key can use Complete state.
return QueryProcessingStage::Complete;
}
// TODO: support additional segments
std::optional<QueryProcessingStage::Enum> StorageDistributed::getOptimizedQueryProcessingStage(const SelectQueryInfo & query_info, const Settings & settings) const
{
bool optimize_sharding_key_aggregation = settings[Setting::optimize_skip_unused_shards] && settings[Setting::optimize_distributed_group_by_sharding_key]
&& has_sharding_key && (settings[Setting::allow_nondeterministic_optimize_skip_unused_shards] || sharding_key_is_deterministic);
QueryProcessingStage::Enum default_stage = QueryProcessingStage::WithMergeableStateAfterAggregation;
if (settings[Setting::distributed_push_down_limit])
default_stage = QueryProcessingStage::WithMergeableStateAfterAggregationAndLimit;
const auto & select = query_info.query->as<ASTSelectQuery &>();
auto expr_contains_sharding_key = [&](const auto & exprs) -> bool
{
std::unordered_set<std::string> expr_columns;
for (auto & expr : exprs)
{
auto id = expr->template as<ASTIdentifier>();
if (!id)
continue;
expr_columns.emplace(id->name());
}
for (const auto & column : sharding_key_expr->getRequiredColumns())
{
if (!expr_columns.contains(column))
return false;
}
return true;
};
// GROUP BY qualifiers
// - TODO: WITH TOTALS can be implemented
// - TODO: WITH ROLLUP can be implemented (I guess)
if (select.group_by_with_totals || select.group_by_with_rollup || select.group_by_with_cube)
return {};
// Window functions are not supported.
if (query_info.has_window)
return {};
// TODO: extremes support can be implemented
if (settings[Setting::extremes])
return {};
// DISTINCT
if (select.distinct)
{
if (!optimize_sharding_key_aggregation || !expr_contains_sharding_key(select.select()->children))
return {};
}
// GROUP BY
const ASTPtr group_by = select.groupBy();
bool has_aggregates = query_info.has_aggregates;
if (query_info.syntax_analyzer_result)
has_aggregates = !query_info.syntax_analyzer_result->aggregates.empty();
if (has_aggregates || group_by)
{
if (!optimize_sharding_key_aggregation || !group_by || !expr_contains_sharding_key(group_by->children))
return {};
}
// LIMIT BY
if (const ASTPtr limit_by = select.limitBy())
{
if (!optimize_sharding_key_aggregation || !expr_contains_sharding_key(limit_by->children))
return {};
}
// ORDER BY
if (const ASTPtr order_by = select.orderBy())
return default_stage;
// LIMIT
// OFFSET
if (select.limitLength() || select.limitOffset())
return default_stage;
// Only simple SELECT FROM GROUP BY sharding_key can use Complete state.
return QueryProcessingStage::Complete;
}
StorageSnapshotPtr StorageDistributed::getStorageSnapshot(const StorageMetadataPtr & metadata_snapshot, ContextPtr) const
{
return std::make_shared<StorageSnapshot>(*this, metadata_snapshot);
}
namespace
{
class ReplaseAliasColumnsVisitor : public InDepthQueryTreeVisitor<ReplaseAliasColumnsVisitor>
{
QueryTreeNodePtr getColumnNodeAliasExpression(const QueryTreeNodePtr & node) const
{
const auto * column_node = node->as<ColumnNode>();
if (!column_node || !column_node->hasExpression())
return nullptr;
const auto & column_source = column_node->getColumnSourceOrNull();
if (!column_source || column_source->getNodeType() == QueryTreeNodeType::JOIN
|| column_source->getNodeType() == QueryTreeNodeType::CROSS_JOIN
|| column_source->getNodeType() == QueryTreeNodeType::ARRAY_JOIN)
return nullptr;
auto column_expression = column_node->getExpression();
const auto & column_name = column_node->getColumnName();
if (!context->getSettingsRef()[Setting::enable_alias_marker])
{
column_expression->setAlias(column_name);
return column_expression;
}
String alias_id;
const auto & source_alias = column_source->getAlias();
if (!source_alias.empty())
alias_id = source_alias + "." + column_name;
else
alias_id = column_name;
if (auto * function_node = column_expression->as<FunctionNode>();
function_node && function_node->getFunctionName() == "__aliasMarker")
{
auto & arguments = function_node->getArguments().getNodes();
if (arguments.size() == 2)
arguments[1] = std::make_shared<ConstantNode>(alias_id, std::make_shared<DataTypeString>());
column_expression->setAlias(column_name);
return column_expression;
}
QueryTreeNodes arguments;
arguments.reserve(2);
arguments.emplace_back(std::move(column_expression));
arguments.emplace_back(std::make_shared<ConstantNode>(alias_id, std::make_shared<DataTypeString>()));
auto alias_marker_node = std::make_shared<FunctionNode>("__aliasMarker");
alias_marker_node->getArguments().getNodes() = std::move(arguments);
alias_marker_node->setAlias(column_name);
resolveOrdinaryFunctionNodeByName(*alias_marker_node, "__aliasMarker", context);
return alias_marker_node;
}
public:
explicit ReplaseAliasColumnsVisitor(ContextPtr context_) : context(std::move(context_)) {}
void visitImpl(QueryTreeNodePtr & node)
{
if (auto column_expression = getColumnNodeAliasExpression(node))
node = column_expression;
}
private:
ContextPtr context;
};
using ColumnNameToColumnNodeMap = std::unordered_map<std::string, ColumnNodePtr>;
ColumnNameToColumnNodeMap buildColumnNodesForTableExpression(const QueryTreeNodePtr & table_expression_node, const ContextPtr & context)
{
const TableNode * table_node = table_expression_node->as<TableNode>();
const TableFunctionNode * table_function_node = table_expression_node->as<TableFunctionNode>();
if (!table_node && !table_function_node)
return {};
// Rebuild per-column nodes (including ALIAS expressions) for the replacement table expression.
const auto & storage_snapshot = table_node ? table_node->getStorageSnapshot() : table_function_node->getStorageSnapshot();
auto get_column_options = GetColumnsOptions(GetColumnsOptions::All).withVirtuals();
if (storage_snapshot->storage.supportsSubcolumns())
get_column_options.withSubcolumns();
auto column_names_and_types = storage_snapshot->getColumns(get_column_options);
const auto & columns_description = storage_snapshot->metadata->getColumns();
ColumnNameToColumnNodeMap column_name_to_node;
column_name_to_node.reserve(column_names_and_types.size());
for (const auto & column_name_and_type : column_names_and_types)
{
const auto & column_default = columns_description.getDefault(column_name_and_type.name);
if (column_default && column_default->kind == ColumnDefaultKind::Alias)
{
auto alias_expression = buildQueryTree(column_default->expression, context);
QueryAnalysisPass(table_expression_node).run(alias_expression, context);
if (!alias_expression->getResultType()->equals(*column_name_and_type.type))
alias_expression = buildCastFunction(alias_expression, column_name_and_type.type, context, true);
auto column_node = std::make_shared<ColumnNode>(column_name_and_type, std::move(alias_expression), table_expression_node);
column_name_to_node.emplace(column_name_and_type.name, std::move(column_node));
}
else
{
auto column_node = std::make_shared<ColumnNode>(column_name_and_type, table_expression_node);
column_name_to_node.emplace(column_name_and_type.name, std::move(column_node));
}
}
return column_name_to_node;
}
class ReplaceColumnNodesForTableExpressionVisitor : public InDepthQueryTreeVisitor<ReplaceColumnNodesForTableExpressionVisitor>
{
public:
ReplaceColumnNodesForTableExpressionVisitor(
const QueryTreeNodePtr & from_,
const QueryTreeNodePtr & to_,
const ColumnNameToColumnNodeMap & column_name_to_node_)
: from(from_), to(to_), column_name_to_node(column_name_to_node_)
{}
void visitImpl(QueryTreeNodePtr & node)
{
auto * column_node = node->as<ColumnNode>();
if (!column_node)
return;
auto column_source = column_node->getColumnSourceOrNull();
if (!column_source)
return;
if (column_source.get() != from.get())
return;
auto it = column_name_to_node.find(column_node->getColumnName());
if (it != column_name_to_node.end())
{
auto replacement = it->second->clone();
replacement->setAlias(column_node->getAlias());
node = std::move(replacement);
}
else
{
// Preserve the column name but rebind its source to the replacement table expression.
column_node->setColumnSource(to);
}
}
static bool needChildVisit(const QueryTreeNodePtr &, const QueryTreeNodePtr & child_node)
{
auto child_node_type = child_node->getNodeType();
return !(child_node_type == QueryTreeNodeType::QUERY || child_node_type == QueryTreeNodeType::UNION);
}
private:
QueryTreeNodePtr from;
QueryTreeNodePtr to;
const ColumnNameToColumnNodeMap & column_name_to_node;
};
class RewriteInToGlobalInVisitor : public InDepthQueryTreeVisitorWithContext<RewriteInToGlobalInVisitor>
{
public:
using Base = InDepthQueryTreeVisitorWithContext<RewriteInToGlobalInVisitor>;
using Base::Base;
void enterImpl(QueryTreeNodePtr & node)
{
if (auto * function_node = node->as<FunctionNode>(); function_node && isNameOfLocalInFunction(function_node->getFunctionName()))
{
auto * query = function_node->getArguments().getNodes()[1]->as<QueryNode>();
if (!query)
return;
bool no_replace = true;
for (const auto & table_node : extractTableExpressions(query->getJoinTree(), false, true))
{
const StorageDistributed * storage_distributed = nullptr;
if (const TableNode * table_node_typed = table_node->as<TableNode>())
storage_distributed = typeid_cast<const StorageDistributed *>(table_node_typed->getStorage().get());
else if (const TableFunctionNode * table_function_node_typed = table_node->as<TableFunctionNode>())
storage_distributed = typeid_cast<const StorageDistributed *>(table_function_node_typed->getStorage().get());
if (!storage_distributed)
{
no_replace = false;
break;
}
}
if (no_replace)
return;
auto result_function = std::make_shared<FunctionNode>(getGlobalInFunctionNameForLocalInFunctionName(function_node->getFunctionName()));
result_function->getArguments().getNodes() = std::move(function_node->getArguments().getNodes());
resolveOrdinaryFunctionNodeByName(*result_function, result_function->getFunctionName(), getContext());
node = result_function;
}
}
static bool needChildVisit(QueryTreeNodePtr & parent, QueryTreeNodePtr &)
{
if (auto * function_node = parent->as<FunctionNode>(); function_node && function_node->getFunctionName().starts_with("global"))
return false;
return true;