forked from apache/datafusion
-
Notifications
You must be signed in to change notification settings - Fork 5
feat: Allow repeated aliases (auto-realias) #187
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change | ||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|
|
|
@@ -21,15 +21,16 @@ use arrow::datatypes::{DataType, DECIMAL_DEFAULT_SCALE, DECIMAL_MAX_PRECISION}; | |||||||||||
| use datafusion_common::DFSchema; | ||||||||||||
| use sqlparser::ast::Ident; | ||||||||||||
|
|
||||||||||||
| use crate::logical_plan::ExprVisitable; | ||||||||||||
| use crate::logical_plan::{Expr, Like, LogicalPlan}; | ||||||||||||
| use crate::logical_plan::{ExprSchemable, ExprVisitable}; | ||||||||||||
| use crate::scalar::ScalarValue; | ||||||||||||
| use crate::{ | ||||||||||||
| error::{DataFusionError, Result}, | ||||||||||||
| logical_plan::{Column, ExpressionVisitor, Recursion}, | ||||||||||||
| }; | ||||||||||||
| use datafusion_expr::expr::GroupingSet; | ||||||||||||
| use std::collections::HashMap; | ||||||||||||
| use std::collections::{HashMap, HashSet}; | ||||||||||||
| use std::mem::replace; | ||||||||||||
|
|
||||||||||||
| /// Collect all deeply nested `Expr::AggregateFunction` and | ||||||||||||
| /// `Expr::AggregateUDF`. They are returned in order of occurrence (depth | ||||||||||||
|
|
@@ -781,6 +782,94 @@ pub(crate) fn normalize_ident(id: Ident) -> String { | |||||||||||
| id.value | ||||||||||||
| } | ||||||||||||
|
|
||||||||||||
| /// Structure holding qualifier and name of an alias. | ||||||||||||
| #[derive(Debug, Clone, PartialEq, Eq, Hash)] | ||||||||||||
| struct QualifiedAlias { | ||||||||||||
| qualifier: Option<String>, | ||||||||||||
| name: String, | ||||||||||||
| } | ||||||||||||
|
|
||||||||||||
| impl QualifiedAlias { | ||||||||||||
| fn new(qualifier: Option<String>, name: String) -> Self { | ||||||||||||
| Self { qualifier, name } | ||||||||||||
| } | ||||||||||||
|
|
||||||||||||
| fn from_expr_schema_and_alias( | ||||||||||||
| expr: &Expr, | ||||||||||||
| schema: &DFSchema, | ||||||||||||
| alias: Option<String>, | ||||||||||||
| ) -> Result<Self> { | ||||||||||||
| let field = expr.to_field(schema)?; | ||||||||||||
| let qualifier = alias.or_else(|| field.qualifier().cloned()); | ||||||||||||
| let name = field.name().clone(); | ||||||||||||
| Ok(Self::new(qualifier, name)) | ||||||||||||
| } | ||||||||||||
|
|
||||||||||||
| fn with_name(&self, name: &str) -> Self { | ||||||||||||
| Self { | ||||||||||||
| qualifier: self.qualifier.clone(), | ||||||||||||
| name: name.to_string(), | ||||||||||||
| } | ||||||||||||
| } | ||||||||||||
| } | ||||||||||||
|
|
||||||||||||
| /// Realias duplicate expression aliases in the provided list of expressions. | ||||||||||||
| pub(crate) fn realias_duplicate_expr_aliases( | ||||||||||||
| mut exprs: Vec<Expr>, | ||||||||||||
| schema: &DFSchema, | ||||||||||||
| alias: Option<String>, | ||||||||||||
| ) -> Result<Vec<Expr>> { | ||||||||||||
| // Two-pass algorithm is used: first collect all the aliases and indices of repeated aliases, | ||||||||||||
| // then realias the collected indices on the second pass. | ||||||||||||
| // This is to avoid realiasing to a name that is valid but is used by another expression | ||||||||||||
| // that was not originally processed. | ||||||||||||
| let mut aliases = HashSet::new(); | ||||||||||||
| let mut indices_to_realias = vec![]; | ||||||||||||
| for (index, expr) in exprs.iter().enumerate() { | ||||||||||||
| let qualified_alias = | ||||||||||||
| QualifiedAlias::from_expr_schema_and_alias(expr, schema, alias.clone())?; | ||||||||||||
| let is_duplicate = !aliases.insert(qualified_alias); | ||||||||||||
| if is_duplicate { | ||||||||||||
| indices_to_realias.push(index); | ||||||||||||
| } | ||||||||||||
| } | ||||||||||||
| const MAX_SUFFIX_LIMIT: usize = 100; | ||||||||||||
| 'outer: for index in indices_to_realias { | ||||||||||||
| let qualified_alias = QualifiedAlias::from_expr_schema_and_alias( | ||||||||||||
| &exprs[index], | ||||||||||||
| schema, | ||||||||||||
| alias.clone(), | ||||||||||||
| )?; | ||||||||||||
| for suffix in 1..=MAX_SUFFIX_LIMIT { | ||||||||||||
| let new_name = format!("{}__{}", qualified_alias.name, suffix); | ||||||||||||
| let new_qualified_alias = qualified_alias.with_name(&new_name); | ||||||||||||
| let is_duplicate = !aliases.insert(new_qualified_alias); | ||||||||||||
| if !is_duplicate { | ||||||||||||
| set_expr_alias(&mut exprs[index], new_name); | ||||||||||||
| continue 'outer; | ||||||||||||
| } | ||||||||||||
| } | ||||||||||||
| return Err(DataFusionError::Internal(format!( | ||||||||||||
| "Unable to realias duplicate expression alias: {:?}", | ||||||||||||
| exprs[index] | ||||||||||||
| ))); | ||||||||||||
| } | ||||||||||||
| Ok(exprs) | ||||||||||||
| } | ||||||||||||
|
|
||||||||||||
| /// Set an alias for an expression, replacing an existing alias or adding one if necessary. | ||||||||||||
| fn set_expr_alias(expr: &mut Expr, alias: String) { | ||||||||||||
| match expr { | ||||||||||||
| Expr::Alias(_, name) => { | ||||||||||||
| *name = alias; | ||||||||||||
| } | ||||||||||||
| _ => { | ||||||||||||
| // Expr::Wildcard is simply a placeholder to please borrow checker | ||||||||||||
| *expr = Expr::Alias(Box::new(replace(expr, Expr::Wildcard)), alias); | ||||||||||||
|
Comment on lines
+867
to
+868
|
||||||||||||
| // Expr::Wildcard is simply a placeholder to please borrow checker | |
| *expr = Expr::Alias(Box::new(replace(expr, Expr::Wildcard)), alias); | |
| // Use std::mem::replace to move the original expression into the Alias variant. | |
| // This avoids borrow checker issues and preserves the original expression semantics. | |
| *expr = Expr::Alias(Box::new(replace(expr, Expr::Alias(Box::new(Expr::Literal(ScalarValue::Null)), alias.clone()))), alias); |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.