Apache DataFusion SQL Query Engine
Fix bugs with CTE aliasing and normalize all identifiers in the SQL planner (#2373)
Andy Grove1825b9ce293d
diff --git a/datafusion/core/src/catalog/mod.rs b/datafusion/core/src/catalog/mod.rsindex 031cd87104..b9bf03e4f9 100644--- a/datafusion/core/src/catalog/mod.rs+++ b/datafusion/core/src/catalog/mod.rs@@ -23,9 +23,6 @@ pub mod catalog;pub mod information_schema;pub mod schema;-use crate::error::DataFusionError;-use std::convert::TryFrom;-/// Represents a resolved path to a table of the form "catalog.schema.table"#[derive(Clone, Copy)]pub struct ResolvedTableReference<'a> {@@ -132,30 +129,3 @@ impl<'a> From<ResolvedTableReference<'a>> for TableReference<'a> {}}}--impl<'a> TryFrom<&'a sqlparser::ast::ObjectName> for TableReference<'a> {- type Error = DataFusionError;-- fn try_from(value: &'a sqlparser::ast::ObjectName) -> Result<Self, Self::Error> {- let idents = &value.0;-- match idents.len() {- 1 => Ok(Self::Bare {- table: &idents[0].value,- }),- 2 => Ok(Self::Partial {- schema: &idents[0].value,- table: &idents[1].value,- }),- 3 => Ok(Self::Full {- catalog: &idents[0].value,- schema: &idents[1].value,- table: &idents[2].value,- }),- _ => Err(DataFusionError::Plan(format!(- "invalid table reference: {}",- value- ))),- }- }-}diff --git a/datafusion/core/src/sql/planner.rs b/datafusion/core/src/sql/planner.rsindex 2c8bce9da1..8325297c5e 100644--- a/datafusion/core/src/sql/planner.rs+++ b/datafusion/core/src/sql/planner.rs@@ -254,9 +254,9 @@ impl<'a, S: ContextProvider> SqlToRel<'a, S> {// Process CTEs from top to bottom// do not allow self-referencesfor cte in with.cte_tables {- // A `WITH` block can't use the same name for many times- let cte_name: &str = cte.alias.name.value.as_ref();- if ctes.contains_key(cte_name) {+ // A `WITH` block can't use the same name more than once+ let cte_name = normalize_ident(&cte.alias.name);+ if ctes.contains_key(&cte_name) {return Err(DataFusionError::SQL(ParserError(format!("WITH query name {:?} specified more than once",cte_name@@ -265,11 +265,11 @@ impl<'a, S: ContextProvider> SqlToRel<'a, S> {// create logical plan & pass backreferencing CTEslet logical_plan = self.query_to_plan_with_alias(cte.query,- Some(cte.alias.name.value.clone()),+ Some(cte_name.clone()),&mut ctes.clone(),outer_query_schema,)?;- ctes.insert(cte.alias.name.value, logical_plan);+ ctes.insert(cte_name, logical_plan);}}let plan = self.set_expr_to_plan(set_expr, alias, ctes, outer_query_schema)?;@@ -415,7 +415,11 @@ impl<'a, S: ContextProvider> SqlToRel<'a, S> {.options.iter().any(|x| x.option == ColumnOption::Null);- fields.push(Field::new(&column.name.value, data_type, allow_null));+ fields.push(Field::new(+ &normalize_ident(&column.name),+ data_type,+ allow_null,+ ));}Ok(Schema::new(fields))@@ -640,7 +644,7 @@ impl<'a, S: ContextProvider> SqlToRel<'a, S> {JoinConstraint::Using(idents) => {let keys: Vec<Column> = idents.into_iter()- .map(|x| Column::from_name(x.value))+ .map(|x| Column::from_name(&normalize_ident(&x))).collect();LogicalPlanBuilder::from(left).join_using(&right, join_type, keys)?@@ -666,28 +670,37 @@ impl<'a, S: ContextProvider> SqlToRel<'a, S> {) -> Result<LogicalPlan> {let (plan, alias) = match relation {TableFactor::Table {- ref name, alias, ..+ name: ref sql_object_name,+ alias,+ ..} => {- let table_name = name.to_string();+ // normalize name and alias+ let table_name = normalize_sql_object_name(sql_object_name);+ let table_ref: TableReference = table_name.as_str().into();+ let table_alias = alias.as_ref().map(|a| normalize_ident(&a.name));let cte = ctes.get(&table_name);(- match (- cte,- self.schema_provider.get_table_provider(name.try_into()?),- ) {- (Some(cte_plan), _) => Ok(cte_plan.clone()),+ match (cte, self.schema_provider.get_table_provider(table_ref)) {+ (Some(cte_plan), _) => match table_alias {+ Some(cte_alias) => project_with_alias(+ cte_plan.clone(),+ vec![Expr::Wildcard],+ Some(cte_alias),+ ),+ _ => Ok(cte_plan.clone()),+ },(_, Some(provider)) => {let scan =LogicalPlanBuilder::scan(&table_name, provider, None);- let scan = match alias {- Some(ref name) => scan?.alias(name.name.value.as_str()),+ let scan = match table_alias.as_ref() {+ Some(ref name) => scan?.alias(name.to_owned().as_str()),_ => scan,};scan?.build()}(None, None) => Err(DataFusionError::Plan(format!("Table or CTE with name '{}' not found",- name+ sql_object_name))),}?,alias,@@ -696,15 +709,16 @@ impl<'a, S: ContextProvider> SqlToRel<'a, S> {TableFactor::Derived {subquery, alias, ..} => {+ let normalized_alias = alias.as_ref().map(|a| normalize_ident(&a.name));// if alias is None, return Err- if alias.is_none() {+ if normalized_alias.is_none() {return Err(DataFusionError::Plan("subquery in FROM must have an alias".to_string(),));}let logical_plan = self.query_to_plan_with_alias(*subquery,- alias.as_ref().map(|a| a.name.value.to_string()),+ normalized_alias.clone(),ctes,outer_query_schema,)?;@@ -716,7 +730,7 @@ impl<'a, S: ContextProvider> SqlToRel<'a, S> {.fields().iter().map(|field| col(field.name())),- alias.as_ref().map(|a| normalize_ident(a.name.clone())),+ normalized_alias,)?,alias,)@@ -747,12 +761,12 @@ impl<'a, S: ContextProvider> SqlToRel<'a, S> {} else {Ok(LogicalPlanBuilder::from(plan.clone()).project_with_alias(- plan.schema()- .fields()- .iter()- .zip(columns_alias.iter())- .map(|(field, ident)| col(field.name()).alias(&ident.value)),- Some(alias.name.value),+ plan.schema().fields().iter().zip(columns_alias.iter()).map(+ |(field, ident)| {+ col(field.name()).alias(&normalize_ident(ident))+ },+ ),+ Some(normalize_ident(&alias.name)),)?.build()?)}@@ -1271,7 +1285,7 @@ impl<'a, S: ContextProvider> SqlToRel<'a, S> {SelectItem::ExprWithAlias { expr, alias } => {let expr = Alias(Box::new(self.sql_to_rex(expr, &input_schema)?),- normalize_ident(alias),+ normalize_ident(&alias),);Ok(vec![normalize_col(expr, plan)?])}@@ -1515,14 +1529,14 @@ impl<'a, S: ContextProvider> SqlToRel<'a, S> {// identifier. (e.g. it is "foo.bar" not foo.bar)Ok(Expr::Column(Column {relation: None,- name: normalize_ident(id),+ name: normalize_ident(&id),}))}}SQLExpr::MapAccess { ref column, keys } => {if let SQLExpr::Identifier(ref id) = column.as_ref() {- plan_indexed(col(&id.value), keys)+ plan_indexed(col(&normalize_ident(id)), keys)} else {Err(DataFusionError::NotImplemented(format!("map access requires an identifier, found column {} instead",@@ -1532,7 +1546,7 @@ impl<'a, S: ContextProvider> SqlToRel<'a, S> {}SQLExpr::CompoundIdentifier(ids) => {- let mut var_names: Vec<_> = ids.into_iter().map(normalize_ident).collect();+ let mut var_names: Vec<_> = ids.into_iter().map(|s| normalize_ident(&s)).collect();if &var_names[0][0..1] == "@" {let ty = self@@ -1774,7 +1788,7 @@ impl<'a, S: ContextProvider> SqlToRel<'a, S> {// (e.g. "foo.bar") for function names yetfunction.name.to_string()} else {- normalize_ident(function.name.0[0].clone())+ normalize_ident(&function.name.0[0])};// first, scalar built-in@@ -2183,7 +2197,7 @@ impl<'a, S: ContextProvider> SqlToRel<'a, S> {&self,extended: bool,full: bool,- table_name: &ObjectName,+ sql_table_name: &ObjectName,filter: Option<&ShowStatementFilter>,) -> Result<LogicalPlan> {if filter.is_some() {@@ -2198,26 +2212,26 @@ impl<'a, S: ContextProvider> SqlToRel<'a, S> {.to_string(),));}+ let table_name = normalize_sql_object_name(sql_table_name);+ let table_ref: TableReference = table_name.as_str().into();- if self- .schema_provider- .get_table_provider(table_name.try_into()?)- .is_none()- {+ if self.schema_provider.get_table_provider(table_ref).is_none() {return Err(DataFusionError::Plan(format!("Unknown relation for SHOW COLUMNS: {}",- table_name+ sql_table_name)));}// Figure out the where clauselet columns = vec!["table_name", "table_schema", "table_catalog"].into_iter();- let where_clause = table_name+ let where_clause = sql_table_name.0.iter().rev().zip(columns)- .map(|(ident, column_name)| format!(r#"{} = '{}'"#, column_name, ident))+ .map(|(ident, column_name)| {+ format!(r#"{} = '{}'"#, column_name, normalize_ident(ident))+ }).collect::<Vec<_>>().join(" AND ");@@ -2292,6 +2306,16 @@ impl<'a, S: ContextProvider> SqlToRel<'a, S> {}}+/// Normalize a SQL object name+fn normalize_sql_object_name(sql_object_name: &ObjectName) -> String {+ sql_object_name+ .0+ .iter()+ .map(normalize_ident)+ .collect::<Vec<String>>()+ .join(".")+}+/// Remove join expressions from a filter expressionfn remove_join_expressions(expr: &Expr,diff --git a/datafusion/core/src/sql/utils.rs b/datafusion/core/src/sql/utils.rsindex 9ed7f0b66c..8578b6d7e9 100644--- a/datafusion/core/src/sql/utils.rs+++ b/datafusion/core/src/sql/utils.rs@@ -547,9 +547,9 @@ pub(crate) fn make_decimal_type(}// Normalize an identifer to a lowercase string unless the identifier is quoted.-pub(crate) fn normalize_ident(id: Ident) -> String {+pub(crate) fn normalize_ident(id: &Ident) -> String {match id.quote_style {- Some(_) => id.value,+ Some(_) => id.value.clone(),None => id.value.to_ascii_lowercase(),}}diff --git a/datafusion/core/tests/sql/information_schema.rs b/datafusion/core/tests/sql/information_schema.rsindex 1317488e70..d3de4d699d 100644--- a/datafusion/core/tests/sql/information_schema.rs+++ b/datafusion/core/tests/sql/information_schema.rs@@ -307,13 +307,13 @@ async fn information_schema_show_columns() {let result = plan_and_collect(&ctx, "SHOW columns from t").await.unwrap();assert_batches_sorted_eq!(expected, &result);- // This isn't ideal but it is consistent behavior for `SELECT * from T`- let err = plan_and_collect(&ctx, "SHOW columns from T")+ // This isn't ideal but it is consistent behavior for `SELECT * from "T"`+ let err = plan_and_collect(&ctx, "SHOW columns from \"T\"").await.unwrap_err();assert_eq!(err.to_string(),- "Error during planning: Unknown relation for SHOW COLUMNS: T"+ "Error during planning: Unknown relation for SHOW COLUMNS: \"T\"");}diff --git a/datafusion/core/tests/sql/mod.rs b/datafusion/core/tests/sql/mod.rsindex 12570a4196..566baefab7 100644--- a/datafusion/core/tests/sql/mod.rs+++ b/datafusion/core/tests/sql/mod.rs@@ -535,19 +535,32 @@ async fn plan_and_collect(ctx: &SessionContext, sql: &str) -> Result<Vec<RecordB/// Execute query and return results as a Vec of RecordBatchesasync fn execute_to_batches(ctx: &SessionContext, sql: &str) -> Vec<RecordBatch> {let msg = format!("Creating logical plan for '{}'", sql);- let plan = ctx.create_logical_plan(sql).expect(&msg);+ let plan = ctx+ .create_logical_plan(sql)+ .map_err(|e| format!("{:?} at {}", e, msg))+ .unwrap();let logical_schema = plan.schema();let msg = format!("Optimizing logical plan for '{}': {:?}", sql, plan);- let plan = ctx.optimize(&plan).expect(&msg);+ let plan = ctx+ .optimize(&plan)+ .map_err(|e| format!("{:?} at {}", e, msg))+ .unwrap();let optimized_logical_schema = plan.schema();let msg = format!("Creating physical plan for '{}': {:?}", sql, plan);- let plan = ctx.create_physical_plan(&plan).await.expect(&msg);+ let plan = ctx+ .create_physical_plan(&plan)+ .await+ .map_err(|e| format!("{:?} at {}", e, msg))+ .unwrap();let msg = format!("Executing physical plan for '{}': {:?}", sql, plan);let task_ctx = ctx.task_ctx();- let results = collect(plan, task_ctx).await.expect(&msg);+ let results = collect(plan, task_ctx)+ .await+ .map_err(|e| format!("{:?} at {}", e, msg))+ .unwrap();assert_eq!(logical_schema.as_ref(), optimized_logical_schema.as_ref());resultsdiff --git a/datafusion/core/tests/sql/select.rs b/datafusion/core/tests/sql/select.rsindex dab7341324..87151b9bf0 100644--- a/datafusion/core/tests/sql/select.rs+++ b/datafusion/core/tests/sql/select.rs@@ -830,6 +830,29 @@ async fn query_on_string_dictionary() -> Result<()> {Ok(())}+#[tokio::test]+async fn query_cte_with_alias() -> Result<()> {+ let ctx = SessionContext::new();+ let schema = Schema::new(vec![+ Field::new("id", DataType::Int16, false),+ Field::new("a", DataType::Int16, false),+ ]);+ let empty_table = Arc::new(EmptyTable::new(Arc::new(schema)));+ ctx.register_table("t1", empty_table)?;+ let sql = "WITH \+ v1 AS (SELECT * FROM t1), \+ v2 AS (SELECT v1.id AS id, v1a.id AS id_a, v1b.id AS id_b \+ FROM v1, v1 v1a, v1 v1b \+ WHERE v1a.id = v1.id - 1 \+ AND v1b.id = v1.id + 1) \+ SELECT * FROM v2";+ let actual = execute_to_batches(&ctx, sql).await;+ // the purpose of this test is just to make sure the query produces a valid plan+ let expected = vec!["++", "++"];+ assert_batches_eq!(expected, &actual);+ Ok(())+}+#[tokio::test]async fn query_cte() -> Result<()> {// Test for SELECT <expression> without FROM.