Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
249 changes: 231 additions & 18 deletions datafusion/optimizer/src/extract_leaf_expressions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -572,6 +572,20 @@ impl<'a> LeafExpressionExtractor<'a> {
}
}

/// Resolves `col` against `schema` and returns it with the qualifier that
/// `schema` gives the field. Returns `None` if `schema` does not hold `col`,
/// or if the name is ambiguous in `schema`.
///
/// Two spellings of the same input column (a bare `c` and a qualified `t.c`)
/// resolve to the same `Column`, so they compare equal. A column pushed into
/// a projection this way uses the name that the input gives it.
fn resolve_against(schema: &DFSchema, col: &Column) -> Option<Column> {
schema
.qualified_field_from_column(col)
.ok()
.map(Column::from)
}

/// Build an extraction projection above the target node (shared by both passes).
///
/// If the target is an existing projection, merges into it. This requires
Expand Down Expand Up @@ -637,29 +651,31 @@ fn build_extraction_projection_impl(
// than target_schema (the projection's output) because columns produced
// by alias expressions (e.g., CSE's __common_expr_N) exist in the output but
// not the input, and cannot be added as pass-through Column references.
//
// Resolve the pass-through columns of `existing` (including same-name
// aliases such as `t.c AS c`) and the columns in `columns_needed`
// against the input schema before comparing them. Otherwise a bare `c`
// and a qualified `t.c` do not match, and the merged projection holds
// both, which `Projection::try_new` rejects as ambiguous.
let input_schema = existing.input.schema();
let existing_cols: IndexSet<Column> = existing
.expr
.iter()
.filter_map(|e| {
if let Expr::Column(c) = e {
Some(c.clone())
} else {
None
}
})
.filter_map(|e| resolve_against(input_schema, passthrough_column(e)?))
.collect();

let input_schema = existing.input.schema();
for col in columns_needed {
let col_expr = Expr::Column(col.clone());
let resolved = replace_cols_by_name(col_expr, &replace_map)?;
if let Expr::Column(resolved_col) = &resolved
&& !existing_cols.contains(resolved_col)
&& input_schema.has_column(resolved_col)
&& let Some(input_col) = resolve_against(input_schema, resolved_col)
&& !existing_cols.contains(&input_col)
{
proj_exprs.push(Expr::Column(resolved_col.clone()));
proj_exprs.push(Expr::Column(input_col));
}
// If resolved to non-column expr, it's already computed by existing projection
// Skip a column that resolves to a non-column expr: the existing
// projection already computes it. Also skip a column that is not in
// the input or is ambiguous there: no single spelling is correct.
}

Projection::try_new(proj_exprs, Arc::clone(&existing.input))
Expand Down Expand Up @@ -757,6 +773,21 @@ fn try_push_input(
split_and_push_projection(proj, alias_generator)
}

/// If this is a passthrough column. I.e,
///
/// - A bare column expression
/// - A trivial alias rename (i.e, `p.column AS column`)
fn passthrough_column(expr: &Expr) -> Option<&Column> {
match expr {
Expr::Column(col) => Some(col),
Expr::Alias(alias) => match alias.expr.as_ref() {
Expr::Column(col) if col.name == alias.name => Some(col),
Comment thread
notfilippo marked this conversation as resolved.
Resolved
_ => None,
},
_ => None,
}
}

/// Splits a projection into extractable pieces, pushes them towards leaf
/// nodes, and adds a recovery projection if needed.
///
Expand Down Expand Up @@ -831,7 +862,13 @@ fn split_and_push_projection(
let mut proj_exprs_captured: usize = 0;

for (expr, (qualifier, field)) in proj.expr.iter().zip(original_schema.iter()) {
if let Expr::Alias(alias) = expr
if let Some(col) = passthrough_column(expr) {
// Pass-through — the input already produces this column, so
// there is nothing to extract; just track it in the extractor.
extractors[0].columns_needed.insert(col.clone());
recovery_exprs.push(expr.clone());
proj_exprs_captured += 1;
} else if let Expr::Alias(alias) = expr
&& alias.name.starts_with(EXTRACTED_EXPR_PREFIX)
{
// Insert the full Alias expression as the key so that
Expand All @@ -847,11 +884,6 @@ fn split_and_push_projection(
.insert(expr.clone(), alias_name.clone());
recovery_exprs.push(Expr::Column(Column::new_unqualified(&alias_name)));
proj_exprs_captured += 1;
} else if let Expr::Column(col) = expr {
// Plain column pass-through — track it in the extractor
extractors[0].columns_needed.insert(col.clone());
recovery_exprs.push(expr.clone());
proj_exprs_captured += 1;
} else {
// Everything else: run through routing_extract
let transformed =
Expand Down Expand Up @@ -2111,6 +2143,113 @@ mod tests {
"#)
}

/// A filter can name a column bare (`a`) while the projection below it
/// outputs the qualified `test.a`. The optimizer leaves this shape when it
/// removes the empty input of a `UNION ALL` (for example
/// `... UNION ALL SELECT ... WHERE 1 = 2`). The merge must match the two, and not add a bare `a`
/// beside `test.a`, which is an ambiguous schema.
#[test]
fn test_merge_bare_column_into_qualified_projection() -> Result<()> {
let table_scan = test_table_scan()?;
let projection = LogicalPlanBuilder::from(table_scan)
.project(vec![
col("test.a"),
col("test.b"),
(col("test.c") + lit(1)).alias("d"),
])?
.build()?;
let predicate =
leaf_udf(Expr::Column(Column::new_unqualified("a")), "x").eq(lit(1));
let plan = LogicalPlan::Filter(datafusion_expr::Filter::try_new(
predicate,
Arc::new(projection),
)?);

assert_stages!(plan, @r#"
## Original Plan
Filter: leaf_udf(a, Utf8("x")) = Int32(1)
Projection: test.a, test.b, test.c + Int32(1) AS d
TableScan: test projection=[a, b, c]

## After Extraction
Projection: test.a, test.b, d
Filter: __datafusion_extracted_1 = Int32(1)
Projection: test.a, test.b, test.c + Int32(1) AS d, leaf_udf(a, Utf8("x")) AS __datafusion_extracted_1
TableScan: test projection=[a, b, c]

## After Pushdown
(same as after extraction)

## Optimized
(same as after pushdown)
"#)
}

/// When the merge appends a needed column that the projection does not
/// keep, it must append the input's qualified column (`test.b`), not the
/// bare `b` that the caller asked for.
#[test]
fn test_merge_appends_qualified_column_for_bare_request() -> Result<()> {
let projection = LogicalPlanBuilder::from(test_table_scan()?)
.project(vec![col("test.a")])?
.build()?;
let target_schema = Arc::clone(projection.schema());
let columns_needed: IndexSet<Column> =
IndexSet::from([Column::new_unqualified("b")]);

let merged = build_extraction_projection_impl(
&[],
&columns_needed,
&Arc::new(projection),
&target_schema,
)?;

assert_eq!(
merged.expr,
vec![
Expr::Column(Column::new(Some("test"), "a")),
Expr::Column(Column::new(Some("test"), "b")),
]
);
Ok(())
}

/// A projection can spell a pass-through column as a same-name alias
/// (`test.a AS a`). Merging an extraction into it must treat that alias as
/// the pass-through it is, and not add `test.a` beside the `a` it outputs,
/// which is an ambiguous schema.
#[test]
fn test_merge_into_projection_with_same_name_alias() -> Result<()> {
let table_scan = test_table_scan()?;
let plan = LogicalPlanBuilder::from(table_scan)
.project(vec![
col("test.a").alias("a"),
col("test.b").alias("b"),
col("test.c").alias("c"),
])?
.filter(leaf_udf(col("a"), "x").eq(lit(1)))?
.build()?;

assert_stages!(plan, @r#"
## Original Plan
Filter: leaf_udf(a, Utf8("x")) = Int32(1)
Projection: test.a AS a, test.b AS b, test.c AS c
TableScan: test projection=[a, b, c]

## After Extraction
Projection: a, b, c
Filter: __datafusion_extracted_1 = Int32(1)
Projection: test.a AS a, test.b AS b, test.c AS c, leaf_udf(test.a, Utf8("x")) AS __datafusion_extracted_1
TableScan: test projection=[a, b, c]

## After Pushdown
(same as after extraction)

## Optimized
(same as after pushdown)
"#)
}

// =========================================================================
// Join extraction tests
// =========================================================================
Expand Down Expand Up @@ -3163,4 +3302,78 @@ mod tests {

Ok(())
}

/// Reproduces a schema-ambiguity failure in `PushDownLeafProjections`.
///
/// ```text
/// Optimizer rule 'push_down_leaf_projections' failed
/// caused by
/// Schema error: Schema contains qualified field name p.__datafusion_extracted_1
/// and unqualified field name __datafusion_extracted_1 which would be ambiguous
/// ```
///
/// Four ingredients, each necessary:
///
/// 1. a `SubqueryAlias` over each join input (bare aliased table scans pass),
/// 2. a **left** join (an inner join passes),
/// 3. a leaf expression on *each* side, so extraction pushes into both inputs,
/// 4. an aggregate above the join (a projection passes).
///
/// With extraction pushed inside both aliases, the left input re-exposes its
/// alias qualified as `p.__datafusion_extracted_1`, while the recovery
/// projection above the join rebuilds the same reference unqualified via
/// `Column::new_unqualified`, so one schema ends up holding both spellings.
///
/// Equivalent SQL:
/// ```sql
/// CREATE VIEW p AS SELECT user, id FROM test;
/// CREATE VIEW c AS SELECT user, id FROM other;
/// SELECT p.user['a'], count(1)
/// FROM p LEFT JOIN c ON p.id = c.id
/// WHERE c.user['t'] IS NOT NULL
/// GROUP BY 1;
/// ```
#[test]
fn test_leaf_expr_on_both_sides_of_left_join_under_aggregate() -> Result<()> {
use datafusion_expr::JoinType;
use datafusion_expr::test::function_stub::count;

fn view(name: &str, table: LogicalPlan) -> Result<LogicalPlan> {
LogicalPlanBuilder::from(table)
.project(vec![col("user"), col("id")])?
.alias(name)?
.build()
}

let left = view("p", test_table_scan_with_struct()?)?;
let right = view("c", test_table_scan_with_struct_named("right")?)?;

let plan = LogicalPlanBuilder::from(left)
.join(right, JoinType::Left, (vec!["id"], vec!["id"]), None)?
.filter(leaf_udf(col("c.user"), "t").is_not_null())?
.aggregate(vec![leaf_udf(col("p.user"), "a")], vec![count(lit(1))])?
.build()?;

// The full optimizer, not `format_optimization_stages`: the triggering
// shape (`p.__datafusion_extracted_1 AS __datafusion_extracted_1`) only
// appears once projection merging has collapsed the recovery projection
// over the `SubqueryAlias`.
let ctx = OptimizerContext::new();
let optimized = Optimizer::new().optimize(plan, &ctx, |_, _| {})?;
insta::assert_snapshot!(format!("{optimized}"), @r#"
Projection: __datafusion_extracted_1 AS leaf_udf(p.user,Utf8("a")), COUNT(Int32(1))
Aggregate: groupBy=[[__datafusion_extracted_1]], aggr=[[COUNT(Int32(1))]]
Projection: p.__datafusion_extracted_1 AS __datafusion_extracted_1
Inner Join: p.id = c.id
SubqueryAlias: p
Projection: test.id, leaf_udf(test.user, Utf8("a")) AS __datafusion_extracted_1
TableScan: test projection=[id, user]
SubqueryAlias: c
Projection: right.id
Filter: __datafusion_extracted_2 IS NOT NULL
Projection: right.id, leaf_udf(right.user, Utf8("t")) AS __datafusion_extracted_2
TableScan: right projection=[id, user]
"#);
Ok(())
}
}
50 changes: 50 additions & 0 deletions datafusion/sqllogictest/test_files/struct.slt
Original file line number Diff line number Diff line change
Expand Up @@ -1733,3 +1733,53 @@ drop view leaf_view;
statement ok
drop table leaf_base;

# Merging an extraction projection into a projection whose output lost its
# qualifier. Eliminating the empty side of the union leaves a projection of
# bare column names over a qualified input, and the merge used to add the
# pass-through columns under those bare names beside the qualified ones the
# projection already carried, which is an ambiguous schema.
statement ok
create table leaf_merge_source(v int, s struct<a int>, env varchar) as values (1, {a: 10}, 'prod'), (2, {a: 20}, 'dev');

statement ok
set datafusion.explain.logical_plan_only = true;

query TT
explain with samples as (
select v, s, env from leaf_merge_source
),
expanded as (
select v, s, env from samples
union all
select v, s, env from samples where 1 = 2
)
select env, sum(s['a']) from expanded group by env order by env;
----
logical_plan
01)Sort: expanded.env ASC NULLS LAST
02)--Projection: expanded.env, sum(__datafusion_extracted_1) AS sum(expanded.s[a])
03)----Aggregate: groupBy=[[expanded.env]], aggr=[[sum(CAST(__datafusion_extracted_1 AS Int64))]]
04)------SubqueryAlias: expanded
05)--------SubqueryAlias: samples
06)----------Projection: leaf_merge_source.env, get_field(s, Utf8("a")) AS __datafusion_extracted_1
07)------------TableScan: leaf_merge_source projection=[s, env]

statement ok
set datafusion.explain.logical_plan_only = false;

query TI
with samples as (
select v, s, env from leaf_merge_source
),
expanded as (
select v, s, env from samples
union all
select v, s, env from samples where 1 = 2
)
select env, sum(s['a']) from expanded group by env order by env;
----
dev 20
prod 10

statement ok
drop table leaf_merge_source;
Loading