Skip to main content

datafusion_optimizer/
decorrelate_lateral_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//! [`DecorrelateLateralJoin`] decorrelates logical plans produced by lateral joins.
6
7use std::sync::Arc;
8
9use crate::decorrelate::{PullUpCorrelatedExpr, UN_MATCHED_ROW_INDICATOR};
10use crate::optimizer::ApplyOrder;
11use crate::utils::evaluates_to_null;
12use crate::{OptimizerConfig, OptimizerRule};
13use datafusion_expr::expr_rewriter::strip_outer_reference;
14use datafusion_expr::{Expr, Join, expr};
15
16use datafusion_common::tree_node::{
17    Transformed, TransformedResult, TreeNode, TreeNodeRecursion,
18};
19use datafusion_common::{Column, DFSchema, Result, ScalarValue, TableReference};
20use datafusion_expr::logical_plan::{JoinType, Subquery};
21use datafusion_expr::utils::conjunction;
22use datafusion_expr::{LogicalPlan, LogicalPlanBuilder, SubqueryAlias};
23
24/// Optimizer rule for rewriting lateral joins to joins
25#[derive(Default, Debug)]
26pub struct DecorrelateLateralJoin {}
27
28impl DecorrelateLateralJoin {
29    #[expect(missing_docs)]
30    pub fn new() -> Self {
31        Self::default()
32    }
33}
34
35impl OptimizerRule for DecorrelateLateralJoin {
36    fn rewrite(
37        &self,
38        plan: LogicalPlan,
39        _config: &dyn OptimizerConfig,
40    ) -> Result<Transformed<LogicalPlan>> {
41        // Find cross joins with outer column references on the right side (i.e., the apply operator).
42        let LogicalPlan::Join(join) = plan else {
43            return Ok(Transformed::no(plan));
44        };
45
46        rewrite_internal(join)
47    }
48
49    fn name(&self) -> &str {
50        "decorrelate_lateral_join"
51    }
52
53    fn apply_order(&self) -> Option<ApplyOrder> {
54        Some(ApplyOrder::TopDown)
55    }
56}
57
58// Build the decorrelated join based on the original lateral join query.
59// Supports INNER and LEFT lateral joins.
60fn rewrite_internal(join: Join) -> Result<Transformed<LogicalPlan>> {
61    if !matches!(join.join_type, JoinType::Inner | JoinType::Left) {
62        return Ok(Transformed::no(LogicalPlan::Join(join)));
63    }
64    let original_join_type = join.join_type;
65
66    // The right side is wrapped in a Subquery node when it contains outer
67    // references. Quickly skip joins that don't have this structure.
68    let Some((subquery, alias)) = extract_lateral_subquery(join.right.as_ref()) else {
69        return Ok(Transformed::no(LogicalPlan::Join(join)));
70    };
71
72    // If the subquery has no outer references, there is nothing to decorrelate.
73    // A LATERAL with no outer references is just a cross join.
74    let has_outer_refs = matches!(
75        subquery.subquery.apply_with_subqueries(|p| {
76            if p.contains_outer_reference() {
77                Ok(TreeNodeRecursion::Stop)
78            } else {
79                Ok(TreeNodeRecursion::Continue)
80            }
81        })?,
82        TreeNodeRecursion::Stop
83    );
84    if !has_outer_refs {
85        return Ok(Transformed::no(LogicalPlan::Join(join)));
86    }
87
88    let subquery_plan = subquery.subquery.as_ref();
89    let original_join_filter = join.filter.clone();
90
91    // Walk the subquery plan bottom-up, extracting correlated filter
92    // predicates into join conditions and converting ungrouped aggregates
93    // into group-by aggregates keyed on the correlation columns.
94    let mut pull_up = PullUpCorrelatedExpr::new().with_need_handle_count_bug(true);
95    let rewritten_subquery = subquery_plan.clone().rewrite(&mut pull_up).data()?;
96    if !pull_up.can_pull_up {
97        return Ok(Transformed::no(LogicalPlan::Join(join)));
98    }
99
100    // TODO: support HAVING in lateral subqueries.
101    // <https://github.com/apache/datafusion/issues/21198>
102    if pull_up.pull_up_having_expr.is_some() {
103        return Ok(Transformed::no(LogicalPlan::Join(join)));
104    }
105
106    // The correlation predicates (extracted from the subquery's WHERE) become
107    // the rewritten join's ON clause. See below for discussion of how the
108    // user's original ON clause is handled.
109    let correlation_filter = conjunction(pull_up.join_filters);
110
111    // Look up each aggregate's default value on empty input (e.g., COUNT → 0,
112    // SUM → NULL). This must happen before wrapping in SubqueryAlias, because
113    // the map is keyed by LogicalPlan and wrapping changes the plan.
114    let collected_count_expr_map = pull_up
115        .collected_count_expr_map
116        .get(&rewritten_subquery)
117        .cloned();
118
119    // Re-wrap in SubqueryAlias if the original had one, preserving the alias name.
120    // The SubqueryAlias re-qualifies all columns with the alias, so we must also
121    // rewrite column references in both the correlation and ON-clause filters.
122    let (right_plan, correlation_filter, original_join_filter) =
123        if let Some(ref alias) = alias {
124            let inner_schema = Arc::clone(rewritten_subquery.schema());
125            let right = LogicalPlan::SubqueryAlias(SubqueryAlias::try_new(
126                Arc::new(rewritten_subquery),
127                alias.clone(),
128            )?);
129            let corr = correlation_filter
130                .map(|f| requalify_filter(f, &inner_schema, alias))
131                .transpose()?;
132            let on = original_join_filter
133                .map(|f| requalify_filter(f, &inner_schema, alias))
134                .transpose()?;
135            (right, corr, on)
136        } else {
137            (rewritten_subquery, correlation_filter, original_join_filter)
138        };
139
140    let correlation_filter = correlation_filter.map(strip_outer_reference);
141
142    // For LEFT lateral joins, verify that all column references in the
143    // correlation filter are resolvable within the join's left and right
144    // schemas. If the lateral subquery references columns from an outer scope,
145    // the extracted filter will contain unresolvable columns and we must skip
146    // decorrelation.
147    //
148    // INNER lateral joins do not need this check: later optimizer passes
149    // (filter pushdown, join reordering) can restructure the plan to resolve
150    // cross-scope references. LEFT joins cannot be freely reordered.
151    if original_join_type == JoinType::Left
152        && let Some(ref filter) = correlation_filter
153    {
154        let left_schema = join.left.schema();
155        let right_schema = right_plan.schema();
156        let has_outer_scope_refs = filter
157            .column_refs()
158            .iter()
159            .any(|col| !left_schema.has_column(col) && !right_schema.has_column(col));
160        if has_outer_scope_refs {
161            return Ok(Transformed::no(LogicalPlan::Join(join)));
162        }
163    }
164
165    // Use a left join when the user wrote LEFT LATERAL or when a scalar
166    // aggregation was pulled up (preserves outer rows with no matches).
167    let join_type =
168        if original_join_type == JoinType::Left || pull_up.pulled_up_scalar_agg {
169            JoinType::Left
170        } else {
171            JoinType::Inner
172        };
173
174    // The correlation predicates (extracted from the subquery's WHERE) are
175    // turned into the rewritten join's ON clause. There are three cases that
176    // determine how the user's original ON clause is handled:
177    //
178    // - INNER lateral: user ON clause becomes a post-join filter. This restores
179    //   inner-join semantics if the join is upgraded to LEFT for count-bug
180    //   handling.
181    //
182    // - LEFT lateral with grouped (or no) agg: user ON clause is merged into
183    //   the rewritten ON clause, alongside the correlation predicates. LEFT
184    //   join semantics correctly preserve unmatched rows with NULLs.
185    //
186    // - LEFT lateral with an ungrouped aggregate (which decorrelation converts
187    //   to a group-by keyed on the correlation columns): user ON clause cannot
188    //   be placed in the join condition (it would conflict with count-bug
189    //   compensation) or as a post-join filter (that would remove
190    //   left-preserved rows). Instead, a projection is added after count-bug
191    //   compensation that replaces each right-side column with NULL when the ON
192    //   condition is not satisfied:
193    //
194    //      CASE WHEN (on_cond) IS NOT TRUE THEN NULL ELSE <col> END
195    //
196    //   This simulates LEFT JOIN semantics for the user's ON clause without
197    //   interfering with count-bug compensation.
198    let (join_filter, post_join_filter, on_condition_for_projection) =
199        if original_join_type == JoinType::Left {
200            if pull_up.pulled_up_scalar_agg {
201                (correlation_filter, None, original_join_filter)
202            } else {
203                let combined = conjunction(
204                    correlation_filter.into_iter().chain(original_join_filter),
205                );
206                (combined, None, None)
207            }
208        } else {
209            (correlation_filter, original_join_filter, None)
210        };
211
212    let left_field_count = join.left.schema().fields().len();
213    let new_plan = LogicalPlanBuilder::from(join.left)
214        .join_on(right_plan, join_type, join_filter)?
215        .build()?;
216
217    // Handle the count bug: in the rewritten left join, unmatched outer
218    // rows get NULLs for all right-side columns. But some aggregates
219    // have non-NULL defaults on empty input (e.g., COUNT returns 0, not
220    // NULL). Add a projection that wraps those columns:
221    //   CASE WHEN __always_true IS NULL THEN <default> ELSE <column> END
222    let new_plan = if let Some(expr_map) = collected_count_expr_map {
223        let join_schema = new_plan.schema();
224        let alias_qualifier = alias.as_ref();
225        let mut proj_exprs: Vec<Expr> = Vec::with_capacity(join_schema.fields().len());
226
227        for (i, (qualifier, field)) in join_schema.iter().enumerate() {
228            let col = Expr::Column(Column::new(qualifier.cloned(), field.name()));
229
230            // Only compensate right-side (subquery) fields. Left-side fields
231            // may share a name with an aggregate alias but must not be wrapped.
232            let name = field.name();
233            if i >= left_field_count
234                && let Some(default_value) = expr_map.get(name.as_str())
235                && !evaluates_to_null(default_value.clone(), default_value.column_refs())?
236            {
237                // Column whose aggregate doesn't naturally return NULL
238                // on empty input (e.g., COUNT returns 0). Wrap it.
239                let indicator_col =
240                    Column::new(alias_qualifier.cloned(), UN_MATCHED_ROW_INDICATOR);
241                let case_expr = Expr::Case(expr::Case {
242                    expr: None,
243                    when_then_expr: vec![(
244                        Box::new(Expr::IsNull(Box::new(Expr::Column(indicator_col)))),
245                        Box::new(default_value.clone()),
246                    )],
247                    else_expr: Some(Box::new(col)),
248                });
249                proj_exprs.push(Expr::Alias(expr::Alias {
250                    expr: Box::new(case_expr),
251                    relation: qualifier.cloned(),
252                    name: name.to_string(),
253                    metadata: None,
254                }));
255                continue;
256            }
257            proj_exprs.push(col);
258        }
259
260        LogicalPlanBuilder::from(new_plan)
261            .project(proj_exprs)?
262            .build()?
263    } else {
264        new_plan
265    };
266
267    // For LEFT lateral joins with an ungrouped aggregate, simulate LEFT JOIN
268    // semantics for the user's ON clause by adding a projection that replaces
269    // right-side columns with NULL when the ON condition is false (see
270    // commentary above).
271    //
272    // Note: the ON condition expression is duplicated per column, so this
273    // assumes it is deterministic.
274    let new_plan = if let Some(on_cond) = on_condition_for_projection {
275        let schema = Arc::clone(new_plan.schema());
276        let mut proj_exprs: Vec<Expr> = Vec::with_capacity(schema.fields().len());
277
278        for (i, (qualifier, field)) in schema.iter().enumerate() {
279            let col = Expr::Column(Column::new(qualifier.cloned(), field.name()));
280
281            if i < left_field_count {
282                proj_exprs.push(col);
283                continue;
284            }
285
286            let typed_null =
287                Expr::Literal(ScalarValue::try_from(field.data_type())?, None);
288            let case_expr = Expr::Case(expr::Case {
289                expr: None,
290                when_then_expr: vec![(
291                    Box::new(Expr::IsNotTrue(Box::new(on_cond.clone()))),
292                    Box::new(typed_null),
293                )],
294                else_expr: Some(Box::new(col)),
295            });
296            proj_exprs.push(case_expr.alias_qualified(qualifier.cloned(), field.name()));
297        }
298
299        LogicalPlanBuilder::from(new_plan)
300            .project(proj_exprs)?
301            .build()?
302    } else {
303        new_plan
304    };
305
306    // Apply the original ON clause as a post-join filter (INNER lateral only).
307    let new_plan = if let Some(on_filter) = post_join_filter {
308        LogicalPlanBuilder::from(new_plan)
309            .filter(on_filter)?
310            .build()?
311    } else {
312        new_plan
313    };
314
315    Ok(Transformed::new(new_plan, true, TreeNodeRecursion::Jump))
316}
317
318/// Extract the Subquery and optional alias from a lateral join's right side.
319fn extract_lateral_subquery(
320    plan: &LogicalPlan,
321) -> Option<(Subquery, Option<TableReference>)> {
322    match plan {
323        LogicalPlan::Subquery(sq) => Some((sq.clone(), None)),
324        LogicalPlan::SubqueryAlias(SubqueryAlias { input, alias, .. }) => {
325            if let LogicalPlan::Subquery(sq) = input.as_ref() {
326                Some((sq.clone(), Some(alias.clone())))
327            } else {
328                None
329            }
330        }
331        _ => None,
332    }
333}
334
335/// Rewrite column references in a join filter expression so that columns
336/// belonging to the inner (right) side use the SubqueryAlias qualifier.
337///
338/// The `PullUpCorrelatedExpr` pass extracts join filters with the inner
339/// columns qualified by their original table names (e.g., `t2.t1_id`).
340/// When the inner plan is wrapped in a `SubqueryAlias("sub")`, those
341/// columns are re-qualified as `sub.t1_id`. This function applies the
342/// same requalification to the filter so it matches the aliased schema.
343fn requalify_filter(
344    filter: Expr,
345    inner_schema: &DFSchema,
346    alias: &TableReference,
347) -> Result<Expr> {
348    filter
349        .transform(|expr| {
350            if let Expr::Column(col) = &expr
351                && inner_schema.has_column(col)
352            {
353                let new_col = Column::new(Some(alias.clone()), col.name.clone());
354                return Ok(Transformed::yes(Expr::Column(new_col)));
355            }
356            Ok(Transformed::no(expr))
357        })
358        .data()
359}