apache / apache/datafusion

Inline aliases are not visible within query

Open
#16,291 0 comments 0 reactions 0 assignees View on GitHub
Dominant language
Rust
Stars
9.3k
Forks
2.4k
Avg merge
3d 7h
Merged PRs (30d)
344

Description

Some queries rely on alias reuse within the same SELECT
```sql
SELECT 'test' AS alias, LENGTH(alias)
```
DataFusion currently does not resolve alias in such cases during planning, which results in
```rust
Schema error: No field named alias
```
Related to https://github.com/apache/datafusion/issues/6543
**Suggestion to add visitor to update expressions before planning**
```rust
#[derive(Debug, Default)]
pub struct InlineAliasesInSelect {}

impl VisitorMut for InlineAliasesInSelect {
type Break = ();

fn pre_visit_query(&mut self, query: &mut Query) -> ControlFlow {
if let SetExpr::Select(select) = &mut *query.body {
let mut alias_expr_map = HashMap::new();

for item in &select.projection {
if let SelectItem::ExprWithAlias { expr, alias } = item {
alias_expr_map.insert(alias.value.clone(), expr.clone());
}
}

for item in &mut select.projection {
match item {
SelectItem::UnnamedExpr(expr) | SelectItem::ExprWithAlias { expr, .. } => {
visit_expressions_mut(expr, &mut |e: &mut Expr| {
if let Expr::Identifier(ident) = e {
if let Some(original) = alias_expr_map.get(&ident.value) {
*e = original.clone();
}
}
ControlFlow::<()>::Continue(())
});
}
_ => {}
}
}
}
ControlFlow::Continue(())
}
}

pub fn visit(stmt: &mut Statement) {
let _ = stmt.visit(&mut InlineAliasesInSelect {});
}
```

✅ Example

Transforms:
```sql
SELECT 'test' AS alias, LENGTH(alias)
```
Into an equivalent form:
```sql
SELECT 'test' AS alias, LENGTH('test')
```

Contributor guide

Open the contributing guide

Research direction

Start with DataFusion's SQL planning path and the visitor approach shown in the issue. Check how SELECT projections and identifiers are processed before planning, then verify that the example query resolves the inline alias and produces the equivalent expression without a schema error.

Written by the indexing model from the issue text.

Assessment

Tech stack
rust, sql
Domain
databases
Issue type
Feature
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.