Repository navigation
Expand file tree
/
Copy pathpush_down_filter.rs
More file actions
4455 lines (4106 loc) · 154 KB
/
Copy pathpush_down_filter.rs
File metadata and controls
4455 lines (4106 loc) · 154 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.
//! [`PushDownFilter`] applies filters as early as possible
use std::collections::{HashMap, HashSet};
use std::sync::Arc;
use arrow::datatypes::DataType;
use indexmap::IndexSet;
use itertools::Itertools;
use log::{Level, debug, log_enabled};
use datafusion_common::instant::Instant;
use datafusion_common::tree_node::{
Transformed, TransformedResult, TreeNode, TreeNodeRecursion,
};
use datafusion_common::{
Column, DFSchema, Result, assert_eq_or_internal_err, internal_err, plan_err,
qualified_name,
};
use datafusion_expr::expr::WindowFunction;
use datafusion_expr::expr_rewriter::replace_col;
use datafusion_expr::logical_plan::{Join, JoinType, LogicalPlan};
use datafusion_expr::utils::{
conjunction, expr_to_columns, split_conjunction, split_conjunction_owned,
};
use datafusion_expr::{
BinaryExpr, Distinct, Expr, Filter, Operator, Projection,
TableProviderFilterPushDown, and, or,
};
use crate::optimizer::ApplyOrder;
use crate::simplify_expressions::{reorder_predicates, simplify_predicates};
use crate::utils::{
ColumnReference, has_all_column_refs, is_restrict_null_predicate, schema_columns,
};
use crate::{OptimizerConfig, OptimizerRule};
use datafusion_expr::ExpressionPlacement;
/// Optimizer rule for pushing (moving) filter expressions down in a plan so
/// they are applied as early as possible.
///
/// # Introduction
///
/// The goal of this rule is to improve query performance by eliminating
/// redundant work.
///
/// For example, given a plan that sorts all values where `a > 10`:
///
/// ```text
/// Filter (a > 10)
/// Sort (a, b)
/// ```
///
/// A better plan is to filter the data *before* the Sort, which sorts fewer
/// rows and therefore does less work overall:
///
/// ```text
/// Sort (a, b)
/// Filter (a > 10) <-- Filter is moved before the sort
/// ```
///
/// However it is not always possible to push filters down. For example, given a
/// plan that finds the top 3 values and then keeps only those that are greater
/// than 10, if the filter is pushed below the limit it would produce a
/// different result.
///
/// ```text
/// Filter (a > 10) <-- cannot move this Filter before the limit
/// Limit (fetch=3)
/// Sort (a, b)
/// ```
///
///
/// More formally, a filter-commutative operation is an operation `op` that
/// satisfies `filter(op(data)) = op(filter(data))`.
///
/// The filter-commutative property is plan and column-specific. A filter on `a`
/// can be pushed through a `Aggregate(group_by = [a], agg=[sum(b)])`. However, a
/// filter on `sum(b)` cannot be pushed through the same aggregate.
///
/// # Handling Conjunctions
///
/// It is possible to only push down **part** of a filter expression if it is
/// connected with `AND`s (more formally if it is a "conjunction").
///
/// For example, given the following plan:
///
/// ```text
/// Filter(a > 10 AND sum(b) < 5)
/// Aggregate(group_by = [a], agg = [sum(b)])
/// ```
///
/// The `a > 10` is commutative with the `Aggregate` but `sum(b) < 5` is not.
/// Therefore it is possible to only push down part of the expression, resulting in:
///
/// ```text
/// Filter(sum(b) < 5)
/// Aggregate(group_by = [a], agg = [sum(b)])
/// Filter(a > 10)
/// ```
///
/// # Handling Column Aliases
///
/// This optimizer must sometimes handle rewriting filter expressions when they are
/// pushed. For example, consider a projection that aliases `a+1` to `"b"`:
///
/// ```text
/// Filter (b > 10)
/// Projection: [a+1 AS "b"] <-- changes the name of `a+1` to `b`
/// ```
///
/// To push this filter below the `Projection`, all references to `b` must be
/// rewritten to `a+1`:
///
/// ```text
/// Projection: [a+1 AS "b"]
/// Filter: (a+1 > 10) <--- changed from b to a+1
/// ```
/// # Implementation Notes
///
/// This implementation performs a single pass through the plan, "pushing" down
/// filters. When it passes through a filter, it stores that filter, and when it
/// reaches a plan node that does not commute with that filter, it adds the
/// filter to that place. When it passes through a projection, it re-writes the
/// filter's expression taking into account that projection.
#[derive(Default, Debug)]
pub struct PushDownFilter {}
/// For a given JOIN type, determine whether each input of the join is preserved
/// for post-join (`WHERE` clause) filters.
///
/// It is only correct to push filters below a join for preserved inputs.
///
/// # Return Value
/// A tuple of booleans - (left_preserved, right_preserved).
///
/// # "Preserved" input definition
///
/// We say a join side is preserved if the join returns all or a subset of the rows from
/// the relevant side, such that each row of the output table directly maps to a row of
/// the preserved input table. If a table is not preserved, it can provide extra null rows.
/// That is, there may be rows in the output table that don't directly map to a row in the
/// input table.
///
/// For example:
/// - In an inner join, both sides are preserved, because each row of the output
/// maps directly to a row from each side.
///
/// - In a left join, the left side is preserved (we can push predicates) but
/// the right is not, because there may be rows in the output that don't
/// directly map to a row in the right input (due to nulls filling where there
/// is no match on the right).
pub(crate) fn lr_is_preserved(join_type: JoinType) -> (bool, bool) {
match join_type {
JoinType::Inner => (true, true),
JoinType::Left => (true, false),
JoinType::Right => (false, true),
JoinType::Full => (false, false),
// No columns from the right side of the join can be referenced in output
// predicates for semi/anti joins, so whether we specify t/f doesn't matter.
JoinType::LeftSemi | JoinType::LeftAnti | JoinType::LeftMark => (true, false),
// No columns from the left side of the join can be referenced in output
// predicates for semi/anti joins, so whether we specify t/f doesn't matter.
JoinType::RightSemi | JoinType::RightAnti | JoinType::RightMark => (false, true),
}
}
/// See [`JoinType::on_lr_is_preserved`] for details.
pub(crate) fn on_lr_is_preserved(join_type: JoinType) -> (bool, bool) {
join_type.on_lr_is_preserved()
}
/// Evaluates the columns referenced in the given expression to see if they refer
/// only to the left or right columns
#[derive(Debug)]
struct ColumnChecker<'a> {
/// schema of left join input
left_schema: &'a DFSchema,
/// columns in left_schema, computed on demand
left_columns: Option<HashSet<ColumnReference<'a>>>,
/// schema of right join input
right_schema: &'a DFSchema,
/// columns in left_schema, computed on demand
right_columns: Option<HashSet<ColumnReference<'a>>>,
}
impl<'a> ColumnChecker<'a> {
fn new(left_schema: &'a DFSchema, right_schema: &'a DFSchema) -> Self {
Self {
left_schema,
left_columns: None,
right_schema,
right_columns: None,
}
}
/// Return true if the expression references only columns from the left side of the join
fn is_left_only(&mut self, predicate: &Expr) -> bool {
if self.left_columns.is_none() {
self.left_columns = Some(schema_columns(self.left_schema));
}
has_all_column_refs(predicate, self.left_columns.as_ref().unwrap())
}
/// Return true if the expression references only columns from the right side of the join
fn is_right_only(&mut self, predicate: &Expr) -> bool {
if self.right_columns.is_none() {
self.right_columns = Some(schema_columns(self.right_schema));
}
has_all_column_refs(predicate, self.right_columns.as_ref().unwrap())
}
}
/// Determine whether the predicate can evaluate as the join conditions
fn can_evaluate_as_join_condition(predicate: &Expr) -> Result<bool> {
let mut is_evaluate = true;
predicate.apply(|expr| match expr {
Expr::Column(_)
| Expr::Literal(_, _)
| Expr::Placeholder(_)
| Expr::ScalarVariable(_, _) => Ok(TreeNodeRecursion::Jump),
Expr::Exists { .. }
| Expr::InSubquery(_)
| Expr::SetComparison(_)
| Expr::ScalarSubquery(_)
| Expr::OuterReferenceColumn(_, _)
| Expr::Unnest(_) => {
is_evaluate = false;
Ok(TreeNodeRecursion::Stop)
}
Expr::Alias(_)
| Expr::BinaryExpr(_)
| Expr::Like(_)
| Expr::SimilarTo(_)
| Expr::Not(_)
| Expr::IsNotNull(_)
| Expr::IsNull(_)
| Expr::IsTrue(_)
| Expr::IsFalse(_)
| Expr::IsUnknown(_)
| Expr::IsNotTrue(_)
| Expr::IsNotFalse(_)
| Expr::IsNotUnknown(_)
| Expr::Negative(_)
| Expr::Between(_)
| Expr::Case(_)
| Expr::Cast(_)
| Expr::TryCast(_)
| Expr::InList { .. }
| Expr::ScalarFunction(_)
| Expr::HigherOrderFunction(_)
| Expr::Lambda(_)
| Expr::LambdaVariable(_) => Ok(TreeNodeRecursion::Continue),
// TODO: remove the next line after `Expr::Wildcard` is removed
#[expect(deprecated)]
Expr::AggregateFunction(_)
| Expr::WindowFunction(_)
| Expr::Wildcard { .. }
| Expr::GroupingSet(_) => internal_err!("Unsupported predicate type"),
})?;
Ok(is_evaluate)
}
/// examine OR clause to see if any useful clauses can be extracted and push down.
/// extract at least one qual from each sub clauses of OR clause, then form the quals
/// to new OR clause as predicate.
///
/// # Example
/// ```text
/// Filter: (a = c and a < 20) or (b = d and b > 10)
/// join/crossjoin:
/// TableScan: projection=[a, b]
/// TableScan: projection=[c, d]
/// ```
///
/// is optimized to
///
/// ```text
/// Filter: (a = c and a < 20) or (b = d and b > 10)
/// join/crossjoin:
/// Filter: (a < 20) or (b > 10)
/// TableScan: projection=[a, b]
/// TableScan: projection=[c, d]
/// ```
///
/// In general, predicates of this form:
///
/// ```sql
/// (A AND B) OR (C AND D)
/// ```
///
/// will be transformed to one of:
///
/// * `((A AND B) OR (C AND D)) AND (A OR C)`
/// * `((A AND B) OR (C AND D)) AND ((A AND B) OR C)`
/// * do nothing.
fn extract_or_clauses_for_join<'a>(
filters: &'a [Expr],
schema_cols: &'a HashSet<ColumnReference>,
) -> impl Iterator<Item = Expr> + 'a {
// new formed OR clauses and their column references
filters.iter().filter_map(move |expr| {
if let Expr::BinaryExpr(BinaryExpr {
left,
op: Operator::Or,
right,
}) = expr
{
let left_expr = extract_or_clause(left.as_ref(), schema_cols);
let right_expr = extract_or_clause(right.as_ref(), schema_cols);
// If nothing can be extracted from any sub clauses, do nothing for this OR clause.
if let (Some(left_expr), Some(right_expr)) = (left_expr, right_expr) {
return Some(or(left_expr, right_expr));
}
}
None
})
}
/// extract qual from OR sub-clause.
///
/// A qual is extracted if it only contains set of column references in schema_columns.
///
/// For AND clause, we extract from both sub-clauses, then make new AND clause by extracted
/// clauses if both extracted; Otherwise, use the extracted clause from any sub-clauses or None.
///
/// For OR clause, we extract from both sub-clauses, then make new OR clause by extracted clauses if both extracted;
/// Otherwise, return None.
///
/// For other clause, apply the rule above to extract clause.
fn extract_or_clause(
expr: &Expr,
schema_columns: &HashSet<ColumnReference>,
) -> Option<Expr> {
let mut predicate = None;
match expr {
Expr::BinaryExpr(BinaryExpr {
left: l_expr,
op: Operator::Or,
right: r_expr,
}) => {
let l_expr = extract_or_clause(l_expr, schema_columns);
let r_expr = extract_or_clause(r_expr, schema_columns);
if let (Some(l_expr), Some(r_expr)) = (l_expr, r_expr) {
predicate = Some(or(l_expr, r_expr));
}
}
Expr::BinaryExpr(BinaryExpr {
left: l_expr,
op: Operator::And,
right: r_expr,
}) => {
let l_expr = extract_or_clause(l_expr, schema_columns);
let r_expr = extract_or_clause(r_expr, schema_columns);
match (l_expr, r_expr) {
(Some(l_expr), Some(r_expr)) => {
predicate = Some(and(l_expr, r_expr));
}
(Some(l_expr), None) => {
predicate = Some(l_expr);
}
(None, Some(r_expr)) => {
predicate = Some(r_expr);
}
(None, None) => {
predicate = None;
}
}
}
_ => {
if has_all_column_refs(expr, schema_columns) {
predicate = Some(expr.clone());
}
}
}
predicate
}
/// push down join/cross-join
fn push_down_all_join(
predicates: Vec<Expr>,
inferred_join_predicates: Vec<Expr>,
mut join: Join,
on_filter: Vec<Expr>,
) -> Result<Transformed<LogicalPlan>> {
let is_inner_join = join.join_type == JoinType::Inner;
// Get pushable predicates from current optimizer state
let (left_preserved, right_preserved) = lr_is_preserved(join.join_type);
// The predicates can be divided to three categories:
// 1) can push through join to its children(left or right)
// 2) can be converted to join conditions if the join type is Inner
// 3) should be kept as filter conditions
let left_schema = join.left.schema();
let right_schema = join.right.schema();
let left_schema_columns = schema_columns(left_schema.as_ref());
let right_schema_columns = schema_columns(right_schema.as_ref());
let mut left_push = vec![];
let mut right_push = vec![];
let mut keep_predicates = vec![];
let mut join_conditions = vec![];
let mut checker = ColumnChecker::new(left_schema, right_schema);
for predicate in predicates {
if left_preserved && checker.is_left_only(&predicate) {
left_push.push(predicate);
} else if right_preserved && checker.is_right_only(&predicate) {
right_push.push(predicate);
} else if is_inner_join && can_evaluate_as_join_condition(&predicate)? {
// Here we do not differ it is eq or non-eq predicate, ExtractEquijoinPredicate will extract the eq predicate
// and convert to the join on condition
join_conditions.push(predicate);
} else {
keep_predicates.push(predicate);
}
}
// Push predicates inferred from the join expression
for predicate in inferred_join_predicates {
if checker.is_left_only(&predicate) {
left_push.push(predicate);
} else if checker.is_right_only(&predicate) {
right_push.push(predicate);
}
}
let mut on_filter_join_conditions = vec![];
let (on_left_preserved, on_right_preserved) = on_lr_is_preserved(join.join_type);
for on in on_filter {
if on_left_preserved && checker.is_left_only(&on) {
left_push.push(on)
} else if on_right_preserved && checker.is_right_only(&on) {
right_push.push(on)
} else {
on_filter_join_conditions.push(on)
}
}
// Extract from OR clause, generate new predicates for both side of join if possible.
// We only track the unpushable predicates above.
if left_preserved {
left_push.extend(extract_or_clauses_for_join(
&keep_predicates,
&left_schema_columns,
));
left_push.extend(extract_or_clauses_for_join(
&join_conditions,
&left_schema_columns,
));
}
if right_preserved {
right_push.extend(extract_or_clauses_for_join(
&keep_predicates,
&right_schema_columns,
));
right_push.extend(extract_or_clauses_for_join(
&join_conditions,
&right_schema_columns,
));
}
// For predicates from join filter, we should check with if a join side is preserved
// in term of join filtering.
if on_left_preserved {
left_push.extend(extract_or_clauses_for_join(
&on_filter_join_conditions,
&left_schema_columns,
));
}
if on_right_preserved {
right_push.extend(extract_or_clauses_for_join(
&on_filter_join_conditions,
&right_schema_columns,
));
}
// Add any new join conditions as the non join predicates
let join_conditions_empty = join_conditions.is_empty();
join_conditions.extend(on_filter_join_conditions);
join.filter = conjunction(join_conditions);
if join_conditions_empty && left_push.is_empty() && right_push.is_empty() {
// wrap the join on the filter whose predicates must be kept, if any
return Ok(Transformed::no(with_filters(
keep_predicates,
LogicalPlan::Join(join),
)));
}
if let Some(predicate) = conjunction(left_push) {
join.left = Arc::new(LogicalPlan::Filter(Filter::new(predicate, join.left)));
}
if let Some(predicate) = conjunction(right_push) {
join.right = Arc::new(LogicalPlan::Filter(Filter::new(predicate, join.right)));
}
// wrap the join on the filter whose predicates must be kept, if any
Ok(Transformed::yes(with_filters(
keep_predicates,
LogicalPlan::Join(join),
)))
}
fn push_down_join(
mut join: Join,
parent_predicate: Option<Expr>,
) -> Result<Transformed<LogicalPlan>> {
// Split the parent predicate into individual conjunctive parts.
let predicates = parent_predicate.map_or_else(Vec::new, split_conjunction_owned);
// Extract conjunctions from the JOIN's ON filter, if present.
let on_filters = join
.filter
.take()
.map_or_else(Vec::new, split_conjunction_owned);
// Are there any new join predicates that can be inferred from the filter expressions?
let inferred_join_predicates = with_debug_timing("infer_join_predicates", || {
infer_join_predicates(&join, &predicates, &on_filters)
})?;
if log_enabled!(Level::Debug) {
debug!(
"push_down_filter: join_type={:?}, parent_predicates={}, on_filters={}, inferred_join_predicates={}",
join.join_type,
predicates.len(),
on_filters.len(),
inferred_join_predicates.len()
);
}
if on_filters.is_empty()
&& predicates.is_empty()
&& inferred_join_predicates.is_empty()
{
return Ok(Transformed::no(LogicalPlan::Join(join)));
}
push_down_all_join(predicates, inferred_join_predicates, join, on_filters)
}
/// Extracts any equi-join join predicates from the given filter expressions.
///
/// Parameters
/// * `join` the join in question
///
/// * `predicates` the pushed down filter expression
///
/// * `on_filters` filters from the join ON clause that have not already been
/// identified as join predicates
fn infer_join_predicates(
join: &Join,
predicates: &[Expr],
on_filters: &[Expr],
) -> Result<Vec<Expr>> {
// Null-aware joins (e.g. `NOT IN` with a nullable subquery) rely on SQL
// three-valued logic: a NULL join key on the right/subquery side makes the
// predicate UNKNOWN and empties the result, so those NULLs must reach the
// join. Inferring an equi-key predicate here would rewrite a left-side
// predicate onto the right side and, because the inferred predicate must be
// null-rejecting, drop the subquery's NULL rows and produce wrong results.
// Skip inference entirely for null-aware joins.
if join.null_aware {
return Ok(vec![]);
}
// Only allow both side key is column.
let join_col_keys = join
.on
.iter()
.filter_map(|(l, r)| {
let left_col = l.try_as_col()?;
let right_col = r.try_as_col()?;
Some((left_col, right_col))
})
.collect::<Vec<_>>();
let join_type = join.join_type;
let mut inferred_predicates = InferredPredicates::new(join_type);
infer_join_predicates_from_predicates(
&join_col_keys,
predicates,
&mut inferred_predicates,
)?;
infer_join_predicates_from_on_filters(
&join_col_keys,
join_type,
on_filters,
&mut inferred_predicates,
)?;
Ok(inferred_predicates.predicates)
}
/// Inferred predicates collector.
/// When the JoinType is not Inner, we need to detect whether the inferred predicate can strictly
/// filter out NULL, otherwise ignore it. e.g.
/// ```text
/// SELECT * FROM t1 LEFT JOIN t2 ON t1.c0 = t2.c0 WHERE t2.c0 IS NULL;
/// ```
/// We cannot infer the predicate `t1.c0 IS NULL`, otherwise the predicate will be pushed down to
/// the left side, resulting in the wrong result.
struct InferredPredicates {
predicates: Vec<Expr>,
is_inner_join: bool,
}
impl InferredPredicates {
fn new(join_type: JoinType) -> Self {
Self {
predicates: vec![],
is_inner_join: join_type == JoinType::Inner,
}
}
fn try_build_predicate(
&mut self,
predicate: Expr,
replace_map: &HashMap<&Column, &Column>,
) -> Result<()> {
if self.is_inner_join
|| matches!(
is_restrict_null_predicate(
predicate.clone(),
replace_map.keys().copied()
),
Ok(true)
)
{
self.predicates.push(replace_col(predicate, replace_map)?);
}
Ok(())
}
}
/// Infer predicates from the pushed down predicates.
///
/// Parameters
/// * `join_col_keys` column pairs from the join ON clause
///
/// * `predicates` the pushed down predicates
///
/// * `inferred_predicates` the inferred results
fn infer_join_predicates_from_predicates(
join_col_keys: &[(&Column, &Column)],
predicates: &[Expr],
inferred_predicates: &mut InferredPredicates,
) -> Result<()> {
infer_join_predicates_impl::<true, true>(
join_col_keys,
predicates,
inferred_predicates,
)
}
/// Infer predicates from the join filter.
///
/// Parameters
/// * `join_col_keys` column pairs from the join ON clause
///
/// * `join_type` the JoinType of Join
///
/// * `on_filters` filters from the join ON clause that have not already been
/// identified as join predicates
///
/// * `inferred_predicates` the inferred results
fn infer_join_predicates_from_on_filters(
join_col_keys: &[(&Column, &Column)],
join_type: JoinType,
on_filters: &[Expr],
inferred_predicates: &mut InferredPredicates,
) -> Result<()> {
match join_type {
JoinType::Full | JoinType::LeftAnti | JoinType::RightAnti => Ok(()),
JoinType::Inner => infer_join_predicates_impl::<true, true>(
join_col_keys,
on_filters,
inferred_predicates,
),
JoinType::Left | JoinType::LeftSemi | JoinType::LeftMark => {
infer_join_predicates_impl::<true, false>(
join_col_keys,
on_filters,
inferred_predicates,
)
}
JoinType::Right | JoinType::RightSemi | JoinType::RightMark => {
infer_join_predicates_impl::<false, true>(
join_col_keys,
on_filters,
inferred_predicates,
)
}
}
}
/// Infer predicates from the given predicates.
///
/// Parameters
/// * `join_col_keys` column pairs from the join ON clause
///
/// * `input_predicates` the given predicates. It can be the pushed down predicates,
/// or it can be the filters of the Join
///
/// * `inferred_predicates` the inferred results
///
/// * `ENABLE_LEFT_TO_RIGHT` indicates that the right table related predicate can
/// be inferred from the left table related predicate
///
/// * `ENABLE_RIGHT_TO_LEFT` indicates that the left table related predicate can
/// be inferred from the right table related predicate
fn infer_join_predicates_impl<
const ENABLE_LEFT_TO_RIGHT: bool,
const ENABLE_RIGHT_TO_LEFT: bool,
>(
join_col_keys: &[(&Column, &Column)],
input_predicates: &[Expr],
inferred_predicates: &mut InferredPredicates,
) -> Result<()> {
for predicate in input_predicates {
let mut join_cols_to_replace = HashMap::new();
for &col in &predicate.column_refs() {
for (l, r) in join_col_keys.iter() {
if ENABLE_LEFT_TO_RIGHT && col == *l {
join_cols_to_replace.insert(col, *r);
break;
}
if ENABLE_RIGHT_TO_LEFT && col == *r {
join_cols_to_replace.insert(col, *l);
break;
}
}
}
if join_cols_to_replace.is_empty() {
continue;
}
inferred_predicates
.try_build_predicate(predicate.clone(), &join_cols_to_replace)?;
}
Ok(())
}
impl OptimizerRule for PushDownFilter {
fn name(&self) -> &str {
"push_down_filter"
}
fn apply_order(&self) -> Option<ApplyOrder> {
Some(ApplyOrder::TopDown)
}
fn supports_rewrite(&self) -> bool {
true
}
fn rewrite(
&self,
plan: LogicalPlan,
config: &dyn OptimizerConfig,
) -> Result<Transformed<LogicalPlan>> {
let _ = config;
if let LogicalPlan::Join(join) = plan {
return push_down_join(join, None);
}
let LogicalPlan::Filter(mut filter) = plan else {
return Ok(Transformed::no(plan));
};
let predicate = split_conjunction_owned(filter.predicate.clone());
let old_predicate_len = predicate.len();
let new_predicates =
with_debug_timing("simplify_predicates", || simplify_predicates(predicate))?;
if log_enabled!(Level::Debug) {
debug!(
"push_down_filter: simplify_predicates old_count={}, new_count={}",
old_predicate_len,
new_predicates.len()
);
}
// Place cheap predicates before expensive ones, so the `AND`
// evaluator's right-side short-circuit can skip evaluating expensive
// predicates on rows that have already been filtered out.
let (new_predicates, reorder_changed) = reorder_predicates(new_predicates);
let count_changed = old_predicate_len != new_predicates.len();
if count_changed || reorder_changed {
let Some(new_predicate) = conjunction(new_predicates) else {
// new_predicates is empty - remove the filter entirely
// Return the child plan without the filter
return Ok(Transformed::yes(Arc::unwrap_or_clone(filter.input)));
};
filter.predicate = new_predicate;
}
// If the child has a fetch (limit) or skip (offset), pushing a filter
// below it would change semantics: the limit/offset should apply before
// the filter, not after.
if filter.input.fetch()?.is_some() || filter.input.skip()?.is_some() {
return Ok(Transformed::no(LogicalPlan::Filter(filter)));
}
match Arc::unwrap_or_clone(filter.input) {
LogicalPlan::Filter(mut child_filter) => {
// Child filters first to preserve execution order.
// Use IndexSet to remove duplicates while preserving predicate order.
let new_predicates: IndexSet<Expr> =
split_conjunction_owned(child_filter.predicate)
.into_iter()
.chain(split_conjunction_owned(filter.predicate))
.collect();
let Some(new_predicate) = conjunction(new_predicates) else {
return plan_err!("at least one expression exists");
};
child_filter.predicate = new_predicate;
self.rewrite(LogicalPlan::Filter(child_filter), config)
}
LogicalPlan::Repartition(mut repartition) => {
filter.input = repartition.input;
repartition.input = Arc::new(LogicalPlan::Filter(filter));
Ok(Transformed::yes(LogicalPlan::Repartition(repartition)))
}
LogicalPlan::Distinct(distinct) => {
let distinct = match distinct {
Distinct::All(input) => {
filter.input = input;
Distinct::All(Arc::new(LogicalPlan::Filter(filter)))
}
Distinct::On(mut distinct) => {
filter.input = distinct.input;
distinct.input = Arc::new(LogicalPlan::Filter(filter));
Distinct::On(distinct)
}
};
Ok(Transformed::yes(LogicalPlan::Distinct(distinct)))
}
LogicalPlan::Sort(mut sort) => {
filter.input = sort.input;
sort.input = Arc::new(LogicalPlan::Filter(filter));
Ok(Transformed::yes(LogicalPlan::Sort(sort)))
}
LogicalPlan::SubqueryAlias(mut subquery_alias) => {
let mut replace_map = HashMap::new();
for (i, (qualifier, field)) in
subquery_alias.input.schema().iter().enumerate()
{
let (sub_qualifier, sub_field) =
subquery_alias.schema.qualified_field(i);
replace_map.insert(
qualified_name(sub_qualifier, sub_field.name()),
Expr::Column(Column::new(qualifier.cloned(), field.name())),
);
}
filter.predicate = replace_cols_by_name(filter.predicate, &replace_map)?;
filter.input = subquery_alias.input;
subquery_alias.input = Arc::new(LogicalPlan::Filter(filter));
Ok(Transformed::yes(LogicalPlan::SubqueryAlias(subquery_alias)))
}
LogicalPlan::Projection(projection) => {
let predicates = split_conjunction_owned(filter.predicate.clone());
let (mut result, keep_predicates) =
rewrite_projection(predicates, projection)?;
if result.transformed {
result.data = with_filters(keep_predicates, result.data)
} else {
filter.input = Arc::new(result.data);
result.data = LogicalPlan::Filter(filter)
}
Ok(result)
}
LogicalPlan::Unnest(mut unnest) => {
let predicates = split_conjunction_owned(filter.predicate.clone());
let mut non_unnest_predicates = vec![];
let mut unnest_predicates = vec![];
let mut unnest_struct_columns = vec![];
for idx in &unnest.struct_type_columns {
let (sub_qualifier, field) =
unnest.input.schema().qualified_field(*idx);
if let DataType::Struct(children) = field.data_type() {
let field_name = field.name();
for child in children {
let child_name = child.name();
unnest_struct_columns.push(Column::new(
sub_qualifier.cloned(),
format!("{field_name}.{child_name}"),
));
}
}
}
for predicate in predicates {
// collect all the Expr::Column in predicate recursively
let mut accum: HashSet<Column> = HashSet::new();
expr_to_columns(&predicate, &mut accum)?;
let contains_list_columns =
unnest.list_type_columns.iter().any(|(_, unnest_list)| {
accum.contains(&unnest_list.output_column)
});
let contains_struct_columns =
unnest_struct_columns.iter().any(|c| accum.contains(c));
if contains_list_columns || contains_struct_columns {
unnest_predicates.push(predicate);
} else {
non_unnest_predicates.push(predicate);
}
}
// Unnest predicates should not be pushed down.
// If no non-unnest predicates exist, early return
if non_unnest_predicates.is_empty() {
filter.input = Arc::new(LogicalPlan::Unnest(unnest));
return Ok(Transformed::no(LogicalPlan::Filter(filter)));
}
// Push down non-unnest filter predicate
// Unnest
// Unnest Input (Projection)
// -> rewritten to
// Unnest
// Filter
// Unnest Input (Projection)
// Safe to unwrap since non_unnest_predicates is not empty.
filter.predicate = conjunction(non_unnest_predicates).unwrap();
filter.input = unnest.input;
// Directly assign new filter plan as the new unnest's input.
// The new filter plan will go through another rewrite pass since the rule itself
// is applied recursively to all the child from top to down
unnest.input = Arc::new(LogicalPlan::Filter(filter));
Ok(Transformed::yes(with_filters(
unnest_predicates,
LogicalPlan::Unnest(unnest),
)))
}
LogicalPlan::Union(mut union) => {
let mut inputs = Vec::with_capacity(union.inputs.len());
for input in union.inputs {
let mut replace_map = HashMap::new();
for (i, (qualifier, field)) in input.schema().iter().enumerate() {
let (union_qualifier, union_field) =
union.schema.qualified_field(i);
replace_map.insert(
qualified_name(union_qualifier, union_field.name()),
Expr::Column(Column::new(qualifier.cloned(), field.name())),
);
}
let push_predicate =
replace_cols_by_name(filter.predicate.clone(), &replace_map)?;
inputs.push(Arc::new(LogicalPlan::Filter(Filter::new(
push_predicate,
input,
))))
}
union.inputs = inputs;
Ok(Transformed::yes(LogicalPlan::Union(union)))
}
LogicalPlan::Aggregate(mut agg) => {
// We can push down Predicate which in groupby_expr.
let group_expr_columns = expr_columns(&agg.group_expr);