Skip to main content

datafusion_optimizer/
eliminate_cross_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//! [`EliminateCrossJoin`] converts `CROSS JOIN` to `INNER JOIN` if join predicates are available.
6use crate::{OptimizerConfig, OptimizerRule};
7use std::sync::Arc;
8
9use crate::join_key_set::JoinKeySet;
10use datafusion_common::tree_node::{Transformed, TreeNode, TreeNodeRecursion};
11use datafusion_common::{NullEquality, Result};
12use datafusion_expr::expr::{BinaryExpr, Expr};
13use datafusion_expr::logical_plan::{
14    Filter, Join, JoinConstraint, JoinType, LogicalPlan, Projection,
15};
16use datafusion_expr::utils::{can_hash, find_valid_equijoin_key_pair};
17use datafusion_expr::{ExprSchemable, Operator, and, build_join_schema};
18
19#[derive(Default, Debug)]
20pub struct EliminateCrossJoin;
21
22impl EliminateCrossJoin {
23    #[expect(missing_docs)]
24    pub fn new() -> Self {
25        Self {}
26    }
27}
28
29/// Eliminate cross joins by rewriting them to inner joins when possible.
30///
31/// # Example
32/// The initial plan for this query:
33/// ```sql
34/// select ... from a, b where a.x = b.y and b.xx = 100;
35/// ```
36///
37/// Looks like this:
38/// ```text
39/// Filter(a.x = b.y AND b.xx = 100)
40///  Cross Join
41///   TableScan a
42///   TableScan b
43/// ```
44///
45/// After the rule is applied, the plan will look like this:
46/// ```text
47/// Filter(b.xx = 100)
48///   InnerJoin(a.x = b.y)
49///     TableScan a
50///     TableScan b
51/// ```
52///
53/// # Other Examples
54/// * 'select ... from a, b where a.x = b.y and b.xx = 100;'
55/// * 'select ... from a, b where (a.x = b.y and b.xx = 100) or (a.x = b.y and b.xx = 200);'
56/// * 'select ... from a, b, c where (a.x = b.y and b.xx = 100 and a.z = c.z)
57/// * or (a.x = b.y and b.xx = 200 and a.z=c.z);'
58/// * 'select ... from a, b where a.x > b.y'
59///
60/// For above queries, the join predicate is available in filters and they are moved to
61/// join nodes appropriately
62///
63/// This fix helps to improve the performance of TPCH Q19. issue#78
64impl OptimizerRule for EliminateCrossJoin {
65    #[cfg_attr(feature = "recursive_protection", recursive::recursive)]
66    fn rewrite(
67        &self,
68        plan: LogicalPlan,
69        config: &dyn OptimizerConfig,
70    ) -> Result<Transformed<LogicalPlan>> {
71        // Fast path: nothing to do if the plan contains no `Join` nodes.
72        // Without this guard the rule still falls through to
73        // `rewrite_children`, which walks the entire plan, processes
74        // uncorrelated subqueries, and rewrites every direct child via
75        // `map_children` (clone-on-write) — paid by every query in the
76        // logical optimizer pipeline. Same shape as the
77        // `plan_has_subqueries` fast-path landed in #22298.
78        if !plan_has_joins(&plan) {
79            return Ok(Transformed::no(plan));
80        }
81
82        let plan_schema = Arc::clone(plan.schema());
83        let mut possible_join_keys = JoinKeySet::new();
84        let mut all_inputs: Vec<LogicalPlan> = vec![];
85        let mut all_filters: Vec<Expr> = vec![];
86        let mut null_equality = NullEquality::NullEqualsNothing;
87
88        let parent_predicate = if let LogicalPlan::Filter(filter) = plan {
89            // if input isn't a join that can potentially be rewritten
90            // avoid unwrapping the input
91            let rewritable = matches!(
92                filter.input.as_ref(),
93                LogicalPlan::Join(Join {
94                    join_type: JoinType::Inner,
95                    ..
96                })
97            );
98
99            if !rewritable {
100                // recursively try to rewrite children
101                return rewrite_children(self, LogicalPlan::Filter(filter), config);
102            }
103
104            let Filter {
105                input, predicate, ..
106            } = filter;
107
108            // Extract null_equality setting from the input join
109            if let LogicalPlan::Join(join) = input.as_ref() {
110                null_equality = join.null_equality;
111            }
112
113            flatten_join_inputs(
114                Arc::unwrap_or_clone(input),
115                &mut possible_join_keys,
116                &mut all_inputs,
117                &mut all_filters,
118            );
119
120            extract_possible_join_keys(&predicate, &mut possible_join_keys);
121            Some(predicate)
122        } else {
123            match plan {
124                LogicalPlan::Join(Join {
125                    join_type: JoinType::Inner,
126                    null_equality: original_null_equality,
127                    ..
128                }) => {
129                    flatten_join_inputs(
130                        plan,
131                        &mut possible_join_keys,
132                        &mut all_inputs,
133                        &mut all_filters,
134                    );
135                    null_equality = original_null_equality;
136                    None
137                }
138                _ => {
139                    // recursively try to rewrite children
140                    return rewrite_children(self, plan, config);
141                }
142            }
143        };
144
145        // Rewrite each flattened input once, before reassembling the joins.
146        // `rewrite` preserves its input's schema, which is all that
147        // `find_inner_join` looks at, so this is equivalent to rewriting the
148        // children of the reassembled join tree, but avoids flattening and
149        // rebuilding the rest of the join chain again at every nesting level.
150        let mut all_inputs = all_inputs
151            .into_iter()
152            .map(|input| self.rewrite(input, config).map(|t| t.data))
153            .collect::<Result<Vec<_>>>()?;
154
155        // Join keys are handled locally:
156        let mut all_join_keys = JoinKeySet::new();
157        let mut left = all_inputs.remove(0);
158        while !all_inputs.is_empty() {
159            left = find_inner_join(
160                left,
161                &mut all_inputs,
162                &possible_join_keys,
163                &mut all_join_keys,
164                null_equality,
165            )?
166            // Join keys may contain uncorrelated subqueries to rewrite
167            .map_uncorrelated_subqueries(|input| self.rewrite(input, config))?
168            .data;
169        }
170
171        if &plan_schema != left.schema() {
172            left = LogicalPlan::Projection(Projection::new_from_schema(
173                Arc::new(left),
174                Arc::clone(&plan_schema),
175            ));
176        }
177
178        if !all_filters.is_empty() {
179            // Add any filters on top - PushDownFilter can push filters down to applicable join
180            let first = all_filters.swap_remove(0);
181            let predicate = all_filters.into_iter().fold(first, and);
182            left = LogicalPlan::Filter(Filter::try_new(predicate, Arc::new(left))?);
183        }
184
185        let Some(predicate) = parent_predicate else {
186            return Ok(Transformed::yes(left));
187        };
188
189        // If there are no join keys then do nothing:
190        if all_join_keys.is_empty() {
191            Filter::try_new(predicate, Arc::new(left))
192                .map(|filter| Transformed::yes(LogicalPlan::Filter(filter)))
193        } else {
194            // Remove join expressions from filter:
195            match remove_join_expressions(predicate, &all_join_keys) {
196                Some(filter_expr) => Filter::try_new(filter_expr, Arc::new(left))
197                    .map(|filter| Transformed::yes(LogicalPlan::Filter(filter))),
198                _ => Ok(Transformed::yes(left)),
199            }
200        }
201    }
202
203    fn name(&self) -> &str {
204        "eliminate_cross_join"
205    }
206}
207
208/// Returns `true` if `plan` contains at least one [`LogicalPlan::Join`]
209/// node, either directly in its tree *or* inside an embedded subquery
210/// plan reachable through `Expr::ScalarSubquery` / `Expr::InSubquery`
211/// / `Expr::Exists` / `Expr::SetComparison`.
212///
213/// Used as a fast-path gate at the top of [`EliminateCrossJoin::rewrite`]
214/// so that join-free plans skip the full recursive rewrite. Subquery
215/// traversal matters because `rewrite_children` also dives into
216/// uncorrelated subqueries via `map_uncorrelated_subqueries`; ignoring
217/// them here would skip optimizing a `CROSS JOIN` that sits only inside
218/// an `IN (SELECT ... FROM a, b)`-style predicate.
219///
220/// `LogicalPlan::apply_with_subqueries` already implements the
221/// "walk this node + every child + every subquery plan" traversal we
222/// need, so the helper is a thin wrapper around it.
223fn plan_has_joins(plan: &LogicalPlan) -> bool {
224    let mut found = false;
225    let _ = plan.apply_with_subqueries(|node| {
226        if matches!(node, LogicalPlan::Join(_)) {
227            found = true;
228            Ok(TreeNodeRecursion::Stop)
229        } else {
230            Ok(TreeNodeRecursion::Continue)
231        }
232    });
233    found
234}
235
236fn rewrite_children(
237    optimizer: &impl OptimizerRule,
238    plan: LogicalPlan,
239    config: &dyn OptimizerConfig,
240) -> Result<Transformed<LogicalPlan>> {
241    // Process uncorrelated subqueries in expressions, then direct children.
242    let transformed_plan = plan
243        .map_uncorrelated_subqueries(|input| optimizer.rewrite(input, config))?
244        .transform_sibling(|plan| {
245            plan.map_children(|input| optimizer.rewrite(input, config))
246        })?;
247
248    // recompute schema if the plan was transformed
249    if transformed_plan.transformed {
250        transformed_plan.map_data(|plan| plan.recompute_schema())
251    } else {
252        Ok(transformed_plan)
253    }
254}
255
256/// Recursively collect inputs, join keys, and filters from inner joins
257/// (including cross joins). Other nodes are retained as inputs without
258/// flattening them.
259fn flatten_join_inputs(
260    plan: LogicalPlan,
261    possible_join_keys: &mut JoinKeySet,
262    all_inputs: &mut Vec<LogicalPlan>,
263    all_filters: &mut Vec<Expr>,
264) {
265    match plan {
266        LogicalPlan::Join(join) if join.join_type == JoinType::Inner => {
267            if let Some(filter) = join.filter {
268                all_filters.push(filter);
269            }
270            possible_join_keys.insert_all_owned(join.on);
271            flatten_join_inputs(
272                Arc::unwrap_or_clone(join.left),
273                possible_join_keys,
274                all_inputs,
275                all_filters,
276            );
277            flatten_join_inputs(
278                Arc::unwrap_or_clone(join.right),
279                possible_join_keys,
280                all_inputs,
281                all_filters,
282            );
283        }
284        _ => {
285            all_inputs.push(plan);
286        }
287    }
288}
289
290/// Finds the next to join with the left input plan,
291///
292/// Finds the next `right` from `rights` that can be joined with `left_input`
293/// plan based on the join keys in `possible_join_keys`.
294///
295/// If such a matching `right` is found:
296/// 1. Adds the matching join keys to `all_join_keys`.
297/// 2. Returns `left_input JOIN right ON (all join keys)`.
298///
299/// If no matching `right` is found:
300/// 1. Removes the first plan from `rights`
301/// 2. Returns `left_input CROSS JOIN right`.
302fn find_inner_join(
303    left_input: LogicalPlan,
304    rights: &mut Vec<LogicalPlan>,
305    possible_join_keys: &JoinKeySet,
306    all_join_keys: &mut JoinKeySet,
307    null_equality: NullEquality,
308) -> Result<LogicalPlan> {
309    for (i, right_input) in rights.iter().enumerate() {
310        let mut join_keys = vec![];
311
312        for (l, r) in possible_join_keys.iter() {
313            let key_pair = find_valid_equijoin_key_pair(
314                l,
315                r,
316                left_input.schema(),
317                right_input.schema(),
318            )?;
319
320            // Save join keys
321            if let Some((valid_l, valid_r)) = key_pair
322                && can_hash(&valid_l.get_type(left_input.schema())?)
323            {
324                join_keys.push((valid_l, valid_r));
325            }
326        }
327
328        // Found one or more matching join keys
329        if !join_keys.is_empty() {
330            all_join_keys.insert_all(join_keys.iter());
331            let right_input = rights.remove(i);
332            let join_schema = Arc::new(build_join_schema(
333                left_input.schema(),
334                right_input.schema(),
335                &JoinType::Inner,
336            )?);
337
338            return Ok(LogicalPlan::Join(Join {
339                left: Arc::new(left_input),
340                right: Arc::new(right_input),
341                join_type: JoinType::Inner,
342                join_constraint: JoinConstraint::On,
343                on: join_keys,
344                filter: None,
345                schema: join_schema,
346                null_equality,
347                null_aware: false,
348                null_aware_value_keys: 0,
349            }));
350        }
351    }
352
353    // no matching right plan had any join keys, cross join with the first right
354    // plan
355    let right = rights.remove(0);
356    let join_schema = Arc::new(build_join_schema(
357        left_input.schema(),
358        right.schema(),
359        &JoinType::Inner,
360    )?);
361
362    Ok(LogicalPlan::Join(Join {
363        left: Arc::new(left_input),
364        right: Arc::new(right),
365        schema: join_schema,
366        on: vec![],
367        filter: None,
368        join_type: JoinType::Inner,
369        join_constraint: JoinConstraint::On,
370        null_equality,
371        null_aware: false,
372        null_aware_value_keys: 0,
373    }))
374}
375
376/// Extract join keys from a WHERE clause
377fn extract_possible_join_keys(expr: &Expr, join_keys: &mut JoinKeySet) {
378    if let Expr::BinaryExpr(BinaryExpr { left, op, right }) = expr {
379        match op {
380            Operator::Eq => {
381                // insert handles ensuring  we don't add the same Join keys multiple times
382                join_keys.insert(left, right);
383            }
384            Operator::And => {
385                extract_possible_join_keys(left, join_keys);
386                extract_possible_join_keys(right, join_keys)
387            }
388            // Fix for issue#78 join predicates from inside of OR expr also pulled up properly.
389            Operator::Or => {
390                let mut left_join_keys = JoinKeySet::new();
391                let mut right_join_keys = JoinKeySet::new();
392
393                extract_possible_join_keys(left, &mut left_join_keys);
394                extract_possible_join_keys(right, &mut right_join_keys);
395
396                join_keys.insert_intersection(&left_join_keys, &right_join_keys)
397            }
398            _ => (),
399        }
400    }
401}
402
403/// Remove join expressions from a filter expression
404///
405/// # Returns
406/// * `Some()` when there are few remaining predicates in filter_expr
407/// * `None` otherwise
408fn remove_join_expressions(expr: Expr, join_keys: &JoinKeySet) -> Option<Expr> {
409    match expr {
410        Expr::BinaryExpr(BinaryExpr {
411            left,
412            op: Operator::Eq,
413            right,
414        }) if join_keys.contains(&left, &right) => {
415            // was a join key, so remove it
416            None
417        }
418        // Fix for issue#78 join predicates from inside of OR expr also pulled up properly.
419        Expr::BinaryExpr(BinaryExpr { left, op, right }) if op == Operator::And => {
420            let l = remove_join_expressions(*left, join_keys);
421            let r = remove_join_expressions(*right, join_keys);
422            match (l, r) {
423                (Some(ll), Some(rr)) => Some(Expr::BinaryExpr(BinaryExpr::new(
424                    Box::new(ll),
425                    op,
426                    Box::new(rr),
427                ))),
428                (Some(ll), _) => Some(ll),
429                (_, Some(rr)) => Some(rr),
430                _ => None,
431            }
432        }
433        Expr::BinaryExpr(BinaryExpr { left, op, right }) if op == Operator::Or => {
434            let l = remove_join_expressions(*left, join_keys);
435            let r = remove_join_expressions(*right, join_keys);
436            match (l, r) {
437                (Some(ll), Some(rr)) => Some(Expr::BinaryExpr(BinaryExpr::new(
438                    Box::new(ll),
439                    op,
440                    Box::new(rr),
441                ))),
442                // When either `left` or `right` is empty, it means they are `true`
443                // so OR'ing anything with them will also be true
444                _ => None,
445            }
446        }
447        _ => Some(expr),
448    }
449}
450
451#[cfg(test)]
452mod tests {
453    use super::*;
454    use crate::optimizer::OptimizerContext;
455    use crate::test::*;
456
457    use datafusion_expr::{
458        Operator::{And, Or},
459        binary_expr, col, lit,
460        logical_plan::builder::LogicalPlanBuilder,
461        scalar_subquery,
462    };
463    use insta::assert_snapshot;
464
465    macro_rules! assert_optimized_plan_equal {
466        (
467            $plan:expr,
468            @ $expected:literal $(,)?
469        ) => {{
470            let starting_schema = Arc::clone($plan.schema());
471            let rule = EliminateCrossJoin::new();
472            let Transformed {transformed: is_plan_transformed, data: optimized_plan, ..} = rule.rewrite($plan, &OptimizerContext::new()).unwrap();
473            let formatted_plan = optimized_plan.display_indent_schema();
474            // Ensure the rule was actually applied
475            assert!(is_plan_transformed, "failed to optimize plan");
476            // Verify the schema remains unchanged
477            assert_eq!(&starting_schema, optimized_plan.schema());
478            assert_snapshot!(
479                formatted_plan,
480                @ $expected,
481            );
482
483            Ok(())
484        }};
485    }
486
487    #[test]
488    fn eliminate_cross_with_simple_and() -> Result<()> {
489        let t1 = test_table_scan_with_name("t1")?;
490        let t2 = test_table_scan_with_name("t2")?;
491
492        // could eliminate to inner join since filter has Join predicates
493        let plan = LogicalPlanBuilder::from(t1)
494            .cross_join(t2)?
495            .filter(binary_expr(
496                col("t1.a").eq(col("t2.a")),
497                And,
498                col("t2.c").lt(lit(20u32)),
499            ))?
500            .build()?;
501
502        assert_optimized_plan_equal!(
503            plan,
504            @ r"
505        Filter: t2.c < UInt32(20) [a:UInt32, b:UInt32, c:UInt32, a:UInt32, b:UInt32, c:UInt32]
506          Inner Join: t1.a = t2.a [a:UInt32, b:UInt32, c:UInt32, a:UInt32, b:UInt32, c:UInt32]
507            TableScan: t1 [a:UInt32, b:UInt32, c:UInt32]
508            TableScan: t2 [a:UInt32, b:UInt32, c:UInt32]
509        "
510        )
511    }
512
513    #[test]
514    fn eliminate_cross_with_simple_or() -> Result<()> {
515        let t1 = test_table_scan_with_name("t1")?;
516        let t2 = test_table_scan_with_name("t2")?;
517
518        // could not eliminate to inner join since filter OR expression and there is no common
519        // Join predicates in left and right of OR expr.
520        let plan = LogicalPlanBuilder::from(t1)
521            .cross_join(t2)?
522            .filter(binary_expr(
523                col("t1.a").eq(col("t2.a")),
524                Or,
525                col("t2.b").eq(col("t1.a")),
526            ))?
527            .build()?;
528
529        assert_optimized_plan_equal!(
530            plan,
531            @ r"
532        Filter: t1.a = t2.a OR t2.b = t1.a [a:UInt32, b:UInt32, c:UInt32, a:UInt32, b:UInt32, c:UInt32]
533          Cross Join: [a:UInt32, b:UInt32, c:UInt32, a:UInt32, b:UInt32, c:UInt32]
534            TableScan: t1 [a:UInt32, b:UInt32, c:UInt32]
535            TableScan: t2 [a:UInt32, b:UInt32, c:UInt32]
536        "
537        )
538    }
539
540    #[test]
541    fn eliminate_cross_with_and() -> Result<()> {
542        let t1 = test_table_scan_with_name("t1")?;
543        let t2 = test_table_scan_with_name("t2")?;
544
545        // could eliminate to inner join
546        let plan = LogicalPlanBuilder::from(t1)
547            .cross_join(t2)?
548            .filter(binary_expr(
549                binary_expr(col("t1.a").eq(col("t2.a")), And, col("t2.c").lt(lit(20u32))),
550                And,
551                binary_expr(col("t1.a").eq(col("t2.a")), And, col("t2.c").eq(lit(10u32))),
552            ))?
553            .build()?;
554
555        assert_optimized_plan_equal!(
556            plan,
557            @ r"
558        Filter: t2.c < UInt32(20) AND t2.c = UInt32(10) [a:UInt32, b:UInt32, c:UInt32, a:UInt32, b:UInt32, c:UInt32]
559          Inner Join: t1.a = t2.a [a:UInt32, b:UInt32, c:UInt32, a:UInt32, b:UInt32, c:UInt32]
560            TableScan: t1 [a:UInt32, b:UInt32, c:UInt32]
561            TableScan: t2 [a:UInt32, b:UInt32, c:UInt32]
562        "
563        )
564    }
565
566    #[test]
567    fn eliminate_cross_with_or() -> Result<()> {
568        let t1 = test_table_scan_with_name("t1")?;
569        let t2 = test_table_scan_with_name("t2")?;
570
571        // could eliminate to inner join since Or predicates have common Join predicates
572        let plan = LogicalPlanBuilder::from(t1)
573            .cross_join(t2)?
574            .filter(binary_expr(
575                binary_expr(col("t1.a").eq(col("t2.a")), And, col("t2.c").lt(lit(15u32))),
576                Or,
577                binary_expr(
578                    col("t1.a").eq(col("t2.a")),
579                    And,
580                    col("t2.c").eq(lit(688u32)),
581                ),
582            ))?
583            .build()?;
584
585        assert_optimized_plan_equal!(
586            plan,
587            @ r"
588        Filter: t2.c < UInt32(15) OR t2.c = UInt32(688) [a:UInt32, b:UInt32, c:UInt32, a:UInt32, b:UInt32, c:UInt32]
589          Inner Join: t1.a = t2.a [a:UInt32, b:UInt32, c:UInt32, a:UInt32, b:UInt32, c:UInt32]
590            TableScan: t1 [a:UInt32, b:UInt32, c:UInt32]
591            TableScan: t2 [a:UInt32, b:UInt32, c:UInt32]
592        "
593        )
594    }
595
596    #[test]
597    fn eliminate_cross_not_possible_simple() -> Result<()> {
598        let t1 = test_table_scan_with_name("t1")?;
599        let t2 = test_table_scan_with_name("t2")?;
600
601        // could not eliminate to inner join
602        let plan = LogicalPlanBuilder::from(t1)
603            .cross_join(t2)?
604            .filter(binary_expr(
605                binary_expr(col("t1.a").eq(col("t2.a")), And, col("t2.c").lt(lit(15u32))),
606                Or,
607                binary_expr(
608                    col("t1.b").eq(col("t2.b")),
609                    And,
610                    col("t2.c").eq(lit(688u32)),
611                ),
612            ))?
613            .build()?;
614
615        assert_optimized_plan_equal!(
616            plan,
617            @ r"
618        Filter: t1.a = t2.a AND t2.c < UInt32(15) OR t1.b = t2.b AND t2.c = UInt32(688) [a:UInt32, b:UInt32, c:UInt32, a:UInt32, b:UInt32, c:UInt32]
619          Cross Join: [a:UInt32, b:UInt32, c:UInt32, a:UInt32, b:UInt32, c:UInt32]
620            TableScan: t1 [a:UInt32, b:UInt32, c:UInt32]
621            TableScan: t2 [a:UInt32, b:UInt32, c:UInt32]
622        "
623        )
624    }
625
626    #[test]
627    fn eliminate_cross_not_possible() -> Result<()> {
628        let t1 = test_table_scan_with_name("t1")?;
629        let t2 = test_table_scan_with_name("t2")?;
630
631        // could not eliminate to inner join
632        let plan = LogicalPlanBuilder::from(t1)
633            .cross_join(t2)?
634            .filter(binary_expr(
635                binary_expr(col("t1.a").eq(col("t2.a")), And, col("t2.c").lt(lit(15u32))),
636                Or,
637                binary_expr(col("t1.a").eq(col("t2.a")), Or, col("t2.c").eq(lit(688u32))),
638            ))?
639            .build()?;
640
641        assert_optimized_plan_equal!(
642            plan,
643            @ r"
644        Filter: t1.a = t2.a AND t2.c < UInt32(15) OR t1.a = t2.a OR t2.c = UInt32(688) [a:UInt32, b:UInt32, c:UInt32, a:UInt32, b:UInt32, c:UInt32]
645          Cross Join: [a:UInt32, b:UInt32, c:UInt32, a:UInt32, b:UInt32, c:UInt32]
646            TableScan: t1 [a:UInt32, b:UInt32, c:UInt32]
647            TableScan: t2 [a:UInt32, b:UInt32, c:UInt32]
648        "
649        )
650    }
651
652    #[test]
653    fn eliminate_cross_possible_nested_inner_join_with_filter() -> Result<()> {
654        let t1 = test_table_scan_with_name("t1")?;
655        let t2 = test_table_scan_with_name("t2")?;
656        let t3 = test_table_scan_with_name("t3")?;
657
658        // could not eliminate to inner join with filter
659        let plan = LogicalPlanBuilder::from(t1)
660            .join(
661                t3,
662                JoinType::Inner,
663                (vec!["t1.a"], vec!["t3.a"]),
664                Some(col("t1.a").gt(lit(20u32))),
665            )?
666            .join(t2, JoinType::Inner, (vec!["t1.a"], vec!["t2.a"]), None)?
667            .filter(col("t1.a").gt(lit(15u32)))?
668            .build()?;
669
670        assert_optimized_plan_equal!(
671            plan,
672            @ r"
673        Filter: t1.a > UInt32(15) [a:UInt32, b:UInt32, c:UInt32, a:UInt32, b:UInt32, c:UInt32, a:UInt32, b:UInt32, c:UInt32]
674          Filter: t1.a > UInt32(20) [a:UInt32, b:UInt32, c:UInt32, a:UInt32, b:UInt32, c:UInt32, a:UInt32, b:UInt32, c:UInt32]
675            Inner Join: t1.a = t2.a [a:UInt32, b:UInt32, c:UInt32, a:UInt32, b:UInt32, c:UInt32, a:UInt32, b:UInt32, c:UInt32]
676              Inner Join: t1.a = t3.a [a:UInt32, b:UInt32, c:UInt32, a:UInt32, b:UInt32, c:UInt32]
677                TableScan: t1 [a:UInt32, b:UInt32, c:UInt32]
678                TableScan: t3 [a:UInt32, b:UInt32, c:UInt32]
679              TableScan: t2 [a:UInt32, b:UInt32, c:UInt32]
680        "
681        )
682    }
683
684    #[test]
685    /// ```txt
686    /// filter: a.id = b.id and a.id = c.id
687    ///   cross_join a (bc)
688    ///     cross_join b c
689    /// ```
690    /// Without reorder, it will be
691    /// ```txt
692    ///   inner_join a (bc) on a.id = b.id and a.id = c.id
693    ///     cross_join b c
694    /// ```
695    /// Reorder it to be
696    /// ```txt
697    ///   inner_join (ab)c and a.id = c.id
698    ///     inner_join a b on a.id = b.id
699    /// ```
700    fn reorder_join_to_eliminate_cross_join_multi_tables() -> Result<()> {
701        let t1 = test_table_scan_with_name("t1")?;
702        let t2 = test_table_scan_with_name("t2")?;
703        let t3 = test_table_scan_with_name("t3")?;
704
705        // could eliminate to inner join
706        let plan = LogicalPlanBuilder::from(t1)
707            .cross_join(t2)?
708            .cross_join(t3)?
709            .filter(binary_expr(
710                binary_expr(col("t3.a").eq(col("t1.a")), And, col("t3.c").lt(lit(15u32))),
711                And,
712                binary_expr(col("t3.a").eq(col("t2.a")), And, col("t3.b").lt(lit(15u32))),
713            ))?
714            .build()?;
715
716        assert_optimized_plan_equal!(
717            plan,
718            @ r"
719        Filter: t3.c < UInt32(15) AND t3.b < UInt32(15) [a:UInt32, b:UInt32, c:UInt32, a:UInt32, b:UInt32, c:UInt32, a:UInt32, b:UInt32, c:UInt32]
720          Projection: t1.a, t1.b, t1.c, t2.a, t2.b, t2.c, t3.a, t3.b, t3.c [a:UInt32, b:UInt32, c:UInt32, a:UInt32, b:UInt32, c:UInt32, a:UInt32, b:UInt32, c:UInt32]
721            Inner Join: t3.a = t2.a [a:UInt32, b:UInt32, c:UInt32, a:UInt32, b:UInt32, c:UInt32, a:UInt32, b:UInt32, c:UInt32]
722              Inner Join: t1.a = t3.a [a:UInt32, b:UInt32, c:UInt32, a:UInt32, b:UInt32, c:UInt32]
723                TableScan: t1 [a:UInt32, b:UInt32, c:UInt32]
724                TableScan: t3 [a:UInt32, b:UInt32, c:UInt32]
725              TableScan: t2 [a:UInt32, b:UInt32, c:UInt32]
726        "
727        )
728    }
729
730    #[test]
731    fn eliminate_cross_join_multi_tables() -> Result<()> {
732        let t1 = test_table_scan_with_name("t1")?;
733        let t2 = test_table_scan_with_name("t2")?;
734        let t3 = test_table_scan_with_name("t3")?;
735        let t4 = test_table_scan_with_name("t4")?;
736
737        // could eliminate to inner join
738        let plan1 = LogicalPlanBuilder::from(t1)
739            .cross_join(t2)?
740            .filter(binary_expr(
741                binary_expr(col("t1.a").eq(col("t2.a")), And, col("t2.c").lt(lit(15u32))),
742                Or,
743                binary_expr(
744                    col("t1.a").eq(col("t2.a")),
745                    And,
746                    col("t2.c").eq(lit(688u32)),
747                ),
748            ))?
749            .build()?;
750
751        let plan2 = LogicalPlanBuilder::from(t3)
752            .cross_join(t4)?
753            .filter(binary_expr(
754                binary_expr(
755                    binary_expr(
756                        col("t3.a").eq(col("t4.a")),
757                        And,
758                        col("t4.c").lt(lit(15u32)),
759                    ),
760                    Or,
761                    binary_expr(
762                        col("t3.a").eq(col("t4.a")),
763                        And,
764                        col("t3.c").eq(lit(688u32)),
765                    ),
766                ),
767                Or,
768                binary_expr(
769                    col("t3.a").eq(col("t4.a")),
770                    And,
771                    col("t3.b").eq(col("t4.b")),
772                ),
773            ))?
774            .build()?;
775
776        let plan = LogicalPlanBuilder::from(plan1)
777            .cross_join(plan2)?
778            .filter(binary_expr(
779                binary_expr(col("t3.a").eq(col("t1.a")), And, col("t4.c").lt(lit(15u32))),
780                Or,
781                binary_expr(
782                    col("t3.a").eq(col("t1.a")),
783                    And,
784                    col("t4.c").eq(lit(688u32)),
785                ),
786            ))?
787            .build()?;
788
789        assert_optimized_plan_equal!(
790            plan,
791            @ r"
792        Filter: t4.c < UInt32(15) OR t4.c = UInt32(688) [a:UInt32, b:UInt32, c:UInt32, a:UInt32, b:UInt32, c:UInt32, a:UInt32, b:UInt32, c:UInt32, a:UInt32, b:UInt32, c:UInt32]
793          Inner Join: t1.a = t3.a [a:UInt32, b:UInt32, c:UInt32, a:UInt32, b:UInt32, c:UInt32, a:UInt32, b:UInt32, c:UInt32, a:UInt32, b:UInt32, c:UInt32]
794            Filter: t2.c < UInt32(15) OR t2.c = UInt32(688) [a:UInt32, b:UInt32, c:UInt32, a:UInt32, b:UInt32, c:UInt32]
795              Inner Join: t1.a = t2.a [a:UInt32, b:UInt32, c:UInt32, a:UInt32, b:UInt32, c:UInt32]
796                TableScan: t1 [a:UInt32, b:UInt32, c:UInt32]
797                TableScan: t2 [a:UInt32, b:UInt32, c:UInt32]
798            Filter: t4.c < UInt32(15) OR t3.c = UInt32(688) OR t3.b = t4.b [a:UInt32, b:UInt32, c:UInt32, a:UInt32, b:UInt32, c:UInt32]
799              Inner Join: t3.a = t4.a [a:UInt32, b:UInt32, c:UInt32, a:UInt32, b:UInt32, c:UInt32]
800                TableScan: t3 [a:UInt32, b:UInt32, c:UInt32]
801                TableScan: t4 [a:UInt32, b:UInt32, c:UInt32]
802        "
803        )
804    }
805
806    #[test]
807    fn eliminate_cross_join_multi_tables_1() -> Result<()> {
808        let t1 = test_table_scan_with_name("t1")?;
809        let t2 = test_table_scan_with_name("t2")?;
810        let t3 = test_table_scan_with_name("t3")?;
811        let t4 = test_table_scan_with_name("t4")?;
812
813        // could eliminate to inner join
814        let plan1 = LogicalPlanBuilder::from(t1)
815            .cross_join(t2)?
816            .filter(binary_expr(
817                binary_expr(col("t1.a").eq(col("t2.a")), And, col("t2.c").lt(lit(15u32))),
818                Or,
819                binary_expr(
820                    col("t1.a").eq(col("t2.a")),
821                    And,
822                    col("t2.c").eq(lit(688u32)),
823                ),
824            ))?
825            .build()?;
826
827        // could eliminate to inner join
828        let plan2 = LogicalPlanBuilder::from(t3)
829            .cross_join(t4)?
830            .filter(binary_expr(
831                binary_expr(
832                    binary_expr(
833                        col("t3.a").eq(col("t4.a")),
834                        And,
835                        col("t4.c").lt(lit(15u32)),
836                    ),
837                    Or,
838                    binary_expr(
839                        col("t3.a").eq(col("t4.a")),
840                        And,
841                        col("t3.c").eq(lit(688u32)),
842                    ),
843                ),
844                Or,
845                binary_expr(
846                    col("t3.a").eq(col("t4.a")),
847                    And,
848                    col("t3.b").eq(col("t4.b")),
849                ),
850            ))?
851            .build()?;
852
853        // could not eliminate to inner join
854        let plan = LogicalPlanBuilder::from(plan1)
855            .cross_join(plan2)?
856            .filter(binary_expr(
857                binary_expr(col("t3.a").eq(col("t1.a")), And, col("t4.c").lt(lit(15u32))),
858                Or,
859                binary_expr(col("t3.a").eq(col("t1.a")), Or, col("t4.c").eq(lit(688u32))),
860            ))?
861            .build()?;
862
863        assert_optimized_plan_equal!(
864            plan,
865            @ r"
866        Filter: t3.a = t1.a AND t4.c < UInt32(15) OR t3.a = t1.a OR t4.c = UInt32(688) [a:UInt32, b:UInt32, c:UInt32, a:UInt32, b:UInt32, c:UInt32, a:UInt32, b:UInt32, c:UInt32, a:UInt32, b:UInt32, c:UInt32]
867          Cross Join: [a:UInt32, b:UInt32, c:UInt32, a:UInt32, b:UInt32, c:UInt32, a:UInt32, b:UInt32, c:UInt32, a:UInt32, b:UInt32, c:UInt32]
868            Filter: t2.c < UInt32(15) OR t2.c = UInt32(688) [a:UInt32, b:UInt32, c:UInt32, a:UInt32, b:UInt32, c:UInt32]
869              Inner Join: t1.a = t2.a [a:UInt32, b:UInt32, c:UInt32, a:UInt32, b:UInt32, c:UInt32]
870                TableScan: t1 [a:UInt32, b:UInt32, c:UInt32]
871                TableScan: t2 [a:UInt32, b:UInt32, c:UInt32]
872            Filter: t4.c < UInt32(15) OR t3.c = UInt32(688) OR t3.b = t4.b [a:UInt32, b:UInt32, c:UInt32, a:UInt32, b:UInt32, c:UInt32]
873              Inner Join: t3.a = t4.a [a:UInt32, b:UInt32, c:UInt32, a:UInt32, b:UInt32, c:UInt32]
874                TableScan: t3 [a:UInt32, b:UInt32, c:UInt32]
875                TableScan: t4 [a:UInt32, b:UInt32, c:UInt32]
876        "
877        )
878    }
879
880    #[test]
881    fn eliminate_cross_join_multi_tables_2() -> Result<()> {
882        let t1 = test_table_scan_with_name("t1")?;
883        let t2 = test_table_scan_with_name("t2")?;
884        let t3 = test_table_scan_with_name("t3")?;
885        let t4 = test_table_scan_with_name("t4")?;
886
887        // could eliminate to inner join
888        let plan1 = LogicalPlanBuilder::from(t1)
889            .cross_join(t2)?
890            .filter(binary_expr(
891                binary_expr(col("t1.a").eq(col("t2.a")), And, col("t2.c").lt(lit(15u32))),
892                Or,
893                binary_expr(
894                    col("t1.a").eq(col("t2.a")),
895                    And,
896                    col("t2.c").eq(lit(688u32)),
897                ),
898            ))?
899            .build()?;
900
901        // could not eliminate to inner join
902        let plan2 = LogicalPlanBuilder::from(t3)
903            .cross_join(t4)?
904            .filter(binary_expr(
905                binary_expr(
906                    binary_expr(
907                        col("t3.a").eq(col("t4.a")),
908                        And,
909                        col("t4.c").lt(lit(15u32)),
910                    ),
911                    Or,
912                    binary_expr(
913                        col("t3.a").eq(col("t4.a")),
914                        And,
915                        col("t3.c").eq(lit(688u32)),
916                    ),
917                ),
918                Or,
919                binary_expr(col("t3.a").eq(col("t4.a")), Or, col("t3.b").eq(col("t4.b"))),
920            ))?
921            .build()?;
922
923        // could eliminate to inner join
924        let plan = LogicalPlanBuilder::from(plan1)
925            .cross_join(plan2)?
926            .filter(binary_expr(
927                binary_expr(col("t3.a").eq(col("t1.a")), And, col("t4.c").lt(lit(15u32))),
928                Or,
929                binary_expr(
930                    col("t3.a").eq(col("t1.a")),
931                    And,
932                    col("t4.c").eq(lit(688u32)),
933                ),
934            ))?
935            .build()?;
936
937        assert_optimized_plan_equal!(
938            plan,
939            @ r"
940        Filter: t4.c < UInt32(15) OR t4.c = UInt32(688) [a:UInt32, b:UInt32, c:UInt32, a:UInt32, b:UInt32, c:UInt32, a:UInt32, b:UInt32, c:UInt32, a:UInt32, b:UInt32, c:UInt32]
941          Inner Join: t1.a = t3.a [a:UInt32, b:UInt32, c:UInt32, a:UInt32, b:UInt32, c:UInt32, a:UInt32, b:UInt32, c:UInt32, a:UInt32, b:UInt32, c:UInt32]
942            Filter: t2.c < UInt32(15) OR t2.c = UInt32(688) [a:UInt32, b:UInt32, c:UInt32, a:UInt32, b:UInt32, c:UInt32]
943              Inner Join: t1.a = t2.a [a:UInt32, b:UInt32, c:UInt32, a:UInt32, b:UInt32, c:UInt32]
944                TableScan: t1 [a:UInt32, b:UInt32, c:UInt32]
945                TableScan: t2 [a:UInt32, b:UInt32, c:UInt32]
946            Filter: t3.a = t4.a AND t4.c < UInt32(15) OR t3.a = t4.a AND t3.c = UInt32(688) OR t3.a = t4.a OR t3.b = t4.b [a:UInt32, b:UInt32, c:UInt32, a:UInt32, b:UInt32, c:UInt32]
947              Cross Join: [a:UInt32, b:UInt32, c:UInt32, a:UInt32, b:UInt32, c:UInt32]
948                TableScan: t3 [a:UInt32, b:UInt32, c:UInt32]
949                TableScan: t4 [a:UInt32, b:UInt32, c:UInt32]
950        "
951        )
952    }
953
954    #[test]
955    fn eliminate_cross_join_multi_tables_3() -> Result<()> {
956        let t1 = test_table_scan_with_name("t1")?;
957        let t2 = test_table_scan_with_name("t2")?;
958        let t3 = test_table_scan_with_name("t3")?;
959        let t4 = test_table_scan_with_name("t4")?;
960
961        // could not eliminate to inner join
962        let plan1 = LogicalPlanBuilder::from(t1)
963            .cross_join(t2)?
964            .filter(binary_expr(
965                binary_expr(col("t1.a").eq(col("t2.a")), Or, col("t2.c").lt(lit(15u32))),
966                Or,
967                binary_expr(
968                    col("t1.a").eq(col("t2.a")),
969                    And,
970                    col("t2.c").eq(lit(688u32)),
971                ),
972            ))?
973            .build()?;
974
975        // could eliminate to inner join
976        let plan2 = LogicalPlanBuilder::from(t3)
977            .cross_join(t4)?
978            .filter(binary_expr(
979                binary_expr(
980                    binary_expr(
981                        col("t3.a").eq(col("t4.a")),
982                        And,
983                        col("t4.c").lt(lit(15u32)),
984                    ),
985                    Or,
986                    binary_expr(
987                        col("t3.a").eq(col("t4.a")),
988                        And,
989                        col("t3.c").eq(lit(688u32)),
990                    ),
991                ),
992                Or,
993                binary_expr(
994                    col("t3.a").eq(col("t4.a")),
995                    And,
996                    col("t3.b").eq(col("t4.b")),
997                ),
998            ))?
999            .build()?;
1000
1001        // could eliminate to inner join
1002        let plan = LogicalPlanBuilder::from(plan1)
1003            .cross_join(plan2)?
1004            .filter(binary_expr(
1005                binary_expr(col("t3.a").eq(col("t1.a")), And, col("t4.c").lt(lit(15u32))),
1006                Or,
1007                binary_expr(
1008                    col("t3.a").eq(col("t1.a")),
1009                    And,
1010                    col("t4.c").eq(lit(688u32)),
1011                ),
1012            ))?
1013            .build()?;
1014
1015        assert_optimized_plan_equal!(
1016            plan,
1017            @ r"
1018        Filter: t4.c < UInt32(15) OR t4.c = UInt32(688) [a:UInt32, b:UInt32, c:UInt32, a:UInt32, b:UInt32, c:UInt32, a:UInt32, b:UInt32, c:UInt32, a:UInt32, b:UInt32, c:UInt32]
1019          Inner Join: t1.a = t3.a [a:UInt32, b:UInt32, c:UInt32, a:UInt32, b:UInt32, c:UInt32, a:UInt32, b:UInt32, c:UInt32, a:UInt32, b:UInt32, c:UInt32]
1020            Filter: t1.a = t2.a OR t2.c < UInt32(15) OR t1.a = t2.a AND t2.c = UInt32(688) [a:UInt32, b:UInt32, c:UInt32, a:UInt32, b:UInt32, c:UInt32]
1021              Cross Join: [a:UInt32, b:UInt32, c:UInt32, a:UInt32, b:UInt32, c:UInt32]
1022                TableScan: t1 [a:UInt32, b:UInt32, c:UInt32]
1023                TableScan: t2 [a:UInt32, b:UInt32, c:UInt32]
1024            Filter: t4.c < UInt32(15) OR t3.c = UInt32(688) OR t3.b = t4.b [a:UInt32, b:UInt32, c:UInt32, a:UInt32, b:UInt32, c:UInt32]
1025              Inner Join: t3.a = t4.a [a:UInt32, b:UInt32, c:UInt32, a:UInt32, b:UInt32, c:UInt32]
1026                TableScan: t3 [a:UInt32, b:UInt32, c:UInt32]
1027                TableScan: t4 [a:UInt32, b:UInt32, c:UInt32]
1028        "
1029        )
1030    }
1031
1032    #[test]
1033    fn eliminate_cross_join_multi_tables_4() -> Result<()> {
1034        let t1 = test_table_scan_with_name("t1")?;
1035        let t2 = test_table_scan_with_name("t2")?;
1036        let t3 = test_table_scan_with_name("t3")?;
1037        let t4 = test_table_scan_with_name("t4")?;
1038
1039        // could eliminate to inner join
1040        // filter: (t1.a = t2.a OR t2.c < 15) AND (t1.a = t2.a AND tc.2 = 688)
1041        let plan1 = LogicalPlanBuilder::from(t1)
1042            .cross_join(t2)?
1043            .filter(binary_expr(
1044                binary_expr(col("t1.a").eq(col("t2.a")), Or, col("t2.c").lt(lit(15u32))),
1045                And,
1046                binary_expr(
1047                    col("t1.a").eq(col("t2.a")),
1048                    And,
1049                    col("t2.c").eq(lit(688u32)),
1050                ),
1051            ))?
1052            .build()?;
1053
1054        // could eliminate to inner join
1055        let plan2 = LogicalPlanBuilder::from(t3).cross_join(t4)?.build()?;
1056
1057        // could eliminate to inner join
1058        // filter:
1059        //   ((t3.a = t1.a AND t4.c < 15) OR (t3.a = t1.a AND t4.c = 688))
1060        //     AND
1061        //   ((t3.a = t4.a AND t4.c < 15) OR (t3.a = t4.a AND t3.c = 688) OR (t3.a = t4.a AND t3.b = t4.b))
1062        let plan = LogicalPlanBuilder::from(plan1)
1063            .cross_join(plan2)?
1064            .filter(binary_expr(
1065                binary_expr(
1066                    binary_expr(
1067                        col("t3.a").eq(col("t1.a")),
1068                        And,
1069                        col("t4.c").lt(lit(15u32)),
1070                    ),
1071                    Or,
1072                    binary_expr(
1073                        col("t3.a").eq(col("t1.a")),
1074                        And,
1075                        col("t4.c").eq(lit(688u32)),
1076                    ),
1077                ),
1078                And,
1079                binary_expr(
1080                    binary_expr(
1081                        binary_expr(
1082                            col("t3.a").eq(col("t4.a")),
1083                            And,
1084                            col("t4.c").lt(lit(15u32)),
1085                        ),
1086                        Or,
1087                        binary_expr(
1088                            col("t3.a").eq(col("t4.a")),
1089                            And,
1090                            col("t3.c").eq(lit(688u32)),
1091                        ),
1092                    ),
1093                    Or,
1094                    binary_expr(
1095                        col("t3.a").eq(col("t4.a")),
1096                        And,
1097                        col("t3.b").eq(col("t4.b")),
1098                    ),
1099                ),
1100            ))?
1101            .build()?;
1102
1103        assert_optimized_plan_equal!(
1104            plan,
1105            @ r"
1106        Filter: (t4.c < UInt32(15) OR t4.c = UInt32(688)) AND (t4.c < UInt32(15) OR t3.c = UInt32(688) OR t3.b = t4.b) [a:UInt32, b:UInt32, c:UInt32, a:UInt32, b:UInt32, c:UInt32, a:UInt32, b:UInt32, c:UInt32, a:UInt32, b:UInt32, c:UInt32]
1107          Inner Join: t3.a = t4.a [a:UInt32, b:UInt32, c:UInt32, a:UInt32, b:UInt32, c:UInt32, a:UInt32, b:UInt32, c:UInt32, a:UInt32, b:UInt32, c:UInt32]
1108            Inner Join: t1.a = t3.a [a:UInt32, b:UInt32, c:UInt32, a:UInt32, b:UInt32, c:UInt32, a:UInt32, b:UInt32, c:UInt32]
1109              Filter: t2.c = UInt32(688) [a:UInt32, b:UInt32, c:UInt32, a:UInt32, b:UInt32, c:UInt32]
1110                Inner Join: t1.a = t2.a [a:UInt32, b:UInt32, c:UInt32, a:UInt32, b:UInt32, c:UInt32]
1111                  TableScan: t1 [a:UInt32, b:UInt32, c:UInt32]
1112                  TableScan: t2 [a:UInt32, b:UInt32, c:UInt32]
1113              TableScan: t3 [a:UInt32, b:UInt32, c:UInt32]
1114            TableScan: t4 [a:UInt32, b:UInt32, c:UInt32]
1115        "
1116        )
1117    }
1118
1119    #[test]
1120    fn eliminate_cross_join_multi_tables_5() -> Result<()> {
1121        let t1 = test_table_scan_with_name("t1")?;
1122        let t2 = test_table_scan_with_name("t2")?;
1123        let t3 = test_table_scan_with_name("t3")?;
1124        let t4 = test_table_scan_with_name("t4")?;
1125
1126        // could eliminate to inner join
1127        let plan1 = LogicalPlanBuilder::from(t1).cross_join(t2)?.build()?;
1128
1129        // could eliminate to inner join
1130        let plan2 = LogicalPlanBuilder::from(t3).cross_join(t4)?.build()?;
1131
1132        // could eliminate to inner join
1133        // Filter:
1134        //  ((t3.a = t1.a AND t4.c < 15) OR (t3.a = t1.a AND t4.c = 688))
1135        //      AND
1136        //  ((t3.a = t4.a AND t4.c < 15) OR (t3.a = t4.a AND t3.c = 688) OR (t3.a = t4.a AND t3.b = t4.b))
1137        //      AND
1138        //  ((t1.a = t2.a OR t2.c < 15) AND (t1.a = t2.a AND t2.c = 688))
1139        let plan = LogicalPlanBuilder::from(plan1)
1140            .cross_join(plan2)?
1141            .filter(binary_expr(
1142                binary_expr(
1143                    binary_expr(
1144                        binary_expr(
1145                            col("t3.a").eq(col("t1.a")),
1146                            And,
1147                            col("t4.c").lt(lit(15u32)),
1148                        ),
1149                        Or,
1150                        binary_expr(
1151                            col("t3.a").eq(col("t1.a")),
1152                            And,
1153                            col("t4.c").eq(lit(688u32)),
1154                        ),
1155                    ),
1156                    And,
1157                    binary_expr(
1158                        binary_expr(
1159                            binary_expr(
1160                                col("t3.a").eq(col("t4.a")),
1161                                And,
1162                                col("t4.c").lt(lit(15u32)),
1163                            ),
1164                            Or,
1165                            binary_expr(
1166                                col("t3.a").eq(col("t4.a")),
1167                                And,
1168                                col("t3.c").eq(lit(688u32)),
1169                            ),
1170                        ),
1171                        Or,
1172                        binary_expr(
1173                            col("t3.a").eq(col("t4.a")),
1174                            And,
1175                            col("t3.b").eq(col("t4.b")),
1176                        ),
1177                    ),
1178                ),
1179                And,
1180                binary_expr(
1181                    binary_expr(
1182                        col("t1.a").eq(col("t2.a")),
1183                        Or,
1184                        col("t2.c").lt(lit(15u32)),
1185                    ),
1186                    And,
1187                    binary_expr(
1188                        col("t1.a").eq(col("t2.a")),
1189                        And,
1190                        col("t2.c").eq(lit(688u32)),
1191                    ),
1192                ),
1193            ))?
1194            .build()?;
1195
1196        assert_optimized_plan_equal!(
1197            plan,
1198            @ r"
1199        Filter: (t4.c < UInt32(15) OR t4.c = UInt32(688)) AND (t4.c < UInt32(15) OR t3.c = UInt32(688) OR t3.b = t4.b) AND t2.c = UInt32(688) [a:UInt32, b:UInt32, c:UInt32, a:UInt32, b:UInt32, c:UInt32, a:UInt32, b:UInt32, c:UInt32, a:UInt32, b:UInt32, c:UInt32]
1200          Inner Join: t3.a = t4.a [a:UInt32, b:UInt32, c:UInt32, a:UInt32, b:UInt32, c:UInt32, a:UInt32, b:UInt32, c:UInt32, a:UInt32, b:UInt32, c:UInt32]
1201            Inner Join: t1.a = t3.a [a:UInt32, b:UInt32, c:UInt32, a:UInt32, b:UInt32, c:UInt32, a:UInt32, b:UInt32, c:UInt32]
1202              Inner Join: t1.a = t2.a [a:UInt32, b:UInt32, c:UInt32, a:UInt32, b:UInt32, c:UInt32]
1203                TableScan: t1 [a:UInt32, b:UInt32, c:UInt32]
1204                TableScan: t2 [a:UInt32, b:UInt32, c:UInt32]
1205              TableScan: t3 [a:UInt32, b:UInt32, c:UInt32]
1206            TableScan: t4 [a:UInt32, b:UInt32, c:UInt32]
1207        "
1208        )
1209    }
1210
1211    #[test]
1212    fn eliminate_cross_join_with_expr_and() -> Result<()> {
1213        let t1 = test_table_scan_with_name("t1")?;
1214        let t2 = test_table_scan_with_name("t2")?;
1215
1216        // could eliminate to inner join since filter has Join predicates
1217        let plan = LogicalPlanBuilder::from(t1)
1218            .cross_join(t2)?
1219            .filter(binary_expr(
1220                (col("t1.a") + lit(100u32)).eq(col("t2.a") * lit(2u32)),
1221                And,
1222                col("t2.c").lt(lit(20u32)),
1223            ))?
1224            .build()?;
1225
1226        assert_optimized_plan_equal!(
1227            plan,
1228            @ r"
1229        Filter: t2.c < UInt32(20) [a:UInt32, b:UInt32, c:UInt32, a:UInt32, b:UInt32, c:UInt32]
1230          Inner Join: t1.a + UInt32(100) = t2.a * UInt32(2) [a:UInt32, b:UInt32, c:UInt32, a:UInt32, b:UInt32, c:UInt32]
1231            TableScan: t1 [a:UInt32, b:UInt32, c:UInt32]
1232            TableScan: t2 [a:UInt32, b:UInt32, c:UInt32]
1233        "
1234        )
1235    }
1236
1237    #[test]
1238    fn eliminate_cross_with_expr_or() -> Result<()> {
1239        let t1 = test_table_scan_with_name("t1")?;
1240        let t2 = test_table_scan_with_name("t2")?;
1241
1242        // could not eliminate to inner join since filter OR expression and there is no common
1243        // Join predicates in left and right of OR expr.
1244        let plan = LogicalPlanBuilder::from(t1)
1245            .cross_join(t2)?
1246            .filter(binary_expr(
1247                (col("t1.a") + lit(100u32)).eq(col("t2.a") * lit(2u32)),
1248                Or,
1249                col("t2.b").eq(col("t1.a")),
1250            ))?
1251            .build()?;
1252
1253        assert_optimized_plan_equal!(
1254            plan,
1255            @ r"
1256        Filter: t1.a + UInt32(100) = t2.a * UInt32(2) OR t2.b = t1.a [a:UInt32, b:UInt32, c:UInt32, a:UInt32, b:UInt32, c:UInt32]
1257          Cross Join: [a:UInt32, b:UInt32, c:UInt32, a:UInt32, b:UInt32, c:UInt32]
1258            TableScan: t1 [a:UInt32, b:UInt32, c:UInt32]
1259            TableScan: t2 [a:UInt32, b:UInt32, c:UInt32]
1260        "
1261        )
1262    }
1263
1264    #[test]
1265    fn eliminate_cross_with_common_expr_and() -> Result<()> {
1266        let t1 = test_table_scan_with_name("t1")?;
1267        let t2 = test_table_scan_with_name("t2")?;
1268
1269        // could eliminate to inner join
1270        let common_join_key = (col("t1.a") + lit(100u32)).eq(col("t2.a") * lit(2u32));
1271        let plan = LogicalPlanBuilder::from(t1)
1272            .cross_join(t2)?
1273            .filter(binary_expr(
1274                binary_expr(common_join_key.clone(), And, col("t2.c").lt(lit(20u32))),
1275                And,
1276                binary_expr(common_join_key, And, col("t2.c").eq(lit(10u32))),
1277            ))?
1278            .build()?;
1279
1280        assert_optimized_plan_equal!(
1281            plan,
1282            @ r"
1283        Filter: t2.c < UInt32(20) AND t2.c = UInt32(10) [a:UInt32, b:UInt32, c:UInt32, a:UInt32, b:UInt32, c:UInt32]
1284          Inner Join: t1.a + UInt32(100) = t2.a * UInt32(2) [a:UInt32, b:UInt32, c:UInt32, a:UInt32, b:UInt32, c:UInt32]
1285            TableScan: t1 [a:UInt32, b:UInt32, c:UInt32]
1286            TableScan: t2 [a:UInt32, b:UInt32, c:UInt32]
1287        "
1288        )
1289    }
1290
1291    #[test]
1292    fn eliminate_cross_with_common_expr_or() -> Result<()> {
1293        let t1 = test_table_scan_with_name("t1")?;
1294        let t2 = test_table_scan_with_name("t2")?;
1295
1296        // could eliminate to inner join since Or predicates have common Join predicates
1297        let common_join_key = (col("t1.a") + lit(100u32)).eq(col("t2.a") * lit(2u32));
1298        let plan = LogicalPlanBuilder::from(t1)
1299            .cross_join(t2)?
1300            .filter(binary_expr(
1301                binary_expr(common_join_key.clone(), And, col("t2.c").lt(lit(15u32))),
1302                Or,
1303                binary_expr(common_join_key, And, col("t2.c").eq(lit(688u32))),
1304            ))?
1305            .build()?;
1306
1307        assert_optimized_plan_equal!(
1308            plan,
1309            @ r"
1310        Filter: t2.c < UInt32(15) OR t2.c = UInt32(688) [a:UInt32, b:UInt32, c:UInt32, a:UInt32, b:UInt32, c:UInt32]
1311          Inner Join: t1.a + UInt32(100) = t2.a * UInt32(2) [a:UInt32, b:UInt32, c:UInt32, a:UInt32, b:UInt32, c:UInt32]
1312            TableScan: t1 [a:UInt32, b:UInt32, c:UInt32]
1313            TableScan: t2 [a:UInt32, b:UInt32, c:UInt32]
1314        "
1315        )
1316    }
1317
1318    #[test]
1319    fn reorder_join_with_expr_key_multi_tables() -> Result<()> {
1320        let t1 = test_table_scan_with_name("t1")?;
1321        let t2 = test_table_scan_with_name("t2")?;
1322        let t3 = test_table_scan_with_name("t3")?;
1323
1324        // could eliminate to inner join
1325        let plan = LogicalPlanBuilder::from(t1)
1326            .cross_join(t2)?
1327            .cross_join(t3)?
1328            .filter(binary_expr(
1329                binary_expr(
1330                    (col("t3.a") + lit(100u32)).eq(col("t1.a") * lit(2u32)),
1331                    And,
1332                    col("t3.c").lt(lit(15u32)),
1333                ),
1334                And,
1335                binary_expr(
1336                    (col("t3.a") + lit(100u32)).eq(col("t2.a") * lit(2u32)),
1337                    And,
1338                    col("t3.b").lt(lit(15u32)),
1339                ),
1340            ))?
1341            .build()?;
1342
1343        assert_optimized_plan_equal!(
1344            plan,
1345            @ r"
1346        Filter: t3.c < UInt32(15) AND t3.b < UInt32(15) [a:UInt32, b:UInt32, c:UInt32, a:UInt32, b:UInt32, c:UInt32, a:UInt32, b:UInt32, c:UInt32]
1347          Projection: t1.a, t1.b, t1.c, t2.a, t2.b, t2.c, t3.a, t3.b, t3.c [a:UInt32, b:UInt32, c:UInt32, a:UInt32, b:UInt32, c:UInt32, a:UInt32, b:UInt32, c:UInt32]
1348            Inner Join: t3.a + UInt32(100) = t2.a * UInt32(2) [a:UInt32, b:UInt32, c:UInt32, a:UInt32, b:UInt32, c:UInt32, a:UInt32, b:UInt32, c:UInt32]
1349              Inner Join: t1.a * UInt32(2) = t3.a + UInt32(100) [a:UInt32, b:UInt32, c:UInt32, a:UInt32, b:UInt32, c:UInt32]
1350                TableScan: t1 [a:UInt32, b:UInt32, c:UInt32]
1351                TableScan: t3 [a:UInt32, b:UInt32, c:UInt32]
1352              TableScan: t2 [a:UInt32, b:UInt32, c:UInt32]
1353        "
1354        )
1355    }
1356
1357    #[test]
1358    fn eliminate_cross_join_in_join_key_subquery() -> Result<()> {
1359        // An uncorrelated subquery containing a cross join that can be eliminated
1360        let subquery = LogicalPlanBuilder::from(test_table_scan_with_name("s1")?)
1361            .cross_join(test_table_scan_with_name("s2")?)?
1362            .filter(col("s1.a").eq(col("s2.a")))?
1363            .project(vec![col("s1.b")])?
1364            .build()?;
1365
1366        // The subquery ends up in the join key of the innermost join
1367        let plan = LogicalPlanBuilder::from(test_table_scan_with_name("t1")?)
1368            .cross_join(test_table_scan_with_name("t2")?)?
1369            .cross_join(test_table_scan_with_name("t3")?)?
1370            .filter(binary_expr(
1371                (col("t1.a") + scalar_subquery(Arc::new(subquery))).eq(col("t2.a")),
1372                And,
1373                col("t2.b").eq(col("t3.b")),
1374            ))?
1375            .build()?;
1376
1377        assert_optimized_plan_equal!(
1378            plan,
1379            @ r"
1380        Inner Join: t2.b = t3.b [a:UInt32, b:UInt32, c:UInt32, a:UInt32, b:UInt32, c:UInt32, a:UInt32, b:UInt32, c:UInt32]
1381          Inner Join: t1.a + (<subquery>) = t2.a [a:UInt32, b:UInt32, c:UInt32, a:UInt32, b:UInt32, c:UInt32]
1382            Subquery: [b:UInt32]
1383              Projection: s1.b [b:UInt32]
1384                Inner Join: s1.a = s2.a [a:UInt32, b:UInt32, c:UInt32, a:UInt32, b:UInt32, c:UInt32]
1385                  TableScan: s1 [a:UInt32, b:UInt32, c:UInt32]
1386                  TableScan: s2 [a:UInt32, b:UInt32, c:UInt32]
1387            TableScan: t1 [a:UInt32, b:UInt32, c:UInt32]
1388            TableScan: t2 [a:UInt32, b:UInt32, c:UInt32]
1389          TableScan: t3 [a:UInt32, b:UInt32, c:UInt32]
1390        "
1391        )
1392    }
1393
1394    #[test]
1395    fn preserve_outer_join_boundary() -> Result<()> {
1396        let plan = LogicalPlanBuilder::from(test_table_scan_with_name("t1")?)
1397            .join(
1398                test_table_scan_with_name("t2")?,
1399                JoinType::Left,
1400                (vec!["t1.a"], vec!["t2.a"]),
1401                Some(col("t1.b").gt(col("t2.b"))),
1402            )?
1403            .join(
1404                test_table_scan_with_name("t3")?,
1405                JoinType::Inner,
1406                (vec!["t1.a"], vec!["t3.a"]),
1407                Some(col("t3.c").gt(lit(7u32))),
1408            )?
1409            .build()?;
1410
1411        assert_optimized_plan_equal!(
1412            plan,
1413            @ r"
1414        Filter: t3.c > UInt32(7) [a:UInt32, b:UInt32, c:UInt32, a:UInt32;N, b:UInt32;N, c:UInt32;N, a:UInt32, b:UInt32, c:UInt32]
1415          Inner Join: t1.a = t3.a [a:UInt32, b:UInt32, c:UInt32, a:UInt32;N, b:UInt32;N, c:UInt32;N, a:UInt32, b:UInt32, c:UInt32]
1416            Left Join: t1.a = t2.a Filter: t1.b > t2.b [a:UInt32, b:UInt32, c:UInt32, a:UInt32;N, b:UInt32;N, c:UInt32;N]
1417              TableScan: t1 [a:UInt32, b:UInt32, c:UInt32]
1418              TableScan: t2 [a:UInt32, b:UInt32, c:UInt32]
1419            TableScan: t3 [a:UInt32, b:UInt32, c:UInt32]
1420        "
1421        )
1422    }
1423
1424    #[test]
1425    fn preserve_null_equality_setting() -> Result<()> {
1426        let t1 = test_table_scan_with_name("t1")?;
1427        let t2 = test_table_scan_with_name("t2")?;
1428
1429        // Create an inner join with NullEquality::NullEqualsNull
1430        let join_schema = Arc::new(build_join_schema(
1431            t1.schema(),
1432            t2.schema(),
1433            &JoinType::Inner,
1434        )?);
1435
1436        let inner_join = LogicalPlan::Join(Join {
1437            left: Arc::new(t1),
1438            right: Arc::new(t2),
1439            join_type: JoinType::Inner,
1440            join_constraint: JoinConstraint::On,
1441            on: vec![],
1442            filter: None,
1443            schema: join_schema,
1444            null_equality: NullEquality::NullEqualsNull, // Test preservation
1445            null_aware: false,
1446            null_aware_value_keys: 0,
1447        });
1448
1449        // Apply filter that can create join conditions
1450        let plan = LogicalPlanBuilder::from(inner_join)
1451            .filter(binary_expr(
1452                col("t1.a").eq(col("t2.a")),
1453                And,
1454                col("t2.c").lt(lit(20u32)),
1455            ))?
1456            .build()?;
1457
1458        let rule = EliminateCrossJoin::new();
1459        let optimized_plan = rule.rewrite(plan, &OptimizerContext::new())?.data;
1460
1461        // Verify that null_equality is preserved in the optimized plan
1462        fn check_null_equality_preserved(plan: &LogicalPlan) -> bool {
1463            match plan {
1464                LogicalPlan::Join(join) => {
1465                    // All joins in the optimized plan should preserve null equality
1466                    if join.null_equality == NullEquality::NullEqualsNothing {
1467                        return false;
1468                    }
1469                    // Recursively check child plans
1470                    plan.inputs()
1471                        .iter()
1472                        .all(|input| check_null_equality_preserved(input))
1473                }
1474                _ => {
1475                    // Recursively check child plans for non-join nodes
1476                    plan.inputs()
1477                        .iter()
1478                        .all(|input| check_null_equality_preserved(input))
1479                }
1480            }
1481        }
1482
1483        assert!(
1484            check_null_equality_preserved(&optimized_plan),
1485            "null_equality setting should be preserved after optimization"
1486        );
1487
1488        Ok(())
1489    }
1490
1491    // ---------------- fast-path tests ----------------
1492
1493    /// `plan_has_joins` detects a `Join` at the root of the plan.
1494    #[test]
1495    fn plan_has_joins_detects_root_join() -> Result<()> {
1496        let plan = LogicalPlanBuilder::from(test_table_scan_with_name("t1")?)
1497            .cross_join(test_table_scan_with_name("t2")?)?
1498            .build()?;
1499        assert!(plan_has_joins(&plan));
1500        Ok(())
1501    }
1502
1503    /// `plan_has_joins` detects a `Join` nested under other operators.
1504    #[test]
1505    fn plan_has_joins_detects_nested_join() -> Result<()> {
1506        let plan = LogicalPlanBuilder::from(test_table_scan_with_name("t1")?)
1507            .cross_join(test_table_scan_with_name("t2")?)?
1508            .filter(col("t1.a").eq(col("t2.a")))?
1509            .project(vec![col("t1.a")])?
1510            .build()?;
1511        assert!(plan_has_joins(&plan));
1512        Ok(())
1513    }
1514
1515    /// Join-free plans return `false` so the fast-path in `rewrite` can
1516    /// bail out before doing any recursion.
1517    #[test]
1518    fn plan_has_joins_returns_false_for_join_free_plan() -> Result<()> {
1519        let plan = LogicalPlanBuilder::from(test_table_scan_with_name("t1")?)
1520            .filter(col("a").gt(lit(0_i32)))?
1521            .project(vec![col("a"), col("b")])?
1522            .build()?;
1523        assert!(!plan_has_joins(&plan));
1524        Ok(())
1525    }
1526
1527    /// `plan_has_joins` walks into embedded subquery plans — e.g. an
1528    /// outer `Filter` whose predicate is `IN (SELECT ... FROM a, b)`
1529    /// where the inner plan contains a `CROSS JOIN`. Without this the
1530    /// fast-path would silently skip optimizing joins-in-subqueries
1531    /// because `LogicalPlan::apply` doesn't descend into subquery
1532    /// plan trees.
1533    #[test]
1534    fn plan_has_joins_detects_join_inside_subquery() -> Result<()> {
1535        use datafusion_expr::in_subquery;
1536
1537        // Subquery plan that itself contains a join.
1538        let subquery_plan =
1539            LogicalPlanBuilder::from(test_table_scan_with_name("sub_t1")?)
1540                .cross_join(test_table_scan_with_name("sub_t2")?)?
1541                .project(vec![col("sub_t1.a")])?
1542                .build()?;
1543
1544        // Outer plan with NO direct Join — only the IN subquery reaches one.
1545        let outer = LogicalPlanBuilder::from(test_table_scan_with_name("t1")?)
1546            .filter(in_subquery(col("a"), Arc::new(subquery_plan)))?
1547            .project(vec![col("a")])?
1548            .build()?;
1549
1550        assert!(
1551            plan_has_joins(&outer),
1552            "plan_has_joins must descend into subquery plans"
1553        );
1554        Ok(())
1555    }
1556
1557    /// `EliminateCrossJoin::rewrite` short-circuits on join-free plans:
1558    /// no recursion into `rewrite_children`, no `Transformed::yes`,
1559    /// the plan comes back identical.
1560    #[test]
1561    fn rewrite_short_circuits_when_plan_has_no_joins() -> Result<()> {
1562        let plan = LogicalPlanBuilder::from(test_table_scan_with_name("t1")?)
1563            .filter(col("a").gt(lit(0_i32)))?
1564            .project(vec![col("a"), col("b")])?
1565            .build()?;
1566
1567        let starting_display = plan.display_indent_schema().to_string();
1568        let starting_schema = Arc::clone(plan.schema());
1569
1570        let rule = EliminateCrossJoin::new();
1571        let Transformed {
1572            transformed,
1573            data: optimized_plan,
1574            ..
1575        } = rule.rewrite(plan, &OptimizerContext::new())?;
1576
1577        assert!(
1578            !transformed,
1579            "join-free plan should not be marked as transformed"
1580        );
1581        assert_eq!(&starting_schema, optimized_plan.schema());
1582        assert_eq!(
1583            starting_display,
1584            optimized_plan.display_indent_schema().to_string()
1585        );
1586        Ok(())
1587    }
1588}