Skip to main content

datafusion_optimizer/
extract_equijoin_predicate.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//! [`ExtractEquijoinPredicate`] identifies equality join (equijoin) predicates
6use crate::optimizer::ApplyOrder;
7use crate::{OptimizerConfig, OptimizerRule};
8use datafusion_common::tree_node::Transformed;
9use datafusion_common::{DFSchema, assert_or_internal_err};
10use datafusion_common::{NullEquality, Result};
11use datafusion_expr::utils::split_conjunction_owned;
12use datafusion_expr::utils::{can_hash, find_valid_equijoin_key_pair};
13use datafusion_expr::{BinaryExpr, Expr, ExprSchemable, Join, LogicalPlan, Operator};
14// equijoin predicate
15type EquijoinPredicate = (Expr, Expr);
16
17/// Optimizer that splits conjunctive join predicates into equijoin
18/// predicates and (other) filter predicates.
19///
20/// Join algorithms are often highly optimized for equality predicates such as `x = y`,
21/// often called `equijoin` predicates, so it is important to locate such predicates
22/// and treat them specially.
23///
24/// For example, `SELECT ... FROM A JOIN B ON (A.x = B.y AND B.z > 50)`
25/// has one equijoin predicate (`A.x = B.y`) and one filter predicate (`B.z > 50`).
26/// See [find_valid_equijoin_key_pair] for more information on what predicates
27/// are considered equijoins.
28#[derive(Default, Debug)]
29pub struct ExtractEquijoinPredicate;
30
31impl ExtractEquijoinPredicate {
32    #[expect(missing_docs)]
33    pub fn new() -> Self {
34        Self {}
35    }
36}
37
38impl OptimizerRule for ExtractEquijoinPredicate {
39    fn name(&self) -> &str {
40        "extract_equijoin_predicate"
41    }
42
43    fn apply_order(&self) -> Option<ApplyOrder> {
44        Some(ApplyOrder::BottomUp)
45    }
46
47    fn rewrite(
48        &self,
49        plan: LogicalPlan,
50        _config: &dyn OptimizerConfig,
51    ) -> Result<Transformed<LogicalPlan>> {
52        match plan {
53            LogicalPlan::Join(Join {
54                left,
55                right,
56                mut on,
57                filter: Some(expr),
58                join_type,
59                join_constraint,
60                schema,
61                null_equality,
62                null_aware,
63                null_aware_value_keys,
64            }) => {
65                let left_schema = left.schema();
66                let right_schema = right.schema();
67                let (equijoin_predicates, non_equijoin_expr) =
68                    split_eq_and_noneq_join_predicate(expr, left_schema, right_schema)?;
69
70                // Equi-join operators like HashJoin support a special behavior
71                // that evaluates `NULL = NULL` as true instead of NULL. Therefore,
72                // we transform `t1.c1 IS NOT DISTINCT FROM t2.c1` into an equi-join
73                // and set the `NullEquality` configuration in the join operator.
74                // This allows certain queries to use Hash Join instead of
75                // Nested Loop Join, resulting in better performance.
76                //
77                // Only convert when there are NO equijoin predicates, to be conservative.
78                if on.is_empty()
79                    && equijoin_predicates.is_empty()
80                    && non_equijoin_expr.is_some()
81                {
82                    // SAFETY: checked in the outer `if`
83                    let expr = non_equijoin_expr.clone().unwrap();
84                    let (equijoin_predicates, non_equijoin_expr) =
85                        split_is_not_distinct_from_and_other_join_predicate(
86                            expr,
87                            left_schema,
88                            right_schema,
89                        )?;
90
91                    if !equijoin_predicates.is_empty() {
92                        on.extend(equijoin_predicates);
93
94                        return Ok(Transformed::yes(LogicalPlan::Join(Join {
95                            left,
96                            right,
97                            on,
98                            filter: non_equijoin_expr,
99                            join_type,
100                            join_constraint,
101                            schema,
102                            // According to `is not distinct from`'s semantics, it's
103                            // safe to override it
104                            null_equality: NullEquality::NullEqualsNull,
105                            null_aware,
106                            null_aware_value_keys,
107                        })));
108                    }
109                }
110
111                if !equijoin_predicates.is_empty() {
112                    on.extend(equijoin_predicates);
113                    Ok(Transformed::yes(LogicalPlan::Join(Join {
114                        left,
115                        right,
116                        on,
117                        filter: non_equijoin_expr,
118                        join_type,
119                        join_constraint,
120                        schema,
121                        null_equality,
122                        null_aware,
123                        null_aware_value_keys,
124                    })))
125                } else {
126                    Ok(Transformed::no(LogicalPlan::Join(Join {
127                        left,
128                        right,
129                        on,
130                        filter: non_equijoin_expr,
131                        join_type,
132                        join_constraint,
133                        schema,
134                        null_equality,
135                        null_aware,
136                        null_aware_value_keys,
137                    })))
138                }
139            }
140            _ => Ok(Transformed::no(plan)),
141        }
142    }
143}
144
145/// Splits an ANDed filter expression into equijoin predicates and remaining filters.
146/// Returns all equijoin predicates and the remaining filters combined with AND.
147///
148/// # Example
149///
150/// For the expression `a.id = b.id AND a.x > 10 AND b.x > b.id`, this function will extract `a.id = b.id` as an equijoin predicate.
151///
152/// It first splits the ANDed sub-expressions:
153/// - expr1: a.id = b.id
154/// - expr2: a.x > 10
155/// - expr3: b.x > b.id
156///
157/// Then, it filters out the equijoin predicates and collects the non-equality expressions.
158/// The equijoin condition is:
159/// - It is an equality expression like `lhs == rhs`
160/// - All column references in `lhs` are from the left schema, and all in `rhs` are from the right schema
161///
162/// According to the above rule, `expr1` is the equijoin predicate, while `expr2` and `expr3` are not.
163/// The function returns Ok(\[expr1\], Some(expr2 AND expr3))
164pub(crate) fn split_eq_and_noneq_join_predicate(
165    filter: Expr,
166    left_schema: &DFSchema,
167    right_schema: &DFSchema,
168) -> Result<(Vec<EquijoinPredicate>, Option<Expr>)> {
169    split_op_and_other_join_predicates(filter, left_schema, right_schema, Operator::Eq)
170}
171
172/// See `split_eq_and_noneq_join_predicate`'s comment for the idea. This function
173/// is splitting out `is not distinct from` expressions instead of equal exprs.
174/// The `is not distinct from` exprs will be return as `EquijoinPredicate`.
175///
176/// # Example
177/// - Input: `a.id IS NOT DISTINCT FROM b.id AND a.x > 10 AND b.x > b.id`
178/// - Output from this splitter: `Ok([a.id, b.id], Some((a.x > 10) AND (b.x > b.id)))`
179///
180/// # Note
181/// Caller should be cautious -- `is not distinct from` is not equivalent to an
182/// equal expression; the caller is responsible for correctly setting the
183/// `nulls equals nulls` property in the join operator (if it supports it) to
184/// make the transformation valid.
185///
186/// For the above example: in downstream, a valid plan that uses the extracted
187/// equijoin keys should look like:
188///
189/// HashJoin
190/// - on: `a.id = b.id` (equality)
191/// - join_filter: `(a.x > 10) AND (b.x > b.id)`
192/// - nulls_equals_null: `true`
193///
194/// This reflects that `IS NOT DISTINCT FROM` treats `NULL = NULL` as true and
195/// thus requires setting `NullEquality::NullEqualsNull` in the join operator to
196/// preserve semantics while enabling an equi-join implementation (e.g., HashJoin).
197fn split_is_not_distinct_from_and_other_join_predicate(
198    filter: Expr,
199    left_schema: &DFSchema,
200    right_schema: &DFSchema,
201) -> Result<(Vec<EquijoinPredicate>, Option<Expr>)> {
202    split_op_and_other_join_predicates(
203        filter,
204        left_schema,
205        right_schema,
206        Operator::IsNotDistinctFrom,
207    )
208}
209
210/// See comments in `split_eq_and_noneq_join_predicate` for details.
211fn split_op_and_other_join_predicates(
212    filter: Expr,
213    left_schema: &DFSchema,
214    right_schema: &DFSchema,
215    operator: Operator,
216) -> Result<(Vec<EquijoinPredicate>, Option<Expr>)> {
217    assert_or_internal_err!(
218        matches!(operator, Operator::Eq | Operator::IsNotDistinctFrom),
219        "split_op_and_other_join_predicates only supports 'Eq' or 'IsNotDistinctFrom' operators, \
220        but received: {:?}",
221        operator
222    );
223
224    let exprs = split_conjunction_owned(filter);
225
226    // Treat 'is not distinct from' comparison as join key in equal joins
227    let mut accum_join_keys: Vec<(Expr, Expr)> = vec![];
228    let mut accum_filters: Vec<Expr> = vec![];
229    for expr in exprs {
230        match expr {
231            Expr::BinaryExpr(BinaryExpr {
232                ref left,
233                ref op,
234                ref right,
235            }) if *op == operator => {
236                let join_key_pair =
237                    find_valid_equijoin_key_pair(left, right, left_schema, right_schema)?;
238
239                if let Some((left_expr, right_expr)) = join_key_pair {
240                    let left_expr_type = left_expr.get_type(left_schema)?;
241                    let right_expr_type = right_expr.get_type(right_schema)?;
242
243                    if can_hash(&left_expr_type) && can_hash(&right_expr_type) {
244                        accum_join_keys.push((left_expr, right_expr));
245                    } else {
246                        accum_filters.push(expr);
247                    }
248                } else {
249                    accum_filters.push(expr);
250                }
251            }
252            _ => accum_filters.push(expr),
253        }
254    }
255
256    let result_filter = accum_filters.into_iter().reduce(Expr::and);
257    Ok((accum_join_keys, result_filter))
258}
259
260#[cfg(test)]
261mod tests {
262    use super::*;
263    use crate::assert_optimized_plan_eq_display_indent_snapshot;
264    use crate::test::*;
265    use arrow::datatypes::DataType;
266    use datafusion_expr::{
267        JoinType, col, lit, logical_plan::builder::LogicalPlanBuilder,
268    };
269    use std::sync::Arc;
270
271    macro_rules! assert_optimized_plan_equal {
272        (
273            $plan:expr,
274            @ $expected:literal $(,)?
275        ) => {{
276            let rule: Arc<dyn crate::OptimizerRule + Send + Sync> = Arc::new(ExtractEquijoinPredicate {});
277            assert_optimized_plan_eq_display_indent_snapshot!(
278                rule,
279                $plan,
280                @ $expected,
281            )
282        }};
283    }
284
285    #[test]
286    fn join_with_only_column_equi_predicate() -> Result<()> {
287        let t1 = test_table_scan_with_name("t1")?;
288        let t2 = test_table_scan_with_name("t2")?;
289
290        let plan = LogicalPlanBuilder::from(t1)
291            .join_on(t2, JoinType::Left, Some(col("t1.a").eq(col("t2.a"))))?
292            .build()?;
293
294        assert_optimized_plan_equal!(
295            plan,
296            @r"
297        Left Join: t1.a = t2.a [a:UInt32, b:UInt32, c:UInt32, a:UInt32;N, b:UInt32;N, c:UInt32;N]
298          TableScan: t1 [a:UInt32, b:UInt32, c:UInt32]
299          TableScan: t2 [a:UInt32, b:UInt32, c:UInt32]
300        "
301        )
302    }
303
304    #[test]
305    fn join_with_only_equi_expr_predicate() -> Result<()> {
306        let t1 = test_table_scan_with_name("t1")?;
307        let t2 = test_table_scan_with_name("t2")?;
308
309        let plan = LogicalPlanBuilder::from(t1)
310            .join_on(
311                t2,
312                JoinType::Left,
313                Some((col("t1.a") + lit(10i64)).eq(col("t2.a") * lit(2u32))),
314            )?
315            .build()?;
316
317        assert_optimized_plan_equal!(
318            plan,
319            @r"
320        Left Join: t1.a + Int64(10) = t2.a * UInt32(2) [a:UInt32, b:UInt32, c:UInt32, a:UInt32;N, b:UInt32;N, c:UInt32;N]
321          TableScan: t1 [a:UInt32, b:UInt32, c:UInt32]
322          TableScan: t2 [a:UInt32, b:UInt32, c:UInt32]
323        "
324        )
325    }
326
327    #[test]
328    fn join_with_only_none_equi_predicate() -> Result<()> {
329        let t1 = test_table_scan_with_name("t1")?;
330        let t2 = test_table_scan_with_name("t2")?;
331
332        let plan = LogicalPlanBuilder::from(t1)
333            .join_on(
334                t2,
335                JoinType::Left,
336                Some(
337                    (col("t1.a") + lit(10i64))
338                        .gt_eq(col("t2.a") * lit(2u32))
339                        .and(col("t1.b").lt(lit(100i32))),
340                ),
341            )?
342            .build()?;
343
344        assert_optimized_plan_equal!(
345            plan,
346            @r"
347        Left Join:  Filter: t1.a + Int64(10) >= t2.a * UInt32(2) AND t1.b < Int32(100) [a:UInt32, b:UInt32, c:UInt32, a:UInt32;N, b:UInt32;N, c:UInt32;N]
348          TableScan: t1 [a:UInt32, b:UInt32, c:UInt32]
349          TableScan: t2 [a:UInt32, b:UInt32, c:UInt32]
350        "
351        )
352    }
353
354    #[test]
355    fn join_with_expr_both_from_filter_and_keys() -> Result<()> {
356        let t1 = test_table_scan_with_name("t1")?;
357        let t2 = test_table_scan_with_name("t2")?;
358
359        let plan = LogicalPlanBuilder::from(t1)
360            .join_with_expr_keys(
361                t2,
362                JoinType::Left,
363                (
364                    vec![col("t1.a") + lit(11u32)],
365                    vec![col("t2.a") * lit(2u32)],
366                ),
367                Some(
368                    (col("t1.a") + lit(10i64))
369                        .eq(col("t2.a") * lit(2u32))
370                        .and(col("t1.b").lt(lit(100i32))),
371                ),
372            )?
373            .build()?;
374
375        assert_optimized_plan_equal!(
376            plan,
377            @r"
378        Left Join: t1.a + UInt32(11) = t2.a * UInt32(2), t1.a + Int64(10) = t2.a * UInt32(2) Filter: t1.b < Int32(100) [a:UInt32, b:UInt32, c:UInt32, a:UInt32;N, b:UInt32;N, c:UInt32;N]
379          TableScan: t1 [a:UInt32, b:UInt32, c:UInt32]
380          TableScan: t2 [a:UInt32, b:UInt32, c:UInt32]
381        "
382        )
383    }
384
385    #[test]
386    fn join_with_and_or_filter() -> Result<()> {
387        let t1 = test_table_scan_with_name("t1")?;
388        let t2 = test_table_scan_with_name("t2")?;
389
390        let plan = LogicalPlanBuilder::from(t1)
391            .join_on(
392                t2,
393                JoinType::Left,
394                Some(
395                    col("t1.c")
396                        .eq(col("t2.c"))
397                        .or((col("t1.a") + col("t1.b")).gt(col("t2.b") + col("t2.c")))
398                        .and(
399                            col("t1.a").eq(col("t2.a")).and(col("t1.b").eq(col("t2.b"))),
400                        ),
401                ),
402            )?
403            .build()?;
404
405        assert_optimized_plan_equal!(
406            plan,
407            @r"
408        Left Join: t1.a = t2.a, t1.b = t2.b Filter: t1.c = t2.c OR t1.a + t1.b > t2.b + t2.c [a:UInt32, b:UInt32, c:UInt32, a:UInt32;N, b:UInt32;N, c:UInt32;N]
409          TableScan: t1 [a:UInt32, b:UInt32, c:UInt32]
410          TableScan: t2 [a:UInt32, b:UInt32, c:UInt32]
411        "
412        )
413    }
414
415    #[test]
416    fn join_with_multiple_table() -> Result<()> {
417        let t1 = test_table_scan_with_name("t1")?;
418        let t2 = test_table_scan_with_name("t2")?;
419        let t3 = test_table_scan_with_name("t3")?;
420
421        let input = LogicalPlanBuilder::from(t2)
422            .join_on(
423                t3,
424                JoinType::Left,
425                Some(
426                    col("t2.a")
427                        .eq(col("t3.a"))
428                        .and((col("t2.a") + col("t3.b")).gt(lit(100u32))),
429                ),
430            )?
431            .build()?;
432        let plan = LogicalPlanBuilder::from(t1)
433            .join_on(
434                input,
435                JoinType::Left,
436                Some(
437                    col("t1.a")
438                        .eq(col("t2.a"))
439                        .and((col("t1.c") + col("t2.c") + col("t3.c")).lt(lit(100u32))),
440                ),
441            )?
442            .build()?;
443
444        assert_optimized_plan_equal!(
445            plan,
446            @r"
447        Left Join: t1.a = t2.a Filter: t1.c + t2.c + t3.c < UInt32(100) [a:UInt32, b:UInt32, c:UInt32, a:UInt32;N, b:UInt32;N, c:UInt32;N, a:UInt32;N, b:UInt32;N, c:UInt32;N]
448          TableScan: t1 [a:UInt32, b:UInt32, c:UInt32]
449          Left Join: t2.a = t3.a Filter: t2.a + t3.b > UInt32(100) [a:UInt32, b:UInt32, c:UInt32, a:UInt32;N, b:UInt32;N, c:UInt32;N]
450            TableScan: t2 [a:UInt32, b:UInt32, c:UInt32]
451            TableScan: t3 [a:UInt32, b:UInt32, c:UInt32]
452        "
453        )
454    }
455
456    #[test]
457    fn join_with_multiple_table_and_eq_filter() -> Result<()> {
458        let t1 = test_table_scan_with_name("t1")?;
459        let t2 = test_table_scan_with_name("t2")?;
460        let t3 = test_table_scan_with_name("t3")?;
461
462        let input = LogicalPlanBuilder::from(t2)
463            .join_on(
464                t3,
465                JoinType::Left,
466                Some(
467                    col("t2.a")
468                        .eq(col("t3.a"))
469                        .and((col("t2.a") + col("t3.b")).gt(lit(100u32))),
470                ),
471            )?
472            .build()?;
473        let plan = LogicalPlanBuilder::from(t1)
474            .join_on(
475                input,
476                JoinType::Left,
477                Some(col("t1.a").eq(col("t2.a")).and(col("t2.c").eq(col("t3.c")))),
478            )?
479            .build()?;
480
481        assert_optimized_plan_equal!(
482            plan,
483            @r"
484        Left Join: t1.a = t2.a Filter: t2.c = t3.c [a:UInt32, b:UInt32, c:UInt32, a:UInt32;N, b:UInt32;N, c:UInt32;N, a:UInt32;N, b:UInt32;N, c:UInt32;N]
485          TableScan: t1 [a:UInt32, b:UInt32, c:UInt32]
486          Left Join: t2.a = t3.a Filter: t2.a + t3.b > UInt32(100) [a:UInt32, b:UInt32, c:UInt32, a:UInt32;N, b:UInt32;N, c:UInt32;N]
487            TableScan: t2 [a:UInt32, b:UInt32, c:UInt32]
488            TableScan: t3 [a:UInt32, b:UInt32, c:UInt32]
489        "
490        )
491    }
492
493    #[test]
494    fn join_with_alias_filter() -> Result<()> {
495        let t1 = test_table_scan_with_name("t1")?;
496        let t2 = test_table_scan_with_name("t2")?;
497
498        let t1_schema = Arc::clone(t1.schema());
499        let t2_schema = Arc::clone(t2.schema());
500
501        // filter: t1.a + CAST(Int64(1), UInt32) = t2.a + CAST(Int64(2), UInt32) as t1.a + 1 = t2.a + 2
502        let filter = Expr::eq(
503            col("t1.a") + lit(1i64).cast_to(&DataType::UInt32, &t1_schema)?,
504            col("t2.a") + lit(2i32).cast_to(&DataType::UInt32, &t2_schema)?,
505        )
506        .alias("t1.a + 1 = t2.a + 2");
507        let plan = LogicalPlanBuilder::from(t1)
508            .join_on(t2, JoinType::Left, Some(filter))?
509            .build()?;
510
511        assert_optimized_plan_equal!(
512            plan,
513            @r"
514        Left Join: t1.a + CAST(Int64(1) AS UInt32) = t2.a + CAST(Int32(2) AS UInt32) [a:UInt32, b:UInt32, c:UInt32, a:UInt32;N, b:UInt32;N, c:UInt32;N]
515          TableScan: t1 [a:UInt32, b:UInt32, c:UInt32]
516          TableScan: t2 [a:UInt32, b:UInt32, c:UInt32]
517        "
518        )
519    }
520}