Skip to content

rewrite col alias in bigquery #1

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

Open
wants to merge 1 commit into
base: v46
Choose a base branch
from
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
40 changes: 40 additions & 0 deletions datafusion/sql/src/unparser/dialect.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ use std::{collections::HashMap, sync::Arc};
use super::{utils::character_length_to_sql, utils::date_part_to_sql, Unparser};
use arrow::datatypes::TimeUnit;
use datafusion_common::Result;
use datafusion_common::alias::AliasGenerator;
use datafusion_expr::Expr;
use regex::Regex;
use sqlparser::tokenizer::Span;
Expand Down Expand Up @@ -154,6 +155,14 @@ pub trait Dialect: Send + Sync {
Ok(None)
}

fn col_alias_overrides(
&self,
_unparser: &Unparser,
_alias: &str,
) -> Result<Option<String>> {
Ok(None)
}

/// Allows the dialect to choose to omit window frame in unparsing
/// based on function name and window frame bound
/// Returns false if specific function name / window frame bound indicates no window frame is needed in unparsing
Expand Down Expand Up @@ -253,7 +262,38 @@ impl Dialect for DefaultDialect {
}
}
}
#[derive(Default)]
pub struct BigQueryDialect {
col_alias_generator: AliasGenerator,
}

impl Dialect for BigQueryDialect {
fn identifier_quote_style(&self, _: &str) -> Option<char> {
Some('`')
}

fn col_alias_overrides(
&self,
_unparser: &Unparser,
alias: &str,
) -> Result<Option<String>> {
// if alias has special characters, rewrite to alias from aliasGenerator
if alias.contains('*') {
Ok(Some(self.col_alias_generator.next("col")))
} else {
Ok(Some(alias.to_string()))
}
}
}

impl BigQueryDialect {
#[must_use]
pub fn new() -> Self {
Self {
col_alias_generator: AliasGenerator::new(),
}
}
}
pub struct PostgreSqlDialect {}

impl Dialect for PostgreSqlDialect {
Expand Down
13 changes: 10 additions & 3 deletions datafusion/sql/src/unparser/plan.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1034,10 +1034,17 @@ impl Unparser<'_> {
match expr {
Expr::Alias(Alias { expr, name, .. }) => {
let inner = self.expr_to_sql(expr)?;

Ok(ast::SelectItem::ExprWithAlias {

// Determine the alias name to use
let alias_name = if let Some(new_name) = self.dialect.col_alias_overrides(self, name)? {
new_name.to_string()
} else {
name.to_string()
};

return Ok(ast::SelectItem::ExprWithAlias {
expr: inner,
alias: self.new_ident_quoted_if_needs(name.to_string()),
alias: self.new_ident_quoted_if_needs(alias_name),
})
}
_ => {
Expand Down
10 changes: 8 additions & 2 deletions datafusion/sql/tests/cases/plan_to_sql.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ use datafusion_functions_window::rank::rank_udwf;
use datafusion_sql::planner::{ContextProvider, PlannerContext, SqlToRel};
use datafusion_sql::unparser::dialect::{
CustomDialectBuilder, DefaultDialect as UnparserDefaultDialect, DefaultDialect,
Dialect as UnparserDialect, MySqlDialect as UnparserMySqlDialect, SqliteDialect,
Dialect as UnparserDialect, MySqlDialect as UnparserMySqlDialect, SqliteDialect, BigQueryDialect as UnparserBigqueryDialect
};
use datafusion_sql::unparser::{expr_to_sql, plan_to_sql, Unparser};
use sqlparser::ast::Statement;
Expand All @@ -54,7 +54,7 @@ use datafusion_sql::unparser::extension_unparser::{
UnparseToStatementResult, UnparseWithinStatementResult,
UserDefinedLogicalNodeUnparser,
};
use sqlparser::dialect::{Dialect, GenericDialect, MySqlDialect};
use sqlparser::dialect::{Dialect, GenericDialect, MySqlDialect, PostgreSqlDialect};
use sqlparser::parser::Parser;

#[test]
Expand Down Expand Up @@ -536,6 +536,12 @@ fn roundtrip_statement_with_dialect() -> Result<()> {
parser_dialect: Box::new(GenericDialect {}),
unparser_dialect: Box::new(SqliteDialect {}),
},
TestStatementWithDialect {
sql: "select min(*) as \"min(*)\" from (select 1 as a)",
expected: "SELECT min(*) AS `col_1` FROM (SELECT 1 AS `a`)",
parser_dialect: Box::new(PostgreSqlDialect {}),
unparser_dialect: Box::new(UnparserBigqueryDialect::new()),
},
TestStatementWithDialect {
sql: "SELECT * FROM UNNEST([1,2,3])",
expected: r#"SELECT * FROM (SELECT UNNEST([1, 2, 3]) AS "UNNEST(make_array(Int64(1),Int64(2),Int64(3)))")"#,
Expand Down
Loading