Skip to content
Open
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
69 changes: 60 additions & 9 deletions datafusion/expr/src/logical_plan/builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -731,8 +731,10 @@ impl LogicalPlanBuilder {
.map(Self::new)
}

/// Apply a projection, aliasing non-Column expressions to match the field
/// names from the provided schema. Existing aliases are renamed.
/// Apply a projection, aliasing non-Column expressions and colliding
/// aliases to match the field names from the provided schema. Unique
/// aliases are preserved so downstream clauses (`GROUP BY`, `HAVING`,
/// `QUALIFY`, `DISTINCT ON`, `ORDER BY`) can still resolve them.
pub fn project_with_validation_and_schema(
self,
expr: impl IntoIterator<Item = impl Into<SelectExpr>>,
Expand Down Expand Up @@ -2250,16 +2252,65 @@ fn project_with_validation(
);
}

// When inside a set expression, alias non-Column expressions to match the
// left side's field names, avoiding duplicate name errors. Existing aliases
// are renamed too, since they can still collide, e.g. `count(*)` is planned
// as `count(1) AS "count(*)"`.
// When inside a set expression, disambiguate duplicate output names against
// the left side's schema while preserving unique user aliases so clauses
// like GROUP BY / HAVING / QUALIFY / DISTINCT ON can still resolve them.
if let Some(schema) = &schema {
for (expr, field) in projected_expr.iter_mut().zip(schema.fields()) {
let output_name = |expr: &Expr| match expr {
Expr::Column(c) => c.name.clone(),
Expr::Alias(a) => a.name.clone(),
_ => expr.schema_name().to_string(),
};
let mut name_counts: HashMap<String, usize> =
HashMap::with_capacity(projected_expr.len());
for expr in &projected_expr {
*name_counts.entry(output_name(expr)).or_default() += 1;
}
let mut reserved: HashSet<String> = projected_expr
.iter()
.filter_map(|expr| match expr {
Expr::Column(c) => Some(c.name.clone()),
Expr::Alias(a) if name_counts.get(&a.name).copied().unwrap_or(0) == 1 => {
Some(a.name.clone())
}
_ => None,
})
.collect();
let next_unique_name =
|base: &str, idx: usize, reserved: &mut HashSet<String>| {
let candidate = if !reserved.contains(base) {
base.to_string()
} else {
let mut name = format!("{base}_{idx}");
while reserved.contains(&name) {
name.push('_');
}
name
};
reserved.insert(candidate.clone());
candidate
};

for (i, (expr, field)) in
projected_expr.iter_mut().zip(schema.fields()).enumerate()
{
match expr {
Expr::Column(_) => {}
Expr::Alias(alias) => alias.name.clone_from(field.name()),
_ => *expr = std::mem::take(expr).alias(field.name()),
Expr::Alias(alias) => {
if name_counts.get(&alias.name).copied().unwrap_or(0) > 1 {
alias.name = next_unique_name(field.name(), i, &mut reserved);
}
}
_ => {
let current = output_name(expr);
let is_dup = name_counts.get(&current).copied().unwrap_or(0) > 1;
if !reserved.contains(field.name()) || is_dup {
let name = next_unique_name(field.name(), i, &mut reserved);
*expr = std::mem::take(expr).alias(name);
} else {
reserved.insert(current);
}
}
}
}
}
Expand Down
93 changes: 93 additions & 0 deletions datafusion/sqllogictest/test_files/union.slt
Original file line number Diff line number Diff line change
Expand Up @@ -1450,3 +1450,96 @@ SELECT CAST(NULL AS SMALLINT) AS x WHERE false
UNION ALL
SELECT CAST(NULL AS BIGINT) AS x WHERE false;
----

# Right branch of set operations can reference its own SELECT aliases in GROUP BY / HAVING / QUALIFY / DISTINCT ON.
statement ok
CREATE TABLE set_alias_t(b INT) AS VALUES (1), (2);

query II rowsort
SELECT 1 AS c1, 2 AS c2
UNION ALL
SELECT b AS m, count(*) FROM set_alias_t GROUP BY m;
----
1 1
1 2
2 1

query II rowsort
SELECT 1 AS c1, 2 AS c2
UNION
SELECT b AS m, count(*) FROM set_alias_t GROUP BY m;
----
1 1
1 2
2 1

query II rowsort
SELECT 1 AS c1, 1 AS c2
INTERSECT
SELECT b AS m, count(*) FROM set_alias_t GROUP BY m;
----
1 1

query II rowsort
SELECT 1 AS c1, 1 AS c2
EXCEPT
SELECT b AS m, count(*) FROM set_alias_t GROUP BY m;
----

# Swapped alias names between left and right branches: HAVING must resolve right branch's alias.
query II rowsort
SELECT 1 AS p, 2 AS q
UNION ALL
SELECT count(*) AS q, sum(b) AS p FROM set_alias_t HAVING p > 2;
----
1 2
2 3

# QUALIFY referencing right branch's own alias.
query II rowsort
SELECT 1 AS c1, CAST(1 AS BIGINT UNSIGNED) AS c2
UNION ALL
SELECT b AS m, row_number() OVER (ORDER BY b) AS rn FROM set_alias_t QUALIFY rn > 1;
----
1 1
2 2

# DISTINCT ON referencing right branch's own alias.
query II rowsort
SELECT 1 AS c1, 2 AS c2
UNION ALL
SELECT DISTINCT ON (m) b AS m, b + 10 FROM set_alias_t;
----
1 11
1 2
2 12

query II rowsort
SELECT 1 AS c1, 2 AS c2
UNION ALL
(SELECT DISTINCT ON (m) b AS m, b + 10 FROM set_alias_t ORDER BY m);
----
1 11
1 2
2 12

# Right branch unique alias matching another position's left-branch field name alongside unaliased / duplicate expressions.
query III rowsort
SELECT 1 AS a, 2 AS b, 3 AS c
UNION ALL
SELECT 10 AS b, 20, 20;
----
1 2 3
10 20 20

query III rowsort
SELECT 1 AS a, 2 AS b, 3 AS c
UNION ALL
SELECT 10 AS x, 20 AS x, b AS a FROM set_alias_t GROUP BY a;
----
1 2 3
10 20 1
10 20 2

statement ok
DROP TABLE set_alias_t;