Repository navigation
Expand file tree
/
Copy pathQueryPipelineBuilder.cpp
More file actions
844 lines (688 loc) · 32.5 KB
/
Copy pathQueryPipelineBuilder.cpp
File metadata and controls
844 lines (688 loc) · 32.5 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
#include <QueryPipeline/QueryPipelineBuilder.h>
#include <Core/SortDescription.h>
#include <Core/UUID.h>
#include <IO/WriteHelpers.h>
#include <Interpreters/Context.h>
#include <Interpreters/IJoin.h>
#include <Interpreters/TableJoin.h>
#include <Processors/ConcatProcessor.h>
#include <Processors/DelayedPortsProcessor.h>
#include <Processors/Executors/PipelineExecutor.h>
#include <Processors/Formats/IOutputFormat.h>
#include <Processors/LimitTransform.h>
#include <Processors/QueryPlan/ExpressionStep.h>
#include <Processors/QueryPlan/QueryPlan.h>
#include <Processors/ResizeProcessor.h>
#include <Processors/RowsBeforeStepCounter.h>
#include <Processors/Sources/RemoteSource.h>
#include <Processors/Sources/SourceFromSingleChunk.h>
#include <Processors/Transforms/CreatingSetsTransform.h>
#include <Processors/Transforms/ExpressionTransform.h>
#include <Processors/Transforms/ExtremesTransform.h>
#include <Processors/Transforms/JoiningTransform.h>
#include <Processors/Transforms/MergeJoinTransform.h>
#include <Processors/Transforms/MergingAggregatedMemoryEfficientTransform.h>
#include <Processors/Transforms/PartialSortingTransform.h>
#include <Processors/Transforms/PasteJoinTransform.h>
#include <Processors/Transforms/SquashingTransform.h>
#include <Processors/Transforms/TotalsHavingTransform.h>
#include <QueryPipeline/narrowPipe.h>
#include <Common/CurrentThread.h>
#include <Common/iota.h>
#include <Common/typeid_cast.h>
namespace DB
{
namespace ErrorCodes
{
extern const int LOGICAL_ERROR;
extern const int NOT_IMPLEMENTED;
}
void QueryPipelineBuilder::checkInitialized()
{
if (!initialized())
throw Exception(ErrorCodes::LOGICAL_ERROR, "QueryPipeline is uninitialized");
}
void QueryPipelineBuilder::checkInitializedAndNotCompleted()
{
checkInitialized();
if (pipe.isCompleted())
throw Exception(ErrorCodes::LOGICAL_ERROR, "QueryPipeline is already completed");
}
static void checkSource(const ProcessorPtr & source, bool can_have_totals)
{
if (!source->getInputs().empty())
throw Exception(
ErrorCodes::LOGICAL_ERROR,
"Source for query pipeline shouldn't have any input, but {} has {} inputs",
source->getName(),
source->getInputs().size());
if (source->getOutputs().empty())
throw Exception(
ErrorCodes::LOGICAL_ERROR, "Source for query pipeline should have single output, but {} doesn't have any", source->getName());
if (!can_have_totals && source->getOutputs().size() != 1)
throw Exception(
ErrorCodes::LOGICAL_ERROR,
"Source for query pipeline should have single output, but {} has {} outputs",
source->getName(),
source->getOutputs().size());
if (source->getOutputs().size() > 2)
throw Exception(
ErrorCodes::LOGICAL_ERROR,
"Source for query pipeline should have 1 or 2 output, but {} has {} outputs",
source->getName(),
source->getOutputs().size());
}
void QueryPipelineBuilder::init(Pipe pipe_)
{
if (initialized())
throw Exception(ErrorCodes::LOGICAL_ERROR, "Pipeline has already been initialized");
if (pipe_.empty())
throw Exception(ErrorCodes::LOGICAL_ERROR, "Can't initialize pipeline with empty pipe");
pipe = std::move(pipe_);
}
void QueryPipelineBuilder::init(QueryPipeline & pipeline)
{
if (initialized())
throw Exception(ErrorCodes::LOGICAL_ERROR, "Pipeline has already been initialized");
if (pipeline.pushing())
throw Exception(ErrorCodes::LOGICAL_ERROR, "Can't initialize pushing pipeline");
if (pipeline.output)
{
pipe.output_ports = {pipeline.output};
pipe.header = pipeline.output->getSharedHeader();
}
else
{
pipe.output_ports.clear();
pipe.header = std::make_shared<const Block>(Block{});
}
pipe.totals_port = pipeline.totals;
pipe.extremes_port = pipeline.extremes;
pipe.max_parallel_streams = pipeline.num_threads;
}
void QueryPipelineBuilder::reset()
{
Pipe pipe_to_destroy(std::move(pipe));
*this = QueryPipelineBuilder();
}
void QueryPipelineBuilder::addSimpleTransform(const Pipe::ProcessorGetterSharedHeader & getter)
{
checkInitializedAndNotCompleted();
pipe.addSimpleTransform(getter);
}
void QueryPipelineBuilder::addSimpleTransform(const Pipe::ProcessorGetterSharedHeaderWithStreamKind & getter)
{
checkInitializedAndNotCompleted();
pipe.addSimpleTransform(getter);
}
void QueryPipelineBuilder::addTransform(ProcessorPtr transform)
{
checkInitializedAndNotCompleted();
pipe.addTransform(std::move(transform));
}
void QueryPipelineBuilder::addTransform(ProcessorPtr transform, InputPort * totals, InputPort * extremes)
{
checkInitializedAndNotCompleted();
pipe.addTransform(std::move(transform), totals, extremes);
}
void QueryPipelineBuilder::addChains(std::vector<Chain> chains)
{
checkInitializedAndNotCompleted();
pipe.addChains(std::move(chains));
}
void QueryPipelineBuilder::addChain(Chain chain)
{
checkInitializedAndNotCompleted();
std::vector<Chain> chains;
chains.emplace_back(std::move(chain));
pipe.resize(1);
pipe.addChains(std::move(chains));
}
void QueryPipelineBuilder::transform(const Transformer & transformer, bool check_ports)
{
checkInitializedAndNotCompleted();
pipe.transform(transformer, check_ports);
}
void QueryPipelineBuilder::setSinks(const Pipe::ProcessorGetterSharedHeaderWithStreamKind & getter)
{
checkInitializedAndNotCompleted();
pipe.setSinks(getter);
}
void QueryPipelineBuilder::addDelayedStream(ProcessorPtr source)
{
checkInitializedAndNotCompleted();
checkSource(source, false);
assertBlocksHaveEqualStructure(getHeader(), source->getOutputs().front().getHeader(), "QueryPipeline");
IProcessor::PortNumbers delayed_streams = { pipe.numOutputPorts() };
pipe.addSource(std::move(source));
auto processor = std::make_shared<DelayedPortsProcessor>(getSharedHeader(), pipe.numOutputPorts(), delayed_streams);
addTransform(std::move(processor));
}
void QueryPipelineBuilder::addMergingAggregatedMemoryEfficientTransform(AggregatingTransformParamsPtr params, size_t num_merging_processors)
{
DB::addMergingAggregatedMemoryEfficientTransform(pipe, std::move(params), num_merging_processors);
}
void QueryPipelineBuilder::resize(size_t num_streams, bool strict, UInt64 min_outstreams_per_resize_after_split)
{
checkInitializedAndNotCompleted();
pipe.resize(num_streams, strict, min_outstreams_per_resize_after_split);
}
void QueryPipelineBuilder::narrow(size_t size)
{
checkInitializedAndNotCompleted();
narrowPipe(pipe, size);
}
void QueryPipelineBuilder::addTotalsHavingTransform(ProcessorPtr transform)
{
checkInitializedAndNotCompleted();
if (!typeid_cast<const TotalsHavingTransform *>(transform.get()))
throw Exception(ErrorCodes::LOGICAL_ERROR, "TotalsHavingTransform is expected for QueryPipeline::addTotalsHavingTransform");
if (pipe.getTotalsPort())
throw Exception(ErrorCodes::LOGICAL_ERROR, "Totals having transform was already added to pipeline");
resize(1);
auto * totals_port = &transform->getOutputs().back();
pipe.addTransform(std::move(transform), totals_port, nullptr);
}
void QueryPipelineBuilder::addDefaultTotals()
{
checkInitializedAndNotCompleted();
if (pipe.getTotalsPort())
throw Exception(ErrorCodes::LOGICAL_ERROR, "Totals having transform was already added to pipeline");
const auto & current_header = getSharedHeader();
Columns columns;
columns.reserve(current_header->columns());
for (size_t i = 0; i < current_header->columns(); ++i)
{
auto column = current_header->getByPosition(i).type->createColumn();
column->insertDefault();
columns.emplace_back(std::move(column));
}
auto source = std::make_shared<SourceFromSingleChunk>(current_header, Chunk(std::move(columns), 1));
pipe.addTotalsSource(std::move(source));
}
void QueryPipelineBuilder::dropTotalsAndExtremes()
{
pipe.dropTotals();
pipe.dropExtremes();
}
void QueryPipelineBuilder::addExtremesTransform()
{
checkInitializedAndNotCompleted();
/// It is possible that pipeline already have extremes.
/// For example, it may be added from VIEW subquery.
/// In this case, recalculate extremes again - they should be calculated for different rows.
if (pipe.getExtremesPort())
pipe.dropExtremes();
resize(1);
auto transform = std::make_shared<ExtremesTransform>(getSharedHeader());
auto * port = &transform->getExtremesPort();
pipe.addTransform(std::move(transform), nullptr, port);
}
QueryPipelineBuilder QueryPipelineBuilder::unitePipelines(
std::vector<std::unique_ptr<QueryPipelineBuilder>> pipelines,
size_t max_threads_limit,
Processors * collected_processors)
{
if (pipelines.empty())
throw Exception(ErrorCodes::LOGICAL_ERROR, "Cannot unite an empty set of pipelines");
/// Should we limit the number of threads for united pipeline. True if all pipelines have max_threads != 0.
/// If true, result max_threads will be sum(max_threads).
/// Note: it may be > than settings.max_threads, so we should apply this limit again.
bool will_limit_max_threads = true;
size_t max_threads = 0;
bool concurrency_control = false;
Pipes pipes;
QueryPlanResourceHolder resources;
for (auto & pipeline_ptr : pipelines)
{
auto & pipeline = *pipeline_ptr;
pipeline.checkInitialized();
resources = std::move(pipeline.resources);
pipeline.pipe.collected_processors = collected_processors;
pipes.emplace_back(std::move(pipeline.pipe));
max_threads += pipeline.max_threads;
will_limit_max_threads = will_limit_max_threads && pipeline.max_threads != 0;
/// If one of pipelines uses more threads then current limit, will keep it.
/// It may happen if max_distributed_connections > max_threads
max_threads_limit = std::max(pipeline.max_threads, max_threads_limit);
// Use concurrency control if at least one of pipelines is using it
concurrency_control = concurrency_control || pipeline.getConcurrencyControl();
}
QueryPipelineBuilder pipeline;
pipeline.init(Pipe::unitePipes(std::move(pipes), collected_processors, false));
pipeline.addResources(std::move(resources));
if (will_limit_max_threads)
{
pipeline.setMaxThreads(max_threads);
pipeline.limitMaxThreads(max_threads_limit);
}
pipeline.setConcurrencyControl(concurrency_control);
pipeline.setCollectedProcessors(nullptr);
return pipeline;
}
QueryPipelineBuilderPtr QueryPipelineBuilder::mergePipelines(
QueryPipelineBuilderPtr left,
QueryPipelineBuilderPtr right,
ProcessorPtr transform,
Processors * collected_processors)
{
if (transform->getOutputs().size() != 1)
throw Exception(ErrorCodes::LOGICAL_ERROR, "Merge transform must have exactly 1 output, got {}", transform->getOutputs().size());
connect(*left->pipe.output_ports.front(), transform->getInputs().front());
connect(*right->pipe.output_ports.front(), transform->getInputs().back());
if (collected_processors)
collected_processors->emplace_back(transform);
left->pipe.output_ports.front() = &transform->getOutputs().front();
left->pipe.processors->emplace_back(transform);
left->pipe.processors->insert(left->pipe.processors->end(), right->pipe.processors->begin(), right->pipe.processors->end());
left->pipe.header = left->pipe.output_ports.front()->getSharedHeader();
left->pipe.max_parallel_streams = std::max(left->pipe.max_parallel_streams, right->pipe.max_parallel_streams);
left->resources = std::move(right->resources);
return left;
}
std::unique_ptr<QueryPipelineBuilder> QueryPipelineBuilder::joinPipelinesYShaped(
std::unique_ptr<QueryPipelineBuilder> left,
std::unique_ptr<QueryPipelineBuilder> right,
JoinPtr join,
SharedHeader & out_header,
size_t max_block_size,
Processors * collected_processors)
{
left->checkInitializedAndNotCompleted();
right->checkInitializedAndNotCompleted();
left->pipe.dropExtremes();
right->pipe.dropExtremes();
if ((left->getNumStreams() != 1 || right->getNumStreams() != 1) && join->getTableJoin().kind() == JoinKind::Paste)
{
left->pipe.resize(1);
right->pipe.resize(1);
}
else if (left->getNumStreams() != 1 || right->getNumStreams() != 1)
throw Exception(ErrorCodes::LOGICAL_ERROR, "Join is supported only for pipelines with one output port, got {} and {}", left->getNumStreams(), right->getNumStreams());
if (left->hasTotals() || right->hasTotals())
throw Exception(ErrorCodes::NOT_IMPLEMENTED, "Current join algorithm is supported only for pipelines without totals");
SharedHeaders inputs = {left->getSharedHeader(), right->getSharedHeader()};
if (join->getTableJoin().kind() == JoinKind::Paste)
{
auto joining = std::make_shared<PasteJoinTransform>(join, inputs, out_header, max_block_size);
return mergePipelines(std::move(left), std::move(right), std::move(joining), collected_processors);
}
auto joining = std::make_shared<MergeJoinTransform>(join, inputs, out_header, max_block_size);
return mergePipelines(std::move(left), std::move(right), std::move(joining), collected_processors);
}
std::unique_ptr<QueryPipelineBuilder> QueryPipelineBuilder::joinPipelinesYShapedByShards(
std::unique_ptr<QueryPipelineBuilder> left,
std::unique_ptr<QueryPipelineBuilder> right,
JoinPtr join,
SharedHeader & out_header,
size_t max_block_size,
Processors * collected_processors)
{
left->checkInitializedAndNotCompleted();
right->checkInitializedAndNotCompleted();
left->pipe.dropExtremes();
right->pipe.dropExtremes();
if (left->getNumStreams() != right->getNumStreams())
throw Exception(ErrorCodes::LOGICAL_ERROR, "Join by layers is supported only for pipelines equal number of output ports, got {} and {}", left->getNumStreams(), right->getNumStreams());
if (left->hasTotals() || right->hasTotals())
throw Exception(ErrorCodes::NOT_IMPLEMENTED, "Current join algorithm is supported only for pipelines without totals");
SharedHeaders inputs = {left->getSharedHeader(), right->getSharedHeader()};
size_t num_streams = left->getNumStreams();
for (size_t i = 0; i < num_streams; ++i)
{
auto joining = std::make_shared<MergeJoinTransform>(join->clone(std::make_shared<TableJoin>(join->getTableJoin()), left->getSharedHeader(), right->getSharedHeader()), inputs, out_header, max_block_size);
connect(*left->pipe.output_ports[i], joining->getInputs().front());
connect(*right->pipe.output_ports[i], joining->getInputs().back());
left->pipe.output_ports[i] = &joining->getOutputPort();
if (collected_processors)
collected_processors->emplace_back(joining);
left->pipe.processors->emplace_back(std::move(joining));
}
left->pipe.processors->insert(left->pipe.processors->end(), right->pipe.processors->begin(), right->pipe.processors->end());
left->pipe.header = left->pipe.output_ports.front()->getSharedHeader();
left->pipe.max_parallel_streams = std::max(left->pipe.max_parallel_streams, right->pipe.max_parallel_streams);
left->resources = std::move(right->resources);
return left;
}
std::unique_ptr<QueryPipelineBuilder> QueryPipelineBuilder::joinPipelinesRightLeft(
std::unique_ptr<QueryPipelineBuilder> left,
std::unique_ptr<QueryPipelineBuilder> right,
JoinPtr join,
SharedHeader & output_header,
size_t max_block_size,
size_t min_block_size_rows,
size_t min_block_size_bytes,
size_t max_streams,
bool keep_left_read_in_order,
Processors * collected_processors)
{
left->checkInitializedAndNotCompleted();
right->checkInitializedAndNotCompleted();
/// Extremes before join are useless. They will be calculated after if needed.
left->pipe.dropExtremes();
right->pipe.dropExtremes();
left->pipe.collected_processors = collected_processors;
/// Remember the last step of the right pipeline.
IQueryPlanStep * step = right->pipe.processors->back()->getQueryPlanStep();
/// Collect the NEW processors for the right pipeline.
QueryPipelineProcessorsCollector collector(*right, step);
/// In case joined subquery has totals, and we don't, add default chunk to totals.
bool default_totals = false;
if (!join->supportTotals() && (left->hasTotals() || right->hasTotals()))
throw Exception(ErrorCodes::NOT_IMPLEMENTED, "Current join algorithm is supported only for pipelines without totals");
if (!left->hasTotals() && right->hasTotals())
{
left->addDefaultTotals();
default_totals = true;
}
/// (left) ──────┐
/// ╞> Joining ─> (joined)
/// (left) ─┐┌───┘
/// └┼───┐
/// (right) ┐ (totals) ──┼─┐ ╞> Joining ─> (joined)
/// ╞> Resize ┐ ╓─┘┌┼─┘
/// (right) ┘ │ ╟──┘└─┐
/// ╞> FillingJoin ─> Resize ╣ ╞> Joining ─> (totals)
/// (totals) ─────────┘ ╙─────┘
size_t num_streams = left->getNumStreams();
if (join->supportParallelJoin() && !right->hasTotals())
{
if (!keep_left_read_in_order)
{
left->resize(max_streams);
num_streams = max_streams;
}
auto filling_finish_counter = std::make_shared<FinishCounter>(max_streams);
right->resize(max_streams);
auto concurrent_right_filling_transform = [&](OutputPortRawPtrs outports)
{
Processors processors;
for (auto & outport : outports)
{
auto squashing = std::make_shared<SimpleSquashingChunksTransform>(right->getSharedHeader(), min_block_size_rows, min_block_size_bytes);
connect(*outport, squashing->getInputs().front());
processors.emplace_back(squashing);
auto adding_joined = std::make_shared<FillingRightJoinSideTransform>(right->getSharedHeader(), join, filling_finish_counter);
connect(squashing->getOutputPort(), adding_joined->getInputs().front());
processors.emplace_back(std::move(adding_joined));
}
return processors;
};
right->transform(concurrent_right_filling_transform);
right->resize(1);
}
else
{
right->resize(1);
auto filling_finish_counter = std::make_shared<FinishCounter>(1);
auto adding_joined = std::make_shared<FillingRightJoinSideTransform>(right->getSharedHeader(), join, filling_finish_counter);
InputPort * totals_port = nullptr;
if (right->hasTotals())
totals_port = adding_joined->addTotalsPort();
right->addTransform(std::move(adding_joined), totals_port, nullptr);
}
size_t num_streams_including_totals = num_streams + (left->hasTotals() ? 1 : 0);
right->resize(num_streams_including_totals);
/// This counter is needed for every Joining except totals, to decide which Joining will generate non joined rows.
auto joining_finish_counter = std::make_shared<FinishCounter>(num_streams);
auto lit = left->pipe.output_ports.begin();
auto rit = right->pipe.output_ports.begin();
std::vector<OutputPort *> joined_output_ports;
std::vector<OutputPort *> delayed_root_output_ports;
std::shared_ptr<DelayedJoinedBlocksTransform> delayed_root = nullptr;
if (join->hasDelayedBlocks())
{
delayed_root = std::make_shared<DelayedJoinedBlocksTransform>(num_streams, join);
if (!delayed_root->getInputs().empty() || delayed_root->getOutputs().size() != num_streams)
throw Exception(ErrorCodes::LOGICAL_ERROR,
"DelayedJoinedBlocksTransform should have no inputs and {} outputs, "
"but has {} inputs and {} outputs",
num_streams, delayed_root->getInputs().size(), delayed_root->getOutputs().size());
if (collected_processors)
collected_processors->emplace_back(delayed_root);
left->pipe.processors->emplace_back(delayed_root);
for (auto & outport : delayed_root->getOutputs())
delayed_root_output_ports.emplace_back(&outport);
}
SharedHeader left_header = left->getSharedHeader();
for (size_t i = 0; i < num_streams; ++i)
{
auto squashing = std::make_shared<SimpleSquashingChunksTransform>(left->getSharedHeader(), min_block_size_rows, min_block_size_bytes);
connect(**lit, squashing->getInputs().front());
auto joining = std::make_shared<JoiningTransform>(
left_header, output_header, join, max_block_size, false, default_totals, joining_finish_counter);
connect(squashing->getOutputPort(), joining->getInputs().front());
connect(**rit, joining->getInputs().back());
if (delayed_root)
{
// Process delayed joined blocks when all JoiningTransform are finished.
auto delayed = std::make_shared<DelayedJoinedBlocksWorkerTransform>(
output_header,
[left_header, output_header, max_block_size, join]()
{ return join->getNonJoinedBlocks(*left_header, *output_header, max_block_size); });
if (delayed->getInputs().size() != 1 || delayed->getOutputs().size() != 1)
throw Exception(ErrorCodes::LOGICAL_ERROR, "DelayedJoinedBlocksWorkerTransform should have one input and one output");
connect(*delayed_root_output_ports[i], delayed->getInputs().front());
joined_output_ports.push_back(&joining->getOutputs().front());
joined_output_ports.push_back(&delayed->getOutputs().front());
if (collected_processors)
collected_processors->emplace_back(delayed);
left->pipe.processors->emplace_back(std::move(delayed));
}
else
{
*lit = &joining->getOutputs().front();
}
++lit;
++rit;
if (collected_processors)
collected_processors->emplace_back(joining);
left->pipe.processors->emplace_back(std::move(squashing));
left->pipe.processors->emplace_back(std::move(joining));
}
if (delayed_root)
{
// Process DelayedJoinedBlocksTransform after all JoiningTransforms.
DelayedPortsProcessor::PortNumbers delayed_ports_numbers;
delayed_ports_numbers.reserve(joined_output_ports.size() / 2);
for (size_t i = 1; i < joined_output_ports.size(); i += 2)
delayed_ports_numbers.push_back(i);
auto delayed_processor = std::make_shared<DelayedPortsProcessor>(output_header, 2 * num_streams, delayed_ports_numbers);
if (collected_processors)
collected_processors->emplace_back(delayed_processor);
left->pipe.processors->emplace_back(delayed_processor);
// Connect @delayed_processor ports with inputs (JoiningTransforms & DelayedJoinedBlocksTransforms) / pipe outputs
auto next_delayed_input = delayed_processor->getInputs().begin();
for (OutputPort * port : joined_output_ports)
connect(*port, *next_delayed_input++);
left->pipe.output_ports.clear();
for (OutputPort & port : delayed_processor->getOutputs())
left->pipe.output_ports.push_back(&port);
left->pipe.header = output_header;
left->resize(num_streams);
}
if (left->hasTotals())
{
auto joining = std::make_shared<JoiningTransform>(left_header, output_header, join, max_block_size, true, default_totals);
connect(*left->pipe.totals_port, joining->getInputs().front());
connect(**rit, joining->getInputs().back());
left->pipe.totals_port = &joining->getOutputs().front();
++rit;
if (collected_processors)
collected_processors->emplace_back(joining);
left->pipe.processors->emplace_back(std::move(joining));
}
/// Move the collected processors to the last step in the right pipeline.
Processors processors = collector.detachProcessors();
if (step)
step->appendExtraProcessors(processors);
left->pipe.processors->insert(left->pipe.processors->end(), right->pipe.processors->begin(), right->pipe.processors->end());
left->resources = std::move(right->resources);
left->pipe.header = left->pipe.output_ports.front()->getSharedHeader();
left->pipe.max_parallel_streams = std::max(left->pipe.max_parallel_streams, right->pipe.max_parallel_streams);
return left;
}
std::unique_ptr<QueryPipelineBuilder> QueryPipelineBuilder::joinPipelinesByShards(
std::unique_ptr<QueryPipelineBuilder> left,
std::unique_ptr<QueryPipelineBuilder> right,
JoinPtr join,
SharedHeader & output_header,
size_t max_block_size,
Processors * collected_processors)
{
left->checkInitializedAndNotCompleted();
right->checkInitializedAndNotCompleted();
/// Extremes before join are useless. They will be calculated after if needed.
left->pipe.dropExtremes();
right->pipe.dropExtremes();
left->pipe.collected_processors = collected_processors;
/// Remember the last step of the right pipeline.
IQueryPlanStep * step = right->pipe.processors->back()->getQueryPlanStep();
/// Collect the NEW processors for the right pipeline.
QueryPipelineProcessorsCollector collector(*right, step);
if (left->hasTotals() || right->hasTotals())
throw Exception(ErrorCodes::NOT_IMPLEMENTED, "Join by layers is supported only for pipelines without totals");
if (!join->isCloneSupported())
throw Exception(ErrorCodes::LOGICAL_ERROR, "Clone is not supported for {}", join->getName());
if (join->hasDelayedBlocks())
throw Exception(ErrorCodes::LOGICAL_ERROR, "Delayed ports from {} are not supported with join by layers", join->getName());
/// (left) ──────┐
/// ╞> Joining ─> (joined)
/// (left) ─┐┌───┘
/// └┼───┐
/// (right) ─> FillingJoin ──────────────────────┘ ╞> Joining ─> (joined)
/// (right) ─> FillingJoin ──────────────────────────┘
size_t num_streams = left->getNumStreams();
if (right->getNumStreams() != num_streams)
throw Exception(ErrorCodes::LOGICAL_ERROR,
"Join by layers expect the same number of ports for the left and the right pipeline. Actual: {} and {}.",
num_streams, right->getNumStreams());
SharedHeader left_header = left->getSharedHeader();
std::vector<JoinPtr> joins;
right->addSimpleTransform([&](const SharedHeader & header)
{
joins.push_back(join->cloneNoParallel(std::make_shared<TableJoin>(join->getTableJoin()), left->getSharedHeader(), header));
auto finish_counter = std::make_shared<FinishCounter>(1);
return std::make_shared<FillingRightJoinSideTransform>(header, joins.back(), finish_counter);
});
auto lit = left->pipe.output_ports.begin();
auto rit = right->pipe.output_ports.begin();
for (size_t i = 0; i < num_streams; ++i)
{
auto finish_counter = std::make_shared<FinishCounter>(1);
auto joining = std::make_shared<JoiningTransform>(
left_header, output_header, joins[i], max_block_size, false, false, finish_counter);
connect(**lit, joining->getInputs().front());
connect(**rit, joining->getInputs().back());
*lit = &joining->getOutputs().front();
++lit;
++rit;
if (collected_processors)
collected_processors->emplace_back(joining);
left->pipe.processors->emplace_back(std::move(joining));
}
/// Move the collected processors to the last step in the right pipeline.
Processors processors = collector.detachProcessors();
if (step)
step->appendExtraProcessors(processors);
left->pipe.processors->insert(left->pipe.processors->end(), right->pipe.processors->begin(), right->pipe.processors->end());
left->resources = std::move(right->resources);
left->pipe.header = left->pipe.output_ports.front()->getSharedHeader();
left->pipe.max_parallel_streams = std::max(left->pipe.max_parallel_streams, right->pipe.max_parallel_streams);
return left;
}
void QueryPipelineBuilder::addCreatingSetsTransform(
SharedHeader res_header,
SetAndKeyPtr set_and_key,
StoragePtr external_table,
const SizeLimits & limits,
PreparedSetsCachePtr prepared_sets_cache)
{
dropTotalsAndExtremes();
resize(1);
auto transform = std::make_shared<CreatingSetsTransform>(
getSharedHeader(),
res_header,
std::move(set_and_key),
std::move(external_table),
limits,
std::move(prepared_sets_cache));
pipe.addTransform(std::move(transform));
}
void QueryPipelineBuilder::addPipelineBefore(QueryPipelineBuilder pipeline)
{
checkInitializedAndNotCompleted();
if (!pipeline.getHeader().empty())
throw Exception(ErrorCodes::LOGICAL_ERROR, "Pipeline for CreatingSets should have empty header. Got: {}",
pipeline.getHeader().dumpStructure());
pipeline.dropTotalsAndExtremes();
bool has_totals = pipe.getTotalsPort();
bool has_extremes = pipe.getExtremesPort();
size_t num_extra_ports = (has_totals ? 1 : 0) + (has_extremes ? 1 : 0);
IProcessor::PortNumbers delayed_streams(pipe.numOutputPorts() + num_extra_ports);
iota(delayed_streams.data(), delayed_streams.size(), IProcessor::PortNumbers::value_type(0));
auto * collected_processors = pipe.collected_processors;
Pipes pipes;
pipes.emplace_back(std::move(pipe));
pipes.emplace_back(QueryPipelineBuilder::getPipe(std::move(pipeline), resources));
pipe = Pipe::unitePipes(std::move(pipes), collected_processors, true);
auto processor = std::make_shared<DelayedPortsProcessor>(getSharedHeader(), pipe.numOutputPorts() + num_extra_ports, delayed_streams, true);
auto in = processor->getInputs().begin();
auto out = processor->getOutputs().begin();
InputPort * totals_in = has_totals ? &*(in++) : nullptr;
InputPort * extremes_in = has_extremes ? &*(in++) : nullptr;
OutputPort * totals_out = has_totals ? &*(out++) : nullptr;
OutputPort * extremes_out = has_extremes ? &*(out++) : nullptr;
pipe.addTransform(std::move(processor), totals_in, extremes_in, totals_out, extremes_out);
}
void QueryPipelineBuilder::setProcessListElement(QueryStatusPtr elem)
{
process_list_element = elem;
}
void QueryPipelineBuilder::setProgressCallback(ProgressCallback callback)
{
progress_callback = callback;
}
PipelineExecutorPtr QueryPipelineBuilder::execute()
{
if (!isCompleted())
throw Exception(ErrorCodes::LOGICAL_ERROR, "Cannot execute pipeline because it is not completed");
return std::make_shared<PipelineExecutor>(pipe.processors, process_list_element);
}
Pipe QueryPipelineBuilder::getPipe(QueryPipelineBuilder pipeline, QueryPlanResourceHolder & resources)
{
resources = std::move(pipeline.resources);
return std::move(pipeline.pipe);
}
QueryPipeline QueryPipelineBuilder::getPipeline(QueryPipelineBuilder builder)
{
QueryPipeline res(std::move(builder.pipe));
res.addResources(std::move(builder.resources));
res.setNumThreads(builder.getNumThreads());
res.setConcurrencyControl(builder.getConcurrencyControl());
res.setProcessListElement(builder.process_list_element);
res.setProgressCallback(builder.progress_callback);
return res;
}
void QueryPipelineBuilder::setCollectedProcessors(Processors * processors)
{
pipe.collected_processors = processors;
}
QueryPipelineProcessorsCollector::QueryPipelineProcessorsCollector(QueryPipelineBuilder & pipeline_, IQueryPlanStep * step_)
: pipeline(pipeline_), step(step_)
{
pipeline.setCollectedProcessors(&processors);
}
QueryPipelineProcessorsCollector::~QueryPipelineProcessorsCollector()
{
pipeline.setCollectedProcessors(nullptr);
}
Processors QueryPipelineProcessorsCollector::detachProcessors(size_t group)
{
for (auto & processor : processors)
processor->setQueryPlanStep(step, group);
Processors res;
res.swap(processors);
return res;
}
}