-
Notifications
You must be signed in to change notification settings - Fork 3.8k
Expand file tree
/
Copy pathscan_operator.cpp
More file actions
1490 lines (1379 loc) · 64.7 KB
/
scan_operator.cpp
File metadata and controls
1490 lines (1379 loc) · 64.7 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
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
#include "exec/operator/scan_operator.h"
#include <fmt/format.h>
#include <gen_cpp/Exprs_types.h>
#include <gen_cpp/Metrics_types.h>
#include <algorithm>
#include <cstdint>
#include <memory>
#include "common/global_types.h"
#include "core/data_type/data_type.h"
#include "core/data_type/data_type_array.h"
#include "exec/operator/file_scan_operator.h"
#include "exec/operator/group_commit_scan_operator.h"
#include "exec/operator/jdbc_scan_operator.h"
#include "exec/operator/meta_scan_operator.h"
#include "exec/operator/mock_scan_operator.h"
#include "exec/operator/olap_scan_operator.h"
#include "exec/operator/operator.h"
#include "exec/runtime_filter/runtime_filter_consumer_helper.h"
#include "exec/scan/scanner_context.h"
#include "exprs/function/in.h"
#include "exprs/runtime_filter_expr.h"
#include "exprs/vcast_expr.h"
#include "exprs/vectorized_fn_call.h"
#include "exprs/vexpr.h"
#include "exprs/vexpr_context.h"
#include "exprs/vexpr_fwd.h"
#include "exprs/vin_predicate.h"
#include "exprs/virtual_slot_ref.h"
#include "exprs/vslot_ref.h"
#include "exprs/vtopn_pred.h"
#include "runtime/descriptors.h"
#include "runtime/runtime_profile.h"
#include "runtime/runtime_profile_counter_names.h"
#include "storage/predicate/null_predicate.h"
#include "storage/predicate/predicate_creator.h"
namespace doris {
#define RETURN_IF_PUSH_DOWN(stmt, status) \
if (pdt == PushDownType::UNACCEPTABLE) { \
status = stmt; \
if (!status.ok()) { \
return; \
} \
} else { \
return; \
}
template <typename Derived>
bool ScanLocalState<Derived>::should_run_serial() const {
return _parent->cast<typename Derived::Parent>()._should_run_serial;
}
Status ScanLocalStateBase::update_late_arrival_runtime_filter(RuntimeState* state,
int& arrived_rf_num) {
// Lock needed because _conjuncts can be accessed concurrently by multiple scanner threads
LockGuard lock(_conjuncts_lock);
size_t conjuncts_before = _conjuncts.size();
RETURN_IF_ERROR(_helper.try_append_late_arrival_runtime_filter(state, _parent->row_descriptor(),
arrived_rf_num, _conjuncts));
if (_scan_filter_profile != nullptr) {
for (size_t i = conjuncts_before; i < _conjuncts.size(); ++i) {
if (_conjuncts[i]->root() != nullptr && !_conjuncts[i]->scan_filter_handle()) {
_conjuncts[i]->attach_scan_filter(
_register_scan_filter(_conjuncts[i]->root(), nullptr));
}
}
}
if (state->enable_adjust_conjunct_order_by_cost()) {
std::ranges::sort(_conjuncts, [](const auto& a, const auto& b) {
return a->execute_cost() < b->execute_cost();
});
};
// Only re-run partition pruning when try_append_late_arrival_runtime_filter
// actually appended new conjuncts. Otherwise this hook would re-scan all
// partition boundaries on every scheduler pass while there are still
// unapplied RFs (Scanner::_applied_rf_num is not advanced here), wasting
// CPU re-evaluating the same set of RFs against the same boundaries.
if (_conjuncts.size() > conjuncts_before) {
RETURN_IF_ERROR(_on_runtime_filter_update());
}
return Status::OK();
}
Status ScanLocalStateBase::clone_conjunct_ctxs(VExprContextSPtrs& scanner_conjuncts) {
// Lock needed because _conjuncts can be accessed concurrently by multiple scanner threads
LockGuard lock(_conjuncts_lock);
scanner_conjuncts.resize(_conjuncts.size());
for (size_t i = 0; i != _conjuncts.size(); ++i) {
RETURN_IF_ERROR(_conjuncts[i]->clone(_state, scanner_conjuncts[i]));
}
return Status::OK();
}
bool ScanLocalStateBase::is_partition_pruned(int64_t partition_id) const {
return _rf_partition_pruner.is_partition_pruned(partition_id);
}
Status ScanLocalStateBase::_on_runtime_filter_update() {
const auto* parsed = _parent->parsed_partition_boundaries();
if (parsed != nullptr && !parsed->empty()) {
RETURN_IF_ERROR(_do_partition_pruning_by_rf());
}
return Status::OK();
}
Status ScanLocalStateBase::_do_partition_pruning_by_rf() {
if (!_state->query_options().enable_runtime_filter_partition_prune) {
return Status::OK();
}
const auto* parsed = _parent->parsed_partition_boundaries();
if (parsed == nullptr || parsed->empty()) {
return Status::OK();
}
int64_t newly_pruned = 0;
RETURN_IF_ERROR(_rf_partition_pruner.prune_by_runtime_filters(
*parsed, _conjuncts, _parent->runtime_filter_descs(), _parent->node_id(),
&newly_pruned));
if (newly_pruned > 0) {
COUNTER_SET(_partitions_pruned_by_rf_counter,
_rf_partition_pruner.pruned_partition_count());
}
return Status::OK();
}
ScanRuntimeFilterPartitionPruningStats ScanLocalStateBase::_runtime_filter_partition_pruning_stats()
const {
return {.total_partitions = _total_partitions_rf_counter->value(),
.pruned_partitions = _partitions_pruned_by_rf_counter->value()};
}
int ScanLocalStateBase::max_scanners_concurrency(RuntimeState* state) const {
// For select * from table limit 10; should just use one thread.
if (should_run_serial()) {
return 1;
}
/*
* The max concurrency of scanners for each ScanLocalStateBase is determined by:
* 1. User specified max_scanners_concurrency which is set through session variable.
* 2. Default: 4
*
* If this is a serial operator, the max concurrency should multiply by the number of parallel instances of the operator.
*/
return (state->max_scanners_concurrency() > 0 ? state->max_scanners_concurrency() : 4) *
(state->query_parallel_instance_num() / _parent->parallelism(state));
}
int ScanLocalStateBase::min_scanners_concurrency(RuntimeState* state) const {
if (should_run_serial()) {
return 1;
}
/*
* The min concurrency of scanners for each ScanLocalStateBase is determined by:
* 1. User specified min_scanners_concurrency which is set through session variable.
* 2. Default: 1
*
* If this is a serial operator, the max concurrency should multiply by the number of parallel instances of the operator.
*/
return (state->min_scanners_concurrency() > 0 ? state->min_scanners_concurrency() : 1) *
(state->query_parallel_instance_num() / _parent->parallelism(state));
}
ScannerScheduler* ScanLocalStateBase::scan_scheduler(RuntimeState* state) const {
return state->get_query_ctx()->get_scan_scheduler();
}
template <typename Derived>
Status ScanLocalState<Derived>::init(RuntimeState* state, LocalStateInfo& info) {
RETURN_IF_ERROR(PipelineXLocalState<>::init(state, info));
_scan_dependency = Dependency::create_shared(_parent->operator_id(), _parent->node_id(),
_parent->get_name() + "_DEPENDENCY");
_wait_for_dependency_timer = ADD_TIMER_WITH_LEVEL(
common_profile(), "WaitForDependency[" + _scan_dependency->name() + "]Time", 1);
SCOPED_TIMER(exec_time_counter());
SCOPED_TIMER(_init_timer);
auto& p = _parent->cast<typename Derived::Parent>();
_max_pushdown_conditions_per_column = p._max_pushdown_conditions_per_column;
if (state->enable_profile() && state->profile_level() >= 1) {
_scan_filter_profile = std::make_shared<ScanFilterProfile>();
}
RETURN_IF_ERROR(_helper.init(state, p.is_serial_operator(), p.node_id(), p.operator_id(),
_filter_dependencies, p.get_name() + "_FILTER_DEPENDENCY"));
RETURN_IF_ERROR(_init_profile());
set_scan_ranges(state, info.scan_ranges);
_wait_for_rf_timer = ADD_TIMER(common_profile(), "WaitForRuntimeFilter");
_instance_idx = info.task_idx;
return Status::OK();
}
static std::string predicates_to_string(
const phmap::flat_hash_map<int, std::vector<std::shared_ptr<ColumnPredicate>>>&
slot_id_to_predicates) {
fmt::memory_buffer debug_string_buffer;
for (const auto& [slot_id, predicates] : slot_id_to_predicates) {
if (predicates.empty()) {
continue;
}
fmt::format_to(debug_string_buffer, "Slot ID: {}: [", slot_id);
for (const auto& predicate : predicates) {
fmt::format_to(debug_string_buffer, "{{{}}}, ", predicate->debug_string());
}
fmt::format_to(debug_string_buffer, "] ");
}
return fmt::to_string(debug_string_buffer);
}
ScanFilterHandle ScanLocalStateBase::_register_scan_filter(const VExprSPtr& root,
const SlotDescriptor* slot) {
if (_scan_filter_profile == nullptr || root == nullptr) {
return {};
}
ScanFilterDesc desc;
desc.kind = ScanFilterKind::NORMAL;
if (root->is_rf_wrapper()) {
desc.kind = ScanFilterKind::RUNTIME_FILTER;
desc.runtime_filter_id = assert_cast<RuntimeFilterExpr*>(root.get())->filter_id();
} else if (root->is_topn_filter()) {
desc.kind = ScanFilterKind::TOPN_FILTER;
desc.topn_filter_source_node_id = assert_cast<VTopNPred*>(root.get())->source_node_id();
}
if (slot != nullptr) {
desc.slot_id = slot->id();
desc.column_name = slot->col_name();
desc.column_id = _parent->intermediate_row_desc().get_column_id(slot->id());
}
desc.debug_string = root->debug_string();
desc.compact_info = desc.debug_string;
return _scan_filter_profile->register_filter(std::move(desc));
}
template <typename Derived>
Status ScanLocalState<Derived>::open(RuntimeState* state) {
SCOPED_TIMER(exec_time_counter());
SCOPED_TIMER(_open_timer);
if (_opened) {
return Status::OK();
}
RETURN_IF_ERROR(PipelineXLocalState<>::open(state));
auto& p = _parent->cast<typename Derived::Parent>();
// init id_file_map() for runtime state
std::vector<SlotDescriptor*> slots = p._output_tuple_desc->slots();
for (auto slot : slots) {
if (slot->col_name().starts_with(BeConsts::GLOBAL_ROWID_COL)) {
state->set_id_file_map();
}
}
_common_expr_ctxs_push_down.resize(p._common_expr_ctxs_push_down.size());
for (size_t i = 0; i < _common_expr_ctxs_push_down.size(); i++) {
RETURN_IF_ERROR(
p._common_expr_ctxs_push_down[i]->clone(state, _common_expr_ctxs_push_down[i]));
}
size_t conjuncts_before = _conjuncts.size();
RETURN_IF_ERROR(_helper.acquire_runtime_filter(state, _conjuncts, p.row_descriptor()));
if (_conjuncts.size() > conjuncts_before) {
RETURN_IF_ERROR(_on_runtime_filter_update());
}
// Disable condition cache in topn filter valid. TODO:: Try to support the topn filter in condition cache
if (state->query_options().condition_cache_digest && p._topn_filter_source_node_ids.empty()) {
_condition_cache_digest = state->query_options().condition_cache_digest;
for (auto& conjunct : _conjuncts) {
_condition_cache_digest = conjunct->get_digest(_condition_cache_digest);
if (!_condition_cache_digest) {
break;
}
}
} else {
_condition_cache_digest = 0;
}
RETURN_IF_ERROR(_process_conjuncts(state));
if (state->enable_profile() && _scan_filter_profile == nullptr) {
custom_profile()->add_info_string("PushDownPredicates",
predicates_to_string(_slot_id_to_predicates));
}
auto status = _eos ? Status::OK() : _prepare_scanners();
RETURN_IF_ERROR(status);
if (auto ctx = _scanner_ctx.load()) {
DCHECK(!_eos && _num_scanners->value() > 0);
RETURN_IF_ERROR(ctx->init());
}
_opened = true;
return status;
}
static void init_slot_value_range(
phmap::flat_hash_map<int, ColumnValueRangeType>& slot_id_to_value_range,
SlotDescriptor* slot, const DataTypePtr type_desc) {
switch (type_desc->get_primitive_type()) {
#define M(NAME) \
case TYPE_##NAME: { \
ColumnValueRange<TYPE_##NAME> range(slot->col_name(), slot->is_nullable(), \
cast_set<int>(type_desc->get_precision()), \
cast_set<int>(type_desc->get_scale())); \
slot_id_to_value_range[slot->id()] = std::move(range); \
break; \
}
#define APPLY_FOR_SCALAR_TYPE(M) \
M(TINYINT) \
M(SMALLINT) \
M(INT) \
M(BIGINT) \
M(LARGEINT) \
M(FLOAT) \
M(DOUBLE) \
M(CHAR) \
M(DATE) \
M(DATETIME) \
M(DATEV2) \
M(DATETIMEV2) \
M(TIMESTAMPTZ) \
M(VARCHAR) \
M(STRING) \
M(DECIMAL32) \
M(DECIMAL64) \
M(DECIMAL128I) \
M(DECIMAL256) \
M(DECIMALV2) \
M(BOOLEAN) \
M(IPV4) \
M(IPV6)
APPLY_FOR_SCALAR_TYPE(M)
#undef M
default: {
break;
}
}
}
/// Step 1 of the scan-key generation pipeline.
///
/// Parse SQL WHERE conjuncts into per-column ColumnValueRange objects stored in
/// _slot_id_to_value_range. Each ColumnValueRange captures all constraints on
/// one column (fixed values from IN / =, or min/max bounds from < / <= / > / >=).
///
/// Example – "WHERE k1 IN (1, 2) AND k2 >= 5 AND k2 < 10 AND v > 100":
/// => ColumnValueRange<k1>: fixed_values = {1, 2}
/// => ColumnValueRange<k2>: scope [5, 10) (low=5 >=, high=10 <)
/// => ColumnValueRange<v>: scope (100, MAX] (low=100 >, high=MAX <=)
/// The k1/k2 ranges will later become scan keys (since they're key columns);
/// v's range stays as a residual predicate / olap filter.
///
/// After this step, _build_key_ranges_and_filters() picks up the key-column
/// ColumnValueRanges and feeds them to OlapScanKeys::extend_scan_key().
template <typename Derived>
Status ScanLocalState<Derived>::_normalize_conjuncts(RuntimeState* state) {
auto& p = _parent->cast<typename Derived::Parent>();
// The conjuncts is always on output tuple, so use _output_tuple_desc;
std::vector<SlotDescriptor*> slots = p._output_tuple_desc->slots();
for (auto& slot : slots) {
init_slot_value_range(_slot_id_to_value_range, slot, slot->type());
_slot_id_to_predicates.insert(
{slot->id(), std::vector<std::shared_ptr<ColumnPredicate>>()});
}
get_cast_types_for_variants();
for (const auto& [colname, type] : _cast_types_for_variants) {
auto* slot = p._slot_id_to_slot_desc[p._colname_to_slot_id[colname]];
init_slot_value_range(_slot_id_to_value_range, slot, type);
_slot_id_to_predicates.insert(
{slot->id(), std::vector<std::shared_ptr<ColumnPredicate>>()});
}
RETURN_IF_ERROR(_get_topn_filters(state));
for (auto it = _conjuncts.begin(); it != _conjuncts.end();) {
auto& conjunct = *it;
if (conjunct->root()) {
VExprSPtr new_root;
RETURN_IF_ERROR(_normalize_predicate(conjunct.get(), conjunct->root(), new_root));
if (new_root) {
conjunct->set_root(new_root);
if (!conjunct->scan_filter_handle()) {
conjunct->attach_scan_filter(_register_scan_filter(conjunct->root(), nullptr));
}
if (_should_push_down_common_expr(conjunct->root())) {
_common_expr_ctxs_push_down.emplace_back(conjunct);
it = _conjuncts.erase(it);
continue;
}
} else { // All conjuncts are pushed down as predicate column
_stale_expr_ctxs.emplace_back(
conjunct); // avoid function context and constant str being freed
it = _conjuncts.erase(it);
continue;
}
}
++it;
}
if (state->enable_profile() && _scan_filter_profile == nullptr) {
std::string message;
for (auto& conjunct : _conjuncts) {
if (conjunct->root()) {
if (!message.empty()) {
message += ", ";
}
message += conjunct->root()->debug_string();
}
}
custom_profile()->add_info_string("RemainedPredicates", message);
}
for (auto& it : _slot_id_to_value_range) {
std::visit(
[&](auto&& range) {
if (range.is_empty_value_range()) {
_eos = true;
_scan_dependency->set_ready();
}
},
it.second);
}
return Status::OK();
}
template <typename Derived>
Status ScanLocalState<Derived>::_normalize_predicate(VExprContext* context, const VExprSPtr& root,
VExprSPtr& output_expr) {
auto expr_root = root->is_rf_wrapper() ? root->get_impl() : root;
PushDownType pdt = PushDownType::UNACCEPTABLE;
if (dynamic_cast<VirtualSlotRef*>(expr_root.get())) {
// If the expr has virtual slot ref, we need to keep it in the tree.
output_expr = expr_root;
return Status::OK();
}
SlotDescriptor* slot = nullptr;
ColumnValueRangeType* range = nullptr;
RETURN_IF_ERROR(_eval_const_conjuncts(context, &pdt));
if (pdt == PushDownType::ACCEPTABLE) {
output_expr = nullptr;
return Status::OK();
}
std::shared_ptr<VSlotRef> slotref;
for (const auto& child : expr_root->children()) {
if (VExpr::expr_without_cast(child)->node_type() != TExprNodeType::SLOT_REF) {
// not a slot ref(column)
continue;
}
slotref = std::dynamic_pointer_cast<VSlotRef>(VExpr::expr_without_cast(child));
}
if (_is_predicate_acting_on_slot(expr_root->children(), &slot, &range)) {
Status status = Status::OK();
auto& slot_predicates = _slot_id_to_predicates[slot->id()];
const size_t predicates_before = slot_predicates.size();
std::visit(
[&](auto& value_range) {
auto expr = root->is_rf_wrapper() ? root->get_impl() : root;
{
Defer attach_defer = [&]() {
if (pdt != PushDownType::UNACCEPTABLE && root->is_rf_wrapper()) {
auto* rf_expr = assert_cast<RuntimeFilterExpr*>(root.get());
slot_predicates.back()->attach_profile_counter(
rf_expr->filter_id(),
rf_expr->predicate_filtered_rows_counter(),
rf_expr->predicate_input_rows_counter(),
rf_expr->predicate_always_true_rows_counter(),
context->get_runtime_filter_selectivity());
}
};
switch (expr->node_type()) {
case TExprNodeType::IN_PRED:
RETURN_IF_PUSH_DOWN(
_normalize_in_predicate(context, expr, slot, slot_predicates,
value_range, &pdt),
status);
break;
case TExprNodeType::BINARY_PRED:
RETURN_IF_PUSH_DOWN(
_normalize_binary_predicate(context, expr, slot,
slot_predicates, value_range, &pdt),
status);
break;
case TExprNodeType::FUNCTION_CALL:
if (expr->is_topn_filter()) {
RETURN_IF_PUSH_DOWN(_normalize_topn_filter(context, expr, slot,
slot_predicates, &pdt),
status);
} else {
RETURN_IF_PUSH_DOWN(_normalize_is_null_predicate(
context, expr, slot, slot_predicates,
value_range, &pdt),
status);
}
break;
case TExprNodeType::BITMAP_PRED:
RETURN_IF_PUSH_DOWN(_normalize_bitmap_filter(context, root, slot,
slot_predicates, &pdt),
status);
break;
case TExprNodeType::BLOOM_PRED:
RETURN_IF_PUSH_DOWN(_normalize_bloom_filter(context, root, slot,
slot_predicates, &pdt),
status);
break;
default:
break;
}
}
// `node_type` of function filter is FUNCTION_CALL or COMPOUND_PRED
if (state()->enable_function_pushdown()) {
RETURN_IF_PUSH_DOWN(_normalize_function_filters(context, slot, &pdt),
status);
}
},
*range);
RETURN_IF_ERROR(status);
if (pdt != PushDownType::UNACCEPTABLE) {
auto handle = context->scan_filter_handle();
if (!handle) {
handle = _register_scan_filter(root, slot);
context->attach_scan_filter(handle);
}
if (handle) {
for (size_t i = predicates_before; i < slot_predicates.size(); ++i) {
slot_predicates[i]->attach_scan_filter(handle);
}
}
}
}
if (pdt == PushDownType::ACCEPTABLE && slotref != nullptr &&
slotref->data_type()->get_primitive_type() == PrimitiveType::TYPE_VARIANT) {
// remaining it in the expr tree, in order to filter by function if the pushdown
// predicate is not applied
output_expr = expr_root; // remaining in conjunct tree
return Status::OK();
}
if (pdt == PushDownType::ACCEPTABLE && _is_key_column(slot->col_name())) {
output_expr = nullptr;
return Status::OK();
} else {
// for PARTIAL_ACCEPTABLE and UNACCEPTABLE, do not remove expr from the tree
output_expr = root;
return Status::OK();
}
output_expr = root;
return Status::OK();
}
Status ScanLocalStateBase::_normalize_bloom_filter(
VExprContext* expr_ctx, const VExprSPtr& root, SlotDescriptor* slot,
std::vector<std::shared_ptr<ColumnPredicate>>& predicates, PushDownType* pdt) {
std::shared_ptr<ColumnPredicate> pred = nullptr;
Defer defer = [&]() {
if (pred) {
DCHECK(*pdt != PushDownType::UNACCEPTABLE) << root->debug_string();
predicates.emplace_back(pred);
} else {
// If exception occurs during processing, do not push down
*pdt = PushDownType::UNACCEPTABLE;
}
};
DCHECK(TExprNodeType::BLOOM_PRED == root->node_type());
auto expr = root->is_rf_wrapper() ? root->get_impl() : root;
DCHECK(expr->get_num_children() == 1);
DCHECK(root->is_rf_wrapper());
*pdt = _should_push_down_bloom_filter();
if (*pdt != PushDownType::UNACCEPTABLE) {
pred = create_bloom_filter_predicate(
_parent->intermediate_row_desc().get_column_id(slot->id()), slot->col_name(),
slot->type()->get_primitive_type() == TYPE_VARIANT ? expr->get_child(0)->data_type()
: slot->type(),
expr->get_bloom_filter_func());
}
return Status::OK();
}
Status ScanLocalStateBase::_normalize_topn_filter(
VExprContext* expr_ctx, const VExprSPtr& root, SlotDescriptor* slot,
std::vector<std::shared_ptr<ColumnPredicate>>& predicates, PushDownType* pdt) {
std::shared_ptr<ColumnPredicate> pred = nullptr;
Defer defer = [&]() {
if (pred) {
DCHECK(*pdt != PushDownType::UNACCEPTABLE) << root->debug_string();
predicates.emplace_back(pred);
} else {
// If exception occurs during processing, do not push down
*pdt = PushDownType::UNACCEPTABLE;
}
};
DCHECK(root->is_topn_filter());
*pdt = _should_push_down_topn_filter();
if (*pdt != PushDownType::UNACCEPTABLE) {
auto& tmp = _state->get_query_ctx()->get_runtime_predicate(
assert_cast<VTopNPred*>(root.get())->source_node_id());
if (_push_down_topn(tmp)) {
pred = tmp.get_predicate(_parent->node_id());
}
}
return Status::OK();
}
Status ScanLocalStateBase::_normalize_bitmap_filter(
VExprContext* expr_ctx, const VExprSPtr& root, SlotDescriptor* slot,
std::vector<std::shared_ptr<ColumnPredicate>>& predicates, PushDownType* pdt) {
std::shared_ptr<ColumnPredicate> pred = nullptr;
Defer defer = [&]() {
if (pred) {
DCHECK(*pdt != PushDownType::UNACCEPTABLE) << root->debug_string();
predicates.emplace_back(pred);
} else {
// If exception occurs during processing, do not push down
*pdt = PushDownType::UNACCEPTABLE;
}
};
DCHECK(TExprNodeType::BITMAP_PRED == root->node_type());
auto expr = root->is_rf_wrapper() ? root->get_impl() : root;
*pdt = _should_push_down_bitmap_filter();
if (*pdt != PushDownType::UNACCEPTABLE) {
DCHECK(expr->get_num_children() == 1);
DCHECK(root->is_rf_wrapper());
pred = create_bitmap_filter_predicate(
_parent->intermediate_row_desc().get_column_id(slot->id()), slot->col_name(),
slot->type()->get_primitive_type() == TYPE_VARIANT ? expr->get_child(0)->data_type()
: slot->type(),
expr->get_bitmap_filter_func());
}
return Status::OK();
}
Status ScanLocalStateBase::_normalize_function_filters(VExprContext* expr_ctx, SlotDescriptor* slot,
PushDownType* pdt) {
auto expr = expr_ctx->root()->is_rf_wrapper() ? expr_ctx->root()->get_impl() : expr_ctx->root();
bool opposite = false;
VExpr* fn_expr = expr.get();
if (TExprNodeType::COMPOUND_PRED == expr->node_type() &&
expr->fn().name.function_name == "not") {
fn_expr = fn_expr->children()[0].get();
opposite = true;
}
if (fn_expr->is_like_expr()) {
doris::FunctionContext* fn_ctx = nullptr;
StringRef val;
PushDownType temp_pdt;
RETURN_IF_ERROR(_should_push_down_function_filter(assert_cast<VectorizedFnCall*>(fn_expr),
expr_ctx, &val, &fn_ctx, temp_pdt));
if (temp_pdt != PushDownType::UNACCEPTABLE) {
std::string col = slot->col_name();
auto handle = expr_ctx->scan_filter_handle();
if (!handle) {
handle = _register_scan_filter(expr_ctx->root(), slot);
expr_ctx->attach_scan_filter(handle);
}
_push_down_functions.emplace_back(opposite, col, fn_ctx, val, handle);
*pdt = temp_pdt;
}
}
return Status::OK();
}
// only one level cast expr could push down for variant type
// check if expr is cast and it's children is slot
static bool is_valid_push_down_cast(const VExprSPtrs& children) {
auto slot_expr = VExpr::expr_without_cast(children[0]);
return slot_expr->data_type()->get_primitive_type() == PrimitiveType::TYPE_VARIANT &&
children[0]->node_type() == TExprNodeType::CAST_EXPR &&
children[0]->children().at(0)->is_slot_ref();
}
template <typename Derived>
bool ScanLocalState<Derived>::_is_predicate_acting_on_slot(const VExprSPtrs& children,
SlotDescriptor** slot_desc,
ColumnValueRangeType** range) {
// children[0] must be slot ref or cast(slot(variant) as type)
if (children.empty() || (children[0]->node_type() != TExprNodeType::SLOT_REF &&
!is_valid_push_down_cast(children))) {
// not a slot ref(column)
return false;
}
std::shared_ptr<VSlotRef> slot_ref =
std::dynamic_pointer_cast<VSlotRef>(VExpr::expr_without_cast(children[0]));
*slot_desc =
_parent->cast<typename Derived::Parent>()._slot_id_to_slot_desc[slot_ref->slot_id()];
auto entry = _slot_id_to_predicates.find(slot_ref->slot_id());
if (_slot_id_to_predicates.end() == entry) {
return false;
}
auto sid_to_range = _slot_id_to_value_range.find(slot_ref->slot_id());
if (_slot_id_to_value_range.end() == sid_to_range) {
return false;
}
if (!_parent->cast<typename Derived::Parent>().can_push_down_column_predicate(*slot_desc)) {
return false;
}
*range = &(sid_to_range->second);
return true;
}
template <typename Derived>
std::string ScanLocalState<Derived>::debug_string(int indentation_level) const {
fmt::memory_buffer debug_string_buffer;
fmt::format_to(debug_string_buffer, "{}, _eos = {} , _opened = {}",
PipelineXLocalState<>::debug_string(indentation_level), _eos.load(),
_opened.load());
if (auto ctx = _scanner_ctx.load()) {
fmt::format_to(debug_string_buffer, "");
fmt::format_to(debug_string_buffer, ", Scanner Context: {}", ctx->debug_string());
} else {
fmt::format_to(debug_string_buffer, "");
fmt::format_to(debug_string_buffer, ", Scanner Context: NULL");
}
return fmt::to_string(debug_string_buffer);
}
Status ScanLocalStateBase::_eval_const_conjuncts(VExprContext* expr_ctx, PushDownType* pdt) {
auto vexpr =
expr_ctx->root()->is_rf_wrapper() ? expr_ctx->root()->get_impl() : expr_ctx->root();
// Used to handle constant expressions, such as '1 = 1' _eval_const_conjuncts does not handle cases like 'colA = 1'
const char* constant_val = nullptr;
if (vexpr->is_constant()) {
std::shared_ptr<ColumnPtrWrapper> const_col_wrapper;
RETURN_IF_ERROR(vexpr->get_const_col(expr_ctx, &const_col_wrapper));
if (const auto* const_column =
check_and_get_column<ColumnConst>(const_col_wrapper->column_ptr.get())) {
constant_val = const_column->get_data_at(0).data;
if (constant_val == nullptr || !*reinterpret_cast<const bool*>(constant_val)) {
*pdt = PushDownType::ACCEPTABLE;
_eos = true;
_scan_dependency->set_ready();
}
} else if (const auto* bool_column =
check_and_get_column<ColumnUInt8>(const_col_wrapper->column_ptr.get())) {
// TODO: If `vexpr->is_constant()` is true, a const column is expected here.
// But now we still don't cover all predicates for const expression.
// For example, for query `SELECT col FROM tbl WHERE 'PROMOTION' LIKE 'AAA%'`,
// predicate `like` will return a ColumnVector<UInt8> which contains a single value.
LOG(WARNING) << "VExpr[" << vexpr->debug_string()
<< "] should return a const column but actually is "
<< const_col_wrapper->column_ptr->get_name();
DCHECK_EQ(bool_column->size(), 1);
/// TODO: There is a DCHECK here, but an additional check is still needed. It should return an error code.
if (bool_column->size() == 1) {
constant_val = bool_column->get_data_at(0).data;
if (constant_val == nullptr || !*reinterpret_cast<const bool*>(constant_val)) {
*pdt = PushDownType::ACCEPTABLE;
_eos = true;
_scan_dependency->set_ready();
}
} else {
LOG(WARNING) << "Constant predicate in scan node should return a bool column with "
"`size == 1` but actually is "
<< bool_column->size();
}
} else {
LOG(WARNING) << "VExpr[" << vexpr->debug_string()
<< "] should return a const column but actually is "
<< const_col_wrapper->column_ptr->get_name();
}
}
return Status::OK();
}
template <PrimitiveType T>
Status ScanLocalStateBase::_normalize_in_predicate(
VExprContext* expr_ctx, const VExprSPtr& root, SlotDescriptor* slot,
std::vector<std::shared_ptr<ColumnPredicate>>& predicates, ColumnValueRange<T>& range,
PushDownType* pdt) {
std::shared_ptr<ColumnPredicate> pred = nullptr;
Defer defer = [&]() {
if (pred) {
DCHECK(*pdt != PushDownType::UNACCEPTABLE) << root->debug_string();
predicates.emplace_back(pred);
} else {
// If exception occurs during processing, do not push down
*pdt = PushDownType::UNACCEPTABLE;
}
};
if (slot->get_virtual_column_expr() != nullptr) {
// virtual column, do not push down
return Status::OK();
}
DCHECK(!root->is_rf_wrapper()) << root->debug_string();
DCHECK(TExprNodeType::IN_PRED == root->node_type()) << root->debug_string();
*pdt = _should_push_down_in_predicate();
if (*pdt == PushDownType::UNACCEPTABLE) {
return Status::OK();
}
HybridSetBase::IteratorBase* iter = nullptr;
auto hybrid_set = root->get_set_func();
auto is_in = false;
if (hybrid_set != nullptr) {
// runtime filter produce VDirectInPredicate
if (hybrid_set->size() <= static_cast<size_t>(_max_pushdown_conditions_per_column)) {
iter = hybrid_set->begin();
}
is_in = true;
} else {
// normal in predicate
auto* tmp = assert_cast<VInPredicate*>(root.get());
// begin to push InPredicate value into ColumnValueRange
auto* state = reinterpret_cast<InState*>(
expr_ctx->fn_context(tmp->fn_context_index())
->get_function_state(FunctionContext::FRAGMENT_LOCAL));
// xx in (col, xx, xx) should not be push down
if (!state->use_set) {
return Status::OK();
}
is_in = !tmp->is_not_in();
if (state->hybrid_set->contain_null() && tmp->is_not_in()) {
_eos = true;
_scan_dependency->set_ready();
return Status::OK();
}
hybrid_set = state->hybrid_set;
iter = state->hybrid_set->begin();
}
if (iter) {
auto empty_range = ColumnValueRange<T>::create_empty_column_value_range(
slot->is_nullable(), range.precision(), range.scale());
auto& temp_range = is_in ? empty_range : range;
auto fn = is_in ? ColumnValueRange<T>::add_fixed_value_range
: (range.is_fixed_value_range()
? ColumnValueRange<T>::remove_fixed_value_range
: ColumnValueRange<T>::empty_function);
while (iter->has_next()) {
// column in (nullptr) is always false so continue to
// dispose next item
DCHECK(iter->get_value() != nullptr);
const auto* value = iter->get_value();
if constexpr (is_string_type(T)) {
const auto* str_value = reinterpret_cast<const StringRef*>(value);
RETURN_IF_ERROR(_change_value_range(
is_in, temp_range,
Field::create_field<T>(std::string(str_value->data, str_value->size)), fn,
is_in ? "in" : "not_in"));
} else {
RETURN_IF_ERROR(_change_value_range(
is_in, temp_range,
Field::create_field<T>(
*reinterpret_cast<const typename PrimitiveTypeTraits<T>::CppType*>(
value)),
fn, is_in ? "in" : "not_in"));
}
iter->next();
}
if (is_in) {
range.intersection(temp_range);
}
}
pred = is_in ? create_in_list_predicate<PredicateType::IN_LIST>(
_parent->intermediate_row_desc().get_column_id(slot->id()),
slot->col_name(),
slot->type()->get_primitive_type() == TYPE_VARIANT
? root->get_child(0)->data_type()
: slot->type(),
hybrid_set, false)
: create_in_list_predicate<PredicateType::NOT_IN_LIST>(
_parent->intermediate_row_desc().get_column_id(slot->id()),
slot->col_name(),
slot->type()->get_primitive_type() == TYPE_VARIANT
? root->get_child(0)->data_type()
: slot->type(),
hybrid_set, false);
return Status::OK();
}
template <PrimitiveType T>
Status ScanLocalStateBase::_normalize_binary_predicate(
VExprContext* expr_ctx, const VExprSPtr& root, SlotDescriptor* slot,
std::vector<std::shared_ptr<ColumnPredicate>>& predicates, ColumnValueRange<T>& range,
PushDownType* pdt) {
std::shared_ptr<ColumnPredicate> pred = nullptr;
Defer defer = [&]() {
if (pred) {
DCHECK(*pdt != PushDownType::UNACCEPTABLE) << root->debug_string();
predicates.emplace_back(pred);
} else {
// If exception occurs during processing, do not push down
*pdt = PushDownType::UNACCEPTABLE;
}
};
if (slot->get_virtual_column_expr() != nullptr) {
// virtual column, do not push down
return Status::OK();
}
DCHECK(!root->is_rf_wrapper()) << root->debug_string();
DCHECK(TExprNodeType::BINARY_PRED == root->node_type()) << root->debug_string();
DCHECK(root->get_num_children() == 2);
Field value;
*pdt = _should_push_down_binary_predicate(assert_cast<VectorizedFnCall*>(root.get()), expr_ctx,
value, {"eq", "ne", "lt", "gt", "le", "ge"});
if (*pdt == PushDownType::UNACCEPTABLE) {
return Status::OK();
}
const std::string& function_name =
assert_cast<VectorizedFnCall*>(root.get())->fn().name.function_name;
auto op = to_olap_filter_type(function_name);
auto is_equal_op = op == SQLFilterOp::FILTER_EQ || op == SQLFilterOp::FILTER_NE;
auto empty_range = ColumnValueRange<T>::create_empty_column_value_range(
slot->is_nullable(), range.precision(), range.scale());
auto& temp_range = op == SQLFilterOp::FILTER_EQ ? empty_range : range;
if (value.get_type() != TYPE_NULL) {
switch (op) {
case SQLFilterOp::FILTER_EQ:
pred = create_comparison_predicate<PredicateType::EQ>(
_parent->intermediate_row_desc().get_column_id(slot->id()), slot->col_name(),
slot->type()->get_primitive_type() == TYPE_VARIANT
? root->get_child(0)->data_type()
: slot->type(),
value, false);
break;
case SQLFilterOp::FILTER_NE:
pred = create_comparison_predicate<PredicateType::NE>(
_parent->intermediate_row_desc().get_column_id(slot->id()), slot->col_name(),
slot->type()->get_primitive_type() == TYPE_VARIANT
? root->get_child(0)->data_type()
: slot->type(),
value, false);
break;
case SQLFilterOp::FILTER_LESS:
pred = create_comparison_predicate<PredicateType::LT>(
_parent->intermediate_row_desc().get_column_id(slot->id()), slot->col_name(),
slot->type()->get_primitive_type() == TYPE_VARIANT
? root->get_child(0)->data_type()
: slot->type(),
value, false);
break;
case SQLFilterOp::FILTER_LARGER:
pred = create_comparison_predicate<PredicateType::GT>(
_parent->intermediate_row_desc().get_column_id(slot->id()), slot->col_name(),
slot->type()->get_primitive_type() == TYPE_VARIANT
? root->get_child(0)->data_type()
: slot->type(),
value, false);
break;
case SQLFilterOp::FILTER_LESS_OR_EQUAL:
pred = create_comparison_predicate<PredicateType::LE>(
_parent->intermediate_row_desc().get_column_id(slot->id()), slot->col_name(),
slot->type()->get_primitive_type() == TYPE_VARIANT
? root->get_child(0)->data_type()
: slot->type(),
value, false);
break;
case SQLFilterOp::FILTER_LARGER_OR_EQUAL:
pred = create_comparison_predicate<PredicateType::GE>(
_parent->intermediate_row_desc().get_column_id(slot->id()), slot->col_name(),
slot->type()->get_primitive_type() == TYPE_VARIANT
? root->get_child(0)->data_type()
: slot->type(),
value, false);
break;
default:
throw Exception(Status::InternalError("Unsupported function name: {}", function_name));
}
auto fn = op == SQLFilterOp::FILTER_EQ ? ColumnValueRange<T>::add_fixed_value_range
: op == SQLFilterOp::FILTER_NE
? (range.is_fixed_value_range()
? ColumnValueRange<T>::remove_fixed_value_range
: ColumnValueRange<T>::empty_function)
: ColumnValueRange<T>::add_value_range;
RETURN_IF_ERROR(_change_value_range(is_equal_op, temp_range, value, fn, function_name));
if (op == SQLFilterOp::FILTER_EQ) {
range.intersection(temp_range);
}
} else {
*pdt = PushDownType::UNACCEPTABLE;
_eos = true;
_scan_dependency->set_ready();