Skip to main content

datafusion_optimizer/
push_down_filter.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership
3// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements
4
5//! [`PushDownFilter`] applies filters as early as possible
6//!
7//! # Precedence: pure extraction projections win
8//!
9//! [`PushDownLeafProjections`] moves a *pure extraction projection* towards the
10//! leaves. Such a projection has only `__datafusion_extracted_N` aliases and
11//! pass-through columns. [`PushDownFilter`] moves filters towards the leaves
12//! too. For an adjacent filter and pure extraction projection the two rules
13//! want the opposite order, so they undo each other on every optimizer pass.
14//!
15//! **Invariant: `PushDownFilter` yields to a pure extraction projection.** A
16//! filter is never moved below such a projection. The extraction projection
17//! stays at the bottom of the plan, next to the scan, and the filter stays
18//! above it.
19//!
20//! The reason is that the extraction projection is the node a source absorbs.
21//! A Parquet scan merges it into the file projection and reads only the struct
22//! leaf, which is what the rule exists for. Keeping the filter one node higher
23//! costs nothing at the scan, because `PushDownFilter` records the predicate in
24//! [`TableScan::filters`](datafusion_expr::logical_plan::TableScan) in the pass
25//! that runs before the extraction projection exists.
26//!
27//! [`PushDownLeafProjections`]: crate::extract_leaf_expressions::PushDownLeafProjections
28
29use datafusion_expr::logical_plan::MaterializedCtePlan;
30use std::collections::{HashMap, HashSet};
31use std::sync::Arc;
32
33use arrow::datatypes::DataType;
34use indexmap::IndexSet;
35use itertools::Itertools;
36use log::{Level, debug, log_enabled};
37
38use datafusion_common::instant::Instant;
39use datafusion_common::tree_node::{
40    Transformed, TransformedResult, TreeNode, TreeNodeRecursion,
41};
42use datafusion_common::{
43    Column, DFSchema, Result, ScalarValue, assert_eq_or_internal_err, internal_err,
44    plan_err, qualified_name,
45};
46use datafusion_expr::expr::WindowFunction;
47use datafusion_expr::expr_rewriter::replace_col;
48use datafusion_expr::logical_plan::{Join, JoinType, LogicalPlan};
49use datafusion_expr::utils::{
50    conjunction, expr_to_columns, split_conjunction, split_conjunction_owned,
51};
52use datafusion_expr::{
53    BinaryExpr, Distinct, EmptyRelation, Expr, Filter, Operator, Projection,
54    TableProviderFilterPushDown, and, or,
55};
56
57use crate::extract_leaf_expressions::is_pure_extraction_projection;
58use crate::optimizer::ApplyOrder;
59use crate::simplify_expressions::{reorder_predicates, simplify_predicates};
60use crate::utils::{
61    ColumnReference, has_all_column_refs, is_restrict_null_predicate, schema_columns,
62};
63use crate::{OptimizerConfig, OptimizerRule};
64use datafusion_expr::ExpressionPlacement;
65
66/// Optimizer rule for pushing (moving) filter expressions down in a plan so
67/// they are applied as early as possible.
68///
69/// # Introduction
70///
71/// The goal of this rule is to improve query performance by eliminating
72/// redundant work.
73///
74/// For example, given a plan that sorts all values where `a > 10`:
75///
76/// ```text
77///  Filter (a > 10)
78///    Sort (a, b)
79/// ```
80///
81/// A better plan is to filter the data *before* the Sort, which sorts fewer
82/// rows and therefore does less work overall:
83///
84/// ```text
85///  Sort (a, b)
86///    Filter (a > 10)  <-- Filter is moved before the sort
87/// ```
88///
89/// However it is not always possible to push filters down. For example, given a
90/// plan that finds the top 3 values and then keeps only those that are greater
91/// than 10, if the filter is pushed below the limit it would produce a
92/// different result.
93///
94/// ```text
95///  Filter (a > 10)   <-- cannot move this Filter before the limit
96///    Limit (fetch=3)
97///      Sort (a, b)
98/// ```
99///
100///
101/// More formally, a filter-commutative operation is an operation `op` that
102/// satisfies `filter(op(data)) = op(filter(data))`.
103///
104/// The filter-commutative property is plan and column-specific. A filter on `a`
105/// can be pushed through a `Aggregate(group_by = [a], agg=[sum(b)])`. However, a
106/// filter on `sum(b)` cannot be pushed through the same aggregate.
107///
108/// # Handling Conjunctions
109///
110/// It is possible to only push down **part** of a filter expression if it is
111/// connected with `AND`s (more formally if it is a "conjunction").
112///
113/// For example, given the following plan:
114///
115/// ```text
116/// Filter(a > 10 AND sum(b) < 5)
117///   Aggregate(group_by = [a], agg = [sum(b)])
118/// ```
119///
120/// The `a > 10` is commutative with the `Aggregate` but `sum(b) < 5` is not.
121/// Therefore it is possible to only push down part of the expression, resulting in:
122///
123/// ```text
124/// Filter(sum(b) < 5)
125///   Aggregate(group_by = [a], agg = [sum(b)])
126///     Filter(a > 10)
127/// ```
128///
129/// # Handling Column Aliases
130///
131/// This optimizer must sometimes handle rewriting filter expressions when they are
132/// pushed. For example, consider a projection that aliases `a+1` to `"b"`:
133///
134/// ```text
135/// Filter (b > 10)
136///     Projection: [a+1 AS "b"]  <-- changes the name of `a+1` to `b`
137/// ```
138///
139/// To push this filter below the `Projection`, all references to `b` must be
140/// rewritten to `a+1`:
141///
142/// ```text
143/// Projection: [a+1 AS "b"]
144///     Filter: (a+1 > 10)  <--- changed from b to a+1
145/// ```
146/// # Implementation Notes
147///
148/// This implementation performs a single pass through the plan, "pushing" down
149/// filters. When it passes through a filter, it stores that filter, and when it
150/// reaches a plan node that does not commute with that filter, it adds the
151/// filter to that place. When it passes through a projection, it re-writes the
152/// filter's expression taking into account that projection.
153#[derive(Default, Debug)]
154pub struct PushDownFilter {}
155
156/// For a given JOIN type, determine whether each input of the join is preserved
157/// for post-join (`WHERE` clause) filters.
158///
159/// It is only correct to push filters below a join for preserved inputs.
160///
161/// # Return Value
162/// A tuple of booleans - (left_preserved, right_preserved).
163///
164/// # "Preserved" input definition
165///
166/// We say a join side is preserved if the join returns all or a subset of the rows from
167/// the relevant side, such that each row of the output table directly maps to a row of
168/// the preserved input table. If a table is not preserved, it can provide extra null rows.
169/// That is, there may be rows in the output table that don't directly map to a row in the
170/// input table.
171///
172/// For example:
173///   - In an inner join, both sides are preserved, because each row of the output
174///     maps directly to a row from each side.
175///
176///   - In a left join, the left side is preserved (we can push predicates) but
177///     the right is not, because there may be rows in the output that don't
178///     directly map to a row in the right input (due to nulls filling where there
179///     is no match on the right).
180pub(crate) fn lr_is_preserved(join_type: JoinType) -> (bool, bool) {
181    match join_type {
182        JoinType::Inner => (true, true),
183        JoinType::Left => (true, false),
184        JoinType::Right => (false, true),
185        JoinType::Full => (false, false),
186        // No columns from the right side of the join can be referenced in output
187        // predicates for semi/anti joins. The right side must stay `false`:
188        // `PullUpCorrelatedExpr` uses it to refuse to pull a correlated filter
189        // out of a side that the join does not output.
190        JoinType::LeftSemi | JoinType::LeftAnti | JoinType::LeftMark => (true, false),
191        // No columns from the left side of the join can be referenced in output
192        // predicates for semi/anti joins. The left side must stay `false`:
193        // `PullUpCorrelatedExpr` uses it to refuse to pull a correlated filter
194        // out of a side that the join does not output.
195        JoinType::RightSemi | JoinType::RightAnti | JoinType::RightMark => (false, true),
196    }
197}
198
199/// See [`JoinType::on_lr_is_preserved`] for details.
200pub(crate) fn on_lr_is_preserved(join_type: JoinType) -> (bool, bool) {
201    join_type.on_lr_is_preserved()
202}
203
204/// Evaluates the columns referenced in the given expression to see if they refer
205/// only to the left or right columns
206#[derive(Debug)]
207struct ColumnChecker<'a> {
208    /// schema of left join input
209    left_schema: &'a DFSchema,
210    /// columns in left_schema, computed on demand
211    left_columns: Option<HashSet<ColumnReference<'a>>>,
212    /// schema of right join input
213    right_schema: &'a DFSchema,
214    /// columns in left_schema, computed on demand
215    right_columns: Option<HashSet<ColumnReference<'a>>>,
216}
217
218impl<'a> ColumnChecker<'a> {
219    fn new(left_schema: &'a DFSchema, right_schema: &'a DFSchema) -> Self {
220        Self {
221            left_schema,
222            left_columns: None,
223            right_schema,
224            right_columns: None,
225        }
226    }
227
228    /// Return true if the expression references only columns from the left side of the join
229    fn is_left_only(&mut self, predicate: &Expr) -> bool {
230        if self.left_columns.is_none() {
231            self.left_columns = Some(schema_columns(self.left_schema));
232        }
233        has_all_column_refs(predicate, self.left_columns.as_ref().unwrap())
234    }
235
236    /// Return true if the expression references only columns from the right side of the join
237    fn is_right_only(&mut self, predicate: &Expr) -> bool {
238        if self.right_columns.is_none() {
239            self.right_columns = Some(schema_columns(self.right_schema));
240        }
241        has_all_column_refs(predicate, self.right_columns.as_ref().unwrap())
242    }
243}
244
245/// Determine whether the predicate can evaluate as the join conditions
246fn can_evaluate_as_join_condition(predicate: &Expr) -> Result<bool> {
247    Ok(!predicate.exists(|expr| match expr {
248        Expr::Exists { .. }
249        | Expr::InSubquery(_)
250        | Expr::SetComparison(_)
251        | Expr::ScalarSubquery(_)
252        | Expr::OuterReferenceColumn(_, _)
253        | Expr::Unnest(_) => Ok(true),
254        Expr::Column(_)
255        | Expr::Literal(_, _)
256        | Expr::Placeholder(_)
257        | Expr::ScalarVariable(_, _)
258        | Expr::Alias(_)
259        | Expr::BinaryExpr(_)
260        | Expr::Like(_)
261        | Expr::SimilarTo(_)
262        | Expr::Not(_)
263        | Expr::IsNotNull(_)
264        | Expr::IsNull(_)
265        | Expr::IsTrue(_)
266        | Expr::IsFalse(_)
267        | Expr::IsUnknown(_)
268        | Expr::IsNotTrue(_)
269        | Expr::IsNotFalse(_)
270        | Expr::IsNotUnknown(_)
271        | Expr::Negative(_)
272        | Expr::Between(_)
273        | Expr::Case(_)
274        | Expr::Cast(_)
275        | Expr::TryCast(_)
276        | Expr::InList { .. }
277        | Expr::ScalarFunction(_)
278        | Expr::HigherOrderFunction(_)
279        | Expr::Lambda(_)
280        | Expr::LambdaVariable(_) => Ok(false),
281        // TODO: remove the next line after `Expr::Wildcard` is removed
282        #[expect(deprecated)]
283        Expr::AggregateFunction(_)
284        | Expr::WindowFunction(_)
285        | Expr::Wildcard { .. }
286        | Expr::GroupingSet(_) => internal_err!("Unsupported predicate type"),
287    })?)
288}
289
290/// examine OR clause to see if any useful clauses can be extracted and push down.
291/// extract at least one qual from each sub clauses of OR clause, then form the quals
292/// to new OR clause as predicate.
293///
294/// # Example
295/// ```text
296/// Filter: (a = c and a < 20) or (b = d and b > 10)
297///     join/crossjoin:
298///          TableScan: projection=[a, b]
299///          TableScan: projection=[c, d]
300/// ```
301///
302/// is optimized to
303///
304/// ```text
305/// Filter: (a = c and a < 20) or (b = d and b > 10)
306///     join/crossjoin:
307///          Filter: (a < 20) or (b > 10)
308///              TableScan: projection=[a, b]
309///          TableScan: projection=[c, d]
310/// ```
311///
312/// In general, predicates of this form:
313///
314/// ```sql
315/// (A AND B) OR (C AND D)
316/// ```
317///
318/// will be transformed to one of:
319///
320/// * `((A AND B) OR (C AND D)) AND (A OR C)`
321/// * `((A AND B) OR (C AND D)) AND ((A AND B) OR C)`
322/// * do nothing.
323fn extract_or_clauses_for_join<'a>(
324    filters: &'a [Expr],
325    schema_cols: &'a HashSet<ColumnReference>,
326) -> impl Iterator<Item = Expr> + 'a {
327    // new formed OR clauses and their column references
328    filters.iter().filter_map(move |expr| {
329        if let Expr::BinaryExpr(BinaryExpr {
330            left,
331            op: Operator::Or,
332            right,
333        }) = expr
334        {
335            let left_expr = extract_or_clause(left.as_ref(), schema_cols);
336            let right_expr = extract_or_clause(right.as_ref(), schema_cols);
337
338            // If nothing can be extracted from any sub clauses, do nothing for this OR clause.
339            if let (Some(left_expr), Some(right_expr)) = (left_expr, right_expr) {
340                return Some(or(left_expr, right_expr));
341            }
342        }
343        None
344    })
345}
346
347/// extract qual from OR sub-clause.
348///
349/// A qual is extracted if it only contains set of column references in schema_columns.
350///
351/// For AND clause, we extract from both sub-clauses, then make new AND clause by extracted
352/// clauses if both extracted; Otherwise, use the extracted clause from any sub-clauses or None.
353///
354/// For OR clause, we extract from both sub-clauses, then make new OR clause by extracted clauses if both extracted;
355/// Otherwise, return None.
356///
357/// For other clause, apply the rule above to extract clause.
358fn extract_or_clause(
359    expr: &Expr,
360    schema_columns: &HashSet<ColumnReference>,
361) -> Option<Expr> {
362    let mut predicate = None;
363
364    match expr {
365        Expr::BinaryExpr(BinaryExpr {
366            left: l_expr,
367            op: Operator::Or,
368            right: r_expr,
369        }) => {
370            let l_expr = extract_or_clause(l_expr, schema_columns);
371            let r_expr = extract_or_clause(r_expr, schema_columns);
372
373            if let (Some(l_expr), Some(r_expr)) = (l_expr, r_expr) {
374                predicate = Some(or(l_expr, r_expr));
375            }
376        }
377        Expr::BinaryExpr(BinaryExpr {
378            left: l_expr,
379            op: Operator::And,
380            right: r_expr,
381        }) => {
382            let l_expr = extract_or_clause(l_expr, schema_columns);
383            let r_expr = extract_or_clause(r_expr, schema_columns);
384
385            match (l_expr, r_expr) {
386                (Some(l_expr), Some(r_expr)) => {
387                    predicate = Some(and(l_expr, r_expr));
388                }
389                (Some(l_expr), None) => {
390                    predicate = Some(l_expr);
391                }
392                (None, Some(r_expr)) => {
393                    predicate = Some(r_expr);
394                }
395                (None, None) => {
396                    predicate = None;
397                }
398            }
399        }
400        _ => {
401            if has_all_column_refs(expr, schema_columns) {
402                predicate = Some(expr.clone());
403            }
404        }
405    }
406
407    predicate
408}
409
410/// push down join/cross-join
411fn push_down_all_join(
412    predicates: Vec<Expr>,
413    inferred_join_predicates: Vec<Expr>,
414    mut join: Join,
415    on_filter: Vec<Expr>,
416) -> Result<Transformed<LogicalPlan>> {
417    let is_inner_join = join.join_type == JoinType::Inner;
418    // Get pushable predicates from current optimizer state
419    let (left_preserved, mut right_preserved) = lr_is_preserved(join.join_type);
420    let (on_left_preserved, mut on_right_preserved) = on_lr_is_preserved(join.join_type);
421
422    // Null-aware joins (e.g. `NOT IN` with a nullable subquery) implement SQL
423    // three-valued logic: a NULL join key on the right/subquery side makes the
424    // predicate UNKNOWN and empties the result. Anything pushed into the right
425    // input runs before the join can observe those NULLs, so a null-rejecting
426    // predicate would drop them and silently produce wrong results.
427    // `infer_join_predicates` skips null-aware joins for the same reason.
428    //
429    // `on_right_preserved` is what actually matters here: it is what lets a
430    // right-only join filter — the shape `<constant> NOT IN (<subquery>)`
431    // produces — reach the subquery. `right_preserved` is already false for
432    // every join type that can carry `null_aware` today, so clearing it is
433    // defence in depth.
434    if join.null_aware {
435        right_preserved = false;
436        on_right_preserved = false;
437    }
438
439    // The predicates can be divided to three categories:
440    // 1) can push through join to its children(left or right)
441    // 2) can be converted to join conditions if the join type is Inner
442    // 3) should be kept as filter conditions
443    let left_schema = join.left.schema();
444    let right_schema = join.right.schema();
445
446    let left_schema_columns = schema_columns(left_schema.as_ref());
447    let right_schema_columns = schema_columns(right_schema.as_ref());
448
449    let mut left_push = vec![];
450    let mut right_push = vec![];
451    let mut keep_predicates = vec![];
452    let mut join_conditions = vec![];
453    let mut checker = ColumnChecker::new(left_schema, right_schema);
454    for predicate in predicates {
455        if left_preserved && checker.is_left_only(&predicate) {
456            left_push.push(predicate);
457        } else if right_preserved && checker.is_right_only(&predicate) {
458            right_push.push(predicate);
459        } else if is_inner_join && can_evaluate_as_join_condition(&predicate)? {
460            // Here we do not differ it is eq or non-eq predicate, ExtractEquijoinPredicate will extract the eq predicate
461            // and convert to the join on condition
462            join_conditions.push(predicate);
463        } else {
464            keep_predicates.push(predicate);
465        }
466    }
467
468    // Push predicates inferred from the join expression
469    for predicate in inferred_join_predicates {
470        if checker.is_left_only(&predicate) {
471            left_push.push(predicate);
472        } else if checker.is_right_only(&predicate) {
473            right_push.push(predicate);
474        }
475    }
476
477    let mut on_filter_join_conditions = vec![];
478    for on in on_filter {
479        if on_left_preserved && checker.is_left_only(&on) {
480            left_push.push(on)
481        } else if on_right_preserved && checker.is_right_only(&on) {
482            right_push.push(on)
483        } else {
484            on_filter_join_conditions.push(on)
485        }
486    }
487
488    // Extract from OR clause, generate new predicates for both side of join if possible.
489    // We only track the unpushable predicates above.
490    if left_preserved {
491        left_push.extend(extract_or_clauses_for_join(
492            &keep_predicates,
493            &left_schema_columns,
494        ));
495        left_push.extend(extract_or_clauses_for_join(
496            &join_conditions,
497            &left_schema_columns,
498        ));
499    }
500    if right_preserved {
501        right_push.extend(extract_or_clauses_for_join(
502            &keep_predicates,
503            &right_schema_columns,
504        ));
505        right_push.extend(extract_or_clauses_for_join(
506            &join_conditions,
507            &right_schema_columns,
508        ));
509    }
510
511    // For predicates from join filter, we should check with if a join side is preserved
512    // in term of join filtering.
513    if on_left_preserved {
514        left_push.extend(extract_or_clauses_for_join(
515            &on_filter_join_conditions,
516            &left_schema_columns,
517        ));
518    }
519    if on_right_preserved {
520        right_push.extend(extract_or_clauses_for_join(
521            &on_filter_join_conditions,
522            &right_schema_columns,
523        ));
524    }
525
526    // Add any new join conditions as the non join predicates
527    let join_conditions_empty = join_conditions.is_empty();
528    join_conditions.extend(on_filter_join_conditions);
529    join.filter = conjunction(join_conditions);
530
531    if join_conditions_empty && left_push.is_empty() && right_push.is_empty() {
532        // wrap the join on the filter whose predicates must be kept, if any
533        return Ok(Transformed::no(with_filters(
534            keep_predicates,
535            LogicalPlan::Join(join),
536        )));
537    }
538
539    if let Some(predicate) = conjunction(left_push) {
540        join.left = Arc::new(LogicalPlan::Filter(Filter::new(predicate, join.left)));
541    }
542
543    if let Some(predicate) = conjunction(right_push) {
544        join.right = Arc::new(LogicalPlan::Filter(Filter::new(predicate, join.right)));
545    }
546
547    // wrap the join on the filter whose predicates must be kept, if any
548    Ok(Transformed::yes(with_filters(
549        keep_predicates,
550        LogicalPlan::Join(join),
551    )))
552}
553
554fn push_down_join(
555    mut join: Join,
556    parent_predicate: Option<Expr>,
557) -> Result<Transformed<LogicalPlan>> {
558    // Split the parent predicate into individual conjunctive parts.
559    let predicates = parent_predicate.map_or_else(Vec::new, split_conjunction_owned);
560
561    // Extract conjunctions from the JOIN's ON filter, if present.
562    let on_filters = join
563        .filter
564        .take()
565        .map_or_else(Vec::new, split_conjunction_owned);
566
567    // Are there any new join predicates that can be inferred from the filter expressions?
568    let inferred_join_predicates = with_debug_timing("infer_join_predicates", || {
569        infer_join_predicates(&join, &predicates, &on_filters)
570    })?;
571
572    if log_enabled!(Level::Debug) {
573        debug!(
574            "push_down_filter: join_type={:?}, parent_predicates={}, on_filters={}, inferred_join_predicates={}",
575            join.join_type,
576            predicates.len(),
577            on_filters.len(),
578            inferred_join_predicates.len()
579        );
580    }
581
582    if on_filters.is_empty()
583        && predicates.is_empty()
584        && inferred_join_predicates.is_empty()
585    {
586        return Ok(Transformed::no(LogicalPlan::Join(join)));
587    }
588
589    push_down_all_join(predicates, inferred_join_predicates, join, on_filters)
590}
591
592/// Extracts any equi-join join predicates from the given filter expressions.
593///
594/// Parameters
595/// * `join` the join in question
596///
597/// * `predicates` the pushed down filter expression
598///
599/// * `on_filters` filters from the join ON clause that have not already been
600///   identified as join predicates
601fn infer_join_predicates(
602    join: &Join,
603    predicates: &[Expr],
604    on_filters: &[Expr],
605) -> Result<Vec<Expr>> {
606    // Null-aware joins (e.g. `NOT IN` with a nullable subquery) rely on SQL
607    // three-valued logic: a NULL join key on the right/subquery side makes the
608    // predicate UNKNOWN and empties the result, so those NULLs must reach the
609    // join. Inferring an equi-key predicate here would rewrite a left-side
610    // predicate onto the right side and, because the inferred predicate must be
611    // null-rejecting, drop the subquery's NULL rows and produce wrong results.
612    // Skip inference entirely for null-aware joins.
613    if join.null_aware {
614        return Ok(vec![]);
615    }
616
617    // Only allow both side key is column.
618    let join_col_keys = join
619        .on
620        .iter()
621        .filter_map(|(l, r)| {
622            let left_col = l.try_as_col()?;
623            let right_col = r.try_as_col()?;
624            Some((left_col, right_col))
625        })
626        .collect::<Vec<_>>();
627
628    let join_type = join.join_type;
629
630    let mut inferred_predicates = InferredPredicates::new(join_type);
631
632    infer_join_predicates_from_predicates(
633        &join_col_keys,
634        predicates,
635        &mut inferred_predicates,
636    )?;
637
638    infer_join_predicates_from_on_filters(
639        &join_col_keys,
640        join_type,
641        on_filters,
642        &mut inferred_predicates,
643    )?;
644
645    Ok(inferred_predicates.predicates)
646}
647
648/// Inferred predicates collector.
649/// When the JoinType is not Inner, we need to detect whether the inferred predicate can strictly
650/// filter out NULL, otherwise ignore it. e.g.
651/// ```text
652/// SELECT * FROM t1 LEFT JOIN t2 ON t1.c0 = t2.c0 WHERE t2.c0 IS NULL;
653/// ```
654/// We cannot infer the predicate `t1.c0 IS NULL`, otherwise the predicate will be pushed down to
655/// the left side, resulting in the wrong result.
656struct InferredPredicates {
657    predicates: Vec<Expr>,
658    is_inner_join: bool,
659}
660
661impl InferredPredicates {
662    fn new(join_type: JoinType) -> Self {
663        Self {
664            predicates: vec![],
665            is_inner_join: join_type == JoinType::Inner,
666        }
667    }
668
669    fn try_build_predicate(
670        &mut self,
671        predicate: Expr,
672        replace_map: &HashMap<&Column, &Column>,
673    ) -> Result<()> {
674        if self.is_inner_join
675            || matches!(
676                is_restrict_null_predicate(
677                    predicate.clone(),
678                    replace_map.keys().copied()
679                ),
680                Ok(true)
681            )
682        {
683            self.predicates.push(replace_col(predicate, replace_map)?);
684        }
685
686        Ok(())
687    }
688}
689
690/// Infer predicates from the pushed down predicates.
691///
692/// Parameters
693/// * `join_col_keys` column pairs from the join ON clause
694///
695/// * `predicates` the pushed down predicates
696///
697/// * `inferred_predicates` the inferred results
698fn infer_join_predicates_from_predicates(
699    join_col_keys: &[(&Column, &Column)],
700    predicates: &[Expr],
701    inferred_predicates: &mut InferredPredicates,
702) -> Result<()> {
703    infer_join_predicates_impl::<true, true>(
704        join_col_keys,
705        predicates,
706        inferred_predicates,
707    )
708}
709
710/// Infer predicates from the join filter.
711///
712/// Parameters
713/// * `join_col_keys` column pairs from the join ON clause
714///
715/// * `join_type` the JoinType of Join
716///
717/// * `on_filters` filters from the join ON clause that have not already been
718///   identified as join predicates
719///
720/// * `inferred_predicates` the inferred results
721fn infer_join_predicates_from_on_filters(
722    join_col_keys: &[(&Column, &Column)],
723    join_type: JoinType,
724    on_filters: &[Expr],
725    inferred_predicates: &mut InferredPredicates,
726) -> Result<()> {
727    match join_type {
728        JoinType::Full | JoinType::LeftAnti | JoinType::RightAnti => Ok(()),
729        JoinType::Inner => infer_join_predicates_impl::<true, true>(
730            join_col_keys,
731            on_filters,
732            inferred_predicates,
733        ),
734        JoinType::Left | JoinType::LeftSemi | JoinType::LeftMark => {
735            infer_join_predicates_impl::<true, false>(
736                join_col_keys,
737                on_filters,
738                inferred_predicates,
739            )
740        }
741        JoinType::Right | JoinType::RightSemi | JoinType::RightMark => {
742            infer_join_predicates_impl::<false, true>(
743                join_col_keys,
744                on_filters,
745                inferred_predicates,
746            )
747        }
748    }
749}
750
751/// Infer predicates from the given predicates.
752///
753/// Parameters
754/// * `join_col_keys` column pairs from the join ON clause
755///
756/// * `input_predicates` the given predicates. It can be the pushed down predicates,
757///   or it can be the filters of the Join
758///
759/// * `inferred_predicates` the inferred results
760///
761/// * `ENABLE_LEFT_TO_RIGHT` indicates that the right table related predicate can
762///   be inferred from the left table related predicate
763///
764/// * `ENABLE_RIGHT_TO_LEFT` indicates that the left table related predicate can
765///   be inferred from the right table related predicate
766fn infer_join_predicates_impl<
767    const ENABLE_LEFT_TO_RIGHT: bool,
768    const ENABLE_RIGHT_TO_LEFT: bool,
769>(
770    join_col_keys: &[(&Column, &Column)],
771    input_predicates: &[Expr],
772    inferred_predicates: &mut InferredPredicates,
773) -> Result<()> {
774    let mut join_cols_to_replace = HashMap::new();
775    for predicate in input_predicates {
776        join_cols_to_replace.clear();
777
778        for &col in &predicate.column_refs() {
779            for (l, r) in join_col_keys.iter() {
780                if ENABLE_LEFT_TO_RIGHT && col == *l {
781                    join_cols_to_replace.insert(col, *r);
782                    break;
783                }
784                if ENABLE_RIGHT_TO_LEFT && col == *r {
785                    join_cols_to_replace.insert(col, *l);
786                    break;
787                }
788            }
789        }
790        if join_cols_to_replace.is_empty() {
791            continue;
792        }
793
794        inferred_predicates
795            .try_build_predicate(predicate.clone(), &join_cols_to_replace)?;
796    }
797    Ok(())
798}
799
800/// Whether `expr` depends on any of the columns named in `names`.
801///
802/// This is the columns `Expr::column_refs` would collect plus the outer columns
803/// that any subquery inside `expr` correlates on. A subquery records those in
804/// `Subquery::outer_ref_columns` rather than as an `Expr::Column` in the
805/// predicate, and `Expr`'s own traversal does not descend into that field, so
806/// looking only at `column_refs` would report such a predicate as depending on
807/// nothing and let it be pushed past a node that asked to keep those columns.
808fn references_any_column(expr: &Expr, names: &HashSet<String>) -> bool {
809    let mut found = false;
810    expr.apply(|e| {
811        let outer_refs = match e {
812            Expr::Column(col) => {
813                if names.contains(&col.name) {
814                    found = true;
815                    return Ok(TreeNodeRecursion::Stop);
816                }
817                return Ok(TreeNodeRecursion::Continue);
818            }
819            Expr::Exists(exists) => &exists.subquery.outer_ref_columns,
820            Expr::InSubquery(in_subquery) => &in_subquery.subquery.outer_ref_columns,
821            Expr::ScalarSubquery(subquery) => &subquery.outer_ref_columns,
822            Expr::SetComparison(set_comparison) => {
823                &set_comparison.subquery.outer_ref_columns
824            }
825            _ => return Ok(TreeNodeRecursion::Continue),
826        };
827        if outer_refs.iter().any(|outer_ref| {
828            matches!(outer_ref, Expr::OuterReferenceColumn(_, c) if names.contains(&c.name))
829        }) {
830            found = true;
831            return Ok(TreeNodeRecursion::Stop);
832        }
833        Ok(TreeNodeRecursion::Continue)
834    })
835    .expect("traversal is infallible");
836    found
837}
838
839impl OptimizerRule for PushDownFilter {
840    fn name(&self) -> &str {
841        "push_down_filter"
842    }
843
844    fn apply_order(&self) -> Option<ApplyOrder> {
845        Some(ApplyOrder::TopDown)
846    }
847
848    fn rewrite(
849        &self,
850        plan: LogicalPlan,
851        config: &dyn OptimizerConfig,
852    ) -> Result<Transformed<LogicalPlan>> {
853        let _ = config;
854        if let LogicalPlan::Join(join) = plan {
855            return push_down_join(join, None);
856        }
857
858        let LogicalPlan::Filter(mut filter) = plan else {
859            return Ok(Transformed::no(plan));
860        };
861
862        let predicate = split_conjunction_owned(filter.predicate.clone());
863        let old_predicate_len = predicate.len();
864        let new_predicates =
865            with_debug_timing("simplify_predicates", || simplify_predicates(predicate))?;
866
867        if log_enabled!(Level::Debug) {
868            debug!(
869                "push_down_filter: simplify_predicates old_count={}, new_count={}",
870                old_predicate_len,
871                new_predicates.len()
872            );
873        }
874
875        // Place cheap predicates before expensive ones, so the `AND`
876        // evaluator's right-side short-circuit can skip evaluating expensive
877        // predicates on rows that have already been filtered out.
878        let (new_predicates, reorder_changed) = reorder_predicates(new_predicates);
879
880        // An OR branch can change without changing the number of conjuncts.
881        // Ignore permutations from grouping comparisons by column: the cost
882        // reordering above decides when to change predicate evaluation order.
883        let predicates_changed = if old_predicate_len != new_predicates.len() {
884            true
885        } else {
886            let old_predicates = split_conjunction(&filter.predicate);
887            new_predicates
888                .iter()
889                .zip(&old_predicates)
890                .any(|(new, old)| new != *old)
891                && {
892                    let new_predicates: IndexSet<_> = new_predicates.iter().collect();
893                    old_predicates
894                        .iter()
895                        .any(|old| !new_predicates.contains(old))
896                }
897        };
898        if predicates_changed || reorder_changed {
899            let Some(new_predicate) = conjunction(new_predicates) else {
900                // new_predicates is empty - remove the filter entirely
901                // Return the child plan without the filter
902                return Ok(Transformed::yes(Arc::unwrap_or_clone(filter.input)));
903            };
904            filter.predicate = new_predicate;
905        }
906
907        // A provider accepting Exact pushdown would absorb FALSE into its scan,
908        // hiding the contradiction from EliminateFilter and still invoking scan().
909        if matches!(
910            filter.predicate,
911            Expr::Literal(ScalarValue::Boolean(Some(false)), _)
912        ) {
913            return Ok(Transformed::yes(LogicalPlan::EmptyRelation(
914                EmptyRelation {
915                    produce_one_row: false,
916                    schema: Arc::clone(filter.input.schema()),
917                },
918            )));
919        }
920
921        // If the child has a fetch (limit) or skip (offset), pushing a filter
922        // below it would change semantics: the limit/offset should apply before
923        // the filter, not after.
924        if filter.input.fetch()?.is_some() || filter.input.skip()?.is_some() {
925            return Ok(Transformed::new(
926                LogicalPlan::Filter(filter),
927                predicates_changed || reorder_changed,
928                TreeNodeRecursion::Continue,
929            ));
930        }
931
932        let result = match Arc::unwrap_or_clone(filter.input) {
933            LogicalPlan::Filter(mut child_filter) => {
934                // Child filters first to preserve execution order.
935                // Use IndexSet to remove duplicates while preserving predicate order.
936                let new_predicates: IndexSet<Expr> =
937                    split_conjunction_owned(child_filter.predicate)
938                        .into_iter()
939                        .chain(split_conjunction_owned(filter.predicate))
940                        .collect();
941
942                let Some(new_predicate) = conjunction(new_predicates) else {
943                    return plan_err!("at least one expression exists");
944                };
945
946                child_filter.predicate = new_predicate;
947                self.rewrite(LogicalPlan::Filter(child_filter), config)
948            }
949            LogicalPlan::Repartition(mut repartition) => {
950                filter.input = repartition.input;
951                repartition.input = Arc::new(LogicalPlan::Filter(filter));
952                Ok(Transformed::yes(LogicalPlan::Repartition(repartition)))
953            }
954            LogicalPlan::Distinct(distinct) => {
955                let distinct = match distinct {
956                    Distinct::All(input) => {
957                        filter.input = input;
958                        Distinct::All(Arc::new(LogicalPlan::Filter(filter)))
959                    }
960                    Distinct::On(mut distinct) => {
961                        filter.input = distinct.input;
962                        distinct.input = Arc::new(LogicalPlan::Filter(filter));
963                        Distinct::On(distinct)
964                    }
965                };
966
967                Ok(Transformed::yes(LogicalPlan::Distinct(distinct)))
968            }
969            LogicalPlan::Sort(mut sort) => {
970                filter.input = sort.input;
971                sort.input = Arc::new(LogicalPlan::Filter(filter));
972                Ok(Transformed::yes(LogicalPlan::Sort(sort)))
973            }
974            LogicalPlan::SubqueryAlias(mut subquery_alias) => {
975                let mut replace_map =
976                    HashMap::with_capacity(subquery_alias.input.schema().fields().len());
977                for (i, (qualifier, field)) in
978                    subquery_alias.input.schema().iter().enumerate()
979                {
980                    let (sub_qualifier, sub_field) =
981                        subquery_alias.schema.qualified_field(i);
982                    replace_map.insert(
983                        qualified_name(sub_qualifier, sub_field.name()),
984                        Expr::Column(Column::new(qualifier.cloned(), field.name())),
985                    );
986                }
987
988                filter.predicate = replace_cols_by_name(filter.predicate, &replace_map)?;
989                filter.input = subquery_alias.input;
990                subquery_alias.input = Arc::new(LogicalPlan::Filter(filter));
991                Ok(Transformed::yes(LogicalPlan::SubqueryAlias(subquery_alias)))
992            }
993            LogicalPlan::Projection(projection) => {
994                let predicates = split_conjunction_owned(filter.predicate.clone());
995                let (mut result, keep_predicates) =
996                    rewrite_projection(predicates, projection)?;
997                if result.transformed {
998                    result.data = with_filters(keep_predicates, result.data)
999                } else {
1000                    filter.input = Arc::new(result.data);
1001                    result.data = LogicalPlan::Filter(filter)
1002                }
1003
1004                Ok(result)
1005            }
1006            LogicalPlan::Unnest(mut unnest) => {
1007                let predicates = split_conjunction_owned(filter.predicate.clone());
1008                let mut non_unnest_predicates = vec![];
1009                let mut unnest_predicates = vec![];
1010                let mut unnest_struct_columns = vec![];
1011
1012                for idx in &unnest.struct_type_columns {
1013                    let (sub_qualifier, field) =
1014                        unnest.input.schema().qualified_field(*idx);
1015                    if let DataType::Struct(children) = field.data_type() {
1016                        let field_name = field.name();
1017                        for child in children {
1018                            let child_name = child.name();
1019                            unnest_struct_columns.push(Column::new(
1020                                sub_qualifier.cloned(),
1021                                format!("{field_name}.{child_name}"),
1022                            ));
1023                        }
1024                    }
1025                }
1026
1027                let mut accum: HashSet<Column> = HashSet::new();
1028                for predicate in predicates {
1029                    // collect all the Expr::Column in predicate recursively
1030                    accum.clear();
1031                    expr_to_columns(&predicate, &mut accum)?;
1032
1033                    let contains_list_columns =
1034                        unnest.list_type_columns.iter().any(|(_, unnest_list)| {
1035                            accum.contains(&unnest_list.output_column)
1036                        });
1037                    let contains_struct_columns =
1038                        unnest_struct_columns.iter().any(|c| accum.contains(c));
1039
1040                    if contains_list_columns || contains_struct_columns {
1041                        unnest_predicates.push(predicate);
1042                    } else {
1043                        non_unnest_predicates.push(predicate);
1044                    }
1045                }
1046
1047                // Unnest predicates should not be pushed down.
1048                // If no non-unnest predicates exist, early return
1049                if non_unnest_predicates.is_empty() {
1050                    filter.input = Arc::new(LogicalPlan::Unnest(unnest));
1051                    return Ok(Transformed::new(
1052                        LogicalPlan::Filter(filter),
1053                        predicates_changed || reorder_changed,
1054                        TreeNodeRecursion::Continue,
1055                    ));
1056                }
1057
1058                // Push down non-unnest filter predicate
1059                // Unnest
1060                //   Unnest Input (Projection)
1061                // -> rewritten to
1062                // Unnest
1063                //   Filter
1064                //     Unnest Input (Projection)
1065
1066                // Safe to unwrap since non_unnest_predicates is not empty.
1067                filter.predicate = conjunction(non_unnest_predicates).unwrap();
1068                filter.input = unnest.input;
1069                // Directly assign new filter plan as the new unnest's input.
1070                // The new filter plan will go through another rewrite pass since the rule itself
1071                // is applied recursively to all the child from top to down
1072                unnest.input = Arc::new(LogicalPlan::Filter(filter));
1073                Ok(Transformed::yes(with_filters(
1074                    unnest_predicates,
1075                    LogicalPlan::Unnest(unnest),
1076                )))
1077            }
1078            LogicalPlan::Union(mut union) => {
1079                let mut inputs = Vec::with_capacity(union.inputs.len());
1080                let mut replace_map = HashMap::with_capacity(union.schema.fields().len());
1081                for input in union.inputs {
1082                    replace_map.clear();
1083                    for (i, (qualifier, field)) in input.schema().iter().enumerate() {
1084                        let (union_qualifier, union_field) =
1085                            union.schema.qualified_field(i);
1086                        replace_map.insert(
1087                            qualified_name(union_qualifier, union_field.name()),
1088                            Expr::Column(Column::new(qualifier.cloned(), field.name())),
1089                        );
1090                    }
1091
1092                    let push_predicate =
1093                        replace_cols_by_name(filter.predicate.clone(), &replace_map)?;
1094                    inputs.push(Arc::new(LogicalPlan::Filter(Filter::new(
1095                        push_predicate,
1096                        input,
1097                    ))))
1098                }
1099
1100                union.inputs = inputs;
1101                Ok(Transformed::yes(LogicalPlan::Union(union)))
1102            }
1103            LogicalPlan::Aggregate(mut agg) => {
1104                // We can push down Predicate which in groupby_expr.
1105                // Volatile group keys are excluded: below the aggregate, the
1106                // predicate would evaluate the key again and see a different
1107                // value than the one used for grouping.
1108                let non_volatile_group_exprs: Vec<Expr> = agg
1109                    .group_expr
1110                    .iter()
1111                    .filter(|expr| !expr.is_volatile())
1112                    .cloned()
1113                    .collect();
1114                let group_expr_columns = expr_columns(&non_volatile_group_exprs);
1115
1116                // As for plan Filter: Column(a+b) > 0 -- Agg: groupby:[Column(a)+Column(b)]
1117                // After push, we need to replace `a+b` with Column(a)+Column(b)
1118                // So we need create a replace_map, add {`a+b` --> Expr(Column(a)+Column(b))}
1119                //
1120                // Keyed by the output column, the same key `group_expr_columns`
1121                // is built from, so a predicate admitted below cannot miss its
1122                // replacement. See `replace_cols_by_column` for why the flat
1123                // name is not enough.
1124                let mut replace_map = HashMap::with_capacity(agg.group_expr.len());
1125                for expr in &agg.group_expr {
1126                    let (relation, name) = expr.qualified_name();
1127                    replace_map.insert(Column::new(relation, name), unalias(expr));
1128                }
1129
1130                let predicates = split_conjunction_owned(filter.predicate);
1131                let mut keep_predicates = vec![];
1132                let mut push_predicates = vec![];
1133                for expr in predicates {
1134                    let cols = expr.column_refs();
1135                    if cols.iter().all(|c| group_expr_columns.contains(c)) {
1136                        push_predicates.push(replace_cols_by_column(expr, &replace_map)?);
1137                    } else {
1138                        keep_predicates.push(expr);
1139                    }
1140                }
1141
1142                // If we have a filter to push, we push it down to the input of the aggregate
1143                let result = if let Some(predicate) = conjunction(push_predicates) {
1144                    filter.predicate = predicate;
1145                    filter.input = agg.input;
1146                    agg.input = Arc::new(LogicalPlan::Filter(filter));
1147                    Transformed::yes(LogicalPlan::Aggregate(agg))
1148                } else {
1149                    Transformed::no(LogicalPlan::Aggregate(agg))
1150                };
1151
1152                // If there are any remaining predicates we can't push, add them back as a filter
1153                result.map_data(|plan| Ok(with_filters(keep_predicates, plan)))
1154            }
1155            // Tries to push filters based on the partition key(s) of the window function(s) used.
1156            // Example:
1157            //   Before:
1158            //     Filter: (a > 1) and (b > 1) and (c > 1)
1159            //      Window: func() PARTITION BY [a] ...
1160            //   ---
1161            //   After:
1162            //     Filter: (b > 1) and (c > 1)
1163            //      Window: func() PARTITION BY [a] ...
1164            //        Filter: (a > 1)
1165            LogicalPlan::Window(mut window) => {
1166                // Retrieve the set of potential partition keys where we can push filters by.
1167                // Unlike aggregations, where there is only one statement per SELECT, there can be
1168                // multiple window functions, each with potentially different partition keys.
1169                // Therefore, we need to ensure that any potential partition key returned is used in
1170                // ALL window functions. Otherwise, filters cannot be pushed by through that column.
1171                // Arrow buffer memory accounting does not affect expression hashing.
1172                #[allow(clippy::allow_attributes, clippy::mutable_key_type)]
1173                fn extract_partition_keys(func: &WindowFunction) -> HashSet<&Expr> {
1174                    func.params.partition_by.iter().collect()
1175                }
1176
1177                // Arrow buffer memory accounting does not affect expression hashing.
1178                #[allow(clippy::allow_attributes, clippy::mutable_key_type)]
1179                let potential_partition_keys = window
1180                    .window_expr
1181                    .iter()
1182                    .map(|e| {
1183                        match e {
1184                            Expr::WindowFunction(window_func) => {
1185                                extract_partition_keys(window_func)
1186                            }
1187                            Expr::Alias(alias) => {
1188                                if let Expr::WindowFunction(window_func) =
1189                                    alias.expr.as_ref()
1190                                {
1191                                    extract_partition_keys(window_func)
1192                                } else {
1193                                    // window functions expressions are only Expr::WindowFunction
1194                                    unreachable!()
1195                                }
1196                            }
1197                            _ => {
1198                                // window functions expressions are only Expr::WindowFunction
1199                                unreachable!()
1200                            }
1201                        }
1202                    })
1203                    // performs the set intersection of the partition keys of all window functions,
1204                    // returning only the common ones
1205                    .reduce(|a, b| &a & &b)
1206                    .unwrap_or_default();
1207
1208                let predicates = split_conjunction_owned(filter.predicate);
1209                let mut keep_predicates = vec![];
1210                let mut push_predicates = vec![];
1211                for expr in predicates {
1212                    // A volatile predicate has to stay above the window: pushing it
1213                    // changes which rows the window function sees.
1214                    if !expr.is_volatile()
1215                        && reads_only_partition_keys(&expr, &potential_partition_keys)?
1216                    {
1217                        push_predicates.push(expr);
1218                    } else {
1219                        keep_predicates.push(expr);
1220                    }
1221                }
1222
1223                // Unlike with aggregations, there are no cases where we have to replace, e.g.,
1224                // `a+b` with Column(a+b). This is because partition expressions are not available
1225                // as standalone columns to the user: while an aggregation on `a+b` becomes
1226                // Column(a + b), in a window partition it stays `func() PARTITION BY [a + b] ...`.
1227                // That is why the predicate is matched against the key expressions themselves and
1228                // can be pushed unchanged.
1229
1230                // If we have a filter to push, we push it down to the input of the aggregate
1231                let result = if let Some(predicate) = conjunction(push_predicates) {
1232                    filter.predicate = predicate;
1233                    filter.input = window.input;
1234                    window.input = Arc::new(LogicalPlan::Filter(filter));
1235                    Transformed::yes(LogicalPlan::Window(window))
1236                } else {
1237                    Transformed::no(LogicalPlan::Window(window))
1238                };
1239
1240                // If there are any remaining predicates we can't push, add them back as a filter
1241                result.map_data(|plan| Ok(with_filters(keep_predicates, plan)))
1242            }
1243            LogicalPlan::Join(join) => push_down_join(join, Some(filter.predicate)),
1244            // Pushes deterministic left-only predicates below the ASOF join and
1245            // mirrors eligible equality-key predicates to the right input.
1246            // Example:
1247            //   Before:
1248            //     Filter: l.key = 42
1249            //       AsOfJoin: on=[l.key = r.key]
1250            //         Left
1251            //         Right
1252            //   ---
1253            //   After:
1254            //     AsOfJoin: on=[l.key = r.key]
1255            //       Filter: l.key = 42
1256            //         Left
1257            //       Filter: r.key = 42
1258            //         Right
1259            LogicalPlan::AsOfJoin(mut join) => {
1260                // ASOF emits exactly one output row per left row without
1261                // changing left values, so deterministic left-only predicates
1262                // can run before matching. Right or mixed predicates must stay
1263                // above the join because unmatched right fields are NULL-padded.
1264                let (push_predicates, keep_predicates): (Vec<_>, Vec<_>) =
1265                    split_conjunction_owned(filter.predicate)
1266                        .into_iter()
1267                        .partition(|predicate| {
1268                            !predicate.is_volatile()
1269                                && predicate.column_refs().iter().all(|column| {
1270                                    join.left.schema().is_column_from_schema(column)
1271                                })
1272                        });
1273
1274                // Every matching pair has equal key values, so a deterministic
1275                // predicate that refers only to left keys also holds for the
1276                // corresponding right keys. Expression-based join keys are not
1277                // mirrored because they cannot be replaced column-for-column.
1278                let key_replacements = join
1279                    .on
1280                    .iter()
1281                    .filter_map(|(left, right)| {
1282                        Some((left.try_as_col()?, right.try_as_col()?))
1283                    })
1284                    .collect::<HashMap<_, _>>();
1285                let mut right_predicates = Vec::new();
1286                for predicate in &push_predicates {
1287                    let columns = predicate.column_refs();
1288                    if !columns.is_empty()
1289                        && columns
1290                            .iter()
1291                            .all(|column| key_replacements.contains_key(column))
1292                    {
1293                        right_predicates
1294                            .push(replace_col(predicate.clone(), &key_replacements)?);
1295                    }
1296                }
1297                if let Some(predicate) = conjunction(right_predicates) {
1298                    join.right =
1299                        Arc::new(LogicalPlan::Filter(Filter::new(predicate, join.right)));
1300                }
1301
1302                let result = if let Some(predicate) = conjunction(push_predicates) {
1303                    filter.predicate = predicate;
1304                    filter.input = join.left;
1305                    join.left = Arc::new(LogicalPlan::Filter(filter));
1306                    Transformed::yes(LogicalPlan::AsOfJoin(join))
1307                } else {
1308                    Transformed::no(LogicalPlan::AsOfJoin(join))
1309                };
1310
1311                result.map_data(|plan| Ok(with_filters(keep_predicates, plan)))
1312            }
1313            LogicalPlan::TableScan(mut scan) => {
1314                let filter_predicates = split_conjunction(&filter.predicate);
1315                // Filters containing scalar subqueries cannot be pushed to
1316                // providers because the subquery result is not available
1317                // until execution time.
1318                let (subquery_filters, pushdown_candidates): (Vec<&Expr>, Vec<&Expr>) =
1319                    filter_predicates
1320                        .into_iter()
1321                        .partition(|pred| pred.contains_scalar_subquery());
1322
1323                let (volatile_filters, non_volatile_filters): (Vec<&Expr>, Vec<&Expr>) =
1324                    pushdown_candidates
1325                        .into_iter()
1326                        .partition(|pred| pred.is_volatile());
1327
1328                // Check which non-volatile filters are supported by source
1329                let supported_filters = scan
1330                    .source
1331                    .supports_filters_pushdown(non_volatile_filters.as_slice())?;
1332                assert_eq_or_internal_err!(
1333                    non_volatile_filters.len(),
1334                    supported_filters.len(),
1335                    "Vec returned length: {} from supports_filters_pushdown is not the same size as the filters passed, which length is: {}",
1336                    supported_filters.len(),
1337                    non_volatile_filters.len()
1338                );
1339
1340                if supported_filters
1341                    .iter()
1342                    .all(|res| res == &TableProviderFilterPushDown::Unsupported)
1343                {
1344                    filter.input = Arc::new(LogicalPlan::TableScan(scan));
1345                    return Ok(Transformed::new(
1346                        LogicalPlan::Filter(filter),
1347                        predicates_changed || reorder_changed,
1348                        TreeNodeRecursion::Continue,
1349                    ));
1350                }
1351
1352                // Compose scan filters from non-volatile filters of `Exact` or `Inexact` pushdown type
1353                let zip = non_volatile_filters.iter().zip(supported_filters.iter());
1354
1355                let new_scan_filters = zip
1356                    .clone()
1357                    .filter(|(_, res)| *res != &TableProviderFilterPushDown::Unsupported)
1358                    .map(|(&pred, _)| pred);
1359
1360                // Add new scan filters
1361                let new_scan_filters: Vec<Expr> = scan
1362                    .filters
1363                    .iter()
1364                    .chain(new_scan_filters)
1365                    .unique()
1366                    .cloned()
1367                    .collect();
1368
1369                if supported_filters
1370                    .iter()
1371                    .all(|res| res == &TableProviderFilterPushDown::Inexact)
1372                    && scan.filters == new_scan_filters
1373                {
1374                    filter.input = Arc::new(LogicalPlan::TableScan(scan));
1375                    return Ok(Transformed::new(
1376                        LogicalPlan::Filter(filter),
1377                        predicates_changed || reorder_changed,
1378                        TreeNodeRecursion::Continue,
1379                    ));
1380                } else {
1381                    scan.filters = new_scan_filters;
1382                }
1383
1384                // Compose predicates to be of `Unsupported` or `Inexact` pushdown type,
1385                // and also include volatile and subquery-containing filters
1386                let new_predicate: Vec<Expr> = zip
1387                    .filter(|(_, res)| *res != &TableProviderFilterPushDown::Exact)
1388                    .map(|(&pred, _)| pred)
1389                    .chain(volatile_filters)
1390                    .chain(subquery_filters)
1391                    .cloned()
1392                    .collect();
1393
1394                Ok(Transformed::yes(with_filters(
1395                    new_predicate,
1396                    LogicalPlan::TableScan(scan),
1397                )))
1398            }
1399            LogicalPlan::MaterializedCte(MaterializedCtePlan::Cte(mut cte)) => {
1400                // The output is the output of the continuation, so the filter
1401                // moves onto the continuation. The body is shared by every scan
1402                // of the CTE and is never filtered for one of them.
1403                cte.continuation = Arc::new(LogicalPlan::Filter(Filter::new(
1404                    filter.predicate,
1405                    cte.continuation,
1406                )));
1407                Ok(Transformed::yes(LogicalPlan::MaterializedCte(
1408                    MaterializedCtePlan::Cte(cte),
1409                )))
1410            }
1411            // A scan reads the shared body, so the filter stays above it.
1412            scan @ LogicalPlan::MaterializedCte(MaterializedCtePlan::Scan(_)) => {
1413                filter.input = Arc::new(scan);
1414                Ok(Transformed::no(LogicalPlan::Filter(filter)))
1415            }
1416            LogicalPlan::Extension(extension_plan) => {
1417                // This check prevents the Filter from being removed when the extension node has no children,
1418                // so we return the original Filter unchanged.
1419                if extension_plan.node.inputs().is_empty() {
1420                    filter.input = Arc::new(LogicalPlan::Extension(extension_plan));
1421                    return Ok(Transformed::new(
1422                        LogicalPlan::Filter(filter),
1423                        predicates_changed || reorder_changed,
1424                        TreeNodeRecursion::Continue,
1425                    ));
1426                }
1427                let prevent_cols =
1428                    extension_plan.node.prevent_predicate_push_down_columns();
1429
1430                // determine if we can push any predicates down past the extension node
1431
1432                // each element is true for push, false to keep
1433                let predicate_push_or_keep: Vec<bool> =
1434                    split_conjunction(&filter.predicate)
1435                        .iter()
1436                        .map(|expr| !references_any_column(expr, &prevent_cols))
1437                        .collect();
1438
1439                // all predicates are kept, no changes needed
1440                if predicate_push_or_keep.iter().all(|&x| !x) {
1441                    filter.input = Arc::new(LogicalPlan::Extension(extension_plan));
1442                    return Ok(Transformed::new(
1443                        LogicalPlan::Filter(filter),
1444                        predicates_changed || reorder_changed,
1445                        TreeNodeRecursion::Continue,
1446                    ));
1447                }
1448
1449                // going to push some predicates down, so split the predicates
1450                let mut keep_predicates = vec![];
1451                let mut push_predicates = vec![];
1452                for (push, expr) in predicate_push_or_keep
1453                    .into_iter()
1454                    .zip(split_conjunction_owned(filter.predicate))
1455                {
1456                    if !push {
1457                        keep_predicates.push(expr);
1458                    } else {
1459                        push_predicates.push(expr);
1460                    }
1461                }
1462
1463                // Unwrap - push_predicates is not empty, predicate_push_or_keep checked.
1464                let predicate = conjunction(push_predicates).unwrap();
1465                let new_children = extension_plan
1466                    .node
1467                    .inputs()
1468                    .into_iter()
1469                    .map(|child| {
1470                        LogicalPlan::Filter(Filter::new(
1471                            predicate.clone(),
1472                            Arc::new(child.clone()),
1473                        ))
1474                    })
1475                    .collect();
1476
1477                // extension with new inputs.
1478                let extension = LogicalPlan::Extension(extension_plan);
1479                let new_plan =
1480                    extension.with_new_exprs(extension.expressions(), new_children)?;
1481                Ok(Transformed::yes(with_filters(keep_predicates, new_plan)))
1482            }
1483            child => {
1484                filter.input = Arc::new(child);
1485                Ok(Transformed::no(LogicalPlan::Filter(filter)))
1486            }
1487        };
1488        result.map(|mut result| {
1489            result.transformed |= predicates_changed || reorder_changed;
1490            result
1491        })
1492    }
1493}
1494
1495/// Attempts to push `predicate` into a `FilterExec` below `projection
1496///
1497/// # Returns
1498/// (plan, remaining_predicate)
1499///
1500/// `plan` is a LogicalPlan for `projection` with possibly a new FilterExec below it.
1501/// `remaining_predicate` is any part of the predicate that could not be pushed down
1502///
1503/// # Args
1504/// - predicates: Split predicates like `[foo=5, bar=6]`
1505/// - projection: The target projection plan to push down the predicates
1506///
1507/// # Example
1508///
1509/// Pushing a predicate like `foo=5 AND bar=6` with an input plan like this:
1510///
1511/// ```text
1512/// Projection(foo, c+d as bar)
1513/// ```
1514///
1515/// Might result in returning `remaining_predicate` of `bar=6` and a plan like
1516///
1517/// ```text
1518/// Projection(foo, c+d as bar)
1519///  Filter(foo=5)
1520///   ...
1521/// ```
1522fn rewrite_projection(
1523    predicates: Vec<Expr>,
1524    mut projection: Projection,
1525) -> Result<(Transformed<LogicalPlan>, Vec<Expr>)> {
1526    // Precedence rule: a filter never moves below a pure extraction projection.
1527    //
1528    // `PushDownLeafProjections` moves such a projection below an adjacent
1529    // filter, so a filter that moved below it is put back above it in the same
1530    // optimizer pass. The two rules then undo each other on every pass until
1531    // the pass limit stops them, and the surviving plan is decided by rule
1532    // order alone. `PushDownFilter` yields here, because the extraction
1533    // projection is the node the source absorbs: leaving it at the bottom keeps
1534    // Parquet struct field pruning, and a filter kept one node higher still
1535    // reaches the scan through `TableScan::filters`, which the pass that
1536    // created the extraction projection has already set.
1537    //
1538    // See the module documentation of `extract_leaf_expressions` for the
1539    // full statement of the invariant.
1540    if is_pure_extraction_projection(&projection.expr) {
1541        return Ok((
1542            Transformed::no(LogicalPlan::Projection(projection)),
1543            predicates,
1544        ));
1545    }
1546
1547    // Partition projection expressions into non-pushable vs pushable.
1548    // Non-pushable expressions are volatile (must not be duplicated) or
1549    // MoveTowardsLeafNodes (cheap expressions like get_field where re-inlining
1550    // into a filter causes optimizer instability — ExtractLeafExpressions will
1551    // undo the push-down, creating an infinite loop that runs until the
1552    // iteration limit is hit).
1553    //
1554    // Keyed by the output column rather than its flat name, for the reason
1555    // given on `replace_cols_by_column`. `EliminateGroupByConstant` can leave a
1556    // projection that outputs both `t.a` and `CAST(t.a AS ...)` under that one
1557    // name.
1558    let (non_pushable_map, pushable_map): (HashMap<_, _>, HashMap<_, _>) = projection
1559        .schema
1560        .iter()
1561        .zip(projection.expr.iter())
1562        .map(|((qualifier, field), expr)| {
1563            (Column::new(qualifier.cloned(), field.name()), unalias(expr))
1564        })
1565        .partition(|(_, value)| {
1566            value.is_volatile()
1567                || value.placement() == ExpressionPlacement::MoveTowardsLeafNodes
1568        });
1569
1570    let mut push_predicates = vec![];
1571    let mut keep_predicates = vec![];
1572    for expr in predicates {
1573        if contains_column(&expr, &non_pushable_map) {
1574            keep_predicates.push(expr);
1575        } else {
1576            push_predicates.push(expr);
1577        }
1578    }
1579
1580    let projection = if let Some(expr) = conjunction(push_predicates) {
1581        // re-write all filters based on this projection
1582        // E.g. in `Filter: b\n  Projection: a > 1 as b`, we can swap them, but the filter must be "a > 1"
1583        projection.input = Arc::new(LogicalPlan::Filter(Filter::new(
1584            replace_cols_by_column(expr, &pushable_map)?,
1585            projection.input,
1586        )));
1587
1588        Transformed::yes(LogicalPlan::Projection(projection))
1589    } else {
1590        Transformed::no(LogicalPlan::Projection(projection))
1591    };
1592
1593    Ok((projection, keep_predicates))
1594}
1595
1596/// Creates a new LogicalPlan::Filter node.
1597///
1598/// Deprecated: use [`Filter::try_new`] directly.
1599#[deprecated(since = "55.0.0", note = "Use `Filter::try_new` instead")]
1600pub fn make_filter(predicate: Expr, input: Arc<LogicalPlan>) -> Result<LogicalPlan> {
1601    Filter::try_new(predicate, input).map(LogicalPlan::Filter)
1602}
1603
1604impl PushDownFilter {
1605    #[expect(missing_docs)]
1606    pub fn new() -> Self {
1607        Self {}
1608    }
1609}
1610
1611fn with_debug_timing<T, F>(label: &'static str, f: F) -> Result<T>
1612where
1613    F: FnOnce() -> Result<T>,
1614{
1615    if !log_enabled!(Level::Debug) {
1616        return f();
1617    }
1618    let start = Instant::now();
1619    let result = f();
1620    debug!(
1621        "push_down_filter_timing: section={label}, elapsed_us={}",
1622        start.elapsed().as_micros()
1623    );
1624    result
1625}
1626
1627/// replaces columns by its name on the projection.
1628pub fn replace_cols_by_name(
1629    e: Expr,
1630    replace_map: &HashMap<String, impl AsRef<Expr>>,
1631) -> Result<Expr> {
1632    e.transform_up(|expr| {
1633        if let Expr::Column(c) = &expr
1634            && let Some(new_expr) = replace_map.get(&c.flat_name())
1635        {
1636            Ok(Transformed::yes(new_expr.as_ref().clone()))
1637        } else {
1638            Ok(Transformed::no(expr))
1639        }
1640    })
1641    .data()
1642}
1643
1644/// Replaces column references by the expression the node below computes for
1645/// that column.
1646///
1647/// Keyed by [`Column`] rather than by its flat name, because a qualified column
1648/// `t.a` and an unqualified field named `t.a` are different columns that share a
1649/// flat name, and a node can output both.
1650fn replace_cols_by_column(
1651    e: Expr,
1652    replace_map: &HashMap<Column, impl AsRef<Expr>>,
1653) -> Result<Expr> {
1654    e.transform_up(|expr| {
1655        if let Expr::Column(c) = &expr
1656            && let Some(new_expr) = replace_map.get(c)
1657        {
1658            Ok(Transformed::yes(new_expr.as_ref().clone()))
1659        } else {
1660            Ok(Transformed::no(expr))
1661        }
1662    })
1663    .data()
1664}
1665
1666/// Unalias expression reference.
1667fn unalias(expr: &Expr) -> &Expr {
1668    if let Expr::Alias(alias) = expr {
1669        unalias(&alias.expr)
1670    } else {
1671        expr
1672    }
1673}
1674
1675/// check whether the expression uses the columns in `check_map`.
1676fn contains_column<T>(e: &Expr, check_map: &HashMap<Column, T>) -> bool {
1677    e.exists(|expr| Ok(matches!(expr, Expr::Column(c) if check_map.contains_key(c))))
1678        .unwrap()
1679}
1680
1681fn with_filters(predicates: Vec<Expr>, plan: LogicalPlan) -> LogicalPlan {
1682    if let Some(predicate) = conjunction(predicates) {
1683        LogicalPlan::Filter(Filter::new(predicate, Arc::new(plan)))
1684    } else {
1685        plan
1686    }
1687}
1688
1689/// Can `expr` be evaluated below a window with these `PARTITION BY` keys?
1690///
1691/// A predicate that reads only the partition keys is constant within each
1692/// partition, so filtering before the window drops whole partitions and leaves
1693/// the surviving rows' window values unchanged. "Reads only the keys" is checked
1694/// structurally: every column reference must sit inside a subtree that is equal
1695/// to one of the keys. Given `PARTITION BY a, b + c`:
1696///
1697/// * `a < 5`, `b + c = 4` and `(b + c) + 1 > 10` can be pushed down
1698/// * `d < 5` and `b < 5` cannot (`b` on its own is not a key), and neither can
1699///   `c + b = 4` (the match is structural, `c + b` is not `b + c`)
1700///
1701/// A predicate containing a subquery is never pushed: what the subquery reads is
1702/// not visible from the expression tree.
1703#[allow(clippy::allow_attributes, clippy::mutable_key_type)] // Arrow buffer memory accounting does not affect expression hashing.
1704fn reads_only_partition_keys(
1705    expr: &Expr,
1706    partition_keys: &HashSet<&Expr>,
1707) -> Result<bool> {
1708    let mut reads_something_else = false;
1709    expr.apply(|node| {
1710        Ok(if partition_keys.contains(&node) {
1711            // the whole key was matched, so whatever it reads is accounted for
1712            TreeNodeRecursion::Jump
1713        } else if reads_beyond_this_node(node) {
1714            reads_something_else = true;
1715            TreeNodeRecursion::Stop
1716        } else {
1717            TreeNodeRecursion::Continue
1718        })
1719    })?;
1720    Ok(!reads_something_else)
1721}
1722
1723/// Does this node read data that walking its children cannot account for? A
1724/// column reads itself; a subquery reads whatever its plan reads, which
1725/// `Expr::apply` does not visit.
1726fn reads_beyond_this_node(node: &Expr) -> bool {
1727    matches!(
1728        node,
1729        Expr::Column(_)
1730            | Expr::OuterReferenceColumn(..)
1731            | Expr::ScalarSubquery(_)
1732            | Expr::Exists(_)
1733            | Expr::InSubquery(_)
1734            | Expr::SetComparison(_)
1735    )
1736}
1737
1738fn expr_columns(exprs: &[Expr]) -> HashSet<Column> {
1739    exprs
1740        .iter()
1741        .map(|expr| {
1742            let (relation, name) = expr.qualified_name();
1743            Column::new(relation, name)
1744        })
1745        .collect()
1746}
1747
1748#[cfg(test)]
1749mod tests {
1750    use std::cmp::Ordering;
1751    use std::fmt::{Debug, Formatter};
1752
1753    use arrow::datatypes::{Field, Metadata, Schema, SchemaRef};
1754    use async_trait::async_trait;
1755
1756    use datafusion_common::{DFSchemaRef, DataFusionError, ScalarValue, Spans};
1757    use datafusion_expr::expr::{ScalarFunction, SetComparison, SetQuantifier};
1758    use datafusion_expr::logical_plan::table_scan;
1759    use datafusion_expr::{
1760        ColumnarValue, ExprFunctionExt, Extension, LogicalPlanBuilder,
1761        ScalarFunctionArgs, ScalarUDF, ScalarUDFImpl, Signature, Subquery, TableScan,
1762        TableSource, TableType, UserDefinedLogicalNodeCore, Volatility,
1763        WindowFunctionDefinition, col, exists, in_list, in_subquery, lit, out_ref_col,
1764    };
1765
1766    use crate::OptimizerContext;
1767    use crate::assert_optimized_plan_eq_snapshot;
1768    use crate::optimizer::Optimizer;
1769    use crate::simplify_expressions::SimplifyExpressions;
1770    use crate::test::udfs::leaf_udf_expr;
1771    use crate::test::*;
1772    use datafusion_expr::test::function_stub::{count, sum};
1773    use insta::assert_snapshot;
1774
1775    use super::*;
1776
1777    fn observe(_plan: &LogicalPlan, _rule: &dyn OptimizerRule) {}
1778
1779    macro_rules! assert_optimized_plan_equal {
1780        (
1781            $plan:expr,
1782            @ $expected:literal $(,)?
1783        ) => {{
1784            let optimizer_ctx = OptimizerContext::new().with_max_passes(1);
1785            let rules: Vec<Arc<dyn crate::OptimizerRule + Send + Sync>> = vec![Arc::new(PushDownFilter::new())];
1786            assert_optimized_plan_eq_snapshot!(
1787                optimizer_ctx,
1788                rules,
1789                $plan,
1790                @ $expected,
1791            )
1792        }};
1793    }
1794
1795    macro_rules! assert_optimized_plan_eq_with_rewrite_predicate {
1796        (
1797            $plan:expr,
1798            @ $expected:literal $(,)?
1799        ) => {{
1800            let optimizer = Optimizer::with_rules(vec![
1801                Arc::new(SimplifyExpressions::new()),
1802                Arc::new(PushDownFilter::new()),
1803            ]);
1804            let optimized_plan = optimizer.optimize($plan, &OptimizerContext::new(), observe)?;
1805            assert_snapshot!(optimized_plan, @ $expected);
1806            Ok::<(), DataFusionError>(())
1807        }};
1808    }
1809
1810    /// For testing that we don't return [Transformed::yes] when not necessary,
1811    /// as it triggers rebuilding parent plan nodes.
1812    macro_rules! assert_plan_not_transformed {
1813        ($plan:expr) => {{
1814            let transformed = PushDownFilter::new()
1815                .rewrite($plan, &OptimizerContext::new())
1816                .expect("failed to optimize plan");
1817            assert!(!transformed.transformed);
1818        }};
1819    }
1820
1821    #[test]
1822    fn filter_before_projection() -> Result<()> {
1823        let table_scan = test_table_scan()?;
1824        let plan = LogicalPlanBuilder::from(table_scan)
1825            .project(vec![col("a"), col("b")])?
1826            .filter(col("a").eq(lit(1i64)))?
1827            .build()?;
1828        // filter is before projection
1829        assert_optimized_plan_equal!(
1830            plan,
1831            @r"
1832        Projection: test.a, test.b
1833          TableScan: test, full_filters=[test.a = Int64(1)]
1834        "
1835        )
1836    }
1837
1838    #[test]
1839    fn filter_after_limit() -> Result<()> {
1840        let table_scan = test_table_scan()?;
1841        let plan = LogicalPlanBuilder::from(table_scan)
1842            .project(vec![col("a"), col("b")])?
1843            .limit(0, Some(10))?
1844            .filter(col("a").eq(lit(1i64)))?
1845            .build()?;
1846        // filter is before single projection
1847        assert_optimized_plan_equal!(
1848            plan,
1849            @r"
1850        Filter: test.a = Int64(1)
1851          Limit: skip=0, fetch=10
1852            Projection: test.a, test.b
1853              TableScan: test
1854        "
1855        )
1856    }
1857
1858    #[test]
1859    fn filter_no_columns() -> Result<()> {
1860        let table_scan = test_table_scan()?;
1861        let plan = LogicalPlanBuilder::from(table_scan)
1862            .filter(lit(0i64).eq(lit(1i64)))?
1863            .build()?;
1864        assert_optimized_plan_equal!(
1865            plan,
1866            @"TableScan: test, full_filters=[Int64(0) = Int64(1)]"
1867        )
1868    }
1869
1870    #[test]
1871    fn filter_jump_2_plans() -> Result<()> {
1872        let table_scan = test_table_scan()?;
1873        let plan = LogicalPlanBuilder::from(table_scan)
1874            .project(vec![col("a"), col("b"), col("c")])?
1875            .project(vec![col("c"), col("b")])?
1876            .filter(col("a").eq(lit(1i64)))?
1877            .build()?;
1878        // filter is before double projection
1879        assert_optimized_plan_equal!(
1880            plan,
1881            @r"
1882        Projection: test.c, test.b
1883          Projection: test.a, test.b, test.c
1884            TableScan: test, full_filters=[test.a = Int64(1)]
1885        "
1886        )
1887    }
1888
1889    #[test]
1890    fn filter_move_agg() -> Result<()> {
1891        let table_scan = test_table_scan()?;
1892        let plan = LogicalPlanBuilder::from(table_scan)
1893            .aggregate(vec![col("a")], vec![sum(col("b")).alias("total_salary")])?
1894            .filter(col("a").gt(lit(10i64)))?
1895            .build()?;
1896        // filter of key aggregation is commutative
1897        assert_optimized_plan_equal!(
1898            plan,
1899            @r"
1900        Aggregate: groupBy=[[test.a]], aggr=[[sum(test.b) AS total_salary]]
1901          TableScan: test, full_filters=[test.a > Int64(10)]
1902        "
1903        )
1904    }
1905
1906    /// verifies that filters with unusual column names are pushed down through aggregate operators
1907    #[test]
1908    fn filter_move_agg_special() -> Result<()> {
1909        let schema = Schema::new(vec![
1910            Field::new("$a", DataType::UInt32, false),
1911            Field::new("$b", DataType::UInt32, false),
1912            Field::new("$c", DataType::UInt32, false),
1913        ]);
1914        let table_scan = table_scan(Some("test"), &schema, None)?.build()?;
1915
1916        let plan = LogicalPlanBuilder::from(table_scan)
1917            .aggregate(vec![col("$a")], vec![sum(col("$b")).alias("total_salary")])?
1918            .filter(col("$a").gt(lit(10i64)))?
1919            .build()?;
1920        // filter of key aggregation is commutative
1921        assert_optimized_plan_equal!(
1922            plan,
1923            @r"
1924        Aggregate: groupBy=[[test.$a]], aggr=[[sum(test.$b) AS total_salary]]
1925          TableScan: test, full_filters=[test.$a > Int64(10)]
1926        "
1927        )
1928    }
1929
1930    #[test]
1931    fn filter_complex_group_by() -> Result<()> {
1932        let table_scan = test_table_scan()?;
1933        let plan = LogicalPlanBuilder::from(table_scan)
1934            .aggregate(vec![add(col("b"), col("a"))], vec![sum(col("a")), col("b")])?
1935            .filter(col("b").gt(lit(10i64)))?
1936            .build()?;
1937        assert_optimized_plan_equal!(
1938            plan,
1939            @r"
1940        Filter: test.b > Int64(10)
1941          Aggregate: groupBy=[[test.b + test.a]], aggr=[[sum(test.a), test.b]]
1942            TableScan: test
1943        "
1944        )
1945    }
1946
1947    #[test]
1948    fn push_agg_need_replace_expr() -> Result<()> {
1949        let plan = LogicalPlanBuilder::from(test_table_scan()?)
1950            .aggregate(vec![add(col("b"), col("a"))], vec![sum(col("a")), col("b")])?
1951            .filter(col("test.b + test.a").gt(lit(10i64)))?
1952            .build()?;
1953        assert_optimized_plan_equal!(
1954            plan,
1955            @r"
1956        Aggregate: groupBy=[[test.b + test.a]], aggr=[[sum(test.a), test.b]]
1957          TableScan: test, full_filters=[test.b + test.a > Int64(10)]
1958        "
1959        )
1960    }
1961
1962    #[test]
1963    fn filter_keep_agg() -> Result<()> {
1964        let table_scan = test_table_scan()?;
1965        let plan = LogicalPlanBuilder::from(table_scan)
1966            .aggregate(vec![col("a")], vec![sum(col("b")).alias("b")])?
1967            .filter(col("b").gt(lit(10i64)))?
1968            .build()?;
1969        assert_plan_not_transformed!(plan.clone());
1970
1971        // filter of aggregate is after aggregation since they are non-commutative
1972        assert_optimized_plan_equal!(
1973            plan,
1974            @r"
1975        Filter: b > Int64(10)
1976          Aggregate: groupBy=[[test.a]], aggr=[[sum(test.b) AS b]]
1977            TableScan: test
1978        "
1979        )
1980    }
1981
1982    /// verifies that when partitioning by 'a' and 'b', and filtering by 'b', 'b' is pushed
1983    #[test]
1984    fn filter_move_window() -> Result<()> {
1985        let table_scan = test_table_scan()?;
1986
1987        let window = Expr::from(WindowFunction::new(
1988            WindowFunctionDefinition::WindowUDF(
1989                datafusion_functions_window::rank::rank_udwf(),
1990            ),
1991            vec![],
1992        ))
1993        .partition_by(vec![col("a"), col("b")])
1994        .order_by(vec![col("c").sort(true, true)])
1995        .build()
1996        .unwrap();
1997
1998        let plan = LogicalPlanBuilder::from(table_scan)
1999            .window(vec![window])?
2000            .filter(col("b").gt(lit(10i64)))?
2001            .build()?;
2002
2003        assert_optimized_plan_equal!(
2004            plan,
2005            @r"
2006        WindowAggr: windowExpr=[[rank() PARTITION BY [test.a, test.b] ORDER BY [test.c ASC NULLS FIRST] ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW]]
2007          TableScan: test, full_filters=[test.b > Int64(10)]
2008        "
2009        )
2010    }
2011
2012    /// verifies that filters with unusual identifier names are pushed down through window functions
2013    #[test]
2014    fn filter_window_special_identifier() -> Result<()> {
2015        let schema = Schema::new(vec![
2016            Field::new("$a", DataType::UInt32, false),
2017            Field::new("$b", DataType::UInt32, false),
2018            Field::new("$c", DataType::UInt32, false),
2019        ]);
2020        let table_scan = table_scan(Some("test"), &schema, None)?.build()?;
2021
2022        let window = Expr::from(WindowFunction::new(
2023            WindowFunctionDefinition::WindowUDF(
2024                datafusion_functions_window::rank::rank_udwf(),
2025            ),
2026            vec![],
2027        ))
2028        .partition_by(vec![col("$a"), col("$b")])
2029        .order_by(vec![col("$c").sort(true, true)])
2030        .build()
2031        .unwrap();
2032
2033        let plan = LogicalPlanBuilder::from(table_scan)
2034            .window(vec![window])?
2035            .filter(col("$b").gt(lit(10i64)))?
2036            .build()?;
2037
2038        assert_optimized_plan_equal!(
2039            plan,
2040            @r"
2041        WindowAggr: windowExpr=[[rank() PARTITION BY [test.$a, test.$b] ORDER BY [test.$c ASC NULLS FIRST] ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW]]
2042          TableScan: test, full_filters=[test.$b > Int64(10)]
2043        "
2044        )
2045    }
2046
2047    /// verifies that when partitioning by 'a' and 'b', and filtering by 'a' and 'b', both 'a' and
2048    /// 'b' are pushed
2049    #[test]
2050    fn filter_move_complex_window() -> Result<()> {
2051        let table_scan = test_table_scan()?;
2052
2053        let window = Expr::from(WindowFunction::new(
2054            WindowFunctionDefinition::WindowUDF(
2055                datafusion_functions_window::rank::rank_udwf(),
2056            ),
2057            vec![],
2058        ))
2059        .partition_by(vec![col("a"), col("b")])
2060        .order_by(vec![col("c").sort(true, true)])
2061        .build()
2062        .unwrap();
2063
2064        let plan = LogicalPlanBuilder::from(table_scan)
2065            .window(vec![window])?
2066            .filter(and(col("a").gt(lit(10i64)), col("b").eq(lit(1i64))))?
2067            .build()?;
2068
2069        assert_optimized_plan_equal!(
2070            plan,
2071            @r"
2072        WindowAggr: windowExpr=[[rank() PARTITION BY [test.a, test.b] ORDER BY [test.c ASC NULLS FIRST] ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW]]
2073          TableScan: test, full_filters=[test.a > Int64(10), test.b = Int64(1)]
2074        "
2075        )
2076    }
2077
2078    /// verifies that when partitioning by 'a' and filtering by 'a' and 'b', only 'a' is pushed
2079    #[test]
2080    fn filter_move_partial_window() -> Result<()> {
2081        let table_scan = test_table_scan()?;
2082
2083        let window = Expr::from(WindowFunction::new(
2084            WindowFunctionDefinition::WindowUDF(
2085                datafusion_functions_window::rank::rank_udwf(),
2086            ),
2087            vec![],
2088        ))
2089        .partition_by(vec![col("a")])
2090        .order_by(vec![col("c").sort(true, true)])
2091        .build()
2092        .unwrap();
2093
2094        let plan = LogicalPlanBuilder::from(table_scan)
2095            .window(vec![window])?
2096            .filter(and(col("a").gt(lit(10i64)), col("b").eq(lit(1i64))))?
2097            .build()?;
2098
2099        assert_optimized_plan_equal!(
2100            plan,
2101            @r"
2102        Filter: test.b = Int64(1)
2103          WindowAggr: windowExpr=[[rank() PARTITION BY [test.a] ORDER BY [test.c ASC NULLS FIRST] ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW]]
2104            TableScan: test, full_filters=[test.a > Int64(10)]
2105        "
2106        )
2107    }
2108
2109    /// verifies that a filter on an expression partition key is pushed; the
2110    /// remaining shapes (mixed keys, operand order, subqueries, volatile
2111    /// predicates, several windows) are covered in
2112    /// `push_down_filter_regression.slt`
2113    #[test]
2114    fn filter_expression_move_window() -> Result<()> {
2115        let table_scan = test_table_scan()?;
2116
2117        let window = Expr::from(WindowFunction::new(
2118            WindowFunctionDefinition::WindowUDF(
2119                datafusion_functions_window::rank::rank_udwf(),
2120            ),
2121            vec![],
2122        ))
2123        .partition_by(vec![add(col("a"), col("b"))]) // PARTITION BY a + b
2124        .order_by(vec![col("c").sort(true, true)])
2125        .build()
2126        .unwrap();
2127
2128        let plan = LogicalPlanBuilder::from(table_scan)
2129            .window(vec![window])?
2130            .filter(add(col("a"), col("b")).gt(lit(10i64)))? // a + b > 10
2131            .build()?;
2132
2133        assert_optimized_plan_equal!(
2134            plan,
2135            @r"
2136        WindowAggr: windowExpr=[[rank() PARTITION BY [test.a + test.b] ORDER BY [test.c ASC NULLS FIRST] ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW]]
2137          TableScan: test, full_filters=[test.a + test.b > Int64(10)]
2138        "
2139        )
2140    }
2141
2142    /// verifies that when we use multiple window functions with a common partition key, the filter
2143    /// on that key is pushed
2144    #[test]
2145    fn filter_multiple_windows_common_partitions() -> Result<()> {
2146        let table_scan = test_table_scan()?;
2147
2148        let window1 = Expr::from(WindowFunction::new(
2149            WindowFunctionDefinition::WindowUDF(
2150                datafusion_functions_window::rank::rank_udwf(),
2151            ),
2152            vec![],
2153        ))
2154        .partition_by(vec![col("a")])
2155        .order_by(vec![col("c").sort(true, true)])
2156        .build()
2157        .unwrap();
2158
2159        let window2 = Expr::from(WindowFunction::new(
2160            WindowFunctionDefinition::WindowUDF(
2161                datafusion_functions_window::rank::rank_udwf(),
2162            ),
2163            vec![],
2164        ))
2165        .partition_by(vec![col("b"), col("a")])
2166        .order_by(vec![col("c").sort(true, true)])
2167        .build()
2168        .unwrap();
2169
2170        let plan = LogicalPlanBuilder::from(table_scan)
2171            .window(vec![window1, window2])?
2172            .filter(col("a").gt(lit(10i64)))? // a appears in both window functions
2173            .build()?;
2174
2175        assert_optimized_plan_equal!(
2176            plan,
2177            @r"
2178        WindowAggr: windowExpr=[[rank() PARTITION BY [test.a] ORDER BY [test.c ASC NULLS FIRST] ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW, rank() PARTITION BY [test.b, test.a] ORDER BY [test.c ASC NULLS FIRST] ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW]]
2179          TableScan: test, full_filters=[test.a > Int64(10)]
2180        "
2181        )
2182    }
2183
2184    /// verifies that when we use multiple window functions with different partitions keys, the
2185    /// filter cannot be pushed
2186    #[test]
2187    fn filter_multiple_windows_disjoint_partitions() -> Result<()> {
2188        let table_scan = test_table_scan()?;
2189
2190        let window1 = Expr::from(WindowFunction::new(
2191            WindowFunctionDefinition::WindowUDF(
2192                datafusion_functions_window::rank::rank_udwf(),
2193            ),
2194            vec![],
2195        ))
2196        .partition_by(vec![col("a")])
2197        .order_by(vec![col("c").sort(true, true)])
2198        .build()
2199        .unwrap();
2200
2201        let window2 = Expr::from(WindowFunction::new(
2202            WindowFunctionDefinition::WindowUDF(
2203                datafusion_functions_window::rank::rank_udwf(),
2204            ),
2205            vec![],
2206        ))
2207        .partition_by(vec![col("b"), col("a")])
2208        .order_by(vec![col("c").sort(true, true)])
2209        .build()
2210        .unwrap();
2211
2212        let plan = LogicalPlanBuilder::from(table_scan)
2213            .window(vec![window1, window2])?
2214            .filter(col("b").gt(lit(10i64)))? // b only appears in one window function
2215            .build()?;
2216
2217        assert_optimized_plan_equal!(
2218            plan,
2219            @r"
2220        Filter: test.b > Int64(10)
2221          WindowAggr: windowExpr=[[rank() PARTITION BY [test.a] ORDER BY [test.c ASC NULLS FIRST] ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW, rank() PARTITION BY [test.b, test.a] ORDER BY [test.c ASC NULLS FIRST] ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW]]
2222            TableScan: test
2223        "
2224        )
2225    }
2226
2227    /// verifies that a filter is pushed to before a projection, the filter expression is correctly re-written
2228    #[test]
2229    fn alias() -> Result<()> {
2230        let table_scan = test_table_scan()?;
2231        let plan = LogicalPlanBuilder::from(table_scan)
2232            .project(vec![col("a").alias("b"), col("c")])?
2233            .filter(col("b").eq(lit(1i64)))?
2234            .build()?;
2235        // filter is before projection
2236        assert_optimized_plan_equal!(
2237            plan,
2238            @r"
2239        Projection: test.a AS b, test.c
2240          TableScan: test, full_filters=[test.a = Int64(1)]
2241        "
2242        )
2243    }
2244
2245    fn add(left: Expr, right: Expr) -> Expr {
2246        Expr::BinaryExpr(BinaryExpr::new(
2247            Box::new(left),
2248            Operator::Plus,
2249            Box::new(right),
2250        ))
2251    }
2252
2253    fn multiply(left: Expr, right: Expr) -> Expr {
2254        Expr::BinaryExpr(BinaryExpr::new(
2255            Box::new(left),
2256            Operator::Multiply,
2257            Box::new(right),
2258        ))
2259    }
2260
2261    /// verifies that a filter is pushed to before a projection with a complex expression, the filter expression is correctly re-written
2262    #[test]
2263    fn complex_expression() -> Result<()> {
2264        let table_scan = test_table_scan()?;
2265        let plan = LogicalPlanBuilder::from(table_scan)
2266            .project(vec![
2267                add(multiply(col("a"), lit(2)), col("c")).alias("b"),
2268                col("c"),
2269            ])?
2270            .filter(col("b").eq(lit(1i64)))?
2271            .build()?;
2272
2273        // not part of the test, just good to know:
2274        assert_snapshot!(plan,
2275        @r"
2276        Filter: b = Int64(1)
2277          Projection: test.a * Int32(2) + test.c AS b, test.c
2278            TableScan: test
2279        ",
2280        );
2281        // filter is before projection
2282        assert_optimized_plan_equal!(
2283            plan,
2284            @r"
2285        Projection: test.a * Int32(2) + test.c AS b, test.c
2286          TableScan: test, full_filters=[test.a * Int32(2) + test.c = Int64(1)]
2287        "
2288        )
2289    }
2290
2291    /// verifies that when a filter is pushed to after 2 projections, the filter expression is correctly re-written
2292    #[test]
2293    fn complex_plan() -> Result<()> {
2294        let table_scan = test_table_scan()?;
2295        let plan = LogicalPlanBuilder::from(table_scan)
2296            .project(vec![
2297                add(multiply(col("a"), lit(2)), col("c")).alias("b"),
2298                col("c"),
2299            ])?
2300            // second projection where we rename columns, just to make it difficult
2301            .project(vec![multiply(col("b"), lit(3)).alias("a"), col("c")])?
2302            .filter(col("a").eq(lit(1i64)))?
2303            .build()?;
2304
2305        // not part of the test, just good to know:
2306        assert_snapshot!(plan,
2307        @r"
2308        Filter: a = Int64(1)
2309          Projection: b * Int32(3) AS a, test.c
2310            Projection: test.a * Int32(2) + test.c AS b, test.c
2311              TableScan: test
2312        ",
2313        );
2314        // filter is before the projections
2315        assert_optimized_plan_equal!(
2316            plan,
2317            @r"
2318        Projection: b * Int32(3) AS a, test.c
2319          Projection: test.a * Int32(2) + test.c AS b, test.c
2320            TableScan: test, full_filters=[(test.a * Int32(2) + test.c) * Int32(3) = Int64(1)]
2321        "
2322        )
2323    }
2324
2325    #[derive(Debug, PartialEq, Eq, Hash)]
2326    struct NoopPlan {
2327        input: Vec<LogicalPlan>,
2328        schema: DFSchemaRef,
2329    }
2330
2331    // Manual implementation needed because of `schema` field. Comparison excludes this field.
2332    impl PartialOrd for NoopPlan {
2333        fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
2334            self.input
2335                .partial_cmp(&other.input)
2336                // TODO (https://github.com/apache/datafusion/issues/17477) avoid recomparing all fields
2337                .filter(|cmp| *cmp != Ordering::Equal || self == other)
2338        }
2339    }
2340
2341    impl UserDefinedLogicalNodeCore for NoopPlan {
2342        fn name(&self) -> &str {
2343            "NoopPlan"
2344        }
2345
2346        fn inputs(&self) -> Vec<&LogicalPlan> {
2347            self.input.iter().collect()
2348        }
2349
2350        fn schema(&self) -> &DFSchemaRef {
2351            &self.schema
2352        }
2353
2354        fn expressions(&self) -> Vec<Expr> {
2355            self.input
2356                .iter()
2357                .flat_map(|child| child.expressions())
2358                .collect()
2359        }
2360
2361        fn prevent_predicate_push_down_columns(&self) -> HashSet<String> {
2362            HashSet::from_iter(vec!["c".to_string()])
2363        }
2364
2365        fn fmt_for_explain(&self, f: &mut Formatter) -> std::fmt::Result {
2366            write!(f, "NoopPlan")
2367        }
2368
2369        fn with_exprs_and_inputs(
2370            &self,
2371            _exprs: Vec<Expr>,
2372            inputs: Vec<LogicalPlan>,
2373        ) -> Result<Self> {
2374            Ok(Self {
2375                input: inputs,
2376                schema: Arc::clone(&self.schema),
2377            })
2378        }
2379
2380        fn supports_limit_pushdown(&self) -> bool {
2381            false // Disallow limit push-down by default
2382        }
2383    }
2384
2385    #[test]
2386    fn user_defined_plan_outer_referenced_column() -> Result<()> {
2387        let table_scan = test_table_scan()?;
2388
2389        // A subquery correlated on `test.c` — the column `NoopPlan` refuses to
2390        // have predicates pushed past. The correlation is carried by the
2391        // subquery's `outer_ref_columns`, not by an `Expr::Column` in the
2392        // predicate itself.
2393        let subquery = LogicalPlanBuilder::from(test_table_scan_with_name("sq")?)
2394            .filter(out_ref_col(DataType::UInt32, "test.c").eq(col("sq.a")))?
2395            .project(vec![col("sq.a")])?
2396            .build()?;
2397
2398        let custom_plan = LogicalPlan::Extension(Extension {
2399            node: Arc::new(NoopPlan {
2400                input: vec![table_scan.clone()],
2401                schema: Arc::clone(table_scan.schema()),
2402            }),
2403        });
2404        let plan = LogicalPlanBuilder::from(custom_plan)
2405            .filter(exists(Arc::new(subquery)))?
2406            .build()?;
2407
2408        // The predicate depends on `test.c`, so it must stay above NoopPlan.
2409        assert_optimized_plan_equal!(
2410            plan,
2411            @r"
2412        Filter: EXISTS (<subquery>)
2413          Subquery:
2414            Projection: sq.a
2415              TableScan: sq, full_filters=[outer_ref(test.c) = sq.a]
2416          NoopPlan
2417            TableScan: test
2418        "
2419        )
2420    }
2421
2422    #[test]
2423    fn user_defined_plan_outer_referenced_column_set_comparison() -> Result<()> {
2424        let table_scan = test_table_scan()?;
2425
2426        // `test.a > ANY (SELECT sq.a FROM sq WHERE test.c = sq.a)`: the
2427        // comparison expression names only `test.a`, so the dependency on
2428        // `test.c` exists solely in the subquery's `outer_ref_columns`.
2429        let subquery = LogicalPlanBuilder::from(test_table_scan_with_name("sq")?)
2430            .filter(out_ref_col(DataType::UInt32, "test.c").eq(col("sq.a")))?
2431            .project(vec![col("sq.a")])?
2432            .build()?;
2433        let outer_ref_columns = subquery.all_out_ref_exprs();
2434        let set_comparison = Expr::SetComparison(SetComparison::new(
2435            Box::new(col("test.a")),
2436            Subquery {
2437                subquery: Arc::new(subquery),
2438                outer_ref_columns,
2439                spans: Spans::new(),
2440            },
2441            Operator::Gt,
2442            SetQuantifier::Any,
2443        ));
2444
2445        let custom_plan = LogicalPlan::Extension(Extension {
2446            node: Arc::new(NoopPlan {
2447                input: vec![table_scan.clone()],
2448                schema: Arc::clone(table_scan.schema()),
2449            }),
2450        });
2451        let plan = LogicalPlanBuilder::from(custom_plan)
2452            .filter(set_comparison)?
2453            .build()?;
2454
2455        // The predicate depends on `test.c`, so it must stay above NoopPlan.
2456        assert_optimized_plan_equal!(
2457            plan,
2458            @r"
2459        Filter: test.a > ANY (<subquery>)
2460          Subquery:
2461            Projection: sq.a
2462              TableScan: sq, full_filters=[outer_ref(test.c) = sq.a]
2463          NoopPlan
2464            TableScan: test
2465        "
2466        )
2467    }
2468
2469    #[test]
2470    fn user_defined_plan() -> Result<()> {
2471        let table_scan = test_table_scan()?;
2472
2473        let custom_plan = LogicalPlan::Extension(Extension {
2474            node: Arc::new(NoopPlan {
2475                input: vec![table_scan.clone()],
2476                schema: Arc::clone(table_scan.schema()),
2477            }),
2478        });
2479        let plan = LogicalPlanBuilder::from(custom_plan)
2480            .filter(col("a").eq(lit(1i64)))?
2481            .build()?;
2482
2483        // Push filter below NoopPlan
2484        assert_optimized_plan_equal!(
2485            plan,
2486            @r"
2487        NoopPlan
2488          TableScan: test, full_filters=[test.a = Int64(1)]
2489        "
2490        )?;
2491
2492        let custom_plan = LogicalPlan::Extension(Extension {
2493            node: Arc::new(NoopPlan {
2494                input: vec![table_scan.clone()],
2495                schema: Arc::clone(table_scan.schema()),
2496            }),
2497        });
2498        let plan = LogicalPlanBuilder::from(custom_plan)
2499            .filter(col("a").eq(lit(1i64)).and(col("c").eq(lit(2i64))))?
2500            .build()?;
2501
2502        // Push only predicate on `a` below NoopPlan
2503        assert_optimized_plan_equal!(
2504            plan,
2505            @r"
2506        Filter: test.c = Int64(2)
2507          NoopPlan
2508            TableScan: test, full_filters=[test.a = Int64(1)]
2509        "
2510        )?;
2511
2512        let custom_plan = LogicalPlan::Extension(Extension {
2513            node: Arc::new(NoopPlan {
2514                input: vec![table_scan.clone(), table_scan.clone()],
2515                schema: Arc::clone(table_scan.schema()),
2516            }),
2517        });
2518        let plan = LogicalPlanBuilder::from(custom_plan)
2519            .filter(col("a").eq(lit(1i64)))?
2520            .build()?;
2521
2522        // Push filter below NoopPlan for each child branch
2523        assert_optimized_plan_equal!(
2524            plan,
2525            @r"
2526        NoopPlan
2527          TableScan: test, full_filters=[test.a = Int64(1)]
2528          TableScan: test, full_filters=[test.a = Int64(1)]
2529        "
2530        )?;
2531
2532        let custom_plan = LogicalPlan::Extension(Extension {
2533            node: Arc::new(NoopPlan {
2534                input: vec![table_scan.clone(), table_scan.clone()],
2535                schema: Arc::clone(table_scan.schema()),
2536            }),
2537        });
2538        let plan = LogicalPlanBuilder::from(custom_plan)
2539            .filter(col("a").eq(lit(1i64)).and(col("c").eq(lit(2i64))))?
2540            .build()?;
2541
2542        // Push only predicate on `a` below NoopPlan
2543        assert_optimized_plan_equal!(
2544            plan,
2545            @r"
2546        Filter: test.c = Int64(2)
2547          NoopPlan
2548            TableScan: test, full_filters=[test.a = Int64(1)]
2549            TableScan: test, full_filters=[test.a = Int64(1)]
2550        "
2551        )
2552    }
2553
2554    /// verifies that when two filters apply after an aggregation that only allows one to be pushed, one is pushed
2555    /// and the other not.
2556    #[test]
2557    fn multi_filter() -> Result<()> {
2558        // the aggregation allows one filter to pass (b), and the other one to not pass (sum(c))
2559        let table_scan = test_table_scan()?;
2560        let plan = LogicalPlanBuilder::from(table_scan)
2561            .project(vec![col("a").alias("b"), col("c")])?
2562            .aggregate(vec![col("b")], vec![sum(col("c"))])?
2563            .filter(col("b").gt(lit(10i64)))?
2564            .filter(col("sum(test.c)").gt(lit(10i64)))?
2565            .build()?;
2566
2567        // not part of the test, just good to know:
2568        assert_snapshot!(plan,
2569        @r"
2570        Filter: sum(test.c) > Int64(10)
2571          Filter: b > Int64(10)
2572            Aggregate: groupBy=[[b]], aggr=[[sum(test.c)]]
2573              Projection: test.a AS b, test.c
2574                TableScan: test
2575        ",
2576        );
2577        // filter is before the projections
2578        assert_optimized_plan_equal!(
2579            plan,
2580            @r"
2581        Filter: sum(test.c) > Int64(10)
2582          Aggregate: groupBy=[[b]], aggr=[[sum(test.c)]]
2583            Projection: test.a AS b, test.c
2584              TableScan: test, full_filters=[test.a > Int64(10)]
2585        "
2586        )
2587    }
2588
2589    /// verifies that when a filter with two predicates is applied after an aggregation that only allows one to be pushed, one is pushed
2590    /// and the other not.
2591    #[test]
2592    fn split_filter() -> Result<()> {
2593        // the aggregation allows one filter to pass (b), and the other one to not pass (sum(c))
2594        let table_scan = test_table_scan()?;
2595        let plan = LogicalPlanBuilder::from(table_scan)
2596            .project(vec![col("a").alias("b"), col("c")])?
2597            .aggregate(vec![col("b")], vec![sum(col("c"))])?
2598            .filter(and(
2599                col("sum(test.c)").gt(lit(10i64)),
2600                and(col("b").gt(lit(10i64)), col("sum(test.c)").lt(lit(20i64))),
2601            ))?
2602            .build()?;
2603
2604        // not part of the test, just good to know:
2605        assert_snapshot!(plan,
2606        @r"
2607        Filter: sum(test.c) > Int64(10) AND b > Int64(10) AND sum(test.c) < Int64(20)
2608          Aggregate: groupBy=[[b]], aggr=[[sum(test.c)]]
2609            Projection: test.a AS b, test.c
2610              TableScan: test
2611        ",
2612        );
2613        // filter is before the projections
2614        assert_optimized_plan_equal!(
2615            plan,
2616            @r"
2617        Filter: sum(test.c) > Int64(10) AND sum(test.c) < Int64(20)
2618          Aggregate: groupBy=[[b]], aggr=[[sum(test.c)]]
2619            Projection: test.a AS b, test.c
2620              TableScan: test, full_filters=[test.a > Int64(10)]
2621        "
2622        )
2623    }
2624
2625    /// verifies that when two limits are in place, we jump neither
2626    #[test]
2627    fn double_limit() -> Result<()> {
2628        let table_scan = test_table_scan()?;
2629        let plan = LogicalPlanBuilder::from(table_scan)
2630            .project(vec![col("a"), col("b")])?
2631            .limit(0, Some(20))?
2632            .limit(0, Some(10))?
2633            .project(vec![col("a"), col("b")])?
2634            .filter(col("a").eq(lit(1i64)))?
2635            .build()?;
2636        // filter does not just any of the limits
2637        assert_optimized_plan_equal!(
2638            plan,
2639            @r"
2640        Projection: test.a, test.b
2641          Filter: test.a = Int64(1)
2642            Limit: skip=0, fetch=10
2643              Limit: skip=0, fetch=20
2644                Projection: test.a, test.b
2645                  TableScan: test
2646        "
2647        )
2648    }
2649
2650    #[test]
2651    fn union_all() -> Result<()> {
2652        let table_scan = test_table_scan()?;
2653        let table_scan2 = test_table_scan_with_name("test2")?;
2654        let plan = LogicalPlanBuilder::from(table_scan)
2655            .union(LogicalPlanBuilder::from(table_scan2).build()?)?
2656            .filter(col("a").eq(lit(1i64)))?
2657            .build()?;
2658        // filter appears below Union
2659        assert_optimized_plan_equal!(
2660            plan,
2661            @r"
2662        Union
2663          TableScan: test, full_filters=[test.a = Int64(1)]
2664          TableScan: test2, full_filters=[test2.a = Int64(1)]
2665        "
2666        )
2667    }
2668
2669    #[test]
2670    fn union_all_on_projection() -> Result<()> {
2671        let table_scan = test_table_scan()?;
2672        let table = LogicalPlanBuilder::from(table_scan)
2673            .project(vec![col("a").alias("b")])?
2674            .alias("test2")?;
2675
2676        let plan = table
2677            .clone()
2678            .union(table.build()?)?
2679            .filter(col("b").eq(lit(1i64)))?
2680            .build()?;
2681
2682        // filter appears below Union
2683        assert_optimized_plan_equal!(
2684            plan,
2685            @r"
2686        Union
2687          SubqueryAlias: test2
2688            Projection: test.a AS b
2689              TableScan: test, full_filters=[test.a = Int64(1)]
2690          SubqueryAlias: test2
2691            Projection: test.a AS b
2692              TableScan: test, full_filters=[test.a = Int64(1)]
2693        "
2694        )
2695    }
2696
2697    #[test]
2698    fn test_union_different_schema() -> Result<()> {
2699        let left = LogicalPlanBuilder::from(test_table_scan()?)
2700            .project(vec![col("a"), col("b"), col("c")])?
2701            .build()?;
2702
2703        let schema = Schema::new(vec![
2704            Field::new("d", DataType::UInt32, false),
2705            Field::new("e", DataType::UInt32, false),
2706            Field::new("f", DataType::UInt32, false),
2707        ]);
2708        let right = table_scan(Some("test1"), &schema, None)?
2709            .project(vec![col("d"), col("e"), col("f")])?
2710            .build()?;
2711        let filter = and(col("test.a").eq(lit(1)), col("test1.d").gt(lit(2)));
2712        let plan = LogicalPlanBuilder::from(left)
2713            .cross_join(right)?
2714            .project(vec![col("test.a"), col("test1.d")])?
2715            .filter(filter)?
2716            .build()?;
2717
2718        assert_optimized_plan_equal!(
2719            plan,
2720            @r"
2721        Projection: test.a, test1.d
2722          Cross Join:
2723            Projection: test.a, test.b, test.c
2724              TableScan: test, full_filters=[test.a = Int32(1)]
2725            Projection: test1.d, test1.e, test1.f
2726              TableScan: test1, full_filters=[test1.d > Int32(2)]
2727        "
2728        )
2729    }
2730
2731    #[test]
2732    fn test_project_same_name_different_qualifier() -> Result<()> {
2733        let table_scan = test_table_scan()?;
2734        let left = LogicalPlanBuilder::from(table_scan)
2735            .project(vec![col("a"), col("b"), col("c")])?
2736            .build()?;
2737        let right_table_scan = test_table_scan_with_name("test1")?;
2738        let right = LogicalPlanBuilder::from(right_table_scan)
2739            .project(vec![col("a"), col("b"), col("c")])?
2740            .build()?;
2741        let filter = and(col("test.a").eq(lit(1)), col("test1.a").gt(lit(2)));
2742        let plan = LogicalPlanBuilder::from(left)
2743            .cross_join(right)?
2744            .project(vec![col("test.a"), col("test1.a")])?
2745            .filter(filter)?
2746            .build()?;
2747
2748        assert_optimized_plan_equal!(
2749            plan,
2750            @r"
2751        Projection: test.a, test1.a
2752          Cross Join:
2753            Projection: test.a, test.b, test.c
2754              TableScan: test, full_filters=[test.a = Int32(1)]
2755            Projection: test1.a, test1.b, test1.c
2756              TableScan: test1, full_filters=[test1.a > Int32(2)]
2757        "
2758        )
2759    }
2760
2761    /// verifies that filters with the same columns are correctly placed
2762    #[test]
2763    fn filter_2_breaks_limits() -> Result<()> {
2764        let table_scan = test_table_scan()?;
2765        let plan = LogicalPlanBuilder::from(table_scan)
2766            .project(vec![col("a")])?
2767            .filter(col("a").lt_eq(lit(1i64)))?
2768            .limit(0, Some(1))?
2769            .project(vec![col("a")])?
2770            .filter(col("a").gt_eq(lit(1i64)))?
2771            .build()?;
2772        // Should be able to move both filters below the projections
2773
2774        // not part of the test
2775        assert_snapshot!(plan,
2776        @r"
2777        Filter: test.a >= Int64(1)
2778          Projection: test.a
2779            Limit: skip=0, fetch=1
2780              Filter: test.a <= Int64(1)
2781                Projection: test.a
2782                  TableScan: test
2783        ",
2784        );
2785        assert_optimized_plan_equal!(
2786            plan,
2787            @r"
2788        Projection: test.a
2789          Filter: test.a >= Int64(1)
2790            Limit: skip=0, fetch=1
2791              Projection: test.a
2792                TableScan: test, full_filters=[test.a <= Int64(1)]
2793        "
2794        )
2795    }
2796
2797    /// verifies that filters to be placed on the same depth are ANDed
2798    #[test]
2799    fn two_filters_on_same_depth() -> Result<()> {
2800        let table_scan = test_table_scan()?;
2801        let plan = LogicalPlanBuilder::from(table_scan)
2802            .limit(0, Some(1))?
2803            .filter(col("a").lt_eq(lit(1i64)))?
2804            .filter(col("a").gt_eq(lit(1i64)))?
2805            .project(vec![col("a")])?
2806            .build()?;
2807
2808        // not part of the test
2809        assert_snapshot!(plan,
2810        @r"
2811        Projection: test.a
2812          Filter: test.a >= Int64(1)
2813            Filter: test.a <= Int64(1)
2814              Limit: skip=0, fetch=1
2815                TableScan: test
2816        ",
2817        );
2818        assert_optimized_plan_equal!(
2819            plan,
2820            @r"
2821        Projection: test.a
2822          Filter: test.a <= Int64(1) AND test.a >= Int64(1)
2823            Limit: skip=0, fetch=1
2824              TableScan: test
2825        "
2826        )
2827    }
2828
2829    /// verifies that filters on a plan with user nodes are not lost
2830    /// (ARROW-10547)
2831    #[test]
2832    fn filters_user_defined_node() -> Result<()> {
2833        let table_scan = test_table_scan()?;
2834        let plan = LogicalPlanBuilder::from(table_scan)
2835            .filter(col("a").lt_eq(lit(1i64)))?
2836            .build()?;
2837
2838        let plan = user_defined::new(plan);
2839
2840        // not part of the test
2841        assert_snapshot!(plan,
2842        @r"
2843        TestUserDefined
2844          Filter: test.a <= Int64(1)
2845            TableScan: test
2846        ",
2847        );
2848        assert_optimized_plan_equal!(
2849            plan,
2850            @r"
2851        TestUserDefined
2852          TableScan: test, full_filters=[test.a <= Int64(1)]
2853        "
2854        )
2855    }
2856
2857    /// post-on-join predicates on a column common to both sides is pushed to both sides
2858    #[test]
2859    fn filter_on_join_on_common_independent() -> Result<()> {
2860        let table_scan = test_table_scan()?;
2861        let left = LogicalPlanBuilder::from(table_scan).build()?;
2862        let right_table_scan = test_table_scan_with_name("test2")?;
2863        let right = LogicalPlanBuilder::from(right_table_scan)
2864            .project(vec![col("a")])?
2865            .build()?;
2866        let plan = LogicalPlanBuilder::from(left)
2867            .join(
2868                right,
2869                JoinType::Inner,
2870                (vec![Column::from_name("a")], vec![Column::from_name("a")]),
2871                None,
2872            )?
2873            .filter(col("test.a").lt_eq(lit(1i64)))?
2874            .build()?;
2875
2876        // not part of the test, just good to know:
2877        assert_snapshot!(plan,
2878        @r"
2879        Filter: test.a <= Int64(1)
2880          Inner Join: test.a = test2.a
2881            TableScan: test
2882            Projection: test2.a
2883              TableScan: test2
2884        ",
2885        );
2886        // filter sent to side before the join
2887        assert_optimized_plan_equal!(
2888            plan,
2889            @r"
2890        Inner Join: test.a = test2.a
2891          TableScan: test, full_filters=[test.a <= Int64(1)]
2892          Projection: test2.a
2893            TableScan: test2, full_filters=[test2.a <= Int64(1)]
2894        "
2895        )
2896    }
2897
2898    /// post-using-join predicates on a column common to both sides is pushed to both sides
2899    #[test]
2900    fn filter_using_join_on_common_independent() -> Result<()> {
2901        let table_scan = test_table_scan()?;
2902        let left = LogicalPlanBuilder::from(table_scan).build()?;
2903        let right_table_scan = test_table_scan_with_name("test2")?;
2904        let right = LogicalPlanBuilder::from(right_table_scan)
2905            .project(vec![col("a")])?
2906            .build()?;
2907        let plan = LogicalPlanBuilder::from(left)
2908            .join_using(
2909                right,
2910                JoinType::Inner,
2911                vec![Column::from_name("a".to_string())],
2912            )?
2913            .filter(col("a").lt_eq(lit(1i64)))?
2914            .build()?;
2915
2916        // not part of the test, just good to know:
2917        assert_snapshot!(plan,
2918        @r"
2919        Filter: test.a <= Int64(1)
2920          Inner Join: Using test.a = test2.a
2921            TableScan: test
2922            Projection: test2.a
2923              TableScan: test2
2924        ",
2925        );
2926        // filter sent to side before the join
2927        assert_optimized_plan_equal!(
2928            plan,
2929            @r"
2930        Inner Join: Using test.a = test2.a
2931          TableScan: test, full_filters=[test.a <= Int64(1)]
2932          Projection: test2.a
2933            TableScan: test2, full_filters=[test2.a <= Int64(1)]
2934        "
2935        )
2936    }
2937
2938    /// post-join predicates with columns from both sides are converted to join filters
2939    #[test]
2940    fn filter_join_on_common_dependent() -> Result<()> {
2941        let table_scan = test_table_scan()?;
2942        let left = LogicalPlanBuilder::from(table_scan)
2943            .project(vec![col("a"), col("c")])?
2944            .build()?;
2945        let right_table_scan = test_table_scan_with_name("test2")?;
2946        let right = LogicalPlanBuilder::from(right_table_scan)
2947            .project(vec![col("a"), col("b")])?
2948            .build()?;
2949        let plan = LogicalPlanBuilder::from(left)
2950            .join(
2951                right,
2952                JoinType::Inner,
2953                (vec![Column::from_name("a")], vec![Column::from_name("a")]),
2954                None,
2955            )?
2956            .filter(col("c").lt_eq(col("b")))?
2957            .build()?;
2958
2959        // not part of the test, just good to know:
2960        assert_snapshot!(plan,
2961        @r"
2962        Filter: test.c <= test2.b
2963          Inner Join: test.a = test2.a
2964            Projection: test.a, test.c
2965              TableScan: test
2966            Projection: test2.a, test2.b
2967              TableScan: test2
2968        ",
2969        );
2970        // Filter is converted to Join Filter
2971        assert_optimized_plan_equal!(
2972            plan,
2973            @r"
2974        Inner Join: test.a = test2.a Filter: test.c <= test2.b
2975          Projection: test.a, test.c
2976            TableScan: test
2977          Projection: test2.a, test2.b
2978            TableScan: test2
2979        "
2980        )
2981    }
2982
2983    /// post-join predicates with columns from one side of a join are pushed only to that side
2984    #[test]
2985    fn filter_join_on_one_side() -> Result<()> {
2986        let table_scan = test_table_scan()?;
2987        let left = LogicalPlanBuilder::from(table_scan)
2988            .project(vec![col("a"), col("b")])?
2989            .build()?;
2990        let table_scan_right = test_table_scan_with_name("test2")?;
2991        let right = LogicalPlanBuilder::from(table_scan_right)
2992            .project(vec![col("a"), col("c")])?
2993            .build()?;
2994
2995        let plan = LogicalPlanBuilder::from(left)
2996            .join(
2997                right,
2998                JoinType::Inner,
2999                (vec![Column::from_name("a")], vec![Column::from_name("a")]),
3000                None,
3001            )?
3002            .filter(col("b").lt_eq(lit(1i64)))?
3003            .build()?;
3004
3005        // not part of the test, just good to know:
3006        assert_snapshot!(plan,
3007        @r"
3008        Filter: test.b <= Int64(1)
3009          Inner Join: test.a = test2.a
3010            Projection: test.a, test.b
3011              TableScan: test
3012            Projection: test2.a, test2.c
3013              TableScan: test2
3014        ",
3015        );
3016        assert_optimized_plan_equal!(
3017            plan,
3018            @r"
3019        Inner Join: test.a = test2.a
3020          Projection: test.a, test.b
3021            TableScan: test, full_filters=[test.b <= Int64(1)]
3022          Projection: test2.a, test2.c
3023            TableScan: test2
3024        "
3025        )
3026    }
3027
3028    /// post-join predicates on the right side of a left join are not duplicated
3029    /// TODO: In this case we can sometimes convert the join to an INNER join
3030    #[test]
3031    fn filter_using_left_join() -> Result<()> {
3032        let table_scan = test_table_scan()?;
3033        let left = LogicalPlanBuilder::from(table_scan).build()?;
3034        let right_table_scan = test_table_scan_with_name("test2")?;
3035        let right = LogicalPlanBuilder::from(right_table_scan)
3036            .project(vec![col("a")])?
3037            .build()?;
3038        let plan = LogicalPlanBuilder::from(left)
3039            .join_using(
3040                right,
3041                JoinType::Left,
3042                vec![Column::from_name("a".to_string())],
3043            )?
3044            .filter(col("test2.a").lt_eq(lit(1i64)))?
3045            .build()?;
3046
3047        // not part of the test, just good to know:
3048        assert_snapshot!(plan,
3049        @r"
3050        Filter: test2.a <= Int64(1)
3051          Left Join: Using test.a = test2.a
3052            TableScan: test
3053            Projection: test2.a
3054              TableScan: test2
3055        ",
3056        );
3057        // filter not duplicated nor pushed down - i.e. noop
3058        assert_optimized_plan_equal!(
3059            plan,
3060            @r"
3061        Filter: test2.a <= Int64(1)
3062          Left Join: Using test.a = test2.a
3063            TableScan: test, full_filters=[test.a <= Int64(1)]
3064            Projection: test2.a
3065              TableScan: test2
3066        "
3067        )
3068    }
3069
3070    /// post-join predicates on the left side of a right join are not duplicated
3071    #[test]
3072    fn filter_using_right_join() -> Result<()> {
3073        let table_scan = test_table_scan()?;
3074        let left = LogicalPlanBuilder::from(table_scan).build()?;
3075        let right_table_scan = test_table_scan_with_name("test2")?;
3076        let right = LogicalPlanBuilder::from(right_table_scan)
3077            .project(vec![col("a")])?
3078            .build()?;
3079        let plan = LogicalPlanBuilder::from(left)
3080            .join_using(
3081                right,
3082                JoinType::Right,
3083                vec![Column::from_name("a".to_string())],
3084            )?
3085            .filter(col("test.a").lt_eq(lit(1i64)))?
3086            .build()?;
3087
3088        // not part of the test, just good to know:
3089        assert_snapshot!(plan,
3090        @r"
3091        Filter: test.a <= Int64(1)
3092          Right Join: Using test.a = test2.a
3093            TableScan: test
3094            Projection: test2.a
3095              TableScan: test2
3096        ",
3097        );
3098        // filter not duplicated nor pushed down - i.e. noop
3099        assert_optimized_plan_equal!(
3100            plan,
3101            @r"
3102        Filter: test.a <= Int64(1)
3103          Right Join: Using test.a = test2.a
3104            TableScan: test
3105            Projection: test2.a
3106              TableScan: test2, full_filters=[test2.a <= Int64(1)]
3107        "
3108        )
3109    }
3110
3111    /// post-left-join predicate on a column common to both sides is pushed to both sides
3112    #[test]
3113    fn filter_using_left_join_on_common() -> Result<()> {
3114        let table_scan = test_table_scan()?;
3115        let left = LogicalPlanBuilder::from(table_scan).build()?;
3116        let right_table_scan = test_table_scan_with_name("test2")?;
3117        let right = LogicalPlanBuilder::from(right_table_scan)
3118            .project(vec![col("a")])?
3119            .build()?;
3120        let plan = LogicalPlanBuilder::from(left)
3121            .join_using(
3122                right,
3123                JoinType::Left,
3124                vec![Column::from_name("a".to_string())],
3125            )?
3126            .filter(col("a").lt_eq(lit(1i64)))?
3127            .build()?;
3128
3129        // not part of the test, just good to know:
3130        assert_snapshot!(plan,
3131        @r"
3132        Filter: test.a <= Int64(1)
3133          Left Join: Using test.a = test2.a
3134            TableScan: test
3135            Projection: test2.a
3136              TableScan: test2
3137        ",
3138        );
3139        // filter sent to left side of the join and to the right
3140        assert_optimized_plan_equal!(
3141            plan,
3142            @r"
3143        Left Join: Using test.a = test2.a
3144          TableScan: test, full_filters=[test.a <= Int64(1)]
3145          Projection: test2.a
3146            TableScan: test2, full_filters=[test2.a <= Int64(1)]
3147        "
3148        )
3149    }
3150
3151    /// post-right-join predicate on a column common to both sides is pushed to both sides
3152    #[test]
3153    fn filter_using_right_join_on_common() -> Result<()> {
3154        let table_scan = test_table_scan()?;
3155        let left = LogicalPlanBuilder::from(table_scan).build()?;
3156        let right_table_scan = test_table_scan_with_name("test2")?;
3157        let right = LogicalPlanBuilder::from(right_table_scan)
3158            .project(vec![col("a")])?
3159            .build()?;
3160        let plan = LogicalPlanBuilder::from(left)
3161            .join_using(
3162                right,
3163                JoinType::Right,
3164                vec![Column::from_name("a".to_string())],
3165            )?
3166            .filter(col("test2.a").lt_eq(lit(1i64)))?
3167            .build()?;
3168
3169        // not part of the test, just good to know:
3170        assert_snapshot!(plan,
3171        @r"
3172        Filter: test2.a <= Int64(1)
3173          Right Join: Using test.a = test2.a
3174            TableScan: test
3175            Projection: test2.a
3176              TableScan: test2
3177        ",
3178        );
3179        // filter sent to right side of join, sent to the left as well
3180        assert_optimized_plan_equal!(
3181            plan,
3182            @r"
3183        Right Join: Using test.a = test2.a
3184          TableScan: test, full_filters=[test.a <= Int64(1)]
3185          Projection: test2.a
3186            TableScan: test2, full_filters=[test2.a <= Int64(1)]
3187        "
3188        )
3189    }
3190
3191    /// single table predicate parts of ON condition should be pushed to both inputs
3192    #[test]
3193    fn join_on_with_filter() -> Result<()> {
3194        let table_scan = test_table_scan()?;
3195        let left = LogicalPlanBuilder::from(table_scan)
3196            .project(vec![col("a"), col("b"), col("c")])?
3197            .build()?;
3198        let right_table_scan = test_table_scan_with_name("test2")?;
3199        let right = LogicalPlanBuilder::from(right_table_scan)
3200            .project(vec![col("a"), col("b"), col("c")])?
3201            .build()?;
3202        let filter = col("test.c")
3203            .gt(lit(1u32))
3204            .and(col("test.b").lt(col("test2.b")))
3205            .and(col("test2.c").gt(lit(4u32)));
3206        let plan = LogicalPlanBuilder::from(left)
3207            .join(
3208                right,
3209                JoinType::Inner,
3210                (vec![Column::from_name("a")], vec![Column::from_name("a")]),
3211                Some(filter),
3212            )?
3213            .build()?;
3214
3215        // not part of the test, just good to know:
3216        assert_snapshot!(plan,
3217        @r"
3218        Inner Join: test.a = test2.a Filter: test.c > UInt32(1) AND test.b < test2.b AND test2.c > UInt32(4)
3219          Projection: test.a, test.b, test.c
3220            TableScan: test
3221          Projection: test2.a, test2.b, test2.c
3222            TableScan: test2
3223        ",
3224        );
3225        assert_optimized_plan_equal!(
3226            plan,
3227            @r"
3228        Inner Join: test.a = test2.a Filter: test.b < test2.b
3229          Projection: test.a, test.b, test.c
3230            TableScan: test, full_filters=[test.c > UInt32(1)]
3231          Projection: test2.a, test2.b, test2.c
3232            TableScan: test2, full_filters=[test2.c > UInt32(4)]
3233        "
3234        )
3235    }
3236
3237    /// join filter should be completely removed after pushdown
3238    #[test]
3239    fn join_filter_removed() -> Result<()> {
3240        let table_scan = test_table_scan()?;
3241        let left = LogicalPlanBuilder::from(table_scan)
3242            .project(vec![col("a"), col("b"), col("c")])?
3243            .build()?;
3244        let right_table_scan = test_table_scan_with_name("test2")?;
3245        let right = LogicalPlanBuilder::from(right_table_scan)
3246            .project(vec![col("a"), col("b"), col("c")])?
3247            .build()?;
3248        let filter = col("test.b")
3249            .gt(lit(1u32))
3250            .and(col("test2.c").gt(lit(4u32)));
3251        let plan = LogicalPlanBuilder::from(left)
3252            .join(
3253                right,
3254                JoinType::Inner,
3255                (vec![Column::from_name("a")], vec![Column::from_name("a")]),
3256                Some(filter),
3257            )?
3258            .build()?;
3259
3260        // not part of the test, just good to know:
3261        assert_snapshot!(plan,
3262        @r"
3263        Inner Join: test.a = test2.a Filter: test.b > UInt32(1) AND test2.c > UInt32(4)
3264          Projection: test.a, test.b, test.c
3265            TableScan: test
3266          Projection: test2.a, test2.b, test2.c
3267            TableScan: test2
3268        ",
3269        );
3270        assert_optimized_plan_equal!(
3271            plan,
3272            @r"
3273        Inner Join: test.a = test2.a
3274          Projection: test.a, test.b, test.c
3275            TableScan: test, full_filters=[test.b > UInt32(1)]
3276          Projection: test2.a, test2.b, test2.c
3277            TableScan: test2, full_filters=[test2.c > UInt32(4)]
3278        "
3279        )
3280    }
3281
3282    /// predicate on join key in filter expression should be pushed down to both inputs
3283    #[test]
3284    fn join_filter_on_common() -> Result<()> {
3285        let table_scan = test_table_scan()?;
3286        let left = LogicalPlanBuilder::from(table_scan)
3287            .project(vec![col("a")])?
3288            .build()?;
3289        let right_table_scan = test_table_scan_with_name("test2")?;
3290        let right = LogicalPlanBuilder::from(right_table_scan)
3291            .project(vec![col("b")])?
3292            .build()?;
3293        let filter = col("test.a").gt(lit(1u32));
3294        let plan = LogicalPlanBuilder::from(left)
3295            .join(
3296                right,
3297                JoinType::Inner,
3298                (vec![Column::from_name("a")], vec![Column::from_name("b")]),
3299                Some(filter),
3300            )?
3301            .build()?;
3302
3303        // not part of the test, just good to know:
3304        assert_snapshot!(plan,
3305        @r"
3306        Inner Join: test.a = test2.b Filter: test.a > UInt32(1)
3307          Projection: test.a
3308            TableScan: test
3309          Projection: test2.b
3310            TableScan: test2
3311        ",
3312        );
3313        assert_optimized_plan_equal!(
3314            plan,
3315            @r"
3316        Inner Join: test.a = test2.b
3317          Projection: test.a
3318            TableScan: test, full_filters=[test.a > UInt32(1)]
3319          Projection: test2.b
3320            TableScan: test2, full_filters=[test2.b > UInt32(1)]
3321        "
3322        )
3323    }
3324
3325    /// single table predicate parts of ON condition should be pushed to right input
3326    #[test]
3327    fn left_join_on_with_filter() -> Result<()> {
3328        let table_scan = test_table_scan()?;
3329        let left = LogicalPlanBuilder::from(table_scan)
3330            .project(vec![col("a"), col("b"), col("c")])?
3331            .build()?;
3332        let right_table_scan = test_table_scan_with_name("test2")?;
3333        let right = LogicalPlanBuilder::from(right_table_scan)
3334            .project(vec![col("a"), col("b"), col("c")])?
3335            .build()?;
3336        let filter = col("test.a")
3337            .gt(lit(1u32))
3338            .and(col("test.b").lt(col("test2.b")))
3339            .and(col("test2.c").gt(lit(4u32)));
3340        let plan = LogicalPlanBuilder::from(left)
3341            .join(
3342                right,
3343                JoinType::Left,
3344                (vec![Column::from_name("a")], vec![Column::from_name("a")]),
3345                Some(filter),
3346            )?
3347            .build()?;
3348
3349        // not part of the test, just good to know:
3350        assert_snapshot!(plan,
3351        @r"
3352        Left Join: test.a = test2.a Filter: test.a > UInt32(1) AND test.b < test2.b AND test2.c > UInt32(4)
3353          Projection: test.a, test.b, test.c
3354            TableScan: test
3355          Projection: test2.a, test2.b, test2.c
3356            TableScan: test2
3357        ",
3358        );
3359        assert_optimized_plan_equal!(
3360            plan,
3361            @r"
3362        Left Join: test.a = test2.a Filter: test.a > UInt32(1) AND test.b < test2.b
3363          Projection: test.a, test.b, test.c
3364            TableScan: test
3365          Projection: test2.a, test2.b, test2.c
3366            TableScan: test2, full_filters=[test2.a > UInt32(1), test2.c > UInt32(4)]
3367        "
3368        )
3369    }
3370
3371    /// single table predicate parts of ON condition should be pushed to left input
3372    #[test]
3373    fn right_join_on_with_filter() -> Result<()> {
3374        let table_scan = test_table_scan()?;
3375        let left = LogicalPlanBuilder::from(table_scan)
3376            .project(vec![col("a"), col("b"), col("c")])?
3377            .build()?;
3378        let right_table_scan = test_table_scan_with_name("test2")?;
3379        let right = LogicalPlanBuilder::from(right_table_scan)
3380            .project(vec![col("a"), col("b"), col("c")])?
3381            .build()?;
3382        let filter = col("test.a")
3383            .gt(lit(1u32))
3384            .and(col("test.b").lt(col("test2.b")))
3385            .and(col("test2.c").gt(lit(4u32)));
3386        let plan = LogicalPlanBuilder::from(left)
3387            .join(
3388                right,
3389                JoinType::Right,
3390                (vec![Column::from_name("a")], vec![Column::from_name("a")]),
3391                Some(filter),
3392            )?
3393            .build()?;
3394
3395        // not part of the test, just good to know:
3396        assert_snapshot!(plan,
3397        @r"
3398        Right Join: test.a = test2.a Filter: test.a > UInt32(1) AND test.b < test2.b AND test2.c > UInt32(4)
3399          Projection: test.a, test.b, test.c
3400            TableScan: test
3401          Projection: test2.a, test2.b, test2.c
3402            TableScan: test2
3403        ",
3404        );
3405        assert_optimized_plan_equal!(
3406            plan,
3407            @r"
3408        Right Join: test.a = test2.a Filter: test.b < test2.b AND test2.c > UInt32(4)
3409          Projection: test.a, test.b, test.c
3410            TableScan: test, full_filters=[test.a > UInt32(1)]
3411          Projection: test2.a, test2.b, test2.c
3412            TableScan: test2
3413        "
3414        )
3415    }
3416
3417    /// single table predicate parts of ON condition should not be pushed
3418    #[test]
3419    fn full_join_on_with_filter() -> Result<()> {
3420        let table_scan = test_table_scan()?;
3421        let left = LogicalPlanBuilder::from(table_scan)
3422            .project(vec![col("a"), col("b"), col("c")])?
3423            .build()?;
3424        let right_table_scan = test_table_scan_with_name("test2")?;
3425        let right = LogicalPlanBuilder::from(right_table_scan)
3426            .project(vec![col("a"), col("b"), col("c")])?
3427            .build()?;
3428        let filter = col("test.a")
3429            .gt(lit(1u32))
3430            .and(col("test.b").lt(col("test2.b")))
3431            .and(col("test2.c").gt(lit(4u32)));
3432        let plan = LogicalPlanBuilder::from(left)
3433            .join(
3434                right,
3435                JoinType::Full,
3436                (vec![Column::from_name("a")], vec![Column::from_name("a")]),
3437                Some(filter),
3438            )?
3439            .build()?;
3440        assert_plan_not_transformed!(plan.clone());
3441
3442        // not part of the test, just good to know:
3443        assert_snapshot!(plan,
3444        @r"
3445        Full Join: test.a = test2.a Filter: test.a > UInt32(1) AND test.b < test2.b AND test2.c > UInt32(4)
3446          Projection: test.a, test.b, test.c
3447            TableScan: test
3448          Projection: test2.a, test2.b, test2.c
3449            TableScan: test2
3450        ",
3451        );
3452        assert_optimized_plan_equal!(
3453            plan,
3454            @r"
3455        Full Join: test.a = test2.a Filter: test.a > UInt32(1) AND test.b < test2.b AND test2.c > UInt32(4)
3456          Projection: test.a, test.b, test.c
3457            TableScan: test
3458          Projection: test2.a, test2.b, test2.c
3459            TableScan: test2
3460        "
3461        )
3462    }
3463
3464    struct PushDownProvider {
3465        pub filter_support: TableProviderFilterPushDown,
3466    }
3467
3468    #[async_trait]
3469    impl TableSource for PushDownProvider {
3470        fn schema(&self) -> SchemaRef {
3471            Arc::new(Schema::new(vec![
3472                Field::new("a", DataType::Int32, true),
3473                Field::new("b", DataType::Int32, true),
3474            ]))
3475        }
3476
3477        fn table_type(&self) -> TableType {
3478            TableType::Base
3479        }
3480
3481        fn supports_filters_pushdown(
3482            &self,
3483            filters: &[&Expr],
3484        ) -> Result<Vec<TableProviderFilterPushDown>> {
3485            Ok((0..filters.len())
3486                .map(|_| self.filter_support.clone())
3487                .collect())
3488        }
3489    }
3490
3491    fn table_scan_with_pushdown_provider_builder(
3492        filter_support: TableProviderFilterPushDown,
3493        filters: Vec<Expr>,
3494        projection: Option<Vec<usize>>,
3495    ) -> Result<LogicalPlanBuilder> {
3496        let test_provider = PushDownProvider { filter_support };
3497
3498        let table_scan = LogicalPlan::TableScan(TableScan {
3499            table_name: "test".into(),
3500            filters,
3501            projected_schema: Arc::new(DFSchema::try_from(test_provider.schema())?),
3502            projection,
3503            source: Arc::new(test_provider),
3504            fetch: None,
3505            skip: None,
3506            statistics_requests: Box::default(),
3507        });
3508
3509        Ok(LogicalPlanBuilder::from(table_scan))
3510    }
3511
3512    fn table_scan_with_pushdown_provider(
3513        filter_support: TableProviderFilterPushDown,
3514    ) -> Result<LogicalPlan> {
3515        table_scan_with_pushdown_provider_builder(filter_support, vec![], None)?
3516            .filter(col("a").eq(lit(1i64)))?
3517            .build()
3518    }
3519
3520    #[test]
3521    fn filter_with_table_provider_exact() -> Result<()> {
3522        let plan = table_scan_with_pushdown_provider(TableProviderFilterPushDown::Exact)?;
3523
3524        assert_optimized_plan_equal!(
3525            plan,
3526            @"TableScan: test, full_filters=[a = Int64(1)]"
3527        )
3528    }
3529
3530    #[test]
3531    fn filter_with_table_provider_inexact() -> Result<()> {
3532        let plan =
3533            table_scan_with_pushdown_provider(TableProviderFilterPushDown::Inexact)?;
3534
3535        assert_optimized_plan_equal!(
3536            plan,
3537            @r"
3538        Filter: a = Int64(1)
3539          TableScan: test, partial_filters=[a = Int64(1)]
3540        "
3541        )
3542    }
3543
3544    #[test]
3545    fn filter_with_table_provider_multiple_invocations() -> Result<()> {
3546        let plan =
3547            table_scan_with_pushdown_provider(TableProviderFilterPushDown::Inexact)?;
3548
3549        let optimized = PushDownFilter::new()
3550            .rewrite(plan, &OptimizerContext::new())
3551            .expect("failed to optimize plan");
3552        assert!(optimized.transformed);
3553        assert_plan_not_transformed!(optimized.data.clone());
3554
3555        // Optimizing the same plan multiple times should produce the same plan
3556        // each time.
3557        assert_optimized_plan_equal!(
3558            optimized.data,
3559            @r"
3560        Filter: a = Int64(1)
3561          TableScan: test, partial_filters=[a = Int64(1)]
3562        "
3563        )
3564    }
3565
3566    #[test]
3567    fn filter_with_table_provider_unsupported() -> Result<()> {
3568        let plan =
3569            table_scan_with_pushdown_provider(TableProviderFilterPushDown::Unsupported)?;
3570        assert_plan_not_transformed!(plan.clone());
3571
3572        assert_optimized_plan_equal!(
3573            plan,
3574            @r"
3575        Filter: a = Int64(1)
3576          TableScan: test
3577        "
3578        )
3579    }
3580
3581    #[test]
3582    fn multi_combined_filter() -> Result<()> {
3583        let plan = table_scan_with_pushdown_provider_builder(
3584            TableProviderFilterPushDown::Inexact,
3585            vec![col("a").eq(lit(10i64)), col("b").gt(lit(11i64))],
3586            Some(vec![0]),
3587        )?
3588        .filter(and(col("a").eq(lit(10i64)), col("b").gt(lit(11i64))))?
3589        .project(vec![col("a"), col("b")])?
3590        .build()?;
3591
3592        assert_optimized_plan_equal!(
3593            plan,
3594            @r"
3595        Projection: a, b
3596          Filter: a = Int64(10) AND b > Int64(11)
3597            TableScan: test projection=[a], partial_filters=[a = Int64(10), b > Int64(11)]
3598        "
3599        )
3600    }
3601
3602    #[test]
3603    fn multi_combined_two_filters() -> Result<()> {
3604        let plan = table_scan_with_pushdown_provider_builder(
3605            TableProviderFilterPushDown::Inexact,
3606            vec![col("a").eq(lit(10i64)), col("b").gt(lit(11i64))],
3607            Some(vec![0]),
3608        )?
3609        .filter(col("a").eq(lit(10i64)))?
3610        .filter(col("b").gt(lit(11i64)))?
3611        .project(vec![col("a"), col("b")])?
3612        .build()?;
3613
3614        assert_optimized_plan_equal!(
3615            plan,
3616            @r"
3617        Projection: a, b
3618          Filter: a = Int64(10) AND b > Int64(11)
3619            TableScan: test projection=[a], partial_filters=[a = Int64(10), b > Int64(11)]
3620        "
3621        )
3622    }
3623
3624    #[test]
3625    fn multi_combined_filter_exact() -> Result<()> {
3626        let plan = table_scan_with_pushdown_provider_builder(
3627            TableProviderFilterPushDown::Exact,
3628            vec![],
3629            Some(vec![0]),
3630        )?
3631        .filter(and(col("a").eq(lit(10i64)), col("b").gt(lit(11i64))))?
3632        .project(vec![col("a"), col("b")])?
3633        .build()?;
3634
3635        assert_optimized_plan_equal!(
3636            plan,
3637            @r"
3638        Projection: a, b
3639          TableScan: test projection=[a], full_filters=[a = Int64(10), b > Int64(11)]
3640        "
3641        )
3642    }
3643
3644    #[test]
3645    fn multi_combined_two_filters_exact() -> Result<()> {
3646        let plan = table_scan_with_pushdown_provider_builder(
3647            TableProviderFilterPushDown::Exact,
3648            vec![],
3649            Some(vec![0]),
3650        )?
3651        .filter(col("a").eq(lit(10i64)))?
3652        .filter(col("b").gt(lit(11i64)))?
3653        .project(vec![col("a"), col("b")])?
3654        .build()?;
3655
3656        assert_optimized_plan_equal!(
3657            plan,
3658            @r"
3659        Projection: a, b
3660          TableScan: test projection=[a], full_filters=[a = Int64(10), b > Int64(11)]
3661        "
3662        )
3663    }
3664
3665    #[test]
3666    fn test_filter_with_alias() -> Result<()> {
3667        // in table scan the true col name is 'test.a',
3668        // but we rename it as 'b', and use col 'b' in filter
3669        // we need rewrite filter col before push down.
3670        let table_scan = test_table_scan()?;
3671        let plan = LogicalPlanBuilder::from(table_scan)
3672            .project(vec![col("a").alias("b"), col("c")])?
3673            .filter(and(col("b").gt(lit(10i64)), col("c").gt(lit(10i64))))?
3674            .build()?;
3675
3676        // filter on col b
3677        assert_snapshot!(plan,
3678        @r"
3679        Filter: b > Int64(10) AND test.c > Int64(10)
3680          Projection: test.a AS b, test.c
3681            TableScan: test
3682        ",
3683        );
3684        // rewrite filter col b to test.a
3685        assert_optimized_plan_equal!(
3686            plan,
3687            @r"
3688        Projection: test.a AS b, test.c
3689          TableScan: test, full_filters=[test.a > Int64(10), test.c > Int64(10)]
3690        "
3691        )
3692    }
3693
3694    #[test]
3695    fn test_filter_with_alias_2() -> Result<()> {
3696        // in table scan the true col name is 'test.a',
3697        // but we rename it as 'b', and use col 'b' in filter
3698        // we need rewrite filter col before push down.
3699        let table_scan = test_table_scan()?;
3700        let plan = LogicalPlanBuilder::from(table_scan)
3701            .project(vec![col("a").alias("b"), col("c")])?
3702            .project(vec![col("b"), col("c")])?
3703            .filter(and(col("b").gt(lit(10i64)), col("c").gt(lit(10i64))))?
3704            .build()?;
3705
3706        // filter on col b
3707        assert_snapshot!(plan,
3708        @r"
3709        Filter: b > Int64(10) AND test.c > Int64(10)
3710          Projection: b, test.c
3711            Projection: test.a AS b, test.c
3712              TableScan: test
3713        ",
3714        );
3715        // rewrite filter col b to test.a
3716        assert_optimized_plan_equal!(
3717            plan,
3718            @r"
3719        Projection: b, test.c
3720          Projection: test.a AS b, test.c
3721            TableScan: test, full_filters=[test.a > Int64(10), test.c > Int64(10)]
3722        "
3723        )
3724    }
3725
3726    #[test]
3727    fn test_filter_with_multi_alias() -> Result<()> {
3728        let table_scan = test_table_scan()?;
3729        let plan = LogicalPlanBuilder::from(table_scan)
3730            .project(vec![col("a").alias("b"), col("c").alias("d")])?
3731            .filter(and(col("b").gt(lit(10i64)), col("d").gt(lit(10i64))))?
3732            .build()?;
3733
3734        // filter on col b and d
3735        assert_snapshot!(plan,
3736        @r"
3737        Filter: b > Int64(10) AND d > Int64(10)
3738          Projection: test.a AS b, test.c AS d
3739            TableScan: test
3740        ",
3741        );
3742        // rewrite filter col b to test.a, col d to test.c
3743        assert_optimized_plan_equal!(
3744            plan,
3745            @r"
3746        Projection: test.a AS b, test.c AS d
3747          TableScan: test, full_filters=[test.a > Int64(10), test.c > Int64(10)]
3748        "
3749        )
3750    }
3751
3752    /// predicate on join key in filter expression should be pushed down to both inputs
3753    #[test]
3754    fn join_filter_with_alias() -> Result<()> {
3755        let table_scan = test_table_scan()?;
3756        let left = LogicalPlanBuilder::from(table_scan)
3757            .project(vec![col("a").alias("c")])?
3758            .build()?;
3759        let right_table_scan = test_table_scan_with_name("test2")?;
3760        let right = LogicalPlanBuilder::from(right_table_scan)
3761            .project(vec![col("b").alias("d")])?
3762            .build()?;
3763        let filter = col("c").gt(lit(1u32));
3764        let plan = LogicalPlanBuilder::from(left)
3765            .join(
3766                right,
3767                JoinType::Inner,
3768                (vec![Column::from_name("c")], vec![Column::from_name("d")]),
3769                Some(filter),
3770            )?
3771            .build()?;
3772
3773        assert_snapshot!(plan,
3774        @r"
3775        Inner Join: c = d Filter: c > UInt32(1)
3776          Projection: test.a AS c
3777            TableScan: test
3778          Projection: test2.b AS d
3779            TableScan: test2
3780        ",
3781        );
3782        // Change filter on col `c`, 'd' to `test.a`, 'test.b'
3783        assert_optimized_plan_equal!(
3784            plan,
3785            @r"
3786        Inner Join: c = d
3787          Projection: test.a AS c
3788            TableScan: test, full_filters=[test.a > UInt32(1)]
3789          Projection: test2.b AS d
3790            TableScan: test2, full_filters=[test2.b > UInt32(1)]
3791        "
3792        )
3793    }
3794
3795    #[test]
3796    fn test_in_filter_with_alias() -> Result<()> {
3797        // in table scan the true col name is 'test.a',
3798        // but we rename it as 'b', and use col 'b' in filter
3799        // we need rewrite filter col before push down.
3800        let table_scan = test_table_scan()?;
3801        let filter_value = vec![lit(1u32), lit(2u32), lit(3u32), lit(4u32)];
3802        let plan = LogicalPlanBuilder::from(table_scan)
3803            .project(vec![col("a").alias("b"), col("c")])?
3804            .filter(in_list(col("b"), filter_value, false))?
3805            .build()?;
3806
3807        // filter on col b
3808        assert_snapshot!(plan,
3809        @r"
3810        Filter: b IN ([UInt32(1), UInt32(2), UInt32(3), UInt32(4)])
3811          Projection: test.a AS b, test.c
3812            TableScan: test
3813        ",
3814        );
3815        // rewrite filter col b to test.a
3816        assert_optimized_plan_equal!(
3817            plan,
3818            @r"
3819        Projection: test.a AS b, test.c
3820          TableScan: test, full_filters=[test.a IN ([UInt32(1), UInt32(2), UInt32(3), UInt32(4)])]
3821        "
3822        )
3823    }
3824
3825    #[test]
3826    fn test_in_filter_with_alias_2() -> Result<()> {
3827        // in table scan the true col name is 'test.a',
3828        // but we rename it as 'b', and use col 'b' in filter
3829        // we need rewrite filter col before push down.
3830        let table_scan = test_table_scan()?;
3831        let filter_value = vec![lit(1u32), lit(2u32), lit(3u32), lit(4u32)];
3832        let plan = LogicalPlanBuilder::from(table_scan)
3833            .project(vec![col("a").alias("b"), col("c")])?
3834            .project(vec![col("b"), col("c")])?
3835            .filter(in_list(col("b"), filter_value, false))?
3836            .build()?;
3837
3838        // filter on col b
3839        assert_snapshot!(plan,
3840        @r"
3841        Filter: b IN ([UInt32(1), UInt32(2), UInt32(3), UInt32(4)])
3842          Projection: b, test.c
3843            Projection: test.a AS b, test.c
3844              TableScan: test
3845        ",
3846        );
3847        // rewrite filter col b to test.a
3848        assert_optimized_plan_equal!(
3849            plan,
3850            @r"
3851        Projection: b, test.c
3852          Projection: test.a AS b, test.c
3853            TableScan: test, full_filters=[test.a IN ([UInt32(1), UInt32(2), UInt32(3), UInt32(4)])]
3854        "
3855        )
3856    }
3857
3858    #[test]
3859    fn test_in_subquery_with_alias() -> Result<()> {
3860        // in table scan the true col name is 'test.a',
3861        // but we rename it as 'b', and use col 'b' in subquery filter
3862        let table_scan = test_table_scan()?;
3863        let table_scan_sq = test_table_scan_with_name("sq")?;
3864        let subplan = Arc::new(
3865            LogicalPlanBuilder::from(table_scan_sq)
3866                .project(vec![col("c")])?
3867                .build()?,
3868        );
3869        let plan = LogicalPlanBuilder::from(table_scan)
3870            .project(vec![col("a").alias("b"), col("c")])?
3871            .filter(in_subquery(col("b"), subplan))?
3872            .build()?;
3873
3874        // filter on col b in subquery
3875        assert_snapshot!(plan,
3876        @r"
3877        Filter: b IN (<subquery>)
3878          Subquery:
3879            Projection: sq.c
3880              TableScan: sq
3881          Projection: test.a AS b, test.c
3882            TableScan: test
3883        ",
3884        );
3885        // rewrite filter col b to test.a
3886        assert_optimized_plan_equal!(
3887            plan,
3888            @r"
3889        Projection: test.a AS b, test.c
3890          TableScan: test, full_filters=[test.a IN (<subquery>)]
3891            Subquery:
3892              Projection: sq.c
3893                TableScan: sq
3894        "
3895        )
3896    }
3897
3898    #[test]
3899    fn test_propagation_of_optimized_inner_filters_with_projections() -> Result<()> {
3900        // SELECT a FROM (SELECT 1 AS a) b WHERE b.a = 1
3901        let plan = LogicalPlanBuilder::empty(true)
3902            .project(vec![lit(0i64).alias("a")])?
3903            .alias("b")?
3904            .project(vec![col("b.a")])?
3905            .alias("b")?
3906            .filter(col("b.a").eq(lit(1i64)))?
3907            .project(vec![col("b.a")])?
3908            .build()?;
3909
3910        assert_snapshot!(plan,
3911        @r"
3912        Projection: b.a
3913          Filter: b.a = Int64(1)
3914            SubqueryAlias: b
3915              Projection: b.a
3916                SubqueryAlias: b
3917                  Projection: Int64(0) AS a
3918                    EmptyRelation: rows=1
3919        ",
3920        );
3921        // Ensure that the predicate without any columns (0 = 1) is
3922        // still there.
3923        assert_optimized_plan_equal!(
3924            plan,
3925            @r"
3926        Projection: b.a
3927          SubqueryAlias: b
3928            Projection: b.a
3929              SubqueryAlias: b
3930                Projection: Int64(0) AS a
3931                  Filter: Int64(0) = Int64(1)
3932                    EmptyRelation: rows=1
3933        "
3934        )
3935    }
3936
3937    #[test]
3938    fn test_crossjoin_with_or_clause() -> Result<()> {
3939        // select * from test,test1 where (test.a = test1.a and test.b > 1) or (test.b = test1.b and test.c < 10);
3940        let table_scan = test_table_scan()?;
3941        let left = LogicalPlanBuilder::from(table_scan)
3942            .project(vec![col("a"), col("b"), col("c")])?
3943            .build()?;
3944        let right_table_scan = test_table_scan_with_name("test1")?;
3945        let right = LogicalPlanBuilder::from(right_table_scan)
3946            .project(vec![col("a").alias("d"), col("a").alias("e")])?
3947            .build()?;
3948        let filter = or(
3949            and(col("a").eq(col("d")), col("b").gt(lit(1u32))),
3950            and(col("b").eq(col("e")), col("c").lt(lit(10u32))),
3951        );
3952        let plan = LogicalPlanBuilder::from(left)
3953            .cross_join(right)?
3954            .filter(filter)?
3955            .build()?;
3956
3957        assert_optimized_plan_eq_with_rewrite_predicate!(plan.clone(), @r"
3958        Inner Join:  Filter: test.a = d AND test.b > UInt32(1) OR test.b = e AND test.c < UInt32(10)
3959          Projection: test.a, test.b, test.c
3960            TableScan: test, full_filters=[test.b > UInt32(1) OR test.c < UInt32(10)]
3961          Projection: test1.a AS d, test1.a AS e
3962            TableScan: test1
3963        ")?;
3964
3965        // Originally global state which can help to avoid duplicate Filters been generated and pushed down.
3966        // Now the global state is removed. Need to double confirm that avoid duplicate Filters.
3967        let optimized_plan = PushDownFilter::new()
3968            .rewrite(plan, &OptimizerContext::new())
3969            .expect("failed to optimize plan")
3970            .data;
3971        assert_optimized_plan_equal!(
3972            optimized_plan,
3973            @r"
3974        Inner Join:  Filter: test.a = d AND test.b > UInt32(1) OR test.b = e AND test.c < UInt32(10)
3975          Projection: test.a, test.b, test.c
3976            TableScan: test, full_filters=[test.b > UInt32(1) OR test.c < UInt32(10)]
3977          Projection: test1.a AS d, test1.a AS e
3978            TableScan: test1
3979        "
3980        )
3981    }
3982
3983    #[test]
3984    fn left_semi_join() -> Result<()> {
3985        let left = test_table_scan_with_name("test1")?;
3986        let right_table_scan = test_table_scan_with_name("test2")?;
3987        let right = LogicalPlanBuilder::from(right_table_scan)
3988            .project(vec![col("a"), col("b")])?
3989            .build()?;
3990        let plan = LogicalPlanBuilder::from(left)
3991            .join(
3992                right,
3993                JoinType::LeftSemi,
3994                (
3995                    vec![Column::from_qualified_name("test1.a")],
3996                    vec![Column::from_qualified_name("test2.a")],
3997                ),
3998                None,
3999            )?
4000            .filter(col("test2.a").lt_eq(lit(1i64)))?
4001            .build()?;
4002
4003        // not part of the test, just good to know:
4004        assert_snapshot!(plan,
4005        @r"
4006        Filter: test2.a <= Int64(1)
4007          LeftSemi Join: test1.a = test2.a
4008            TableScan: test1
4009            Projection: test2.a, test2.b
4010              TableScan: test2
4011        ",
4012        );
4013        // Inferred the predicate `test1.a <= Int64(1)` and push it down to the left side.
4014        assert_optimized_plan_equal!(
4015            plan,
4016            @r"
4017        Filter: test2.a <= Int64(1)
4018          LeftSemi Join: test1.a = test2.a
4019            TableScan: test1, full_filters=[test1.a <= Int64(1)]
4020            Projection: test2.a, test2.b
4021              TableScan: test2
4022        "
4023        )
4024    }
4025
4026    #[test]
4027    fn left_semi_join_with_filters() -> Result<()> {
4028        let left = test_table_scan_with_name("test1")?;
4029        let right_table_scan = test_table_scan_with_name("test2")?;
4030        let right = LogicalPlanBuilder::from(right_table_scan)
4031            .project(vec![col("a"), col("b")])?
4032            .build()?;
4033        let plan = LogicalPlanBuilder::from(left)
4034            .join(
4035                right,
4036                JoinType::LeftSemi,
4037                (
4038                    vec![Column::from_qualified_name("test1.a")],
4039                    vec![Column::from_qualified_name("test2.a")],
4040                ),
4041                Some(
4042                    col("test1.b")
4043                        .gt(lit(1u32))
4044                        .and(col("test2.b").gt(lit(2u32))),
4045                ),
4046            )?
4047            .build()?;
4048
4049        // not part of the test, just good to know:
4050        assert_snapshot!(plan,
4051        @r"
4052        LeftSemi Join: test1.a = test2.a Filter: test1.b > UInt32(1) AND test2.b > UInt32(2)
4053          TableScan: test1
4054          Projection: test2.a, test2.b
4055            TableScan: test2
4056        ",
4057        );
4058        // Both side will be pushed down.
4059        assert_optimized_plan_equal!(
4060            plan,
4061            @r"
4062        LeftSemi Join: test1.a = test2.a
4063          TableScan: test1, full_filters=[test1.b > UInt32(1)]
4064          Projection: test2.a, test2.b
4065            TableScan: test2, full_filters=[test2.b > UInt32(2)]
4066        "
4067        )
4068    }
4069
4070    #[test]
4071    fn right_semi_join() -> Result<()> {
4072        let left = test_table_scan_with_name("test1")?;
4073        let right_table_scan = test_table_scan_with_name("test2")?;
4074        let right = LogicalPlanBuilder::from(right_table_scan)
4075            .project(vec![col("a"), col("b")])?
4076            .build()?;
4077        let plan = LogicalPlanBuilder::from(left)
4078            .join(
4079                right,
4080                JoinType::RightSemi,
4081                (
4082                    vec![Column::from_qualified_name("test1.a")],
4083                    vec![Column::from_qualified_name("test2.a")],
4084                ),
4085                None,
4086            )?
4087            .filter(col("test1.a").lt_eq(lit(1i64)))?
4088            .build()?;
4089
4090        // not part of the test, just good to know:
4091        assert_snapshot!(plan,
4092        @r"
4093        Filter: test1.a <= Int64(1)
4094          RightSemi Join: test1.a = test2.a
4095            TableScan: test1
4096            Projection: test2.a, test2.b
4097              TableScan: test2
4098        ",
4099        );
4100        // Inferred the predicate `test2.a <= Int64(1)` and push it down to the right side.
4101        assert_optimized_plan_equal!(
4102            plan,
4103            @r"
4104        Filter: test1.a <= Int64(1)
4105          RightSemi Join: test1.a = test2.a
4106            TableScan: test1
4107            Projection: test2.a, test2.b
4108              TableScan: test2, full_filters=[test2.a <= Int64(1)]
4109        "
4110        )
4111    }
4112
4113    #[test]
4114    fn right_semi_join_with_filters() -> Result<()> {
4115        let left = test_table_scan_with_name("test1")?;
4116        let right_table_scan = test_table_scan_with_name("test2")?;
4117        let right = LogicalPlanBuilder::from(right_table_scan)
4118            .project(vec![col("a"), col("b")])?
4119            .build()?;
4120        let plan = LogicalPlanBuilder::from(left)
4121            .join(
4122                right,
4123                JoinType::RightSemi,
4124                (
4125                    vec![Column::from_qualified_name("test1.a")],
4126                    vec![Column::from_qualified_name("test2.a")],
4127                ),
4128                Some(
4129                    col("test1.b")
4130                        .gt(lit(1u32))
4131                        .and(col("test2.b").gt(lit(2u32))),
4132                ),
4133            )?
4134            .build()?;
4135
4136        // not part of the test, just good to know:
4137        assert_snapshot!(plan,
4138        @r"
4139        RightSemi Join: test1.a = test2.a Filter: test1.b > UInt32(1) AND test2.b > UInt32(2)
4140          TableScan: test1
4141          Projection: test2.a, test2.b
4142            TableScan: test2
4143        ",
4144        );
4145        // Both side will be pushed down.
4146        assert_optimized_plan_equal!(
4147            plan,
4148            @r"
4149        RightSemi Join: test1.a = test2.a
4150          TableScan: test1, full_filters=[test1.b > UInt32(1)]
4151          Projection: test2.a, test2.b
4152            TableScan: test2, full_filters=[test2.b > UInt32(2)]
4153        "
4154        )
4155    }
4156
4157    #[test]
4158    fn left_anti_join() -> Result<()> {
4159        let table_scan = test_table_scan_with_name("test1")?;
4160        let left = LogicalPlanBuilder::from(table_scan)
4161            .project(vec![col("a"), col("b")])?
4162            .build()?;
4163        let right_table_scan = test_table_scan_with_name("test2")?;
4164        let right = LogicalPlanBuilder::from(right_table_scan)
4165            .project(vec![col("a"), col("b")])?
4166            .build()?;
4167        let plan = LogicalPlanBuilder::from(left)
4168            .join(
4169                right,
4170                JoinType::LeftAnti,
4171                (
4172                    vec![Column::from_qualified_name("test1.a")],
4173                    vec![Column::from_qualified_name("test2.a")],
4174                ),
4175                None,
4176            )?
4177            .filter(col("test2.a").gt(lit(2u32)))?
4178            .build()?;
4179
4180        // not part of the test, just good to know:
4181        assert_snapshot!(plan,
4182        @r"
4183        Filter: test2.a > UInt32(2)
4184          LeftAnti Join: test1.a = test2.a
4185            Projection: test1.a, test1.b
4186              TableScan: test1
4187            Projection: test2.a, test2.b
4188              TableScan: test2
4189        ",
4190        );
4191        // For left anti, filter of the right side filter can be pushed down.
4192        assert_optimized_plan_equal!(
4193            plan,
4194            @r"
4195        Filter: test2.a > UInt32(2)
4196          LeftAnti Join: test1.a = test2.a
4197            Projection: test1.a, test1.b
4198              TableScan: test1, full_filters=[test1.a > UInt32(2)]
4199            Projection: test2.a, test2.b
4200              TableScan: test2
4201        "
4202        )
4203    }
4204
4205    /// Regression test: for a null-aware LeftAnti join (the shape produced by
4206    /// `NOT IN` with a nullable subquery), a right-side predicate must NOT be
4207    /// inferred onto the join. Inference would push a null-rejecting predicate
4208    /// to the subquery side, dropping its NULL rows and breaking the
4209    /// three-valued `NOT IN` semantics.
4210    #[test]
4211    fn null_aware_left_anti_join_no_inferred_pushdown() -> Result<()> {
4212        let table_scan = test_table_scan_with_name("test1")?;
4213        let left = LogicalPlanBuilder::from(table_scan)
4214            .project(vec![col("a"), col("b")])?
4215            .build()?;
4216        let right_table_scan = test_table_scan_with_name("test2")?;
4217        let right = LogicalPlanBuilder::from(right_table_scan)
4218            .project(vec![col("a"), col("b")])?
4219            .build()?;
4220        let plan = LogicalPlanBuilder::from(left)
4221            .join_detailed_with_options(
4222                right,
4223                JoinType::LeftAnti,
4224                (
4225                    vec![Column::from_qualified_name("test1.a")],
4226                    vec![Column::from_qualified_name("test2.a")],
4227                ),
4228                None,
4229                datafusion_common::NullEquality::NullEqualsNothing,
4230                true,
4231            )?
4232            .filter(col("test1.a").gt(lit(2u32)))?
4233            .build()?;
4234
4235        // The left-side filter is pushed to the left input, but — unlike the
4236        // non-null-aware `left_anti_join` test — no `test2.a > 2` predicate is
4237        // inferred onto the right/subquery side.
4238        assert_optimized_plan_equal!(
4239            plan,
4240            @r"
4241        LeftAnti Join: test1.a = test2.a null_aware
4242          Projection: test1.a, test1.b
4243            TableScan: test1, full_filters=[test1.a > UInt32(2)]
4244          Projection: test2.a, test2.b
4245            TableScan: test2
4246        "
4247        )
4248    }
4249
4250    /// Regression test for a null-aware LeftAnti join whose join filter only
4251    /// references the subquery side, the shape produced by
4252    /// `<constant> NOT IN (<subquery>)`. Pushing that filter into the right
4253    /// input would drop the subquery's NULL rows before the join can observe
4254    /// them, so `NOT IN` would wrongly evaluate to TRUE instead of UNKNOWN.
4255    #[test]
4256    fn null_aware_left_anti_join_keeps_right_only_join_filter() -> Result<()> {
4257        let table_scan = test_table_scan_with_name("test1")?;
4258        let left = LogicalPlanBuilder::from(table_scan)
4259            .project(vec![col("a"), col("b")])?
4260            .build()?;
4261        let right_table_scan = test_table_scan_with_name("test2")?;
4262        let right = LogicalPlanBuilder::from(right_table_scan)
4263            .project(vec![col("a"), col("b")])?
4264            .build()?;
4265        let plan = LogicalPlanBuilder::from(left)
4266            .join_detailed_with_options(
4267                right,
4268                JoinType::LeftAnti,
4269                (Vec::<Column>::new(), Vec::<Column>::new()),
4270                Some(lit(3u32).eq(col("test2.a"))),
4271                datafusion_common::NullEquality::NullEqualsNothing,
4272                true,
4273            )?
4274            .build()?;
4275
4276        // `UInt32(3) = test2.a` stays on the join: it must not become a
4277        // `TableScan: test2, full_filters=[...]`.
4278        assert_optimized_plan_equal!(
4279            plan,
4280            @r"
4281        LeftAnti Join:  Filter: UInt32(3) = test2.a null_aware
4282          Projection: test1.a, test1.b
4283            TableScan: test1
4284          Projection: test2.a, test2.b
4285            TableScan: test2
4286        "
4287        )
4288    }
4289
4290    #[test]
4291    fn left_anti_join_with_filters() -> Result<()> {
4292        let table_scan = test_table_scan_with_name("test1")?;
4293        let left = LogicalPlanBuilder::from(table_scan)
4294            .project(vec![col("a"), col("b")])?
4295            .build()?;
4296        let right_table_scan = test_table_scan_with_name("test2")?;
4297        let right = LogicalPlanBuilder::from(right_table_scan)
4298            .project(vec![col("a"), col("b")])?
4299            .build()?;
4300        let plan = LogicalPlanBuilder::from(left)
4301            .join(
4302                right,
4303                JoinType::LeftAnti,
4304                (
4305                    vec![Column::from_qualified_name("test1.a")],
4306                    vec![Column::from_qualified_name("test2.a")],
4307                ),
4308                Some(
4309                    col("test1.b")
4310                        .gt(lit(1u32))
4311                        .and(col("test2.b").gt(lit(2u32))),
4312                ),
4313            )?
4314            .build()?;
4315
4316        // not part of the test, just good to know:
4317        assert_snapshot!(plan,
4318        @r"
4319        LeftAnti Join: test1.a = test2.a Filter: test1.b > UInt32(1) AND test2.b > UInt32(2)
4320          Projection: test1.a, test1.b
4321            TableScan: test1
4322          Projection: test2.a, test2.b
4323            TableScan: test2
4324        ",
4325        );
4326        // For left anti, filter of the right side filter can be pushed down.
4327        assert_optimized_plan_equal!(
4328            plan,
4329            @r"
4330        LeftAnti Join: test1.a = test2.a Filter: test1.b > UInt32(1)
4331          Projection: test1.a, test1.b
4332            TableScan: test1
4333          Projection: test2.a, test2.b
4334            TableScan: test2, full_filters=[test2.b > UInt32(2)]
4335        "
4336        )
4337    }
4338
4339    #[test]
4340    fn right_anti_join() -> Result<()> {
4341        let table_scan = test_table_scan_with_name("test1")?;
4342        let left = LogicalPlanBuilder::from(table_scan)
4343            .project(vec![col("a"), col("b")])?
4344            .build()?;
4345        let right_table_scan = test_table_scan_with_name("test2")?;
4346        let right = LogicalPlanBuilder::from(right_table_scan)
4347            .project(vec![col("a"), col("b")])?
4348            .build()?;
4349        let plan = LogicalPlanBuilder::from(left)
4350            .join(
4351                right,
4352                JoinType::RightAnti,
4353                (
4354                    vec![Column::from_qualified_name("test1.a")],
4355                    vec![Column::from_qualified_name("test2.a")],
4356                ),
4357                None,
4358            )?
4359            .filter(col("test1.a").gt(lit(2u32)))?
4360            .build()?;
4361
4362        // not part of the test, just good to know:
4363        assert_snapshot!(plan,
4364        @r"
4365        Filter: test1.a > UInt32(2)
4366          RightAnti Join: test1.a = test2.a
4367            Projection: test1.a, test1.b
4368              TableScan: test1
4369            Projection: test2.a, test2.b
4370              TableScan: test2
4371        ",
4372        );
4373        // For right anti, filter of the left side can be pushed down.
4374        assert_optimized_plan_equal!(
4375            plan,
4376            @r"
4377        Filter: test1.a > UInt32(2)
4378          RightAnti Join: test1.a = test2.a
4379            Projection: test1.a, test1.b
4380              TableScan: test1
4381            Projection: test2.a, test2.b
4382              TableScan: test2, full_filters=[test2.a > UInt32(2)]
4383        "
4384        )
4385    }
4386
4387    #[test]
4388    fn right_anti_join_with_filters() -> Result<()> {
4389        let table_scan = test_table_scan_with_name("test1")?;
4390        let left = LogicalPlanBuilder::from(table_scan)
4391            .project(vec![col("a"), col("b")])?
4392            .build()?;
4393        let right_table_scan = test_table_scan_with_name("test2")?;
4394        let right = LogicalPlanBuilder::from(right_table_scan)
4395            .project(vec![col("a"), col("b")])?
4396            .build()?;
4397        let plan = LogicalPlanBuilder::from(left)
4398            .join(
4399                right,
4400                JoinType::RightAnti,
4401                (
4402                    vec![Column::from_qualified_name("test1.a")],
4403                    vec![Column::from_qualified_name("test2.a")],
4404                ),
4405                Some(
4406                    col("test1.b")
4407                        .gt(lit(1u32))
4408                        .and(col("test2.b").gt(lit(2u32))),
4409                ),
4410            )?
4411            .build()?;
4412
4413        // not part of the test, just good to know:
4414        assert_snapshot!(plan,
4415        @r"
4416        RightAnti Join: test1.a = test2.a Filter: test1.b > UInt32(1) AND test2.b > UInt32(2)
4417          Projection: test1.a, test1.b
4418            TableScan: test1
4419          Projection: test2.a, test2.b
4420            TableScan: test2
4421        ",
4422        );
4423        // For right anti, filter of the left side can be pushed down.
4424        assert_optimized_plan_equal!(
4425            plan,
4426            @r"
4427        RightAnti Join: test1.a = test2.a Filter: test2.b > UInt32(2)
4428          Projection: test1.a, test1.b
4429            TableScan: test1, full_filters=[test1.b > UInt32(1)]
4430          Projection: test2.a, test2.b
4431            TableScan: test2
4432        "
4433        )
4434    }
4435
4436    #[derive(Debug, PartialEq, Eq, Hash)]
4437    struct TestScalarUDF {
4438        signature: Signature,
4439    }
4440
4441    impl ScalarUDFImpl for TestScalarUDF {
4442        fn name(&self) -> &str {
4443            "TestScalarUDF"
4444        }
4445
4446        fn signature(&self) -> &Signature {
4447            &self.signature
4448        }
4449
4450        fn return_type(&self, _arg_types: &[DataType]) -> Result<DataType> {
4451            Ok(DataType::Int32)
4452        }
4453
4454        fn invoke_with_args(&self, _args: ScalarFunctionArgs) -> Result<ColumnarValue> {
4455            Ok(ColumnarValue::Scalar(ScalarValue::from(1)))
4456        }
4457    }
4458
4459    #[test]
4460    fn test_push_down_volatile_function_in_aggregate() -> Result<()> {
4461        // SELECT t.a, t.r FROM (SELECT a, sum(b),  TestScalarUDF()+1 AS r FROM test1 GROUP BY a) AS t WHERE t.a > 5 AND t.r > 0.5;
4462        let table_scan = test_table_scan_with_name("test1")?;
4463        let fun = ScalarUDF::new_from_impl(TestScalarUDF {
4464            signature: Signature::exact(vec![], Volatility::Volatile),
4465        });
4466        let expr = Expr::ScalarFunction(ScalarFunction::new_udf(Arc::new(fun), vec![]));
4467
4468        let plan = LogicalPlanBuilder::from(table_scan)
4469            .aggregate(vec![col("a")], vec![sum(col("b"))])?
4470            .project(vec![col("a"), sum(col("b")), add(expr, lit(1)).alias("r")])?
4471            .alias("t")?
4472            .filter(col("t.a").gt(lit(5)).and(col("t.r").gt(lit(0.5))))?
4473            .project(vec![col("t.a"), col("t.r")])?
4474            .build()?;
4475
4476        assert_snapshot!(plan,
4477        @r"
4478        Projection: t.a, t.r
4479          Filter: t.a > Int32(5) AND t.r > Float64(0.5)
4480            SubqueryAlias: t
4481              Projection: test1.a, sum(test1.b), TestScalarUDF() + Int32(1) AS r
4482                Aggregate: groupBy=[[test1.a]], aggr=[[sum(test1.b)]]
4483                  TableScan: test1
4484        ",
4485        );
4486        assert_optimized_plan_equal!(
4487            plan,
4488            @r"
4489        Projection: t.a, t.r
4490          SubqueryAlias: t
4491            Filter: r > Float64(0.5)
4492              Projection: test1.a, sum(test1.b), TestScalarUDF() + Int32(1) AS r
4493                Aggregate: groupBy=[[test1.a]], aggr=[[sum(test1.b)]]
4494                  TableScan: test1, full_filters=[test1.a > Int32(5)]
4495        "
4496        )
4497    }
4498
4499    #[test]
4500    fn test_filter_on_volatile_group_key_not_pushed_below_aggregate() -> Result<()> {
4501        // SELECT r, sum(b) FROM test1 GROUP BY a, TestScalarUDF() + 1 AS r HAVING a > 5 AND r > 0.5
4502        let table_scan = test_table_scan_with_name("test1")?;
4503        let fun = ScalarUDF::new_from_impl(TestScalarUDF {
4504            signature: Signature::exact(vec![], Volatility::Volatile),
4505        });
4506        let expr = Expr::ScalarFunction(ScalarFunction::new_udf(Arc::new(fun), vec![]));
4507
4508        let plan = LogicalPlanBuilder::from(table_scan)
4509            .aggregate(
4510                vec![col("a"), add(expr, lit(1)).alias("r")],
4511                vec![sum(col("b"))],
4512            )?
4513            .filter(col("a").gt(lit(5)).and(col("r").gt(lit(0.5))))?
4514            .build()?;
4515
4516        // `a > 5` is pushed below the aggregate, `r > 0.5` must stay above it
4517        assert_optimized_plan_equal!(
4518            plan,
4519            @r"
4520        Filter: r > Float64(0.5)
4521          Aggregate: groupBy=[[test1.a, TestScalarUDF() + Int32(1) AS r]], aggr=[[sum(test1.b)]]
4522            TableScan: test1, full_filters=[test1.a > Int32(5)]
4523        "
4524        )
4525    }
4526
4527    #[test]
4528    fn test_push_down_volatile_function_in_join() -> Result<()> {
4529        // SELECT t.a, t.r FROM (SELECT test1.a AS a, TestScalarUDF() AS r FROM test1 join test2 ON test1.a = test2.a) AS t WHERE t.r > 0.5;
4530        let table_scan = test_table_scan_with_name("test1")?;
4531        let fun = ScalarUDF::new_from_impl(TestScalarUDF {
4532            signature: Signature::exact(vec![], Volatility::Volatile),
4533        });
4534        let expr = Expr::ScalarFunction(ScalarFunction::new_udf(Arc::new(fun), vec![]));
4535        let left = LogicalPlanBuilder::from(table_scan).build()?;
4536        let right_table_scan = test_table_scan_with_name("test2")?;
4537        let right = LogicalPlanBuilder::from(right_table_scan).build()?;
4538        let plan = LogicalPlanBuilder::from(left)
4539            .join(
4540                right,
4541                JoinType::Inner,
4542                (
4543                    vec![Column::from_qualified_name("test1.a")],
4544                    vec![Column::from_qualified_name("test2.a")],
4545                ),
4546                None,
4547            )?
4548            .project(vec![col("test1.a").alias("a"), expr.alias("r")])?
4549            .alias("t")?
4550            .filter(col("t.r").gt(lit(0.8)))?
4551            .project(vec![col("t.a"), col("t.r")])?
4552            .build()?;
4553
4554        assert_snapshot!(plan,
4555        @r"
4556        Projection: t.a, t.r
4557          Filter: t.r > Float64(0.8)
4558            SubqueryAlias: t
4559              Projection: test1.a AS a, TestScalarUDF() AS r
4560                Inner Join: test1.a = test2.a
4561                  TableScan: test1
4562                  TableScan: test2
4563        ",
4564        );
4565        assert_optimized_plan_equal!(
4566            plan,
4567            @r"
4568        Projection: t.a, t.r
4569          SubqueryAlias: t
4570            Filter: r > Float64(0.8)
4571              Projection: test1.a AS a, TestScalarUDF() AS r
4572                Inner Join: test1.a = test2.a
4573                  TableScan: test1
4574                  TableScan: test2
4575        "
4576        )
4577    }
4578
4579    #[test]
4580    fn test_push_down_volatile_table_scan() -> Result<()> {
4581        // SELECT test.a, test.b FROM test as t WHERE TestScalarUDF() > 0.1;
4582        let table_scan = test_table_scan()?;
4583        let fun = ScalarUDF::new_from_impl(TestScalarUDF {
4584            signature: Signature::exact(vec![], Volatility::Volatile),
4585        });
4586        let expr = Expr::ScalarFunction(ScalarFunction::new_udf(Arc::new(fun), vec![]));
4587        let plan = LogicalPlanBuilder::from(table_scan)
4588            .project(vec![col("a"), col("b")])?
4589            .filter(expr.gt(lit(0.1)))?
4590            .build()?;
4591
4592        assert_snapshot!(plan,
4593        @r"
4594        Filter: TestScalarUDF() > Float64(0.1)
4595          Projection: test.a, test.b
4596            TableScan: test
4597        ",
4598        );
4599        assert_optimized_plan_equal!(
4600            plan,
4601            @r"
4602        Projection: test.a, test.b
4603          Filter: TestScalarUDF() > Float64(0.1)
4604            TableScan: test
4605        "
4606        )
4607    }
4608
4609    #[test]
4610    fn test_push_down_volatile_mixed_table_scan() -> Result<()> {
4611        // SELECT test.a, test.b FROM test as t WHERE TestScalarUDF() > 0.1 and test.a > 5 and test.b > 10;
4612        let table_scan = test_table_scan()?;
4613        let fun = ScalarUDF::new_from_impl(TestScalarUDF {
4614            signature: Signature::exact(vec![], Volatility::Volatile),
4615        });
4616        let expr = Expr::ScalarFunction(ScalarFunction::new_udf(Arc::new(fun), vec![]));
4617        let plan = LogicalPlanBuilder::from(table_scan)
4618            .project(vec![col("a"), col("b")])?
4619            .filter(
4620                expr.gt(lit(0.1))
4621                    .and(col("t.a").gt(lit(5)))
4622                    .and(col("t.b").gt(lit(10))),
4623            )?
4624            .build()?;
4625
4626        assert_snapshot!(plan,
4627        @r"
4628        Filter: TestScalarUDF() > Float64(0.1) AND t.a > Int32(5) AND t.b > Int32(10)
4629          Projection: test.a, test.b
4630            TableScan: test
4631        ",
4632        );
4633        assert_optimized_plan_equal!(
4634            plan,
4635            @r"
4636        Projection: test.a, test.b
4637          Filter: TestScalarUDF() > Float64(0.1)
4638            TableScan: test, full_filters=[t.a > Int32(5), t.b > Int32(10)]
4639        "
4640        )
4641    }
4642
4643    #[test]
4644    fn test_push_down_volatile_mixed_unsupported_table_scan() -> Result<()> {
4645        // SELECT test.a, test.b FROM test as t WHERE TestScalarUDF() > 0.1 and test.a > 5 and test.b > 10;
4646        let fun = ScalarUDF::new_from_impl(TestScalarUDF {
4647            signature: Signature::exact(vec![], Volatility::Volatile),
4648        });
4649        let expr = Expr::ScalarFunction(ScalarFunction::new_udf(Arc::new(fun), vec![]));
4650        let plan = table_scan_with_pushdown_provider_builder(
4651            TableProviderFilterPushDown::Unsupported,
4652            vec![],
4653            None,
4654        )?
4655        .project(vec![col("a"), col("b")])?
4656        .filter(
4657            expr.gt(lit(0.1))
4658                .and(col("t.a").gt(lit(5)))
4659                .and(col("t.b").gt(lit(10))),
4660        )?
4661        .build()?;
4662
4663        assert_snapshot!(plan,
4664        @r"
4665        Filter: TestScalarUDF() > Float64(0.1) AND t.a > Int32(5) AND t.b > Int32(10)
4666          Projection: a, b
4667            TableScan: test
4668        ",
4669        );
4670        assert_optimized_plan_equal!(
4671            plan,
4672            @r"
4673        Projection: a, b
4674          Filter: TestScalarUDF() > Float64(0.1) AND t.a > Int32(5) AND t.b > Int32(10)
4675            TableScan: test
4676        "
4677        )
4678    }
4679
4680    #[test]
4681    fn test_push_down_filter_to_user_defined_node() -> Result<()> {
4682        // Define a custom user-defined logical node
4683        #[derive(Debug, Hash, Eq, PartialEq)]
4684        struct TestUserNode {
4685            schema: DFSchemaRef,
4686        }
4687
4688        impl PartialOrd for TestUserNode {
4689            fn partial_cmp(&self, _other: &Self) -> Option<Ordering> {
4690                None
4691            }
4692        }
4693
4694        impl TestUserNode {
4695            fn new() -> Self {
4696                let schema = Arc::new(
4697                    DFSchema::new_with_metadata(
4698                        vec![(None, Field::new("a", DataType::Int64, false).into())],
4699                        Metadata::new(),
4700                    )
4701                    .unwrap(),
4702                );
4703
4704                Self { schema }
4705            }
4706        }
4707
4708        impl UserDefinedLogicalNodeCore for TestUserNode {
4709            fn name(&self) -> &str {
4710                "test_node"
4711            }
4712
4713            fn inputs(&self) -> Vec<&LogicalPlan> {
4714                vec![]
4715            }
4716
4717            fn schema(&self) -> &DFSchemaRef {
4718                &self.schema
4719            }
4720
4721            fn expressions(&self) -> Vec<Expr> {
4722                vec![]
4723            }
4724
4725            fn fmt_for_explain(&self, f: &mut Formatter) -> std::fmt::Result {
4726                write!(f, "TestUserNode")
4727            }
4728
4729            fn with_exprs_and_inputs(
4730                &self,
4731                exprs: Vec<Expr>,
4732                inputs: Vec<LogicalPlan>,
4733            ) -> Result<Self> {
4734                assert!(exprs.is_empty());
4735                assert!(inputs.is_empty());
4736                Ok(Self {
4737                    schema: Arc::clone(&self.schema),
4738                })
4739            }
4740        }
4741
4742        // Create a node and build a plan with a filter
4743        let node = LogicalPlan::Extension(Extension {
4744            node: Arc::new(TestUserNode::new()),
4745        });
4746
4747        let plan = LogicalPlanBuilder::from(node).filter(lit(false))?.build()?;
4748
4749        // Check the original plan format (not part of the test assertions)
4750        assert_snapshot!(plan,
4751        @r"
4752        Filter: Boolean(false)
4753          TestUserNode
4754        ",
4755        );
4756        // An impossible filter eliminates even a leaf extension before pushdown.
4757        assert_optimized_plan_equal!(plan, @"EmptyRelation: rows=0")
4758    }
4759
4760    /// Test that filters are NOT pushed through MoveTowardsLeafNodes projections.
4761    /// These are cheap expressions (like get_field) where re-inlining into a filter
4762    /// has no benefit and causes optimizer instability — ExtractLeafExpressions will
4763    /// undo the push-down, creating an infinite loop that runs until the iteration
4764    /// limit is hit.
4765    #[test]
4766    fn filter_not_pushed_through_move_towards_leaves_projection() -> Result<()> {
4767        let table_scan = test_table_scan()?;
4768
4769        // Create a projection with a MoveTowardsLeafNodes expression
4770        let proj = LogicalPlanBuilder::from(table_scan)
4771            .project(vec![
4772                leaf_udf_expr(col("a")).alias("val"),
4773                col("b"),
4774                col("c"),
4775            ])?
4776            .build()?;
4777
4778        // Put a filter on the MoveTowardsLeafNodes column
4779        let plan = LogicalPlanBuilder::from(proj)
4780            .filter(col("val").gt(lit(150i64)))?
4781            .build()?;
4782
4783        // Filter should NOT be pushed through — val maps to a MoveTowardsLeafNodes expr
4784        assert_optimized_plan_equal!(
4785            plan,
4786            @r"
4787        Filter: val > Int64(150)
4788          Projection: leaf_udf(test.a) AS val, test.b, test.c
4789            TableScan: test
4790        "
4791        )
4792    }
4793
4794    /// Test mixed predicates: Column predicate pushed, MoveTowardsLeafNodes kept.
4795    #[test]
4796    fn filter_mixed_predicates_partial_push() -> Result<()> {
4797        let table_scan = test_table_scan()?;
4798
4799        // Create a projection with both MoveTowardsLeafNodes and Column expressions
4800        let proj = LogicalPlanBuilder::from(table_scan)
4801            .project(vec![
4802                leaf_udf_expr(col("a")).alias("val"),
4803                col("b"),
4804                col("c"),
4805            ])?
4806            .build()?;
4807
4808        // Filter with both: val > 150 (MoveTowardsLeafNodes) AND b > 5 (Column)
4809        let plan = LogicalPlanBuilder::from(proj)
4810            .filter(col("val").gt(lit(150i64)).and(col("b").gt(lit(5i64))))?
4811            .build()?;
4812
4813        // val > 150 should be kept above, b > 5 should be pushed through
4814        assert_optimized_plan_equal!(
4815            plan,
4816            @r"
4817        Filter: val > Int64(150)
4818          Projection: leaf_udf(test.a) AS val, test.b, test.c
4819            TableScan: test, full_filters=[test.b > Int64(5)]
4820        "
4821        )
4822    }
4823
4824    /// A filter is not moved below a pure extraction projection, even when its
4825    /// predicate only references pass-through columns.
4826    ///
4827    /// `PushDownLeafProjections` moves such a projection back below the filter,
4828    /// so pushing here would make the two rules undo each other on every
4829    /// optimizer pass. See <https://github.com/apache/datafusion/issues/14540>
4830    /// and the module documentation.
4831    #[test]
4832    fn filter_not_pushed_through_pure_extraction_projection() -> Result<()> {
4833        let table_scan = test_table_scan()?;
4834
4835        // The shape `ExtractLeafExpressions` produces: one extraction alias
4836        // plus pass-through columns.
4837        let proj = LogicalPlanBuilder::from(table_scan)
4838            .project(vec![
4839                leaf_udf_expr(col("a")).alias("__datafusion_extracted_1"),
4840                col("b"),
4841                col("c"),
4842            ])?
4843            .build()?;
4844
4845        // `b` is a plain pass-through column, so without the precedence rule
4846        // this predicate would reach the scan as a `full_filters` entry.
4847        let plan = LogicalPlanBuilder::from(proj)
4848            .filter(col("b").gt(lit(5i64)))?
4849            .build()?;
4850
4851        assert_optimized_plan_equal!(
4852            plan,
4853            @r"
4854        Filter: test.b > Int64(5)
4855          Projection: leaf_udf(test.a) AS __datafusion_extracted_1, test.b, test.c
4856            TableScan: test
4857        "
4858        )
4859    }
4860
4861    /// Runs the default optimizer and returns, for each pass, the names of the
4862    /// rules that changed the plan in that pass.
4863    fn rules_that_changed_plan_per_pass(plan: LogicalPlan) -> Result<Vec<Vec<String>>> {
4864        let optimizer = Optimizer::new();
4865        let rules_per_pass = optimizer.rules.len();
4866        let mut previous = plan.display_indent().to_string();
4867        let mut calls = 0;
4868        let mut passes: Vec<Vec<String>> = vec![];
4869        optimizer.optimize(plan, &OptimizerContext::new(), |plan, rule| {
4870            if calls % rules_per_pass == 0 {
4871                passes.push(vec![]);
4872            }
4873            calls += 1;
4874            let current = plan.display_indent().to_string();
4875            if current != previous {
4876                passes.last_mut().unwrap().push(rule.name().to_string());
4877                previous = current;
4878            }
4879        })?;
4880        Ok(passes)
4881    }
4882
4883    /// `PushDownFilter` and `PushDownLeafProjections` must not undo each other
4884    /// for a filter next to a pure extraction projection
4885    /// (<https://github.com/apache/datafusion/issues/14540>). The source does
4886    /// not absorb filters, so the `Filter` node stays in the plan. Also,
4887    /// `PushDownLeafProjections` must not split a projection that
4888    /// `OptimizeProjections` merges back. No rule may change the plan in the
4889    /// last optimizer pass.
4890    #[test]
4891    fn filter_and_extraction_projection_reach_fixed_point() -> Result<()> {
4892        let scan = || {
4893            table_scan_with_pushdown_provider_builder(
4894                TableProviderFilterPushDown::Unsupported,
4895                vec![],
4896                None,
4897            )
4898        };
4899        let simple = scan()?
4900            .filter(col("b").gt(lit(5)))?
4901            .project(vec![leaf_udf_expr(col("a"))])?
4902            .build()?;
4903        // Two filters, one of them on an extracted leaf.
4904        let two_filters = scan()?
4905            .filter(col("b").gt(lit(5)))?
4906            .filter(leaf_udf_expr(col("a")).eq(lit(1)))?
4907            .project(vec![leaf_udf_expr(col("a")), col("b")])?
4908            .build()?;
4909
4910        // No filter: the extraction projection cannot move below the scan.
4911        let no_filter = LogicalPlanBuilder::from(test_table_scan()?)
4912            .project(vec![leaf_udf_expr(col("a"))])?
4913            .build()?;
4914
4915        // Leaf expression above an Aggregate: the Aggregate blocks movement.
4916        let above_aggregate = LogicalPlanBuilder::from(test_table_scan_with_struct()?)
4917            .aggregate(vec![col("user")], vec![count(lit(1))])?
4918            .project(vec![
4919                leaf_udf_expr(col("user")).is_not_null().alias("has_name"),
4920                col("COUNT(Int32(1))"),
4921            ])?
4922            .build()?;
4923
4924        for plan in [simple, two_filters, no_filter, above_aggregate] {
4925            let passes = rules_that_changed_plan_per_pass(plan)?;
4926            let last = passes.last().unwrap();
4927            assert!(
4928                last.is_empty(),
4929                "rules changed the plan in the last pass: {passes:?}"
4930            );
4931        }
4932        Ok(())
4933    }
4934
4935    /// A projection that mixes an extraction alias with a computed expression is
4936    /// not a pure extraction projection, so the filter still moves below it.
4937    #[test]
4938    fn filter_pushed_through_mixed_extraction_projection() -> Result<()> {
4939        let table_scan = test_table_scan()?;
4940
4941        let proj = LogicalPlanBuilder::from(table_scan)
4942            .project(vec![
4943                leaf_udf_expr(col("a")).alias("__datafusion_extracted_1"),
4944                (col("b") + lit(1i64)).alias("b_plus"),
4945                col("c"),
4946            ])?
4947            .build()?;
4948
4949        let plan = LogicalPlanBuilder::from(proj)
4950            .filter(col("c").gt(lit(5i64)))?
4951            .build()?;
4952
4953        assert_optimized_plan_equal!(
4954            plan,
4955            @r"
4956        Projection: leaf_udf(test.a) AS __datafusion_extracted_1, test.b + Int64(1) AS b_plus, test.c
4957          TableScan: test, full_filters=[test.c > Int64(5)]
4958        "
4959        )
4960    }
4961
4962    #[test]
4963    fn filter_not_pushed_down_through_table_scan_with_fetch() -> Result<()> {
4964        let scan = test_table_scan()?;
4965        let scan_with_fetch = match scan {
4966            LogicalPlan::TableScan(scan) => LogicalPlan::TableScan(TableScan {
4967                fetch: Some(10),
4968                ..scan
4969            }),
4970            _ => unreachable!(),
4971        };
4972        let plan = LogicalPlanBuilder::from(scan_with_fetch)
4973            .filter(col("a").gt(lit(10i64)))?
4974            .build()?;
4975        // Filter must NOT be pushed into the table scan when it has a fetch (limit)
4976        assert_optimized_plan_equal!(
4977            plan,
4978            @r"
4979        Filter: test.a > Int64(10)
4980          TableScan: test, fetch=10
4981        "
4982        )
4983    }
4984
4985    #[test]
4986    fn filter_push_down_through_sort_without_fetch() -> Result<()> {
4987        let table_scan = test_table_scan()?;
4988        let plan = LogicalPlanBuilder::from(table_scan)
4989            .sort(vec![col("a").sort(true, true)])?
4990            .filter(col("a").gt(lit(10i64)))?
4991            .build()?;
4992        // Filter should be pushed below the sort
4993        assert_optimized_plan_equal!(
4994            plan,
4995            @r"
4996        Sort: test.a ASC NULLS FIRST
4997          TableScan: test, full_filters=[test.a > Int64(10)]
4998        "
4999        )
5000    }
5001
5002    #[test]
5003    fn filter_not_pushed_down_through_sort_with_fetch() -> Result<()> {
5004        let table_scan = test_table_scan()?;
5005        let plan = LogicalPlanBuilder::from(table_scan)
5006            .sort_with_limit(vec![col("a").sort(true, true)], Some(5))?
5007            .filter(col("a").gt(lit(10i64)))?
5008            .build()?;
5009        // Filter must NOT be pushed below the sort when it has a fetch (limit),
5010        // because the limit should apply before the filter.
5011        assert_optimized_plan_equal!(
5012            plan,
5013            @r"
5014        Filter: test.a > Int64(10)
5015          Sort: test.a ASC NULLS FIRST, fetch=5
5016            TableScan: test
5017        "
5018        )
5019    }
5020}