forked from ClickHouse/ClickHouse
-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathQueryPipeline.cpp
More file actions
887 lines (754 loc) · 31.4 KB
/
Copy pathQueryPipeline.cpp
File metadata and controls
887 lines (754 loc) · 31.4 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
#include <QueryPipeline/QueryPipeline.h>
#include <iterator>
#include <tuple>
#include <Common/MapWithMemoryTracking.h>
#include <Common/QueueWithMemoryTracking.h>
#include <Common/UnorderedSetWithMemoryTracking.h>
#include <Core/Settings.h>
#include <Interpreters/ActionsDAG.h>
#include <Interpreters/ExpressionActions.h>
#include <Interpreters/Cache/QueryResultCache.h>
#include <Interpreters/Context.h>
#include <Processors/Formats/IOutputFormat.h>
#include <Processors/IProcessor.h>
#include <Processors/ISource.h>
#include <Processors/LimitTransform.h>
#include <Processors/NegativeLimitTransform.h>
#include <Processors/FractionalLimitTransform.h>
#include <Processors/QueryPlan/ReadFromPreparedSource.h>
#include <Processors/Sinks/EmptySink.h>
#include <Processors/Sinks/SinkToStorage.h>
#include <Processors/Sources/DelayedSource.h>
#include <Processors/Sources/NullSource.h>
#include <Processors/Sources/RemoteSource.h>
#include <Processors/Sources/SourceFromChunks.h>
#include <Processors/Transforms/AggregatingInOrderTransform.h>
#include <Processors/Transforms/AggregatingTransform.h>
#include <Processors/Transforms/CountingTransform.h>
#include <Processors/Transforms/CreatingSetsTransform.h>
#include <Processors/Transforms/DroppingTransform.h>
#include <Processors/Transforms/ExpressionTransform.h>
#include <Processors/Transforms/LimitByTransform.h>
#include <Processors/Transforms/LimitsCheckingTransform.h>
#include <Processors/Transforms/MaterializingTransform.h>
#include <Processors/Transforms/MemoryBoundMerging.h>
#include <Processors/Transforms/MergingAggregatedTransform.h>
#include <Processors/Transforms/MergingAggregatedMemoryEfficientTransform.h>
#include <Processors/Transforms/PartialSortingTransform.h>
#include <Processors/Transforms/StreamInQueryResultCacheTransform.h>
#include <Processors/Transforms/TotalsHavingTransform.h>
#include <Processors/StepWallClockRegistry.h>
#include <QueryPipeline/Chain.h>
#include <QueryPipeline/Pipe.h>
#include <QueryPipeline/ReadProgressCallback.h>
#include <QueryPipeline/printPipeline.h>
namespace DB
{
namespace Setting
{
extern const SettingsBool rows_before_aggregation;
}
namespace ErrorCodes
{
extern const int LOGICAL_ERROR;
}
QueryPipeline::QueryPipeline()
: processors(std::make_shared<Processors>())
{
}
QueryPipeline::QueryPipeline(QueryPipeline &&) noexcept = default;
QueryPipeline & QueryPipeline::operator=(QueryPipeline &&) = default; /// NOLINT(hicpp-noexcept-move,performance-noexcept-move-constructor)
QueryPipeline::~QueryPipeline() = default;
static void checkInput(const InputPort & input, const ProcessorPtr & processor)
{
if (!input.isConnected())
throw Exception(
ErrorCodes::LOGICAL_ERROR,
"Cannot create QueryPipeline because {} has disconnected input",
processor->getName());
}
static void checkOutput(const OutputPort & output, const ProcessorPtr & processor, const Processors & processors = {})
{
if (!output.isConnected())
{
WriteBufferFromOwnString out;
if (!processors.empty())
printPipeline(processors, out);
throw Exception(
ErrorCodes::LOGICAL_ERROR,
"Cannot create QueryPipeline because {} {} has disconnected output: {}",
processor->getName(), processor->getDescription(), out.str());
}
}
static void checkPulling(
Processors & processors,
OutputPort * output,
OutputPort * totals,
OutputPort * extremes)
{
if (!output || output->isConnected())
throw Exception(
ErrorCodes::LOGICAL_ERROR,
"Cannot create pulling QueryPipeline because its output port is connected or null");
if (totals && totals->isConnected())
throw Exception(
ErrorCodes::LOGICAL_ERROR,
"Cannot create pulling QueryPipeline because its totals port is connected");
if (extremes && extremes->isConnected())
throw Exception(
ErrorCodes::LOGICAL_ERROR,
"Cannot create pulling QueryPipeline because its extremes port is connected");
bool found_output = false;
bool found_totals = false;
bool found_extremes = false;
for (const auto & processor : processors)
{
for (const auto & in : processor->getInputs())
checkInput(in, processor);
for (const auto & out : processor->getOutputs())
{
if (&out == output)
found_output = true;
else if (totals && &out == totals)
found_totals = true;
else if (extremes && &out == extremes)
found_extremes = true;
else
checkOutput(out, processor, processors);
}
}
if (!found_output)
throw Exception(
ErrorCodes::LOGICAL_ERROR,
"Cannot create pulling QueryPipeline because its output port does not belong to any processor");
if (totals && !found_totals)
throw Exception(
ErrorCodes::LOGICAL_ERROR,
"Cannot create pulling QueryPipeline because its totals port does not belong to any processor");
if (extremes && !found_extremes)
throw Exception(
ErrorCodes::LOGICAL_ERROR,
"Cannot create pulling QueryPipeline because its extremes port does not belong to any processor");
}
static void checkCompleted(Processors & processors)
{
for (const auto & processor : processors)
{
for (const auto & in : processor->getInputs())
checkInput(in, processor);
for (const auto & out : processor->getOutputs())
checkOutput(out, processor);
}
}
static void initRowsBeforeLimit(IOutputFormat * output_format)
{
RowsBeforeStepCounterPtr rows_before_limit_at_least;
UnorderedSetWithMemoryTracking<IProcessor *> processors;
/// Start at the output and follow inputs toward the sources. For each path, remember which
/// limit is being counted and which of its input ports the path came through. A shared processor
/// may need to be visited more than once when it feeds different limits or limit inputs.
///
/// `counted_inputs_by_limit` records limit inputs whose rows are counted closer to the source.
/// The limit itself counts rows only for the other inputs.
MapWithMemoryTracking<IProcessor *, UnorderedSetWithMemoryTracking<size_t>> counted_inputs_by_limit;
MapWithMemoryTracking<std::tuple<IProcessor *, IProcessor *, ssize_t>, bool> visited;
bool has_limit = false;
struct QueuedEntry
{
IProcessor * processor;
IProcessor * limit_being_counted;
ssize_t limit_input_port;
};
QueueWithMemoryTracking<QueuedEntry> queue;
auto mark_limit_input_as_counted = [&](IProcessor * limit, ssize_t input_port)
{
if (input_port < 0 || static_cast<size_t>(input_port) >= limit->getInputs().size())
throw Exception(
ErrorCodes::LOGICAL_ERROR,
"Invalid input port {} while placing the rows_before_limit_at_least counter",
input_port);
counted_inputs_by_limit[limit].emplace(static_cast<size_t>(input_port));
};
queue.push({ output_format, nullptr, -1 });
while (!queue.empty())
{
auto * processor = queue.front().processor;
auto * limit_being_counted = queue.front().limit_being_counted;
auto limit_input_port = queue.front().limit_input_port;
queue.pop();
/// The same processor can be reached under different limits or parent input ports.
if (!visited.emplace(std::tuple(processor, limit_being_counted, limit_input_port), true).second)
continue;
/// Set counter based on the following cases:
/// 1. Remote: Set counter on Remote
/// 2. Limit ... PartialSorting: Set counter on PartialSorting
/// 3. Limit ... TotalsHaving(with filter) ... Remote: Set counter on the input port of Limit
/// 4. Limit ... MergingAggregated ... Remote: Set counter on the input port of Limit
/// 5. Limit ... Remote: Set counter on Remote
/// 6. Limit ... LimitBy: Set counter on LimitBy, as it may not be executed on initiator
/// 7. Limit ... : Set counter on the input port of Limit
/// Case 1.
if ((typeid_cast<RemoteSource *>(processor) || typeid_cast<DelayedSource *>(processor)) && !limit_being_counted)
{
processors.emplace(processor);
continue;
}
auto * limit = typeid_cast<LimitTransform *>(processor);
auto * negative_limit = typeid_cast<NegativeLimitTransform *>(processor);
if (((limit && limit->isShardLimit()) || (negative_limit && negative_limit->isShardLimit()))
&& limit_being_counted)
{
/// Rows discarded by a shard limit still belong to the parent limit's total. Mark the
/// parent input as counted, then continue toward the source past the shard limit.
mark_limit_input_as_counted(limit_being_counted, limit_input_port);
limit_being_counted = processor;
counted_inputs_by_limit.try_emplace(limit_being_counted);
}
else if (limit || negative_limit || typeid_cast<FractionalLimitTransform *>(processor))
{
has_limit = true;
/// A limit from the query changes the rows seen by an outer limit. Do not count through it.
if (limit_being_counted)
continue;
limit_being_counted = processor;
counted_inputs_by_limit.try_emplace(limit_being_counted);
}
else if (limit_being_counted)
{
/// Case 2.
if (typeid_cast<PartialSortingTransform *>(processor))
{
processors.emplace(processor);
mark_limit_input_as_counted(limit_being_counted, limit_input_port);
continue;
}
/// Case 3.
if (auto * having = typeid_cast<TotalsHavingTransform *>(processor))
{
if (having->hasFilter())
continue;
}
/// Case 4.
if (typeid_cast<MergingAggregatedTransform *>(processor) || typeid_cast<MergingAggregatedBucketTransform *>(processor)
|| typeid_cast<SortingAggregatedTransform *>(processor)
|| typeid_cast<SortingAggregatedForMemoryBoundMergingTransform *>(processor))
{
continue;
}
/// Case 5.
if (typeid_cast<RemoteSource *>(processor) || typeid_cast<DelayedSource *>(processor))
{
processors.emplace(processor);
mark_limit_input_as_counted(limit_being_counted, limit_input_port);
continue;
}
/// Case 6.
if (typeid_cast<LimitByTransform *>(processor) || typeid_cast<LimitBySortedStreamTransform *>(processor))
{
processors.emplace(processor);
mark_limit_input_as_counted(limit_being_counted, limit_input_port);
continue;
}
}
/// Skip totals and extremes port for output format.
if (auto * format = dynamic_cast<IOutputFormat *>(processor))
{
auto * child_processor = &format->getPort(IOutputFormat::PortKind::Main).getOutputPort().getProcessor();
queue.push({ child_processor, limit_being_counted, limit_input_port });
continue;
}
/// Skip CreatingSetsTransform
if (typeid_cast<CreatingSetsTransform *>(processor))
continue;
if (limit_being_counted == processor)
{
ssize_t i = 0;
for (auto & child_port : processor->getInputs())
{
auto * child_processor = &child_port.getOutputPort().getProcessor();
queue.push({ child_processor, limit_being_counted, i });
++i;
}
}
else
{
for (auto & child_port : processor->getInputs())
{
auto * child_processor = &child_port.getOutputPort().getProcessor();
queue.push({ child_processor, limit_being_counted, limit_input_port });
}
}
}
/// Case 7.
for (auto && [limit, ports] : counted_inputs_by_limit)
{
/// If there are some input ports which don't have the counter, add it to the limit processor.
if (ports.size() < limit->getInputs().size())
{
processors.emplace(limit);
for (auto port : ports)
{
if (auto * lim = typeid_cast<LimitTransform *>(limit))
lim->setInputPortHasCounter(port);
else if (auto * neg_lim = typeid_cast<NegativeLimitTransform *>(limit))
neg_lim->setInputPortHasCounter(port);
else if (auto * frac_lim = typeid_cast<FractionalLimitTransform *>(limit))
frac_lim->setInputPortHasCounter(port);
}
}
}
if (!processors.empty())
{
rows_before_limit_at_least = std::make_shared<RowsBeforeStepCounter>();
for (const auto & processor : processors)
processor->setRowsBeforeLimitCounter(rows_before_limit_at_least);
/// If there is a limit, then enable rows_before_limit_at_least
/// It is needed when zero rows is read, but we still want rows_before_limit_at_least in result.
if (has_limit)
rows_before_limit_at_least->add(0);
output_format->setRowsBeforeLimitCounter(rows_before_limit_at_least);
}
}
static void initRowsBeforeAggregation(std::shared_ptr<Processors> processors, IOutputFormat * output_format)
{
bool has_aggregation = false;
if (!processors->empty())
{
RowsBeforeStepCounterPtr rows_before_aggregation = std::make_shared<RowsBeforeStepCounter>();
for (const auto & processor : *processors)
{
if (typeid_cast<AggregatingTransform *>(processor.get()) || typeid_cast<AggregatingInOrderTransform *>(processor.get()))
{
processor->setRowsBeforeAggregationCounter(rows_before_aggregation);
has_aggregation = true;
}
if (typeid_cast<RemoteSource *>(processor.get()) || typeid_cast<DelayedSource *>(processor.get()))
processor->setRowsBeforeAggregationCounter(rows_before_aggregation);
}
if (has_aggregation)
rows_before_aggregation->add(0);
output_format->setRowsBeforeAggregationCounter(rows_before_aggregation);
}
}
QueryPipeline::QueryPipeline(
QueryPlanResourceHolder resources_,
std::shared_ptr<Processors> processors_)
: resources(std::move(resources_))
, processors(std::move(processors_))
{
checkCompleted(*processors);
}
QueryPipeline::QueryPipeline(
QueryPlanResourceHolder resources_,
std::shared_ptr<Processors> processors_,
InputPort * input_)
: resources(std::move(resources_))
, processors(std::move(processors_))
, input(input_)
{
if (!input || input->isConnected())
throw Exception(
ErrorCodes::LOGICAL_ERROR,
"Cannot create pushing QueryPipeline because its input port is connected or null");
bool found_input = false;
for (const auto & processor : *processors)
{
for (const auto & in : processor->getInputs())
{
if (&in == input)
found_input = true;
else
checkInput(in, processor);
}
for (const auto & out : processor->getOutputs())
checkOutput(out, processor);
}
if (!found_input)
throw Exception(
ErrorCodes::LOGICAL_ERROR,
"Cannot create pushing QueryPipeline because its input port does not belong to any processor");
}
QueryPipeline::QueryPipeline(std::shared_ptr<ISource> source) : QueryPipeline(Pipe(std::move(source))) {}
QueryPipeline::QueryPipeline(
QueryPlanResourceHolder resources_,
std::shared_ptr<Processors> processors_,
OutputPort * output_,
OutputPort * totals_,
OutputPort * extremes_)
: resources(std::move(resources_))
, processors(std::move(processors_))
, output(output_)
, totals(totals_)
, extremes(extremes_)
{
checkPulling(*processors, output, totals, extremes);
}
QueryPipeline::QueryPipeline(Pipe pipe)
{
if (pipe.numOutputPorts() > 0)
{
pipe.resize(1);
output = pipe.getOutputPort(0);
totals = pipe.getTotalsPort();
extremes = pipe.getExtremesPort();
processors = std::move(pipe.processors);
checkPulling(*processors, output, totals, extremes);
}
else
{
processors = std::move(pipe.processors);
checkCompleted(*processors);
}
}
QueryPipeline::QueryPipeline(Chain chain)
: resources(chain.detachResources())
, processors(std::make_shared<Processors>())
, input(&chain.getInputPort())
, num_threads(chain.getNumThreads())
{
for (auto processor : chain.getProcessors())
processors->emplace_back(std::move(processor));
auto sink = std::make_shared<EmptySink>(chain.getOutputPort().getSharedHeader());
connect(chain.getOutputPort(), sink->getPort());
processors->emplace_back(std::move(sink));
input = &chain.getInputPort();
}
QueryPipeline::QueryPipeline(std::shared_ptr<IOutputFormat> format)
: processors(std::make_shared<Processors>())
{
auto & format_main = format->getPort(IOutputFormat::PortKind::Main);
auto & format_totals = format->getPort(IOutputFormat::PortKind::Totals);
auto & format_extremes = format->getPort(IOutputFormat::PortKind::Extremes);
if (!totals)
{
auto source = std::make_shared<NullSource>(format_totals.getSharedHeader());
totals = &source->getPort();
processors->emplace_back(std::move(source));
}
if (!extremes)
{
auto source = std::make_shared<NullSource>(format_extremes.getSharedHeader());
extremes = &source->getPort();
processors->emplace_back(std::move(source));
}
connect(*totals, format_totals);
connect(*extremes, format_extremes);
input = &format_main;
totals = nullptr;
extremes = nullptr;
output_format = format.get();
processors->emplace_back(std::move(format));
}
/// Discards `totals`/`extremes` without adding a childless node; see `DroppingTransform`.
/// Requires `output != nullptr`.
static void dropTotalsAndExtremesViaTransform(
OutputPort *& output, OutputPort *& totals, OutputPort *& extremes, Processors & processors)
{
if (!totals && !extremes)
return;
chassert(output);
auto dropping = std::make_shared<DroppingTransform>(
output->getSharedHeader(),
/*num_streams_=*/1,
totals ? totals->getSharedHeader() : nullptr,
extremes ? extremes->getSharedHeader() : nullptr);
connect(*output, dropping->getInputs().front());
if (totals)
{
connect(*totals, *dropping->getTotalsPort());
totals = nullptr;
}
if (extremes)
{
connect(*extremes, *dropping->getExtremesPort());
extremes = nullptr;
}
output = &dropping->getOutputs().front();
processors.emplace_back(std::move(dropping));
}
QueryPipeline::QueryPipeline(std::shared_ptr<SinkToStorage> sink) : QueryPipeline(Chain(std::move(sink))) {}
void QueryPipeline::complete(std::shared_ptr<ISink> sink)
{
if (!pulling())
throw Exception(ErrorCodes::LOGICAL_ERROR, "Pipeline must be pulling to be completed with sink");
dropTotalsAndExtremesViaTransform(output, totals, extremes, *processors);
connect(*output, sink->getPort());
processors->emplace_back(std::move(sink));
output = nullptr;
}
void QueryPipeline::complete(Chain chain)
{
if (!pulling())
throw Exception(ErrorCodes::LOGICAL_ERROR, "Pipeline must be pulling to be completed with chain");
resources = chain.detachResources();
dropTotalsAndExtremesViaTransform(output, totals, extremes, *processors);
for (auto processor : chain.getProcessors())
processors->emplace_back(std::move(processor));
auto sink = std::make_shared<EmptySink>(chain.getOutputPort().getSharedHeader());
connect(*output, chain.getInputPort());
connect(chain.getOutputPort(), sink->getPort());
processors->emplace_back(std::move(sink));
output = nullptr;
}
void QueryPipeline::complete(std::shared_ptr<SinkToStorage> sink)
{
complete(Chain(std::move(sink)));
}
void QueryPipeline::complete(Pipe pipe)
{
if (!pushing())
throw Exception(ErrorCodes::LOGICAL_ERROR, "Pipeline must be pushing to be completed with pipe");
pipe.resize(1);
pipe.dropTotalsAndExtremes();
connect(*pipe.getOutputPort(0), *input);
input = nullptr;
auto pipe_processors = Pipe::detachProcessors(std::move(pipe));
processors->insert(processors->end(), pipe_processors.begin(), pipe_processors.end());
}
static void addMaterializing(OutputPort *& output, Processors & processors, bool remove_special_column_representations)
{
if (!output)
return;
auto materializing = std::make_shared<MaterializingTransform>(output->getSharedHeader(), remove_special_column_representations);
connect(*output, materializing->getInputPort());
output = &materializing->getOutputPort();
processors.emplace_back(std::move(materializing));
}
void QueryPipeline::complete(std::shared_ptr<IOutputFormat> format)
{
if (!pulling())
throw Exception(ErrorCodes::LOGICAL_ERROR, "Pipeline must be pulling to be completed with output format");
if (format->expectMaterializedColumns())
{
bool remove_special_column_representations = !format->supportsSpecialSerializationKinds();
addMaterializing(output, *processors, remove_special_column_representations);
addMaterializing(totals, *processors, remove_special_column_representations);
addMaterializing(extremes, *processors, remove_special_column_representations);
}
auto & format_main = format->getPort(IOutputFormat::PortKind::Main);
auto & format_totals = format->getPort(IOutputFormat::PortKind::Totals);
auto & format_extremes = format->getPort(IOutputFormat::PortKind::Extremes);
if (!totals)
{
auto source = std::make_shared<NullSource>(format_totals.getSharedHeader());
totals = &source->getPort();
processors->emplace_back(std::move(source));
}
if (!extremes)
{
auto source = std::make_shared<NullSource>(format_extremes.getSharedHeader());
extremes = &source->getPort();
processors->emplace_back(std::move(source));
}
connect(*output, format_main);
connect(*totals, format_totals);
connect(*extremes, format_extremes);
output = nullptr;
totals = nullptr;
extremes = nullptr;
initRowsBeforeLimit(format.get());
for (const auto & context : resources.interpreter_context)
{
if (context->getSettingsRef()[Setting::rows_before_aggregation])
{
initRowsBeforeAggregation(processors, format.get());
break;
}
}
output_format = format.get();
processors->emplace_back(std::move(format));
}
Block QueryPipeline::getHeader() const
{
if (input)
return input->getHeader();
if (output)
return output->getHeader();
throw Exception(ErrorCodes::LOGICAL_ERROR, "Header is available only for pushing or pulling QueryPipeline");
}
SharedHeader QueryPipeline::getSharedHeader() const
{
if (input)
return input->getSharedHeader();
if (output)
return output->getSharedHeader();
throw Exception(ErrorCodes::LOGICAL_ERROR, "Header is available only for pushing or pulling QueryPipeline");
}
void QueryPipeline::setProgressCallback(const ProgressCallback & callback)
{
progress_callback = callback;
}
void QueryPipeline::setProcessListElement(QueryStatusPtr elem)
{
process_list_element = elem;
if (pushing())
{
if (auto * counting = dynamic_cast<CountingTransform *>(&input->getProcessor()))
{
counting->setProcessListElement(elem);
}
}
}
void QueryPipeline::setQuota(std::shared_ptr<const EnabledQuota> quota_)
{
quota = std::move(quota_);
}
void QueryPipeline::setLimitsAndQuota(const StreamLocalLimits & limits, std::shared_ptr<const EnabledQuota> quota_)
{
if (!pulling())
throw Exception(
ErrorCodes::LOGICAL_ERROR,
"It is possible to set limits and quota only to pulling QueryPipeline");
auto transform = std::make_shared<LimitsCheckingTransform>(output->getSharedHeader(), limits);
transform->setQuota(quota_);
transform->setNormalizedQueryHash(normalized_query_hash);
connect(*output, transform->getInputPort());
output = &transform->getOutputPort();
processors->emplace_back(std::move(transform));
}
bool QueryPipeline::tryGetResultRowsAndBytes(UInt64 & result_rows, UInt64 & result_bytes) const
{
if (!output_format)
return false;
result_rows = output_format->getResultRows();
result_bytes = output_format->getResultBytes();
return true;
}
void QueryPipeline::setStepWallClockRegistry(StepWallClockRegistryPtr step_wall_clock_registry_)
{
step_wall_clock_registry = std::move(step_wall_clock_registry_);
}
void QueryPipeline::writeResultIntoQueryResultCache(std::shared_ptr<QueryResultCacheWriter> query_result_cache_writer)
{
chassert(pulling());
/// Attach a special transform to all output ports (result + possibly totals/extremes). The only purpose of the transform is to write
/// each chunk into the query result cache. All transforms hold a refcounted reference to the same query result cache writer object.
/// This ensures that all transforms write to the single same cache entry. The writer object synchronizes internally, the expensive
/// stuff like cloning chunks happens outside lock scopes).
auto add_stream_in_query_result_cache_transform = [&](OutputPort *& out_port, QueryResultCacheWriter::ChunkType chunk_type)
{
if (!out_port)
return;
auto transform = std::make_shared<StreamInQueryResultCacheTransform>(out_port->getHeader(), query_result_cache_writer, chunk_type);
connect(*out_port, transform->getInputPort());
out_port = &transform->getOutputPort();
processors->emplace_back(std::move(transform));
};
using enum QueryResultCacheWriter::ChunkType;
add_stream_in_query_result_cache_transform(output, Result);
add_stream_in_query_result_cache_transform(totals, Totals);
add_stream_in_query_result_cache_transform(extremes, Extremes);
}
void QueryPipeline::finalizeWriteInQueryResultCache()
{
/// QueryPipeline can contain multiple StreamInQueryResultCacheTransforms,
/// and all StreamInQueryResultCacheTransforms can point to different QueryResultCacheWriter objects if subqueries are cached.
/// We should call finalize() on all of them.
for (auto & processor : *processors)
if (auto * stream_processor = dynamic_cast<StreamInQueryResultCacheTransform *>(&*processor); stream_processor)
stream_processor->finalizeWriteInQueryResultCache();
}
void QueryPipeline::readFromQueryResultCache(
std::unique_ptr<SourceFromChunks> source,
std::unique_ptr<SourceFromChunks> source_totals,
std::unique_ptr<SourceFromChunks> source_extremes)
{
/// Construct the pipeline from the input source processors. The processors are provided by the query result cache to produce chunks of
/// a previous query result.
auto add_stream_from_query_result_cache_source = [&](OutputPort *& out_port, std::unique_ptr<SourceFromChunks> source_)
{
if (!source_)
return;
out_port = &source_->getPort();
processors->emplace_back(std::shared_ptr<SourceFromChunks>(std::move(source_)));
};
add_stream_from_query_result_cache_source(output, std::move(source));
add_stream_from_query_result_cache_source(totals, std::move(source_totals));
add_stream_from_query_result_cache_source(extremes, std::move(source_extremes));
}
void QueryPipeline::addStorageHolder(StoragePtr storage)
{
resources.storage_holders.emplace_back(std::move(storage));
}
void QueryPipeline::addCompletedPipeline(QueryPipeline && other)
{
if (!other.completed())
throw Exception(ErrorCodes::LOGICAL_ERROR, "Cannot add not completed pipeline");
resources.append(other.resources);
processors->insert(processors->end(), std::make_move_iterator(other.processors->begin()), std::make_move_iterator(other.processors->end()));
}
void QueryPipeline::addCompletedPipeline(const QueryPipeline & other)
{
if (!other.completed())
throw Exception(ErrorCodes::LOGICAL_ERROR, "Cannot add not completed pipeline");
resources.append(other.resources);
processors->insert(processors->end(), other.processors->begin(), other.processors->end());
}
void QueryPipeline::reset()
{
QueryPipeline to_remove = std::move(*this);
*this = QueryPipeline();
}
void QueryPipeline::cancel() noexcept
{
if (processors)
{
for (auto & processor : *processors)
processor->cancel();
}
}
static void addExpression(OutputPort *& port, ExpressionActionsPtr actions, Processors & processors)
{
if (port)
{
auto transform = std::make_shared<ExpressionTransform>(port->getSharedHeader(), actions);
connect(*port, transform->getInputPort());
port = &transform->getOutputPort();
processors.emplace_back(std::move(transform));
}
}
void QueryPipeline::convertStructureTo(const ColumnsWithTypeAndName & columns, const ContextPtr & context)
{
if (!pulling())
throw Exception(ErrorCodes::LOGICAL_ERROR, "Pipeline must be pulling to convert header");
const auto & source_header = output->getHeader();
/// Prefer matching the source columns to the target structure by name, not by position.
/// This is used to read external dictionaries from a local ClickHouse source: the dictionary expects its
/// columns in keys-first order, but the source query may return them in a different order. Matching by name
/// reorders the columns correctly and keeps the local source consistent with the remote one, which already
/// matches by name (see `adaptBlockStructure` in `RemoteQueryExecutor`).
///
/// Matching by name is only possible when every target column is present in the source by name. When the
/// source query does not name its columns to match the target (e.g. `SELECT 1, 1`), keep the historical
/// positional matching of a local dictionary source, so that such dictionaries continue to load.
auto match_columns_mode = ActionsDAG::MatchColumnsMode::Name;
for (const auto & column : columns)
{
if (!source_header.has(column.name))
{
match_columns_mode = ActionsDAG::MatchColumnsMode::Position;
break;
}
}
auto converting = ActionsDAG::makeConvertingActions(
source_header.getColumnsWithTypeAndName(),
columns,
match_columns_mode,
context);
auto actions = std::make_shared<ExpressionActions>(std::move(converting));
addExpression(output, actions, *processors);
addExpression(totals, actions, *processors);
addExpression(extremes, actions, *processors);
}
std::unique_ptr<ReadProgressCallback> QueryPipeline::getReadProgressCallback() const
{
auto callback = std::make_unique<ReadProgressCallback>();
callback->setProgressCallback(progress_callback);
callback->setQuota(quota);
callback->setNormalizedQueryHash(normalized_query_hash);
callback->setProcessListElement(process_list_element);
if (!update_profile_events)
callback->disableProfileEventUpdate();
return callback;
}
}