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