Skip to main content

datafusion_optimizer/
eliminate_outer_join.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//! [`EliminateOuterJoin`] rewrites outer joins to simpler join types when
6//! filters make the outer rows unnecessary (e.g. `LEFT`/`RIGHT` to `INNER`,
7//! and `FULL` to `LEFT`/`RIGHT`/`INNER`).
8use crate::push_down_filter::replace_cols_by_name;
9use crate::{OptimizerConfig, OptimizerRule};
10use datafusion_common::{Column, DFSchema, Result, qualified_name};
11use datafusion_expr::logical_plan::{Join, JoinType, LogicalPlan, Projection};
12use datafusion_expr::{Expr, Filter, Operator};
13
14use crate::optimizer::ApplyOrder;
15use datafusion_common::tree_node::Transformed;
16use datafusion_expr::expr::{BinaryExpr, Cast, InList, Like, TryCast};
17use std::collections::HashMap;
18use std::sync::Arc;
19
20/// Attempt to simplify outer joins when filters make their null-padded
21/// rows impossible to observe.
22///
23/// Outer joins are generally more expensive than inner joins and can block
24/// predicate pushdown and other optimizations. When a filter above an outer
25/// join removes every row the join would add for unmatched input rows, the
26/// join can be changed to a cheaper join type.
27///
28/// For example:
29///
30/// ```sql
31/// SELECT ...
32/// FROM a LEFT JOIN b ON ...
33/// WHERE b.xx = 100
34/// ```
35///
36/// For unmatched rows from `a`, the LEFT JOIN would produce a row with
37/// `b.xx` set to NULL. The predicate `b.xx = 100` does not pass for those
38/// rows, so the query does not need the LEFT JOIN's null-padded output and
39/// the join can be rewritten as an inner join.
40///
41/// The same reasoning can also simplify FULL joins to LEFT, RIGHT, or INNER
42/// joins when filters remove the rows padded on one or both sides.
43///
44/// This rule looks for a filter above an outer join:
45///
46/// ```text
47/// Filter(predicate)
48///   Join(LEFT/RIGHT/FULL)
49/// ```
50///
51/// It also handles plan shapes where projection pruning has inserted one or
52/// more Projection nodes between the filter and join:
53///
54/// ```text
55/// Filter(predicate over projection output)
56///   Projection(...)
57///     ...
58///       Join(LEFT/RIGHT/FULL)
59/// ```
60///
61/// In the projection case, the rule rewrites a copy of the predicate through
62/// each Projection so it can analyze the predicate against the Join inputs.
63/// The original filter predicate and Projection nodes are preserved when the
64/// plan is rebuilt.
65#[derive(Default, Debug)]
66pub struct EliminateOuterJoin;
67
68impl EliminateOuterJoin {
69    #[expect(missing_docs)]
70    pub fn new() -> Self {
71        Self {}
72    }
73}
74
75/// Attempt to eliminate outer joins.
76impl OptimizerRule for EliminateOuterJoin {
77    fn name(&self) -> &str {
78        "eliminate_outer_join"
79    }
80
81    fn apply_order(&self) -> Option<ApplyOrder> {
82        Some(ApplyOrder::TopDown)
83    }
84
85    fn rewrite(
86        &self,
87        plan: LogicalPlan,
88        _config: &dyn OptimizerConfig,
89    ) -> Result<Transformed<LogicalPlan>> {
90        let LogicalPlan::Filter(filter) = plan else {
91            return Ok(Transformed::no(plan));
92        };
93
94        // Descend through one or more Projection nodes until we find a Join.
95        // For each Projection we encounter, rewrite a working copy of the
96        // predicate by replacing references to projection output columns with
97        // the expressions that define them. Keep the filter's original
98        // predicate intact for eventual use in the rebuilt plan; the rewritten
99        // predicate is used only for the null-rejection analysis.
100        let mut rewritten_predicate = filter.predicate.clone();
101        let mut projections: Vec<Projection> = Vec::new();
102        let mut cur = Arc::clone(&filter.input);
103
104        let new_join = loop {
105            match cur.as_ref() {
106                LogicalPlan::Projection(p) => {
107                    rewritten_predicate =
108                        inline_through_projection(rewritten_predicate, p)?;
109                    let next = Arc::clone(&p.input);
110                    projections.push(p.clone());
111                    cur = next;
112                }
113                LogicalPlan::Join(join) => {
114                    let Some(new_join) = try_simplify_join(join, &rewritten_predicate)
115                    else {
116                        return Ok(Transformed::no(LogicalPlan::Filter(filter)));
117                    };
118                    break new_join;
119                }
120                _ => {
121                    return Ok(Transformed::no(LogicalPlan::Filter(filter)));
122                }
123            }
124        };
125
126        let rebuilt_inner = rewrap_projections(new_join, projections);
127        Filter::try_new(filter.predicate, Arc::new(rebuilt_inner))
128            .map(|f| Transformed::yes(LogicalPlan::Filter(f)))
129    }
130}
131
132/// Attempt to simplify an outer join by analyzing `predicate` for
133/// null-rejection.  If the predicate filters out rows padded with NULLs on one
134/// or both sides, return a copy of `join` rewritten to an equivalent join type
135/// that omits those rows in the first place; otherwise return `None`.
136fn try_simplify_join(join: &Join, predicate: &Expr) -> Option<LogicalPlan> {
137    if !join.join_type.is_outer() {
138        return None;
139    }
140
141    let null_rejecting_sides = extract_null_rejecting_sides(
142        predicate,
143        join.left.schema(),
144        join.right.schema(),
145        true,
146    );
147
148    let new_join_type = eliminate_outer(
149        join.join_type,
150        null_rejecting_sides.left,
151        null_rejecting_sides.right,
152    );
153    if new_join_type == join.join_type {
154        return None;
155    }
156
157    Some(LogicalPlan::Join(Join {
158        left: Arc::clone(&join.left),
159        right: Arc::clone(&join.right),
160        join_type: new_join_type,
161        join_constraint: join.join_constraint,
162        on: join.on.clone(),
163        filter: join.filter.clone(),
164        schema: Arc::clone(&join.schema),
165        null_equality: join.null_equality,
166        null_aware: join.null_aware,
167        null_aware_value_keys: join.null_aware_value_keys,
168    }))
169}
170
171/// Substitute the projection's output column references in `predicate` with
172/// the projection's defining expressions (stripped of any `Alias` wrapper).
173/// The result expresses `predicate` over the projection's *input* schema.
174///
175/// Unlike `PushDownFilter`, this rule does not change expression evaluation
176/// behavior (in fact, the rewritten expressions are only used for analysis
177/// purposes). Therefore, function volatility and `MoveTowardsLeafNodes`
178/// placement can be ignored here.
179fn inline_through_projection(predicate: Expr, p: &Projection) -> Result<Expr> {
180    let mut map: HashMap<String, Expr> = HashMap::with_capacity(p.expr.len());
181    for ((qualifier, field), expr) in p.schema.iter().zip(p.expr.iter()) {
182        map.insert(
183            qualified_name(qualifier, field.name()),
184            unalias(expr).clone(),
185        );
186    }
187    replace_cols_by_name(predicate, &map)
188}
189
190/// Re-attach a stack of projections above `new_inner`, restoring the original
191/// plan shape with the new (possibly retyped) join at the bottom. Projection
192/// schemas are reused as-is; only nullability of columns sourced from the
193/// formerly-outer side may have changed, and the existing rule already takes
194/// this looser-schema approach at the join itself.
195fn rewrap_projections(
196    new_inner: LogicalPlan,
197    projections: Vec<Projection>,
198) -> LogicalPlan {
199    let mut current = new_inner;
200    for mut p in projections.into_iter().rev() {
201        p.input = Arc::new(current);
202        current = LogicalPlan::Projection(p);
203    }
204    current
205}
206
207fn unalias(expr: &Expr) -> &Expr {
208    if let Expr::Alias(a) = expr {
209        unalias(&a.expr)
210    } else {
211        expr
212    }
213}
214
215pub fn eliminate_outer(
216    join_type: JoinType,
217    left_non_nullable: bool,
218    right_non_nullable: bool,
219) -> JoinType {
220    match (join_type, left_non_nullable, right_non_nullable) {
221        (JoinType::Left, _, true) => JoinType::Inner,
222        (JoinType::Right, true, _) => JoinType::Inner,
223        (JoinType::Full, true, true) => JoinType::Inner,
224        (JoinType::Full, true, false) => JoinType::Left,
225        (JoinType::Full, false, true) => JoinType::Right,
226        _ => join_type,
227    }
228}
229
230#[derive(Default, Clone, Copy, Debug, PartialEq, Eq)]
231struct NullRejectingSides {
232    left: bool,
233    right: bool,
234}
235
236impl NullRejectingSides {
237    /// The join side(s) a column belongs to.
238    ///
239    /// A bare column reference is null-rejecting on its own side: if the column
240    /// is NULL, every null-propagating operator above it yields NULL and the row
241    /// is filtered.
242    fn for_column(col: &Column, left_schema: &DFSchema, right_schema: &DFSchema) -> Self {
243        Self {
244            left: left_schema.has_column(col),
245            right: right_schema.has_column(col),
246        }
247    }
248
249    fn union(self, other: Self) -> Self {
250        Self {
251            left: self.left || other.left,
252            right: self.right || other.right,
253        }
254    }
255
256    fn intersection(self, other: Self) -> Self {
257        Self {
258            left: self.left && other.left,
259            right: self.right && other.right,
260        }
261    }
262}
263
264/// Compute which join sides are null-rejected by `expr` in a WHERE clause.
265/// For each marked side, rows padded with NULLs on that side are guaranteed to
266/// evaluate to NULL or false and be filtered out.
267///
268/// `left_schema` and `right_schema` map column references to join sides.
269/// `top_level` is true only while walking the root WHERE context; nested
270/// contexts are more conservative because their boolean result may be combined
271/// by an enclosing expression.
272fn extract_null_rejecting_sides(
273    expr: &Expr,
274    left_schema: &Arc<DFSchema>,
275    right_schema: &Arc<DFSchema>,
276    top_level: bool,
277) -> NullRejectingSides {
278    match expr {
279        Expr::Column(col) => {
280            NullRejectingSides::for_column(col, left_schema, right_schema)
281        }
282        Expr::BinaryExpr(BinaryExpr { left, op, right }) => match op {
283            Operator::And | Operator::Or => {
284                let left_sides = extract_null_rejecting_sides(
285                    left,
286                    left_schema,
287                    right_schema,
288                    top_level,
289                );
290                let right_sides = extract_null_rejecting_sides(
291                    right,
292                    left_schema,
293                    right_schema,
294                    top_level,
295                );
296
297                // Top-level AND: each conjunct is an independent WHERE filter,
298                // so side evidence from either branch is sufficient.
299                // Nested AND is handled like OR because the enclosing context
300                // may still let a NULL-padded row pass.
301                if top_level && *op == Operator::And {
302                    left_sides.union(right_sides)
303                } else {
304                    // OR (and nested AND): a NULL-padded row is rejected only
305                    // if both branches reject NULLs for the same side.
306                    left_sides.intersection(right_sides)
307                }
308            }
309            // Other NULL-on-NULL operators preserve null rejection from either
310            // operand.
311            op if op.returns_null_on_null() => {
312                let left_sides =
313                    extract_null_rejecting_sides(left, left_schema, right_schema, false);
314                let right_sides =
315                    extract_null_rejecting_sides(right, left_schema, right_schema, false);
316                left_sides.union(right_sides)
317            }
318            // Other operators, notably IS [ NOT ] DISTINCT FROM, are not
319            // NULL-propagating and provide no side-level rejection evidence.
320            _ => NullRejectingSides::default(),
321        },
322        Expr::Not(arg) | Expr::Negative(arg) => {
323            extract_null_rejecting_sides(arg, left_schema, right_schema, false)
324        }
325        // These wrappers return FALSE on NULL input, so they reject NULLs only
326        // when they are themselves in the root WHERE context. Under another
327        // expression, that FALSE can be transformed into a NULL-accepting result
328        // (for example by NOT), so recurse only at the top level.
329        Expr::IsNotNull(arg)
330        | Expr::IsTrue(arg)
331        | Expr::IsFalse(arg)
332        | Expr::IsNotUnknown(arg) => {
333            if top_level {
334                extract_null_rejecting_sides(arg, left_schema, right_schema, false)
335            } else {
336                NullRejectingSides::default()
337            }
338        }
339        Expr::Cast(Cast { expr, field: _ })
340        | Expr::TryCast(TryCast { expr, field: _ }) => {
341            extract_null_rejecting_sides(expr, left_schema, right_schema, false)
342        }
343        // IN list and BETWEEN reject NULLs from their input expression; list
344        // values and range bounds do not affect which join side is padded.
345        Expr::InList(InList { expr, .. }) => {
346            extract_null_rejecting_sides(expr, left_schema, right_schema, false)
347        }
348        Expr::Between(between) => {
349            extract_null_rejecting_sides(&between.expr, left_schema, right_schema, false)
350        }
351        Expr::Like(Like { expr, pattern, .. }) => {
352            let expr_sides =
353                extract_null_rejecting_sides(expr, left_schema, right_schema, false);
354            let pattern_sides =
355                extract_null_rejecting_sides(pattern, left_schema, right_schema, false);
356            expr_sides.union(pattern_sides)
357        }
358        // Strict scalar functions are NULL-propagating: if any argument from a
359        // padded join side is NULL, the function result is NULL, and an
360        // enclosing NULL-rejecting predicate filters the row out.
361        Expr::ScalarFunction(func) if func.func.is_strict() => func
362            .args
363            .iter()
364            .map(|arg| {
365                extract_null_rejecting_sides(arg, left_schema, right_schema, false)
366            })
367            .fold(NullRejectingSides::default(), NullRejectingSides::union),
368        // Everything else is conservative: NULL-accepting predicates such as
369        // IS NULL / IS NOT TRUE / IS NOT FALSE / IS UNKNOWN must not eliminate
370        // an outer join, and non-strict functions/subqueries/accessors/literals
371        // have no uniform NULL-propagation contract here.
372        _ => NullRejectingSides::default(),
373    }
374}
375
376#[cfg(test)]
377mod tests {
378    use super::*;
379    use crate::OptimizerContext;
380    use crate::assert_optimized_plan_eq_snapshot;
381    use crate::test::*;
382    use arrow::datatypes::DataType;
383    use datafusion_common::ScalarValue;
384    use datafusion_expr::{
385        ColumnarValue,
386        Operator::{And, Or},
387        ScalarFunctionArgs, ScalarUDF, ScalarUDFImpl, Signature, Volatility, binary_expr,
388        cast, col, lit,
389        logical_plan::builder::LogicalPlanBuilder,
390        not, try_cast,
391    };
392
393    #[test]
394    fn null_rejecting_sides_union() {
395        let left_side = NullRejectingSides {
396            left: true,
397            right: false,
398        };
399        let right_side = NullRejectingSides {
400            left: false,
401            right: true,
402        };
403
404        assert_eq!(
405            left_side.union(right_side),
406            NullRejectingSides {
407                left: true,
408                right: true,
409            }
410        );
411    }
412
413    #[test]
414    fn null_rejecting_sides_intersection() {
415        let both_sides = NullRejectingSides {
416            left: true,
417            right: true,
418        };
419        let right_side = NullRejectingSides {
420            left: false,
421            right: true,
422        };
423
424        assert_eq!(
425            both_sides.intersection(right_side),
426            NullRejectingSides {
427                left: false,
428                right: true,
429            }
430        );
431    }
432
433    macro_rules! assert_optimized_plan_equal {
434        (
435            $plan:expr,
436            @ $expected:literal $(,)?
437        ) => {{
438            let optimizer_ctx = OptimizerContext::new().with_max_passes(1);
439            let rules: Vec<Arc<dyn crate::OptimizerRule + Send + Sync>> = vec![Arc::new(EliminateOuterJoin::new())];
440            assert_optimized_plan_eq_snapshot!(
441                optimizer_ctx,
442                rules,
443                $plan,
444                @ $expected,
445            )
446        }};
447    }
448
449    #[derive(Debug, PartialEq, Eq, Hash)]
450    struct TestUdf {
451        name: &'static str,
452        signature: Signature,
453        strict: bool,
454    }
455
456    impl TestUdf {
457        fn new(name: &'static str, strict: bool) -> Self {
458            Self {
459                name,
460                signature: Signature::uniform(
461                    1,
462                    vec![DataType::UInt32],
463                    Volatility::Immutable,
464                ),
465                strict,
466            }
467        }
468    }
469
470    impl ScalarUDFImpl for TestUdf {
471        fn name(&self) -> &str {
472            self.name
473        }
474
475        fn signature(&self) -> &Signature {
476            &self.signature
477        }
478
479        fn return_type(&self, _arg_types: &[DataType]) -> Result<DataType> {
480            Ok(DataType::UInt32)
481        }
482
483        fn is_strict(&self) -> bool {
484            self.strict
485        }
486
487        fn invoke_with_args(&self, _args: ScalarFunctionArgs) -> Result<ColumnarValue> {
488            unimplemented!()
489        }
490    }
491
492    fn strict_udf(arg: Expr) -> Expr {
493        ScalarUDF::from(TestUdf::new("strict_test", true)).call(vec![arg])
494    }
495
496    fn non_strict_udf(arg: Expr) -> Expr {
497        ScalarUDF::from(TestUdf::new("non_strict_test", false)).call(vec![arg])
498    }
499
500    #[test]
501    fn eliminate_left_with_null() -> Result<()> {
502        let t1 = test_table_scan_with_name("t1")?;
503        let t2 = test_table_scan_with_name("t2")?;
504
505        // could not eliminate to inner join
506        let plan = LogicalPlanBuilder::from(t1)
507            .join(
508                t2,
509                JoinType::Left,
510                (vec![Column::from_name("a")], vec![Column::from_name("a")]),
511                None,
512            )?
513            .filter(col("t2.b").is_null())?
514            .build()?;
515
516        assert_optimized_plan_equal!(plan, @r"
517        Filter: t2.b IS NULL
518          Left Join: t1.a = t2.a
519            TableScan: t1
520            TableScan: t2
521        ")
522    }
523
524    #[test]
525    fn eliminate_left_with_not_null() -> Result<()> {
526        let t1 = test_table_scan_with_name("t1")?;
527        let t2 = test_table_scan_with_name("t2")?;
528
529        // eliminate to inner join
530        let plan = LogicalPlanBuilder::from(t1)
531            .join(
532                t2,
533                JoinType::Left,
534                (vec![Column::from_name("a")], vec![Column::from_name("a")]),
535                None,
536            )?
537            .filter(col("t2.b").is_not_null())?
538            .build()?;
539
540        assert_optimized_plan_equal!(plan, @r"
541        Filter: t2.b IS NOT NULL
542          Inner Join: t1.a = t2.a
543            TableScan: t1
544            TableScan: t2
545        ")
546    }
547
548    #[test]
549    fn eliminate_left_with_strict_function() -> Result<()> {
550        let t1 = test_table_scan_with_name("t1")?;
551        let t2 = test_table_scan_with_name("t2")?;
552
553        let plan = LogicalPlanBuilder::from(t1)
554            .join(
555                t2,
556                JoinType::Left,
557                (vec![Column::from_name("a")], vec![Column::from_name("a")]),
558                None,
559            )?
560            .filter(strict_udf(col("t2.b")).gt(lit(5u32)))?
561            .build()?;
562
563        assert_optimized_plan_equal!(plan, @r"
564        Filter: strict_test(t2.b) > UInt32(5)
565          Inner Join: t1.a = t2.a
566            TableScan: t1
567            TableScan: t2
568        ")
569    }
570
571    #[test]
572    fn no_eliminate_left_with_non_strict_function() -> Result<()> {
573        let t1 = test_table_scan_with_name("t1")?;
574        let t2 = test_table_scan_with_name("t2")?;
575
576        let plan = LogicalPlanBuilder::from(t1)
577            .join(
578                t2,
579                JoinType::Left,
580                (vec![Column::from_name("a")], vec![Column::from_name("a")]),
581                None,
582            )?
583            .filter(non_strict_udf(col("t2.b")).gt(lit(5u32)))?
584            .build()?;
585
586        assert_optimized_plan_equal!(plan, @r"
587        Filter: non_strict_test(t2.b) > UInt32(5)
588          Left Join: t1.a = t2.a
589            TableScan: t1
590            TableScan: t2
591        ")
592    }
593
594    #[test]
595    fn eliminate_left_with_nested_strict_is_not_null() -> Result<()> {
596        let t1 = test_table_scan_with_name("t1")?;
597        let t2 = test_table_scan_with_name("t2")?;
598
599        let plan = LogicalPlanBuilder::from(t1)
600            .join(
601                t2,
602                JoinType::Left,
603                (vec![Column::from_name("a")], vec![Column::from_name("a")]),
604                None,
605            )?
606            .filter(strict_udf(strict_udf(col("t2.b"))).is_not_null())?
607            .build()?;
608
609        assert_optimized_plan_equal!(plan, @r"
610        Filter: strict_test(strict_test(t2.b)) IS NOT NULL
611          Inner Join: t1.a = t2.a
612            TableScan: t1
613            TableScan: t2
614        ")
615    }
616
617    #[test]
618    fn no_eliminate_left_with_strict_function_is_null() -> Result<()> {
619        let t1 = test_table_scan_with_name("t1")?;
620        let t2 = test_table_scan_with_name("t2")?;
621
622        let plan = LogicalPlanBuilder::from(t1)
623            .join(
624                t2,
625                JoinType::Left,
626                (vec![Column::from_name("a")], vec![Column::from_name("a")]),
627                None,
628            )?
629            .filter(strict_udf(col("t2.b")).is_null())?
630            .build()?;
631
632        assert_optimized_plan_equal!(plan, @r"
633        Filter: strict_test(t2.b) IS NULL
634          Left Join: t1.a = t2.a
635            TableScan: t1
636            TableScan: t2
637        ")
638    }
639
640    #[test]
641    fn eliminate_right_with_or() -> Result<()> {
642        let t1 = test_table_scan_with_name("t1")?;
643        let t2 = test_table_scan_with_name("t2")?;
644
645        // eliminate to inner join
646        let plan = LogicalPlanBuilder::from(t1)
647            .join(
648                t2,
649                JoinType::Right,
650                (vec![Column::from_name("a")], vec![Column::from_name("a")]),
651                None,
652            )?
653            .filter(binary_expr(
654                col("t1.b").gt(lit(10u32)),
655                Or,
656                col("t1.c").lt(lit(20u32)),
657            ))?
658            .build()?;
659
660        assert_optimized_plan_equal!(plan, @r"
661        Filter: t1.b > UInt32(10) OR t1.c < UInt32(20)
662          Inner Join: t1.a = t2.a
663            TableScan: t1
664            TableScan: t2
665        ")
666    }
667
668    #[test]
669    fn eliminate_full_with_and() -> Result<()> {
670        let t1 = test_table_scan_with_name("t1")?;
671        let t2 = test_table_scan_with_name("t2")?;
672
673        // eliminate to inner join
674        let plan = LogicalPlanBuilder::from(t1)
675            .join(
676                t2,
677                JoinType::Full,
678                (vec![Column::from_name("a")], vec![Column::from_name("a")]),
679                None,
680            )?
681            .filter(binary_expr(
682                col("t1.b").gt(lit(10u32)),
683                And,
684                col("t2.c").lt(lit(20u32)),
685            ))?
686            .build()?;
687
688        assert_optimized_plan_equal!(plan, @r"
689        Filter: t1.b > UInt32(10) AND t2.c < UInt32(20)
690          Inner Join: t1.a = t2.a
691            TableScan: t1
692            TableScan: t2
693        ")
694    }
695
696    #[test]
697    fn eliminate_left_with_in_list() -> Result<()> {
698        let t1 = test_table_scan_with_name("t1")?;
699        let t2 = test_table_scan_with_name("t2")?;
700
701        // t2.b IN (1, 2, 3) rejects nulls — if t2.b is NULL the IN returns
702        // NULL which is filtered out. So Left Join should become Inner Join.
703        let plan = LogicalPlanBuilder::from(t1)
704            .join(
705                t2,
706                JoinType::Left,
707                (vec![Column::from_name("a")], vec![Column::from_name("a")]),
708                None,
709            )?
710            .filter(col("t2.b").in_list(vec![lit(1u32), lit(2u32), lit(3u32)], false))?
711            .build()?;
712
713        assert_optimized_plan_equal!(plan, @r"
714        Filter: t2.b IN ([UInt32(1), UInt32(2), UInt32(3)])
715          Inner Join: t1.a = t2.a
716            TableScan: t1
717            TableScan: t2
718        ")
719    }
720
721    #[test]
722    fn eliminate_left_with_in_list_containing_null() -> Result<()> {
723        let t1 = test_table_scan_with_name("t1")?;
724        let t2 = test_table_scan_with_name("t2")?;
725
726        // IN list with NULL still rejects null input columns:
727        // if t2.b is NULL, NULL IN (1, NULL) evaluates to NULL, which is filtered out
728        let plan = LogicalPlanBuilder::from(t1)
729            .join(
730                t2,
731                JoinType::Left,
732                (vec![Column::from_name("a")], vec![Column::from_name("a")]),
733                None,
734            )?
735            .filter(
736                col("t2.b")
737                    .in_list(vec![lit(1u32), lit(ScalarValue::UInt32(None))], false),
738            )?
739            .build()?;
740
741        assert_optimized_plan_equal!(plan, @r"
742        Filter: t2.b IN ([UInt32(1), UInt32(NULL)])
743          Inner Join: t1.a = t2.a
744            TableScan: t1
745            TableScan: t2
746        ")
747    }
748
749    #[test]
750    fn eliminate_left_with_not_in_list() -> Result<()> {
751        let t1 = test_table_scan_with_name("t1")?;
752        let t2 = test_table_scan_with_name("t2")?;
753
754        // NOT IN also rejects nulls: if t2.b is NULL, NOT (NULL IN (...))
755        // evaluates to NULL, which is filtered out
756        let plan = LogicalPlanBuilder::from(t1)
757            .join(
758                t2,
759                JoinType::Left,
760                (vec![Column::from_name("a")], vec![Column::from_name("a")]),
761                None,
762            )?
763            .filter(col("t2.b").in_list(vec![lit(1u32), lit(2u32)], true))?
764            .build()?;
765
766        assert_optimized_plan_equal!(plan, @r"
767        Filter: t2.b NOT IN ([UInt32(1), UInt32(2)])
768          Inner Join: t1.a = t2.a
769            TableScan: t1
770            TableScan: t2
771        ")
772    }
773
774    #[test]
775    fn eliminate_left_with_between() -> Result<()> {
776        let t1 = test_table_scan_with_name("t1")?;
777        let t2 = test_table_scan_with_name("t2")?;
778
779        // BETWEEN rejects nulls: if t2.b is NULL, NULL BETWEEN 1 AND 10
780        // evaluates to NULL, which is filtered out
781        let plan = LogicalPlanBuilder::from(t1)
782            .join(
783                t2,
784                JoinType::Left,
785                (vec![Column::from_name("a")], vec![Column::from_name("a")]),
786                None,
787            )?
788            .filter(col("t2.b").between(lit(1u32), lit(10u32)))?
789            .build()?;
790
791        assert_optimized_plan_equal!(plan, @r"
792        Filter: t2.b BETWEEN UInt32(1) AND UInt32(10)
793          Inner Join: t1.a = t2.a
794            TableScan: t1
795            TableScan: t2
796        ")
797    }
798
799    #[test]
800    fn eliminate_right_with_between() -> Result<()> {
801        let t1 = test_table_scan_with_name("t1")?;
802        let t2 = test_table_scan_with_name("t2")?;
803
804        // Right join: filter on left (nullable) side with BETWEEN should convert to Inner
805        let plan = LogicalPlanBuilder::from(t1)
806            .join(
807                t2,
808                JoinType::Right,
809                (vec![Column::from_name("a")], vec![Column::from_name("a")]),
810                None,
811            )?
812            .filter(col("t1.b").between(lit(1u32), lit(10u32)))?
813            .build()?;
814
815        assert_optimized_plan_equal!(plan, @r"
816        Filter: t1.b BETWEEN UInt32(1) AND UInt32(10)
817          Inner Join: t1.a = t2.a
818            TableScan: t1
819            TableScan: t2
820        ")
821    }
822
823    #[test]
824    fn eliminate_full_with_between() -> Result<()> {
825        let t1 = test_table_scan_with_name("t1")?;
826        let t2 = test_table_scan_with_name("t2")?;
827
828        // Full join with BETWEEN on both sides should become Inner
829        let plan = LogicalPlanBuilder::from(t1)
830            .join(
831                t2,
832                JoinType::Full,
833                (vec![Column::from_name("a")], vec![Column::from_name("a")]),
834                None,
835            )?
836            .filter(binary_expr(
837                col("t1.b").between(lit(1u32), lit(10u32)),
838                And,
839                col("t2.b").between(lit(5u32), lit(20u32)),
840            ))?
841            .build()?;
842
843        assert_optimized_plan_equal!(plan, @r"
844        Filter: t1.b BETWEEN UInt32(1) AND UInt32(10) AND t2.b BETWEEN UInt32(5) AND UInt32(20)
845          Inner Join: t1.a = t2.a
846            TableScan: t1
847            TableScan: t2
848        ")
849    }
850
851    #[test]
852    fn eliminate_full_with_in_list() -> Result<()> {
853        let t1 = test_table_scan_with_name("t1")?;
854        let t2 = test_table_scan_with_name("t2")?;
855
856        // Full join with IN filters on both sides should become Inner
857        let plan = LogicalPlanBuilder::from(t1)
858            .join(
859                t2,
860                JoinType::Full,
861                (vec![Column::from_name("a")], vec![Column::from_name("a")]),
862                None,
863            )?
864            .filter(binary_expr(
865                col("t1.b").in_list(vec![lit(1u32), lit(2u32)], false),
866                And,
867                col("t2.b").in_list(vec![lit(3u32), lit(4u32)], false),
868            ))?
869            .build()?;
870
871        assert_optimized_plan_equal!(plan, @r"
872        Filter: t1.b IN ([UInt32(1), UInt32(2)]) AND t2.b IN ([UInt32(3), UInt32(4)])
873          Inner Join: t1.a = t2.a
874            TableScan: t1
875            TableScan: t2
876        ")
877    }
878
879    #[test]
880    fn no_eliminate_left_with_in_list_or_is_null() -> Result<()> {
881        let t1 = test_table_scan_with_name("t1")?;
882        let t2 = test_table_scan_with_name("t2")?;
883
884        // WHERE (t2.b IN (1, 2)) OR (t2.b IS NULL)
885        // The OR with IS NULL makes the predicate null-tolerant:
886        // when t2.b is NULL, IS NULL returns true, so the whole OR is true.
887        // The outer join must be preserved.
888        let plan = LogicalPlanBuilder::from(t1)
889            .join(
890                t2,
891                JoinType::Left,
892                (vec![Column::from_name("a")], vec![Column::from_name("a")]),
893                None,
894            )?
895            .filter(binary_expr(
896                col("t2.b").in_list(vec![lit(1u32), lit(2u32)], false),
897                Or,
898                col("t2.b").is_null(),
899            ))?
900            .build()?;
901
902        // Should NOT be converted to Inner — OR with IS NULL preserves null rows
903        assert_optimized_plan_equal!(plan, @r"
904        Filter: t2.b IN ([UInt32(1), UInt32(2)]) OR t2.b IS NULL
905          Left Join: t1.a = t2.a
906            TableScan: t1
907            TableScan: t2
908        ")
909    }
910
911    #[test]
912    fn eliminate_left_with_like() -> Result<()> {
913        let t1 = test_table_scan_with_name("t1")?;
914        let t2 = test_table_scan_with_name("t2")?;
915
916        // LIKE rejects nulls: if t2.b is NULL, the result is NULL (filtered out)
917        let plan = LogicalPlanBuilder::from(t1)
918            .join(
919                t2,
920                JoinType::Left,
921                (vec![Column::from_name("a")], vec![Column::from_name("a")]),
922                None,
923            )?
924            .filter(col("t2.b").like(lit("%pattern%")))?
925            .build()?;
926
927        assert_optimized_plan_equal!(plan, @r#"
928        Filter: t2.b LIKE Utf8("%pattern%")
929          Inner Join: t1.a = t2.a
930            TableScan: t1
931            TableScan: t2
932        "#)
933    }
934
935    #[test]
936    fn eliminate_left_with_like_pattern_column() -> Result<()> {
937        let t1 = test_table_scan_with_name("t1")?;
938        let t2 = test_table_scan_with_name("t2")?;
939
940        // LIKE with nullable column on the pattern side:
941        // 'x' LIKE t2.b → if t2.b is NULL, result is NULL (filtered out)
942        let plan = LogicalPlanBuilder::from(t1)
943            .join(
944                t2,
945                JoinType::Left,
946                (vec![Column::from_name("a")], vec![Column::from_name("a")]),
947                None,
948            )?
949            .filter(lit("x").like(col("t2.b")))?
950            .build()?;
951
952        assert_optimized_plan_equal!(plan, @r#"
953        Filter: Utf8("x") LIKE t2.b
954          Inner Join: t1.a = t2.a
955            TableScan: t1
956            TableScan: t2
957        "#)
958    }
959
960    #[test]
961    fn eliminate_full_with_like_cross_side() -> Result<()> {
962        let t1 = test_table_scan_with_name("t1")?;
963        let t2 = test_table_scan_with_name("t2")?;
964
965        // LIKE with columns from both sides: t1.c LIKE t2.b
966        // If t1 is NULL → NULL LIKE t2.b → NULL → filtered out (left non-nullable)
967        // If t2 is NULL → t1.c LIKE NULL → NULL → filtered out (right non-nullable)
968        // Both sides are non-nullable → FULL → INNER
969        let plan = LogicalPlanBuilder::from(t1)
970            .join(
971                t2,
972                JoinType::Full,
973                (vec![Column::from_name("a")], vec![Column::from_name("a")]),
974                None,
975            )?
976            .filter(col("t1.c").like(col("t2.b")))?
977            .build()?;
978
979        assert_optimized_plan_equal!(plan, @r"
980        Filter: t1.c LIKE t2.b
981          Inner Join: t1.a = t2.a
982            TableScan: t1
983            TableScan: t2
984        ")
985    }
986
987    #[test]
988    fn eliminate_left_with_is_true() -> Result<()> {
989        let t1 = test_table_scan_with_name("t1")?;
990        let t2 = test_table_scan_with_name("t2")?;
991
992        // IS TRUE rejects nulls: if the expression is NULL, IS TRUE returns false
993        let plan = LogicalPlanBuilder::from(t1)
994            .join(
995                t2,
996                JoinType::Left,
997                (vec![Column::from_name("a")], vec![Column::from_name("a")]),
998                None,
999            )?
1000            .filter(col("t2.b").gt(lit(10u32)).is_true())?
1001            .build()?;
1002
1003        assert_optimized_plan_equal!(plan, @r"
1004        Filter: t2.b > UInt32(10) IS TRUE
1005          Inner Join: t1.a = t2.a
1006            TableScan: t1
1007            TableScan: t2
1008        ")
1009    }
1010
1011    #[test]
1012    fn eliminate_left_with_is_false() -> Result<()> {
1013        let t1 = test_table_scan_with_name("t1")?;
1014        let t2 = test_table_scan_with_name("t2")?;
1015
1016        // IS FALSE rejects nulls: if the expression is NULL, IS FALSE returns false
1017        let plan = LogicalPlanBuilder::from(t1)
1018            .join(
1019                t2,
1020                JoinType::Left,
1021                (vec![Column::from_name("a")], vec![Column::from_name("a")]),
1022                None,
1023            )?
1024            .filter(col("t2.b").gt(lit(10u32)).is_false())?
1025            .build()?;
1026
1027        assert_optimized_plan_equal!(plan, @r"
1028        Filter: t2.b > UInt32(10) IS FALSE
1029          Inner Join: t1.a = t2.a
1030            TableScan: t1
1031            TableScan: t2
1032        ")
1033    }
1034
1035    #[test]
1036    fn eliminate_left_with_is_not_unknown() -> Result<()> {
1037        let t1 = test_table_scan_with_name("t1")?;
1038        let t2 = test_table_scan_with_name("t2")?;
1039
1040        // IS NOT UNKNOWN rejects nulls: if the expression is NULL, IS NOT UNKNOWN returns false
1041        let plan = LogicalPlanBuilder::from(t1)
1042            .join(
1043                t2,
1044                JoinType::Left,
1045                (vec![Column::from_name("a")], vec![Column::from_name("a")]),
1046                None,
1047            )?
1048            .filter(col("t2.b").gt(lit(10u32)).is_not_unknown())?
1049            .build()?;
1050
1051        assert_optimized_plan_equal!(plan, @r"
1052        Filter: t2.b > UInt32(10) IS NOT UNKNOWN
1053          Inner Join: t1.a = t2.a
1054            TableScan: t1
1055            TableScan: t2
1056        ")
1057    }
1058
1059    #[test]
1060    fn no_eliminate_left_with_is_not_true() -> Result<()> {
1061        let t1 = test_table_scan_with_name("t1")?;
1062        let t2 = test_table_scan_with_name("t2")?;
1063
1064        // IS NOT TRUE is NOT null-rejecting: if the expression is NULL,
1065        // IS NOT TRUE returns true, so null rows pass through
1066        let plan = LogicalPlanBuilder::from(t1)
1067            .join(
1068                t2,
1069                JoinType::Left,
1070                (vec![Column::from_name("a")], vec![Column::from_name("a")]),
1071                None,
1072            )?
1073            .filter(col("t2.b").gt(lit(10u32)).is_not_true())?
1074            .build()?;
1075
1076        assert_optimized_plan_equal!(plan, @r"
1077        Filter: t2.b > UInt32(10) IS NOT TRUE
1078          Left Join: t1.a = t2.a
1079            TableScan: t1
1080            TableScan: t2
1081        ")
1082    }
1083
1084    #[test]
1085    fn no_eliminate_left_with_is_unknown() -> Result<()> {
1086        let t1 = test_table_scan_with_name("t1")?;
1087        let t2 = test_table_scan_with_name("t2")?;
1088
1089        // IS UNKNOWN is NOT null-rejecting: if the expression is NULL,
1090        // IS UNKNOWN returns true, so null rows pass through
1091        let plan = LogicalPlanBuilder::from(t1)
1092            .join(
1093                t2,
1094                JoinType::Left,
1095                (vec![Column::from_name("a")], vec![Column::from_name("a")]),
1096                None,
1097            )?
1098            .filter(col("t2.b").gt(lit(10u32)).is_unknown())?
1099            .build()?;
1100
1101        assert_optimized_plan_equal!(plan, @r"
1102        Filter: t2.b > UInt32(10) IS UNKNOWN
1103          Left Join: t1.a = t2.a
1104            TableScan: t1
1105            TableScan: t2
1106        ")
1107    }
1108
1109    #[test]
1110    fn no_eliminate_left_with_not_is_true() -> Result<()> {
1111        let t1 = test_table_scan_with_name("t1")?;
1112        let t2 = test_table_scan_with_name("t2")?;
1113
1114        // NOT(<x> IS TRUE) is equivalent to (<x> IS NOT TRUE): TRUE when
1115        // <x> is FALSE OR NULL. So `WHERE NOT((t2.b > 5) IS TRUE)` accepts
1116        // rows where t2.b is NULL (because t2.b > 5 is NULL → IS TRUE is
1117        // FALSE → NOT FALSE = TRUE). The LEFT JOIN must NOT be converted.
1118        let plan = LogicalPlanBuilder::from(t1)
1119            .join(
1120                t2,
1121                JoinType::Left,
1122                (vec![Column::from_name("a")], vec![Column::from_name("a")]),
1123                None,
1124            )?
1125            .filter(not(col("t2.b").gt(lit(5u32)).is_true()))?
1126            .build()?;
1127
1128        assert_optimized_plan_equal!(plan, @r"
1129        Filter: NOT t2.b > UInt32(5) IS TRUE
1130          Left Join: t1.a = t2.a
1131            TableScan: t1
1132            TableScan: t2
1133        ")
1134    }
1135
1136    #[test]
1137    fn no_eliminate_left_with_not_is_false() -> Result<()> {
1138        let t1 = test_table_scan_with_name("t1")?;
1139        let t2 = test_table_scan_with_name("t2")?;
1140
1141        // Same shape, IS FALSE: NOT(<x> IS FALSE) accepts NULL on the
1142        // inner column.
1143        let plan = LogicalPlanBuilder::from(t1)
1144            .join(
1145                t2,
1146                JoinType::Left,
1147                (vec![Column::from_name("a")], vec![Column::from_name("a")]),
1148                None,
1149            )?
1150            .filter(not(col("t2.b").gt(lit(5u32)).is_false()))?
1151            .build()?;
1152
1153        assert_optimized_plan_equal!(plan, @r"
1154        Filter: NOT t2.b > UInt32(5) IS FALSE
1155          Left Join: t1.a = t2.a
1156            TableScan: t1
1157            TableScan: t2
1158        ")
1159    }
1160
1161    #[test]
1162    fn no_eliminate_left_with_not_is_not_unknown() -> Result<()> {
1163        let t1 = test_table_scan_with_name("t1")?;
1164        let t2 = test_table_scan_with_name("t2")?;
1165
1166        // Same shape, IS NOT UNKNOWN: NOT(<x> IS NOT UNKNOWN) is
1167        // equivalent to (<x> IS UNKNOWN), which is TRUE when <x> is NULL.
1168        let plan = LogicalPlanBuilder::from(t1)
1169            .join(
1170                t2,
1171                JoinType::Left,
1172                (vec![Column::from_name("a")], vec![Column::from_name("a")]),
1173                None,
1174            )?
1175            .filter(not(col("t2.b").gt(lit(5u32)).is_not_unknown()))?
1176            .build()?;
1177
1178        assert_optimized_plan_equal!(plan, @r"
1179        Filter: NOT t2.b > UInt32(5) IS NOT UNKNOWN
1180          Left Join: t1.a = t2.a
1181            TableScan: t1
1182            TableScan: t2
1183        ")
1184    }
1185
1186    #[test]
1187    fn eliminate_full_with_type_cast() -> Result<()> {
1188        let t1 = test_table_scan_with_name("t1")?;
1189        let t2 = test_table_scan_with_name("t2")?;
1190
1191        // eliminate to inner join
1192        let plan = LogicalPlanBuilder::from(t1)
1193            .join(
1194                t2,
1195                JoinType::Full,
1196                (vec![Column::from_name("a")], vec![Column::from_name("a")]),
1197                None,
1198            )?
1199            .filter(binary_expr(
1200                cast(col("t1.b"), DataType::Int64).gt(lit(10u32)),
1201                And,
1202                try_cast(col("t2.c"), DataType::Int64).lt(lit(20u32)),
1203            ))?
1204            .build()?;
1205
1206        assert_optimized_plan_equal!(plan, @r"
1207        Filter: CAST(t1.b AS Int64) > UInt32(10) AND TRY_CAST(t2.c AS Int64) < UInt32(20)
1208          Inner Join: t1.a = t2.a
1209            TableScan: t1
1210            TableScan: t2
1211        ")
1212    }
1213
1214    // ----- FULL JOIN → LEFT / RIGHT tests -----
1215    #[test]
1216    fn eliminate_full_to_left_with_left_filter() -> Result<()> {
1217        let t1 = test_table_scan_with_name("t1")?;
1218        let t2 = test_table_scan_with_name("t2")?;
1219
1220        // FULL JOIN with null-rejecting filter only on left side → LEFT JOIN
1221        // (left side becomes non-nullable, right side stays nullable)
1222        let plan = LogicalPlanBuilder::from(t1)
1223            .join(
1224                t2,
1225                JoinType::Full,
1226                (vec![Column::from_name("a")], vec![Column::from_name("a")]),
1227                None,
1228            )?
1229            .filter(col("t1.b").gt(lit(10u32)))?
1230            .build()?;
1231
1232        assert_optimized_plan_equal!(plan, @r"
1233        Filter: t1.b > UInt32(10)
1234          Left Join: t1.a = t2.a
1235            TableScan: t1
1236            TableScan: t2
1237        ")
1238    }
1239
1240    #[test]
1241    fn eliminate_full_to_right_with_right_filter() -> Result<()> {
1242        let t1 = test_table_scan_with_name("t1")?;
1243        let t2 = test_table_scan_with_name("t2")?;
1244
1245        // FULL JOIN with null-rejecting filter only on right side → RIGHT JOIN
1246        let plan = LogicalPlanBuilder::from(t1)
1247            .join(
1248                t2,
1249                JoinType::Full,
1250                (vec![Column::from_name("a")], vec![Column::from_name("a")]),
1251                None,
1252            )?
1253            .filter(col("t2.b").in_list(vec![lit(1u32), lit(2u32)], false))?
1254            .build()?;
1255
1256        assert_optimized_plan_equal!(plan, @r"
1257        Filter: t2.b IN ([UInt32(1), UInt32(2)])
1258          Right Join: t1.a = t2.a
1259            TableScan: t1
1260            TableScan: t2
1261        ")
1262    }
1263
1264    #[test]
1265    fn eliminate_full_to_left_with_like() -> Result<()> {
1266        let t1 = test_table_scan_with_name("t1")?;
1267        let t2 = test_table_scan_with_name("t2")?;
1268
1269        // FULL JOIN with LIKE on left side only → LEFT JOIN
1270        let plan = LogicalPlanBuilder::from(t1)
1271            .join(
1272                t2,
1273                JoinType::Full,
1274                (vec![Column::from_name("a")], vec![Column::from_name("a")]),
1275                None,
1276            )?
1277            .filter(col("t1.b").like(lit("%val%")))?
1278            .build()?;
1279
1280        assert_optimized_plan_equal!(plan, @r#"
1281        Filter: t1.b LIKE Utf8("%val%")
1282          Left Join: t1.a = t2.a
1283            TableScan: t1
1284            TableScan: t2
1285        "#)
1286    }
1287
1288    #[test]
1289    fn eliminate_full_to_right_with_is_true() -> Result<()> {
1290        let t1 = test_table_scan_with_name("t1")?;
1291        let t2 = test_table_scan_with_name("t2")?;
1292
1293        // FULL JOIN with IS TRUE on right side only → RIGHT JOIN
1294        let plan = LogicalPlanBuilder::from(t1)
1295            .join(
1296                t2,
1297                JoinType::Full,
1298                (vec![Column::from_name("a")], vec![Column::from_name("a")]),
1299                None,
1300            )?
1301            .filter(col("t2.b").gt(lit(10u32)).is_true())?
1302            .build()?;
1303
1304        assert_optimized_plan_equal!(plan, @r"
1305        Filter: t2.b > UInt32(10) IS TRUE
1306          Right Join: t1.a = t2.a
1307            TableScan: t1
1308            TableScan: t2
1309        ")
1310    }
1311
1312    // ----- Nested AND / OR tests -----
1313
1314    #[test]
1315    fn eliminate_left_with_and_multiple_null_rejecting() -> Result<()> {
1316        let t1 = test_table_scan_with_name("t1")?;
1317        let t2 = test_table_scan_with_name("t2")?;
1318
1319        // Multiple null-rejecting predicates combined with AND on nullable side
1320        let plan = LogicalPlanBuilder::from(t1)
1321            .join(
1322                t2,
1323                JoinType::Left,
1324                (vec![Column::from_name("a")], vec![Column::from_name("a")]),
1325                None,
1326            )?
1327            .filter(binary_expr(
1328                col("t2.b").in_list(vec![lit(1u32), lit(2u32)], false),
1329                And,
1330                col("t2.c").between(lit(5u32), lit(20u32)),
1331            ))?
1332            .build()?;
1333
1334        assert_optimized_plan_equal!(plan, @r"
1335        Filter: t2.b IN ([UInt32(1), UInt32(2)]) AND t2.c BETWEEN UInt32(5) AND UInt32(20)
1336          Inner Join: t1.a = t2.a
1337            TableScan: t1
1338            TableScan: t2
1339        ")
1340    }
1341
1342    #[test]
1343    fn eliminate_left_with_or_same_side() -> Result<()> {
1344        let t1 = test_table_scan_with_name("t1")?;
1345        let t2 = test_table_scan_with_name("t2")?;
1346
1347        // OR of two null-rejecting predicates on different columns of the same
1348        // nullable side. If t2 rows are NULL (from LEFT JOIN), both t2.b and
1349        // t2.c are NULL, so the entire OR evaluates to NULL → filtered out.
1350        // This IS null-rejecting, so join should be eliminated.
1351        let plan = LogicalPlanBuilder::from(t1)
1352            .join(
1353                t2,
1354                JoinType::Left,
1355                (vec![Column::from_name("a")], vec![Column::from_name("a")]),
1356                None,
1357            )?
1358            .filter(binary_expr(
1359                col("t2.b").gt(lit(10u32)),
1360                Or,
1361                col("t2.c").lt(lit(20u32)),
1362            ))?
1363            .build()?;
1364
1365        assert_optimized_plan_equal!(plan, @r"
1366        Filter: t2.b > UInt32(10) OR t2.c < UInt32(20)
1367          Inner Join: t1.a = t2.a
1368            TableScan: t1
1369            TableScan: t2
1370        ")
1371    }
1372
1373    #[test]
1374    fn no_eliminate_left_with_or_cross_side() -> Result<()> {
1375        let t1 = test_table_scan_with_name("t1")?;
1376        let t2 = test_table_scan_with_name("t2")?;
1377
1378        // OR with columns from different sides — t1.b (preserved) OR t2.b
1379        // (nullable). When t2 is NULL, t1.b > 10 can still be true, so the
1380        // OR is NOT null-rejecting. Join must be preserved.
1381        let plan = LogicalPlanBuilder::from(t1)
1382            .join(
1383                t2,
1384                JoinType::Left,
1385                (vec![Column::from_name("a")], vec![Column::from_name("a")]),
1386                None,
1387            )?
1388            .filter(binary_expr(
1389                col("t1.b").gt(lit(10u32)),
1390                Or,
1391                col("t2.b").lt(lit(20u32)),
1392            ))?
1393            .build()?;
1394
1395        assert_optimized_plan_equal!(plan, @r"
1396        Filter: t1.b > UInt32(10) OR t2.b < UInt32(20)
1397          Left Join: t1.a = t2.a
1398            TableScan: t1
1399            TableScan: t2
1400        ")
1401    }
1402
1403    // ----- Mixed predicate tests -----
1404
1405    #[test]
1406    fn eliminate_full_with_mixed_predicates() -> Result<()> {
1407        let t1 = test_table_scan_with_name("t1")?;
1408        let t2 = test_table_scan_with_name("t2")?;
1409
1410        // FULL JOIN with different null-rejecting expr types on each side:
1411        // LIKE on left, BETWEEN on right → INNER JOIN
1412        let plan = LogicalPlanBuilder::from(t1)
1413            .join(
1414                t2,
1415                JoinType::Full,
1416                (vec![Column::from_name("a")], vec![Column::from_name("a")]),
1417                None,
1418            )?
1419            .filter(binary_expr(
1420                col("t1.b").like(lit("%pattern%")),
1421                And,
1422                col("t2.b").between(lit(1u32), lit(10u32)),
1423            ))?
1424            .build()?;
1425
1426        assert_optimized_plan_equal!(plan, @r#"
1427        Filter: t1.b LIKE Utf8("%pattern%") AND t2.b BETWEEN UInt32(1) AND UInt32(10)
1428          Inner Join: t1.a = t2.a
1429            TableScan: t1
1430            TableScan: t2
1431        "#)
1432    }
1433
1434    #[test]
1435    fn eliminate_left_with_is_true_and_in_list() -> Result<()> {
1436        let t1 = test_table_scan_with_name("t1")?;
1437        let t2 = test_table_scan_with_name("t2")?;
1438
1439        // AND of IS TRUE and IN on nullable side — both null-rejecting
1440        let plan = LogicalPlanBuilder::from(t1)
1441            .join(
1442                t2,
1443                JoinType::Left,
1444                (vec![Column::from_name("a")], vec![Column::from_name("a")]),
1445                None,
1446            )?
1447            .filter(binary_expr(
1448                col("t2.b").gt(lit(5u32)).is_true(),
1449                And,
1450                col("t2.c").in_list(vec![lit(1u32), lit(2u32)], false),
1451            ))?
1452            .build()?;
1453
1454        assert_optimized_plan_equal!(plan, @r"
1455        Filter: t2.b > UInt32(5) IS TRUE AND t2.c IN ([UInt32(1), UInt32(2)])
1456          Inner Join: t1.a = t2.a
1457            TableScan: t1
1458            TableScan: t2
1459        ")
1460    }
1461
1462    // ----- Filter pierces a Projection to reach the Join -----
1463
1464    #[test]
1465    fn eliminate_left_through_projection() -> Result<()> {
1466        let t1 = test_table_scan_with_name("t1")?;
1467        let t2 = test_table_scan_with_name("t2")?;
1468
1469        // Filter → Projection → LeftJoin is the shape produced by projection
1470        // pruning in queries such as TPC-DS q49, where the post-join
1471        // Projection sits between the filter and the join.
1472        let plan = LogicalPlanBuilder::from(t1)
1473            .join(
1474                t2,
1475                JoinType::Left,
1476                (vec![Column::from_name("a")], vec![Column::from_name("a")]),
1477                None,
1478            )?
1479            .project(vec![col("t1.a"), col("t2.b").alias("bb")])?
1480            .filter(col("bb").gt(lit(10u32)))?
1481            .build()?;
1482
1483        assert_optimized_plan_equal!(plan, @r"
1484        Filter: bb > UInt32(10)
1485          Projection: t1.a, t2.b AS bb
1486            Inner Join: t1.a = t2.a
1487              TableScan: t1
1488              TableScan: t2
1489        ")
1490    }
1491
1492    #[test]
1493    fn no_eliminate_left_through_projection_with_or_cross_side() -> Result<()> {
1494        let t1 = test_table_scan_with_name("t1")?;
1495        let t2 = test_table_scan_with_name("t2")?;
1496
1497        // After inlining the filter is still t1.b > 10 OR t2.b < 20, which
1498        // is null-tolerant when t2 is NULL (the t1.b clause can still hold).
1499        // The LEFT JOIN must be preserved.
1500        let plan = LogicalPlanBuilder::from(t1)
1501            .join(
1502                t2,
1503                JoinType::Left,
1504                (vec![Column::from_name("a")], vec![Column::from_name("a")]),
1505                None,
1506            )?
1507            .project(vec![col("t1.b").alias("x"), col("t2.b").alias("y")])?
1508            .filter(binary_expr(
1509                col("x").gt(lit(10u32)),
1510                Or,
1511                col("y").lt(lit(20u32)),
1512            ))?
1513            .build()?;
1514
1515        assert_optimized_plan_equal!(plan, @r"
1516        Filter: x > UInt32(10) OR y < UInt32(20)
1517          Projection: t1.b AS x, t2.b AS y
1518            Left Join: t1.a = t2.a
1519              TableScan: t1
1520              TableScan: t2
1521        ")
1522    }
1523
1524    #[test]
1525    fn no_eliminate_left_through_projection_with_only_left_filter() -> Result<()> {
1526        let t1 = test_table_scan_with_name("t1")?;
1527        let t2 = test_table_scan_with_name("t2")?;
1528
1529        // A filter that constrains only the preserved (left) side of a
1530        // LEFT JOIN does not justify converting it to INNER — the LEFT
1531        // would still pass nullable right-side rows that the filter
1532        // accepts.
1533        let plan = LogicalPlanBuilder::from(t1)
1534            .join(
1535                t2,
1536                JoinType::Left,
1537                (vec![Column::from_name("a")], vec![Column::from_name("a")]),
1538                None,
1539            )?
1540            .project(vec![col("t1.b").alias("x"), col("t2.b")])?
1541            .filter(col("x").gt(lit(10u32)))?
1542            .build()?;
1543
1544        assert_optimized_plan_equal!(plan, @r"
1545        Filter: x > UInt32(10)
1546          Projection: t1.b AS x, t2.b
1547            Left Join: t1.a = t2.a
1548              TableScan: t1
1549              TableScan: t2
1550        ")
1551    }
1552
1553    #[test]
1554    fn eliminate_left_with_arithmetic_predicate() -> Result<()> {
1555        let t1 = test_table_scan_with_name("t1")?;
1556        let t2 = test_table_scan_with_name("t2")?;
1557
1558        // t2.b * 2 + 1 > 10 is null-rejecting on t2.b: arithmetic
1559        // operators propagate NULL, so the whole expression is NULL when
1560        // t2.b is NULL, and NULL > 10 is filtered out by WHERE.
1561        let plan = LogicalPlanBuilder::from(t1)
1562            .join(
1563                t2,
1564                JoinType::Left,
1565                (vec![Column::from_name("a")], vec![Column::from_name("a")]),
1566                None,
1567            )?
1568            .filter(
1569                binary_expr(
1570                    binary_expr(col("t2.b"), Operator::Multiply, lit(2u32)),
1571                    Operator::Plus,
1572                    lit(1u32),
1573                )
1574                .gt(lit(10u32)),
1575            )?
1576            .build()?;
1577
1578        assert_optimized_plan_equal!(plan, @r"
1579        Filter: t2.b * UInt32(2) + UInt32(1) > UInt32(10)
1580          Inner Join: t1.a = t2.a
1581            TableScan: t1
1582            TableScan: t2
1583        ")
1584    }
1585    #[test]
1586    fn eliminate_left_with_negative_predicate() -> Result<()> {
1587        let t1 = test_table_scan_with_name("t1")?;
1588        let t2 = test_table_scan_with_name("t2")?;
1589
1590        // Unary minus propagates NULL: -NULL is NULL, so `WHERE -t2.b > 0`
1591        // is null-rejecting on t2.b.
1592        let plan = LogicalPlanBuilder::from(t1)
1593            .join(
1594                t2,
1595                JoinType::Left,
1596                (vec![Column::from_name("a")], vec![Column::from_name("a")]),
1597                None,
1598            )?
1599            .filter(Expr::Negative(Box::new(col("t2.b"))).gt(lit(0u32)))?
1600            .build()?;
1601
1602        assert_optimized_plan_equal!(plan, @r"
1603        Filter: (- t2.b) > UInt32(0)
1604          Inner Join: t1.a = t2.a
1605            TableScan: t1
1606            TableScan: t2
1607        ")
1608    }
1609
1610    #[test]
1611    fn no_eliminate_left_with_is_distinct_from() -> Result<()> {
1612        let t1 = test_table_scan_with_name("t1")?;
1613        let t2 = test_table_scan_with_name("t2")?;
1614
1615        // IS DISTINCT FROM is NOT null-rejecting: t2.b IS DISTINCT FROM 5 is
1616        // true when t2.b is NULL (NULL is distinct from 5). Padding rows from
1617        // a LEFT JOIN would survive the filter, so the LEFT JOIN must stay.
1618        let plan = LogicalPlanBuilder::from(t1)
1619            .join(
1620                t2,
1621                JoinType::Left,
1622                (vec![Column::from_name("a")], vec![Column::from_name("a")]),
1623                None,
1624            )?
1625            .filter(binary_expr(
1626                col("t2.b"),
1627                Operator::IsDistinctFrom,
1628                lit(5u32),
1629            ))?
1630            .build()?;
1631
1632        assert_optimized_plan_equal!(plan, @r"
1633        Filter: t2.b IS DISTINCT FROM UInt32(5)
1634          Left Join: t1.a = t2.a
1635            TableScan: t1
1636            TableScan: t2
1637        ")
1638    }
1639
1640    #[test]
1641    fn no_eliminate_left_with_is_not_distinct_from() -> Result<()> {
1642        let t1 = test_table_scan_with_name("t1")?;
1643        let t2 = test_table_scan_with_name("t2")?;
1644
1645        // IS NOT DISTINCT FROM is also not null-rejecting: t2.b IS NOT
1646        // DISTINCT FROM NULL is true when t2.b is NULL. The LEFT JOIN must
1647        // stay.
1648        let plan = LogicalPlanBuilder::from(t1)
1649            .join(
1650                t2,
1651                JoinType::Left,
1652                (vec![Column::from_name("a")], vec![Column::from_name("a")]),
1653                None,
1654            )?
1655            .filter(binary_expr(
1656                col("t2.b"),
1657                Operator::IsNotDistinctFrom,
1658                lit(ScalarValue::UInt32(None)),
1659            ))?
1660            .build()?;
1661
1662        assert_optimized_plan_equal!(plan, @r"
1663        Filter: t2.b IS NOT DISTINCT FROM UInt32(NULL)
1664          Left Join: t1.a = t2.a
1665            TableScan: t1
1666            TableScan: t2
1667        ")
1668    }
1669
1670    #[test]
1671    fn no_eliminate_through_non_transparent() -> Result<()> {
1672        let t1 = test_table_scan_with_name("t1")?;
1673        let t2 = test_table_scan_with_name("t2")?;
1674
1675        // Limit is intentionally not treated as transparent: a Limit below
1676        // the Filter changes which rows survive, so swapping LEFT→INNER
1677        // beneath it could yield a different surviving-row set even when
1678        // the filter is null-rejecting on the right side.
1679        let plan = LogicalPlanBuilder::from(t1)
1680            .join(
1681                t2,
1682                JoinType::Left,
1683                (vec![Column::from_name("a")], vec![Column::from_name("a")]),
1684                None,
1685            )?
1686            .limit(0, Some(5))?
1687            .filter(col("t2.b").gt(lit(10u32)))?
1688            .build()?;
1689
1690        assert_optimized_plan_equal!(plan, @r"
1691        Filter: t2.b > UInt32(10)
1692          Limit: skip=0, fetch=5
1693            Left Join: t1.a = t2.a
1694              TableScan: t1
1695              TableScan: t2
1696        ")
1697    }
1698}