Repository navigation
Expand file tree
/
Copy pathInterpreterInsertQuery.cpp
More file actions
1849 lines (1599 loc) · 91 KB
/
Copy pathInterpreterInsertQuery.cpp
File metadata and controls
1849 lines (1599 loc) · 91 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 <Interpreters/InterpreterFactory.h>
#include <Interpreters/InterpreterInsertQuery.h>
#include <Interpreters/capInsertBlockSizeBytesToMemoryLimit.h>
#include <Core/ProtocolDefines.h>
#include <Interpreters/ClientInfo.h>
#include <Storages/StorageInput.h>
#include <Access/Common/AccessFlags.h>
#include <Common/FailPoint.h>
#include <Common/MemoryTrackerUtils.h>
#include <AggregateFunctions/AggregateFunctionFactory.h>
#include <Columns/ColumnNullable.h>
#include <Core/Settings.h>
#include <Core/SettingsEnums.h>
#include <Core/ServerSettings.h>
#include <Core/DeduplicateInsert.h>
#include <DataTypes/DataTypeNullable.h>
#include <Interpreters/ApplyWithAliasVisitor.h>
#include <Interpreters/ApplyWithSubqueryVisitor.h>
#include <Interpreters/AsynchronousInsertQueue.h>
#include <Interpreters/DatabaseCatalog.h>
#include <Interpreters/MarkTableIdentifiersVisitor.h>
#include <Interpreters/QueryAliasesVisitor.h>
#include <Interpreters/QueryLog.h>
#include <Interpreters/QueryNormalizer.h>
#include <Interpreters/TranslateQualifiedNamesVisitor.h>
#include <Interpreters/processColumnTransformers.h>
#include <Interpreters/InterpreterSelectQueryAnalyzer.h>
#include <Interpreters/ExpressionActions.h>
#include <Interpreters/ClusterProxy/executeQuery.h>
#include <Interpreters/Context.h>
#include <Interpreters/InsertDependenciesBuilder.h>
#include <Parsers/ASTFunction.h>
#include <Parsers/ASTInsertQuery.h>
#include <Parsers/ASTSelectQuery.h>
#include <Parsers/ASTSelectWithUnionQuery.h>
#include <Parsers/ASTTablesInSelectQuery.h>
#include <Parsers/stripQuerySettings.h>
#include <Processors/Sinks/EmptySink.h>
#include <Processors/Transforms/CountingTransform.h>
#include <Processors/Transforms/ExpressionTransform.h>
#include <Processors/Transforms/DeduplicationTokenTransforms.h>
#include <Processors/Transforms/PlanSquashingTransform.h>
#include <Processors/Transforms/ApplySquashingTransform.h>
#include <Processors/Transforms/ShrinkColumnsTransform.h>
#include <Processors/ResizeProcessor.h>
#include <Processors/Transforms/getSourceFromASTInsertQuery.h>
#include <Processors/Transforms/AsyncInsertQueueTransform.h>
#include <QueryPipeline/QueryPipelineBuilder.h>
#include <Storages/StorageValues.h>
#include <Storages/MergeTree/MergeTreeData.h>
#include <Storages/MergeTree/MergeTreeSettings.h>
#include <Storages/StorageAlias.h>
#include <Storages/StorageDistributed.h>
#include <Storages/StorageMaterializedView.h>
#include <Storages/StorageProxy.h>
#include <TableFunctions/TableFunctionFactory.h>
#include <Common/logger_useful.h>
#include <Common/checkStackSize.h>
#include <Common/quoteString.h>
#include <Common/saturatedDuration.h>
#include <Core/Field.h>
#include <QueryPipeline/RemoteQueryExecutor.h>
#include <Processors/Sources/RemoteSource.h>
#include <Storages/IStorageCluster.h>
#include <Storages/StorageSnapshot.h>
#include <Storages/ColumnsDescription.h>
#include <Interpreters/JoinedTables.h>
#include <IO/WriteBufferFromString.h>
#include <Interpreters/ExpressionAnalyzer.h>
#include <Interpreters/TreeRewriter.h>
#include <Interpreters/getEffectiveMaxThreads.h>
#include <memory>
#include <unordered_set>
namespace DB
{
namespace Setting
{
extern const SettingsUInt64 max_expanded_ast_elements;
extern const SettingsBool async_insert;
extern const SettingsBool async_insert_select_as_async_insert;
extern const SettingsBool distributed_foreground_insert;
extern const SettingsBool insert_null_as_default;
extern const SettingsBool optimize_trivial_insert_select;
extern const SettingsBool parallel_view_processing;
extern const SettingsDeduplicateInsertSelectMode deduplicate_insert_select;
extern const SettingsMaxThreads max_threads;
extern const SettingsMaxThreads max_insert_threads;
extern const SettingsUInt64 max_insert_threads_min_free_memory_per_thread;
extern const SettingsBool use_strict_insert_block_limits;
extern const SettingsUInt64Auto insert_quorum;
extern const SettingsBool insert_quorum_parallel;
extern const SettingsBool deduplicate_blocks_in_dependent_materialized_views;
extern const SettingsNonZeroUInt64 max_insert_block_size;
extern const SettingsUInt64 max_insert_block_size_bytes;
extern const SettingsUInt64 min_insert_block_size_rows;
extern const SettingsNonZeroUInt64 max_block_size;
extern const SettingsUInt64 preferred_block_size_bytes;
extern const SettingsUInt64 min_insert_block_size_bytes;
extern const SettingsFloat shrink_over_allocated_columns_min_waste_ratio;
extern const SettingsUInt64 shrink_over_allocated_columns_min_waste_bytes;
extern const SettingsString insert_deduplication_token;
extern const SettingsBool use_concurrency_control;
extern const SettingsSeconds lock_acquire_timeout;
extern const SettingsUInt64 parallel_distributed_insert_select;
extern const SettingsBool enable_parsing_to_custom_serialization;
extern const SettingsUInt64 allow_experimental_parallel_reading_from_replicas;
extern const SettingsBool parallel_replicas_local_plan;
extern const SettingsBool parallel_replicas_prefer_local_replica;
extern const SettingsBool async_query_sending_for_remote;
extern const SettingsBool async_socket_for_remote;
extern const SettingsUInt64 max_distributed_depth;
extern const SettingsBool enable_global_with_statement;
extern const SettingsUInt64 async_insert_max_data_size;
extern const SettingsBool wait_for_async_insert;
extern const SettingsSeconds wait_for_async_insert_timeout;
extern const SettingsUInt64 readonly;
}
namespace MergeTreeSetting
{
extern const MergeTreeSettingsBool add_implicit_sign_column_constraint_for_collapsing_engine;
}
namespace FailPoints
{
extern const char insert_pause_before_reading_serialization_hints[];
}
namespace ServerSetting
{
extern const ServerSettingsBool disable_insertion_and_mutation;
}
namespace ErrorCodes
{
extern const int NOT_IMPLEMENTED;
extern const int NO_SUCH_COLUMN_IN_TABLE;
extern const int ILLEGAL_COLUMN;
extern const int DUPLICATE_COLUMN;
extern const int QUERY_IS_PROHIBITED;
extern const int TOO_LARGE_DISTRIBUTED_DEPTH;
extern const int EMPTY_LIST_OF_COLUMNS_PASSED;
extern const int LOGICAL_ERROR;
extern const int READONLY;
}
InterpreterInsertQuery::InterpreterInsertQuery(
const ASTPtr & query_ptr_, ContextMutablePtr context_, bool allow_materialized_, bool no_squash_, bool no_destination_, bool async_insert_,
bool is_initial_insert_, bool positional_arguments_already_resolved_)
: WithMutableContext(context_)
, logger(getLogger("InterpreterInsertQuery"))
, query_ptr(query_ptr_)
, allow_materialized(allow_materialized_)
, no_squash(no_squash_)
, no_destination(no_destination_)
, async_insert(async_insert_)
, is_initial_insert(is_initial_insert_)
, positional_arguments_already_resolved(positional_arguments_already_resolved_)
{
checkStackSize();
if (auto quota = getContext()->getQuota())
{
quota->checkExceededForQuery(getContext()->getNormalizedQueryHash(), QuotaType::WRITTEN_ROWS);
quota->checkExceededForQuery(getContext()->getNormalizedQueryHash(), QuotaType::WRITTEN_BYTES);
}
const Settings & settings = getContext()->getSettingsRef();
max_threads = getEffectiveMaxThreads(*getContext());
max_insert_threads = limitThreadsByFreeMemory(
*getContext(),
std::min(std::max<size_t>(1, settings[Setting::max_insert_threads]), max_threads),
settings[Setting::max_insert_threads_min_free_memory_per_thread]);
}
StoragePtr InterpreterInsertQuery::getTable(ASTInsertQuery & query)
{
auto current_context = getContext();
if (query.table_function)
{
/// An insert into a table function writes to its source, not to a temporary table,
/// so unlike temporary tables it is not allowed at `readonly = 2` either.
if (current_context->getSettingsRef()[Setting::readonly])
{
const auto & client_info = current_context->getClientInfo();
if (client_info.interface == ClientInfo::Interface::HTTP && client_info.http_method == ClientInfo::HTTPMethod::GET)
throw Exception(ErrorCodes::READONLY,
"{}: Cannot execute query in readonly mode. "
"For queries over HTTP, method GET implies readonly. "
"You should use method POST for modifying queries", current_context->getUserName());
throw Exception(ErrorCodes::READONLY, "{}: Cannot execute query in readonly mode", current_context->getUserName());
}
const auto & factory = TableFunctionFactory::instance();
TableFunctionPtr table_function_ptr = factory.get(query.table_function, current_context);
/// If table function needs structure hint from select query
/// we can create a temporary pipeline and get the header.
if (query.select && table_function_ptr->needStructureHint())
{
auto select_query_options = SelectQueryOptions(QueryProcessingStage::Complete, 1)
.positionalArgumentsAlreadyResolved(positional_arguments_already_resolved);
auto header_block = InterpreterSelectQueryAnalyzer::getSampleBlock(query.select, current_context, select_query_options);
ColumnsDescription structure_hint{header_block->getNamesAndTypesList()};
table_function_ptr->setStructureHint(structure_hint);
}
table_function_ptr->setPartitionBy(query.partition_by);
return table_function_ptr->execute(query.table_function, current_context, table_function_ptr->getName(),
/* cached_columns */ {}, /* use_global_context */ false, /* is_insert_query */true);
}
if (query.table_id)
{
query.table_id = current_context->resolveStorageID(query.table_id);
}
else
{
/// Insert query parser does not fill table_id because table and
/// database can be parameters and be filled after parsing.
StorageID local_table_id(query.getDatabase(), query.getTable());
query.table_id = current_context->resolveStorageID(local_table_id);
}
/// The insert path reads engine facts the proxy of an unloaded table cannot answer.
return resolveStorageProxyLoading(DatabaseCatalog::instance().getTable(query.table_id, current_context));
}
Block InterpreterInsertQuery::getSampleBlock(
const ASTInsertQuery & query,
const StoragePtr & table,
const StorageMetadataPtr & metadata_snapshot,
ContextPtr context_,
bool no_destination,
bool allow_materialized)
{
/// If the query does not include information about columns
if (!query.columns)
{
if (no_destination)
return metadata_snapshot->getSampleBlockWithVirtuals(VirtualsKind::All, VirtualsMaterializationPlace::All);
return metadata_snapshot->getSampleBlockNonMaterialized();
}
/// Form the block based on the column names from the query
const auto columns_ast = processColumnTransformers(context_->getCurrentDatabase(), table, metadata_snapshot, query.columns);
Names names;
names.reserve(columns_ast->children.size());
for (const auto & identifier : columns_ast->children)
{
std::string current_name = identifier->getColumnName();
names.emplace_back(std::move(current_name));
}
return getSampleBlock(names, table, metadata_snapshot, no_destination, allow_materialized);
}
Block InterpreterInsertQuery::getSampleBlock(
const Names & names,
const StoragePtr & table,
const StorageMetadataPtr & metadata_snapshot,
bool allow_virtuals,
bool allow_materialized)
{
std::vector<size_t> missing_positions;
Block table_sample_insertable = metadata_snapshot->getSampleBlockInsertable();
ColumnsWithTypeAndName res{names.size()};
std::unordered_set<String> inserted_names;
for (size_t i = 0; i < names.size(); i++)
{
const auto & current_name = names[i];
if (!inserted_names.insert(current_name).second)
throw Exception(
ErrorCodes::DUPLICATE_COLUMN,
"Column {} in table {} specified more than once",
current_name,
table->getStorageID().getNameForLogs());
const ColumnWithTypeAndName * insertable_col = table_sample_insertable.findByName(current_name);
if (!insertable_col)
missing_positions.emplace_back(i);
else
res[i] = *insertable_col;
}
if (!missing_positions.empty())
{
Block table_sample_physical = metadata_snapshot->getSampleBlock();
Block table_sample_virtuals;
if (allow_virtuals)
table_sample_virtuals = metadata_snapshot->virtuals.getSampleBlock(VirtualsKind::All, VirtualsMaterializationPlace::All);
/// Columns are not ordinary or ephemeral
for (auto pos : missing_positions)
{
const auto & current_name = names[pos];
if (table_sample_physical.has(current_name))
{
/// Column is materialized
if (!allow_materialized)
throw Exception(ErrorCodes::ILLEGAL_COLUMN, "Cannot insert column {}, because it is MATERIALIZED column", current_name);
res[pos] = table_sample_physical.getByName(current_name);
}
else if (table_sample_virtuals.has(current_name))
{
res[pos] = table_sample_virtuals.getByName(current_name);
}
else
{
/// The table does not have a column with that name
throw Exception(
ErrorCodes::NO_SUCH_COLUMN_IN_TABLE,
"No such column {} in table {}",
current_name,
table->getStorageID().getNameForLogs());
}
}
}
return res;
}
static bool hasAggregateFunctions(const IAST * ast)
{
if (const auto * func = typeid_cast<const ASTFunction *>(ast))
if (AggregateUtils::isAggregateFunction(*func))
return true;
for (const auto & child : ast->children)
if (hasAggregateFunctions(child.get()))
return true;
return false;
}
/** A query that just reads all data without any complex computations or filetering.
* If we just pipe the result to INSERT, we don't have to use too many threads for read.
*/
static bool isTrivialSelect(const ASTPtr & select)
{
if (auto * select_query = select->as<ASTSelectQuery>())
{
const auto & tables = select_query->tables();
if (!tables)
return false;
const auto & tables_in_select_query = tables->as<ASTTablesInSelectQuery &>();
if (tables_in_select_query.children.size() != 1)
return false;
const auto & child = tables_in_select_query.children.front();
const auto & table_element = child->as<ASTTablesInSelectQueryElement &>();
const auto & table_expr = table_element.table_expression->as<ASTTableExpression &>();
if (table_expr.subquery)
return false;
/// Note: how to write it in more generic way?
return (!select_query->distinct
&& !select_query->limit_with_ties
&& !select_query->prewhere()
&& !select_query->where()
&& !select_query->groupBy()
&& !select_query->having()
&& !select_query->orderBy()
&& !select_query->limitBy()
&& !hasAggregateFunctions(select_query));
}
/// This query is ASTSelectWithUnionQuery subquery
return false;
}
bool InterpreterInsertQuery::shouldAddSquashingForStorage(const StoragePtr & table, ContextPtr context_)
{
const Settings & settings = context_->getSettingsRef();
/// Do not squash blocks if it is a sync INSERT into Distributed, since it lead to double bufferization on client and server side.
/// Client-side bufferization might cause excessive timeouts (especially in case of big blocks).
return !(settings[Setting::distributed_foreground_insert] && table->isRemote());
}
static std::optional<std::pair<QueryPipelineBuilder, ClusterProxy::LocalPlanParallelReplicasInfo>>
getLocalSelectPipelineForInserSelectWithParallelReplicas(const ASTPtr & select, const ContextPtr & context)
{
auto select_query_options = SelectQueryOptions(QueryProcessingStage::Complete, /*subquery_depth_=*/1);
InterpreterSelectQueryAnalyzer interpreter(select, context, select_query_options);
auto & plan = interpreter.getQueryPlan();
/// Find reading steps for remote replicas and remove them,
/// When building local pipeline, the local replica will be registered in the returned coordinator,
/// and announce its snapshot. The snapshot will be used to assign read tasks to involved replicas
/// So, the remote pipelines, which will be created later, should use the same coordinator.
/// The connection pools and local replica index decided here are returned too, so the remote pass
/// reuses the exact same replica set rather than recomputing liveness from a fresh snapshot.
auto parallel_replicas_info = ClusterProxy::dropReadFromRemoteInPlan(plan);
if (!parallel_replicas_info)
return {};
return std::make_pair(interpreter.buildQueryPipeline(), std::move(*parallel_replicas_info));
}
Block InterpreterInsertQuery::convertSelectToInsertSchema(
QueryPipelineBuilder & pipeline,
const ASTInsertQuery & query,
const StoragePtr & table,
const ContextPtr & context_,
bool no_destination,
bool allow_materialized)
{
auto metadata_snapshot = table->getInMemoryMetadataPtr(context_, false);
auto query_sample_block = getSampleBlock(query, table, metadata_snapshot, context_, no_destination, allow_materialized);
pipeline.dropTotalsAndExtremes();
/// Allow to insert Nullable into non-Nullable columns, NULL values will be added as defaults values.
if (context_->getSettingsRef()[Setting::insert_null_as_default])
{
const auto & input_columns = pipeline.getHeader().getColumnsWithTypeAndName();
const auto & query_columns = query_sample_block.getColumnsWithTypeAndName();
const auto & output_columns = metadata_snapshot->getColumns();
if (input_columns.size() == query_columns.size())
{
for (size_t col_idx = 0; col_idx < query_columns.size(); ++col_idx)
{
/// Change query sample block columns to Nullable to allow inserting nullable columns, where NULL values will be substituted with
/// default column values (in AddingDefaultsTransform), so all values will be cast correctly.
if (isNullableOrLowCardinalityNullable(input_columns[col_idx].type)
&& !isNullableOrLowCardinalityNullable(query_columns[col_idx].type)
&& !isVariant(query_columns[col_idx].type)
&& !isDynamic(query_columns[col_idx].type)
&& output_columns.has(query_columns[col_idx].name))
{
query_sample_block.setColumn(
col_idx,
ColumnWithTypeAndName(
makeNullableOrLowCardinalityNullable(query_columns[col_idx].column),
makeNullableOrLowCardinalityNullable(query_columns[col_idx].type),
query_columns[col_idx].name));
}
}
}
}
auto actions_dag = ActionsDAG::makeConvertingActions(
pipeline.getHeader().getColumnsWithTypeAndName(),
query_sample_block.getColumnsWithTypeAndName(),
ActionsDAG::MatchColumnsMode::Position,
context_);
auto actions = std::make_shared<ExpressionActions>(std::move(actions_dag), ExpressionActionsSettings(context_, CompileExpressions::yes));
pipeline.addSimpleTransform([&](const SharedHeader & in_header) -> ProcessorPtr
{
return std::make_shared<ExpressionTransform>(in_header, actions);
});
return query_sample_block;
}
/// Bounds the Alias chase, so a cyclic catalog state still terminates.
constexpr size_t max_alias_chase_depth = 8;
/// A `StorageAlias` chain is one destination; returns false when it is broken or too deep, counted as unresolvable.
static bool collectDestinationIdentities(const StoragePtr & table, std::unordered_set<const IStorage *> & identities)
{
StoragePtr storage = table;
for (size_t depth = 0; depth <= max_alias_chase_depth; ++depth)
{
if (!storage)
return false;
/// A cycle adds nothing new: everything reachable is already collected.
if (!identities.insert(storage.get()).second)
return true;
const auto * alias = storage->as<StorageAlias>();
if (!alias)
return true;
storage = alias->tryGetTargetTable();
}
return false;
}
/// True if this SELECT pipeline reads the destination table, or if that cannot be established (needed
/// because the queue route would let the SELECT side's lock outlive the wait for the flush's own lock,
/// stalling a DDL write arriving in between). Reads the pipeline's storage holders rather than
/// re-deriving the table set from the AST.
static bool selectPipelineReadsDestinationTable(const QueryPipelineBuilder & pipeline, const StoragePtr & table)
{
std::unordered_set<const IStorage *> destination_identities;
if (!collectDestinationIdentities(table, destination_identities))
return true;
for (const auto & storage : pipeline.getResources().storage_holders)
if (destination_identities.contains(storage.get()))
return true;
return false;
}
QueryPipeline InterpreterInsertQuery::addInsertToSelectPipeline(
ASTInsertQuery & query, StoragePtr table, QueryPipelineBuilder & pipeline, bool add_async_insert_queue_transform,
TableLockHolder * destination_lock)
{
auto context = getContext();
// disable parallel replicas for inserts if enabled
// the insert can trigger update for dependent materialized views
// using parallel replicas in this context is unnecessary
/// Not only on the initiator: a follower or a `*Cluster` worker executing a forwarded INSERT would otherwise
/// start a coordinated read in a materialized view, and nothing coordinates it.
if (context->canUseTaskBasedParallelReplicas())
{
auto mutable_context = Context::createCopy(context);
mutable_context->setSetting("enable_parallel_replicas", Field{0});
context = mutable_context;
}
auto query_sample_block = convertSelectToInsertSchema(pipeline, query, table, context, no_destination, allow_materialized);
/// Frozen for a block diverted to the queue: `query_sample_block` is moved into
/// `insert_dependencies` below.
Names insert_column_names = query_sample_block.getNames();
/// The queue flush has no defaults step to undo the `Nullable` widening `insert_null_as_default`
/// applies, so such a query stays on the sink chain below.
bool needs_null_default_sync = false;
bool select_reads_destination = false;
if (add_async_insert_queue_transform)
{
/// Named handle: converting a temporary `StorageMetadataHandle` to `StorageMetadataPtr` is deleted.
auto metadata_snapshot = table->getInMemoryMetadataPtr(context, false);
needs_null_default_sync = !blocksHaveEqualStructure(
query_sample_block,
getSampleBlock(query, table, metadata_snapshot, context, no_destination, allow_materialized));
select_reads_destination = selectPipelineReadsDestinationTable(pipeline, table);
}
auto deduplicate_insert_select = isDeduplicationEnabledForInsertSelect(
select_query_sorted, context->getSettingsRef(),
context->getSettingsRef()[Setting::insert_deduplication_token].value, logger);
/// Pin the decision whenever the queue route is possible, so it deduplicates the same as the sync
/// route: the queue flush otherwise resolves it through `async_insert_deduplicate` instead.
const bool deduplication_differs_from_sync_default
= deduplicate_insert_select != isDeduplicationEnabledForInsert(false, context->getSettingsRef());
const bool deduplication_differs_from_async_default = add_async_insert_queue_transform
&& deduplicate_insert_select != isDeduplicationEnabledForInsert(true, context->getSettingsRef());
if (deduplication_differs_from_sync_default || deduplication_differs_from_async_default)
{
auto tmp_context = Context::createCopy(context);
overrideDeduplicationSetting(deduplicate_insert_select, tmp_context);
context = tmp_context;
}
auto insert_dependencies = InsertDependenciesBuilder::create(
table, query_ptr, std::make_shared<const Block>(std::move(query_sample_block)),
async_insert, /*skip_destination_table*/ no_destination, max_insert_threads,
context, /*preserve_input_order=*/ pipeline.getNumStreams() == 1);
returning_insert_views_serial = query.returning && insert_dependencies->getViewProcessingNumThreads() == 1;
const auto & settings = context->getSettingsRef();
if (add_async_insert_queue_transform)
{
std::string_view reason;
if (needs_null_default_sync)
reason = "insert_null_as_default widens the block to Nullable";
else if (select_reads_destination)
reason = "SELECT reads the destination table";
/// Views are excluded wholesale, not per view target: a diverted block leaves their sink chain
/// built but unfed. `isViewsInvolved` only sees the dependency graph `collectAllDependencies`
/// walked from `table`; an `Alias` destination hides its target's own dependent views behind
/// the nested `INSERT` its `AliasSink` runs at execution time, so that hop needs its own probe.
else if (insert_dependencies->isViewsInvolved() || InsertDependenciesBuilder::forwardedInsertHidesDependentView(table))
reason = "destination table has dependent views";
if (reason.empty())
LOG_DEBUG(logger, "INSERT ... SELECT is eligible for the asynchronous insert queue route");
else
{
LOG_DEBUG(logger, "INSERT ... SELECT will be executed synchronously (reason: {})", reason);
add_async_insert_queue_transform = false;
}
}
/// Hands the whole destination side over to the queue transform: either divert a single small
/// block to the async queue, or lazily build the same push pipeline a plain `INSERT` would use,
/// once ineligibility is actually confirmed. Building the sink chain below unconditionally would
/// start it (and any start-time side effect it has, e.g. `AliasSink` opening its nested `INSERT`)
/// before that decision is made; see `AsyncInsertQueueTransform`.
if (add_async_insert_queue_transform)
{
/// Only callers that hand the destination lock over may ask for this route.
chassert(destination_lock);
/// Only the main stream may divert a block and take the lock over; collapse to it first.
if (pipeline.getNumStreams() != 1)
pipeline.resize(1);
pipeline.addSimpleTransform([&](const SharedHeader & in_header, QueryPipelineBuilder::StreamType stream_type) -> ProcessorPtr
{
/// Only the main stream carries rows to divert, and only it may take the lock over. A
/// `WITH TOTALS` select also offers totals and extremes streams, whose blocks belong to
/// no insert at all.
if (stream_type != QueryPipelineBuilder::StreamType::Main)
return nullptr;
return std::make_shared<AsyncInsertQueueTransform>(
in_header, context->tryGetAsynchronousInsertQueue(), context, query_ptr, insert_column_names,
settings[Setting::async_insert_max_data_size],
saturatedMilliseconds(settings[Setting::wait_for_async_insert_timeout].totalMilliseconds()).count(),
settings[Setting::wait_for_async_insert],
std::move(*destination_lock),
insert_dependencies, table, max_threads, no_squash, async_insert);
});
pipeline.setSinks([&](const SharedHeader & cur_header, QueryPipelineBuilder::StreamType) -> ProcessorPtr
{
return std::make_shared<EmptySink>(cur_header);
});
return QueryPipelineBuilder::getPipeline(std::move(pipeline));
}
/// Reached only when the async route was never eligible: build the ordinary synchronous
/// `INSERT ... SELECT` tail directly on the `SELECT` pipeline.
pipeline.addSimpleTransform([&](const SharedHeader & in_header) -> ProcessorPtr
{
auto counting = std::make_shared<CountingTransform>(in_header, context->getQuota(), context->getNormalizedQueryHash());
counting->setProcessListElement(context->getProcessListElement());
counting->setProgressCallback(context->getProgressCallback());
return counting;
});
/// Count on the parallel SELECT streams, then collapse: dedup info and squashing need one stream.
if (pipeline.getNumStreams() != 1)
pipeline.resize(1);
bool squash_with_strict_limits = settings[Setting::use_strict_insert_block_limits] && !async_insert;
if (!squash_with_strict_limits)
{
pipeline.addSimpleTransform([&](const SharedHeader & in_header) -> ProcessorPtr
{
return std::make_shared<AddDeduplicationInfoTransform>(
insert_dependencies,
insert_dependencies->getRootViewID(),
context->getSettingsRef()[Setting::insert_deduplication_token].value,
in_header);
});
}
bool should_squash = shouldAddSquashingForStorage(table, getContext()) && !no_squash;
if (should_squash)
{
pipeline.addSimpleTransform(
[&](const SharedHeader & in_header) -> ProcessorPtr
{
size_t min_block_size_bytes = table->prefersLargeBlocks() ? context->getSettingsRef()[Setting::min_insert_block_size_bytes] : 0ULL;
/// On low-memory systems, cap squashing block size to avoid accumulating too much data.
min_block_size_bytes = capInsertBlockSizeBytesToMemoryLimit(min_block_size_bytes, settings);
return std::make_shared<PlanSquashingTransform>(
in_header,
table->prefersLargeBlocks() ? settings[Setting::min_insert_block_size_rows] : settings[Setting::max_block_size],
min_block_size_bytes,
settings[Setting::max_insert_block_size],
settings[Setting::max_insert_block_size_bytes],
squash_with_strict_limits);
});
}
VectorWithMemoryTracking<Chain> sink_chains
= insert_dependencies->createChainWithDependenciesForAllStreams(query.returning ? &returning_output : nullptr);
pipeline.resize(insert_dependencies->getSinkStreamSize());
if (should_squash)
{
pipeline.addSimpleTransform(
[&](const SharedHeader & in_header) -> ProcessorPtr
{
return std::make_shared<ApplySquashingTransform>(in_header);
});
}
if (squash_with_strict_limits)
{
pipeline.addSimpleTransform([&](const SharedHeader & in_header) -> ProcessorPtr
{
return std::make_shared<AddDeduplicationInfoTransform>(
insert_dependencies,
insert_dependencies->getRootViewID(),
settings[Setting::insert_deduplication_token].value,
in_header);
});
}
for (auto & chain : sink_chains)
{
pipeline.addResources(chain.detachResources());
}
pipeline.addChains(std::move(sink_chains));
pipeline.setMaxThreads(max_threads);
// Cap to 1 when parallel_view_processing=0. Pipe::max_parallel_streams is a watermark that
// resize() does not lower, so limitMaxThreads is needed even after resize(sink_stream_size).
pipeline.limitMaxThreads(insert_dependencies->getViewProcessingNumThreads());
pipeline.setSinks([&](const SharedHeader & cur_header, QueryPipelineBuilder::StreamType) -> ProcessorPtr
{
return std::make_shared<EmptySink>(cur_header);
});
return QueryPipelineBuilder::getPipeline(std::move(pipeline));
}
void InterpreterInsertQuery::applyTrivialInsertSelectOptimization(ASTInsertQuery & query, bool prefer_large_blocks, size_t effective_max_insert_threads, ContextPtr & select_context)
{
const Settings & settings = select_context->getSettingsRef();
bool is_trivial_insert_select = false;
if (settings[Setting::optimize_trivial_insert_select])
{
const auto & select_query = query.select->as<ASTSelectWithUnionQuery &>();
const auto & selects = select_query.list_of_selects->children;
const auto & union_modes = select_query.list_of_modes;
/// ASTSelectWithUnionQuery is not normalized now, so it may pass some queries which can be Trivial select queries
const auto mode_is_all = [](const auto & mode) { return mode == SelectUnionMode::UNION_ALL; };
is_trivial_insert_select =
std::all_of(union_modes.begin(), union_modes.end(), std::move(mode_is_all))
&& std::all_of(selects.begin(), selects.end(), isTrivialSelect);
}
if (is_trivial_insert_select)
{
/** When doing trivial INSERT INTO ... SELECT ... FROM table,
* don't need to process SELECT with more than max_insert_threads
* and it's reasonable to set block size for SELECT to the desired block size for INSERT
* to avoid unnecessary squashing.
*/
Settings new_settings = select_context->getSettingsCopy();
/// The effective value from the constructor is already capped by `max_threads` and by the
/// available memory; the raw setting is not.
new_settings[Setting::max_threads] = effective_max_insert_threads;
if (prefer_large_blocks)
{
if (settings[Setting::min_insert_block_size_rows])
new_settings[Setting::max_block_size] = settings[Setting::min_insert_block_size_rows];
if (settings[Setting::min_insert_block_size_bytes])
{
/// On low-memory systems, cap the input format block size.
new_settings[Setting::preferred_block_size_bytes]
= capInsertBlockSizeBytesToMemoryLimit(settings[Setting::min_insert_block_size_bytes], settings);
}
}
auto context_for_trivial_select = Context::createCopy(select_context);
context_for_trivial_select->setSettings(new_settings);
select_context = context_for_trivial_select;
}
}
bool InterpreterInsertQuery::queryHasOrderByAll(const ASTPtr & select)
{
if (auto * select_query = select->as<ASTSelectQuery>())
{
return select_query->order_by_all;
}
else if (auto * union_query = select->as<ASTSelectWithUnionQuery>())
{
if (union_query->list_of_selects->children.size() != 1)
return false;
if (auto * first_select_query = union_query->list_of_selects->children.front()->as<ASTSelectQuery>())
return first_select_query->order_by_all;
}
return false;
}
QueryPipeline InterpreterInsertQuery::buildInsertSelectPipeline(
ASTInsertQuery & query, StoragePtr table, bool add_async_insert_queue_transform, TableLockHolder & destination_lock)
{
ContextPtr select_context = getContext();
applyTrivialInsertSelectOptimization(query, table->prefersLargeBlocks(), max_insert_threads, select_context);
QueryPipelineBuilder pipeline = [&]()
{
auto select_query_options = SelectQueryOptions(QueryProcessingStage::Complete, 1)
.positionalArgumentsAlreadyResolved(positional_arguments_already_resolved);
InterpreterSelectQueryAnalyzer interpreter_select_analyzer(query.select, select_context, select_query_options);
return interpreter_select_analyzer.buildQueryPipeline();
}();
/// ORDER BY ALL should produce a single globally-sorted stream.
/// However, certain edge cases (e.g., BuzzHouse fuzzer findings on specific
/// table engines or optimizer paths) can result in multiple streams.
/// Treat multi-stream output as unsorted — deduplication won't be enabled,
/// but the query executes correctly since addInsertToSelectPipeline()
/// resizes to 1 stream regardless.
select_query_sorted = queryHasOrderByAll(query.select) && pipeline.getNumStreams() <= 1;
return addInsertToSelectPipeline(query, table, pipeline, add_async_insert_queue_transform, &destination_lock);
}
std::optional<std::pair<QueryPipeline, ClusterProxy::LocalPlanParallelReplicasInfo>>
InterpreterInsertQuery::buildLocalInsertSelectPipelineForParallelReplicas(
ASTInsertQuery & query, const StoragePtr & table, ContextPtr select_context)
{
applyTrivialInsertSelectOptimization(query, table->prefersLargeBlocks(), max_insert_threads, select_context);
auto local_select = getLocalSelectPipelineForInserSelectWithParallelReplicas(query.select, select_context);
if (!local_select)
return {};
auto & [pipeline_builder, parallel_replicas_info] = *local_select;
/// Parallel replicas builds its own local pipeline and never routes through the async insert queue,
/// so it hands over no lock and the caller keeps it for the whole pipeline.
auto local_pipeline = addInsertToSelectPipeline(
query, table, pipeline_builder, /* add_async_insert_queue_transform */ false, /* destination_lock */ nullptr);
return std::make_pair(std::move(local_pipeline), std::move(parallel_replicas_info));
}
static bool isInsertSelectTrivialEnoughForDistributedExecution(const ASTInsertQuery & query)
{
const auto & select = query.select->as<ASTSelectWithUnionQuery &>();
const auto & selects = select.list_of_selects->children;
if (selects.size() != 1)
return {};
if (auto * select_query = selects.front()->as<ASTSelectQuery>())
{
const auto & tables = select_query->tables();
if (!tables)
return false;
const auto & tables_in_select_query = tables->as<ASTTablesInSelectQuery &>();
if (tables_in_select_query.children.size() != 1)
return false;
const auto & child = tables_in_select_query.children.front();
const auto & table_element = child->as<ASTTablesInSelectQueryElement &>();
const auto & table_expr = table_element.table_expression->as<ASTTableExpression &>();
if (table_expr.subquery)
return false;
/// TODO: replace with QueryTree analysis after switching to analyzer completely
return (!select_query->distinct
&& !select_query->limit_with_ties
&& !select_query->groupBy()
&& !select_query->having()
&& !select_query->orderBy()
&& !select_query->limitBy()
&& !select_query->limitLength()
&& !select_query->limitAfter()
&& !select_query->limitUntil()
&& !hasAggregateFunctions(select_query));
}
return false;
}
std::optional<QueryPipeline> InterpreterInsertQuery::buildInsertSelectPipelineParallelReplicas(ASTInsertQuery & query, StoragePtr table)
{
const Settings & settings = getContext()->getSettingsRef();
if (settings[Setting::parallel_distributed_insert_select] != 2)
return {};
/// Create a context with automatic_parallel_replicas_mode disabled upfront.
/// INSERT SELECT should use parallel replicas regardless of automatic mode.
auto context = Context::createCopy(getContext());
context->setSetting("automatic_parallel_replicas_mode", Field{0});
/// A follower executing the shipped INSERT never uses the plan-based implementation of parallel
/// replicas: `collaborate_with_initiator` makes `canUseParallelReplicasOnInitiator` false, which is what
/// gates `QueryPlanOptimizationSettings::enable_parallel_replicas`. The initiator takes part as one more
/// replica, so it has to read the way the followers read. This is not a fallback for a declined
/// plan-based query: the feature is defined on top of the query-shipping transport.
context->setSetting("parallel_replicas_plan_based", false);
if (!context->canUseParallelReplicasOnInitiator())
return {};
// NOTE: should we limit it more here?
if (auto storage = getTable(query); storage->isMergeTree() && !storage->supportsReplication())
return {};
if (!isInsertSelectTrivialEnoughForDistributedExecution(query))
return {};
/// Pinning them on the context above is not enough: the nested interpreter re-applies the SELECT's own
/// `SETTINGS` clause on top of the context it is handed (`QueryTreeBuilder::buildSelectExpression`),
/// bringing the plan-based implementation or the automatic mode back for the plans built below, and
/// the automatic mode would make the probe below decline to distribute the insert. `execute` restores
/// `query.select` from its backup once this returns, so the user's query text is not affected.
/// `parallel_replicas_plan_based` is removed from subqueries too: this path is query-based, so the
/// setting has no effect anywhere in it, and a subquery keeping it would be rejected as plan-based.
static constexpr std::array settings_overridden_for_this_path{std::string_view{"automatic_parallel_replicas_mode"}};
removeSettingsFromQueryTopLevel(query.select, settings_overridden_for_this_path);
static constexpr std::array settings_without_effect_on_this_path{std::string_view{"parallel_replicas_plan_based"}};
removeSettingsFromQuery(query.select, settings_without_effect_on_this_path);
auto select = query.select->as<ASTSelectWithUnionQuery &>().list_of_selects->children.front();
if (!ClusterProxy::isSuitableForInsertSelectWithParallelReplicas(select, context))
return {};
LOG_TRACE(logger, "Building distributed insert select pipeline with parallel replicas: table={}", query.getTable());
if (settings[Setting::parallel_replicas_local_plan] && settings[Setting::parallel_replicas_prefer_local_replica])
{
/// The local pipeline executes inside the initiator's pipeline and shares the initiator's 'QueryStatus',
/// so it cannot be bounded by 'max_execution_time_leaf' (the leaf timeout is substituted into
/// 'max_execution_time' only for remote replicas, which build their own 'QueryStatus' from the shipped
/// settings). Skip the local pipeline when the leaf timeout contract differs from the initiator's timeout
/// contract so that all leaf reading happens on remote replicas — the same approach as for SELECT in
/// 'updateContextForParallelReplicas'.
if (ClusterProxy::leafTimeoutRequiresRemoteOnlyLeafReading(settings))
{
LOG_TRACE(
logger,
"Not using the local insert select pipeline because the leaf timeout contract differs from the "
"initiator's: the local pipeline shares the initiator's query status and cannot use the leaf "
"timeout separately");
}
else if (auto local = buildLocalInsertSelectPipelineForParallelReplicas(query, table, context))
{
auto & [local_pipeline, parallel_replicas_info] = *local;
auto coordinator = parallel_replicas_info.coordinator;
auto local_replica_index = parallel_replicas_info.local_replica_index;
return ClusterProxy::executeInsertSelectWithParallelReplicas(
query,
context,
std::move(local_pipeline),
std::move(coordinator),
std::move(parallel_replicas_info.connection_pools),
local_replica_index);
}
else
{
LOG_TRACE(logger, "Not using the local insert select pipeline because the SELECT plan has no local part");
}
}
return ClusterProxy::executeInsertSelectWithParallelReplicas(query, context);
}
/// For INSERT ... RETURNING with the data sent by the client separately, the client receives the result while sending the data.
static void checkClientSupportsReturningWithDataSentSeparately(const ContextPtr & context)
{
auto query_context = context->getQueryContext();
const auto & client_info = query_context->getClientInfo();
bool supported = query_context->getInputBlocksReaderCallback()
&& (client_info.interface == ClientInfo::Interface::LOCAL
|| (client_info.interface == ClientInfo::Interface::TCP
&& client_info.client_tcp_protocol_version >= DBMS_MIN_REVISION_WITH_INSERT_RETURNING));
if (!supported)
throw Exception(ErrorCodes::NOT_IMPLEMENTED,
"RETURNING is not supported for INSERT with the data sent separately by this client or interface. "
"Put the data into the query, or use INSERT SELECT");
}
QueryPipeline InterpreterInsertQuery::buildInsertPipeline(ASTInsertQuery & query, StoragePtr table)
{
auto context = getContext();
// disable parallel replicas for inserts if enabled
// the insert can trigger update for dependent materialized views
// using parallel replicas in this context is unnecessary
/// Not only on the initiator: a follower or a `*Cluster` worker executing a forwarded INSERT would otherwise
/// start a coordinated read in a materialized view, and nothing coordinates it.
if (context->canUseTaskBasedParallelReplicas())
{