Apache DataFusion SQL Query Engine
Add option to control whether to normalize ident (#5124)
Jiacai Liuf8607c238d7c
diff --git a/datafusion/common/src/config.rs b/datafusion/common/src/config.rsindex 86b78aeace..6611094160 100644--- a/datafusion/common/src/config.rs+++ b/datafusion/common/src/config.rs@@ -178,6 +178,18 @@ config_namespace! {}}+config_namespace! {+ /// Options related to SQL parser+ pub struct SqlParserOptions {+ /// Whether to parse float as decimal+ pub parse_float_as_decimal: bool, default = false++ /// Whether to normalize ident+ pub enable_ident_normalization: bool, default = true++ }+}+config_namespace! {/// Options related to query executionpub struct ExecutionOptions {@@ -334,6 +346,8 @@ pub struct ConfigOptions {pub execution: ExecutionOptions,/// Optimizer optionspub optimizer: OptimizerOptions,+ /// SQL parser options+ pub sql_parser: SqlParserOptions,/// Explain optionspub explain: ExplainOptions,/// Optional extensions registered using [`Extensions::insert`]@@ -349,6 +363,7 @@ impl ConfigField for ConfigOptions {"execution" => self.execution.set(rem, value),"optimizer" => self.optimizer.set(rem, value),"explain" => self.explain.set(rem, value),+ "sql_parser" => self.sql_parser.set(rem, value),_ => Err(DataFusionError::Internal(format!("Config value \"{key}\" not found on ConfigOptions"))),diff --git a/datafusion/core/src/execution/context.rs b/datafusion/core/src/execution/context.rsindex 9d4d8367a8..b3243b2188 100644--- a/datafusion/core/src/execution/context.rs+++ b/datafusion/core/src/execution/context.rs@@ -65,7 +65,7 @@ use crate::logical_expr::{SetVariable, TableSource, TableType, UNNAMED_TABLE,};use crate::optimizer::OptimizerRule;-use datafusion_sql::{ResolvedTableReference, TableReference};+use datafusion_sql::{planner::ParserOptions, ResolvedTableReference, TableReference};use crate::physical_optimizer::coalesce_batches::CoalesceBatches;use crate::physical_optimizer::repartition::Repartition;@@ -235,6 +235,16 @@ impl SessionContext {self.session_id.clone()}+ /// Return the enable_ident_normalization of this Session+ pub fn enable_ident_normalization(&self) -> bool {+ self.state+ .read()+ .config+ .options+ .sql_parser+ .enable_ident_normalization+ }+/// Return a copied version of config for this Sessionpub fn copied_config(&self) -> SessionConfig {self.state.read().config.clone()@@ -1747,8 +1757,13 @@ impl SessionState {tables: HashMap::with_capacity(relations.len()),};+ let enable_ident_normalization =+ self.config.options.sql_parser.enable_ident_normalization;+ let parse_float_as_decimal =+ self.config.options.sql_parser.parse_float_as_decimal;for relation in relations {- let reference = object_name_to_table_reference(relation)?;+ let reference =+ object_name_to_table_reference(relation, enable_ident_normalization)?;let resolved = self.resolve_table_ref(reference.as_table_reference());if let Entry::Vacant(v) = provider.tables.entry(resolved.to_string()) {if let Ok(schema) = self.schema_for_ref(resolved) {@@ -1759,7 +1774,13 @@ impl SessionState {}}- let query = SqlToRel::new(&provider);+ let query = SqlToRel::new_with_options(+ &provider,+ ParserOptions {+ parse_float_as_decimal,+ enable_ident_normalization,+ },+ );query.statement_to_plan(statement)}diff --git a/datafusion/core/tests/sqllogictests/src/engines/datafusion/create_table.rs b/datafusion/core/tests/sqllogictests/src/engines/datafusion/create_table.rsindex d7ef8469e9..4504d3d1d2 100644--- a/datafusion/core/tests/sqllogictests/src/engines/datafusion/create_table.rs+++ b/datafusion/core/tests/sqllogictests/src/engines/datafusion/create_table.rs@@ -33,7 +33,8 @@ pub async fn create_table(if_not_exists: bool,or_replace: bool,) -> Result<DBOutput> {- let table_reference = object_name_to_table_reference(name)?;+ let table_reference =+ object_name_to_table_reference(name, ctx.enable_ident_normalization())?;let existing_table = ctx.table(&table_reference).await;match (if_not_exists, or_replace, existing_table) {(true, false, Ok(_)) => Ok(DBOutput::StatementComplete(0)),@@ -60,7 +61,20 @@ fn create_new_table(table_reference: OwnedTableReference,columns: Vec<ColumnDef>,) -> Result<DBOutput> {- let sql_to_rel = SqlToRel::new(&LogicTestContextProvider {});+ let config = ctx.copied_config();+ let sql_to_rel = SqlToRel::new_with_options(+ &LogicTestContextProvider {},+ datafusion_sql::planner::ParserOptions {+ parse_float_as_decimal: config+ .config_options()+ .sql_parser+ .parse_float_as_decimal,+ enable_ident_normalization: config+ .config_options()+ .sql_parser+ .enable_ident_normalization,+ },+ );let schema = Arc::new(sql_to_rel.build_schema(columns)?);let table_provider = Arc::new(MemTable::try_new(schema, vec![])?);ctx.register_table(&table_reference, table_provider)?;diff --git a/datafusion/core/tests/sqllogictests/src/engines/datafusion/insert.rs b/datafusion/core/tests/sqllogictests/src/engines/datafusion/insert.rsindex aa0d563e1b..16fbfb7a5d 100644--- a/datafusion/core/tests/sqllogictests/src/engines/datafusion/insert.rs+++ b/datafusion/core/tests/sqllogictests/src/engines/datafusion/insert.rs@@ -35,7 +35,10 @@ pub async fn insert(ctx: &SessionContext, insert_stmt: SQLStatement) -> Result<DSQLStatement::Insert {table_name, source, ..} => {- table_reference = object_name_to_table_reference(table_name)?;+ table_reference = object_name_to_table_reference(+ table_name,+ ctx.enable_ident_normalization(),+ )?;// Todo: check columns match table schemamatch *source.body {diff --git a/datafusion/core/tests/sqllogictests/test_files/ddl.slt b/datafusion/core/tests/sqllogictests/test_files/ddl.sltindex 2b49bcd034..e59971ee9e 100644--- a/datafusion/core/tests/sqllogictests/test_files/ddl.slt+++ b/datafusion/core/tests/sqllogictests/test_files/ddl.slt@@ -465,3 +465,73 @@ query II rowsortselect * from table_without_values;----10 20++# Enable information_schema, so we can execute show create table+statement ok+set datafusion.catalog.information_schema = true;++statement ok+CREATE OR REPLACE TABLE TABLE_WITH_NORMALIZATION(FIELD1 BIGINT, FIELD2 BIGINT);++# Check table name is in lowercase+query CCCC+show create table table_with_normalization+----+datafusion public table_with_normalization NULL++# Check column name is in uppercase+query CCC+describe table_with_normalization+----+field1 Int64 NO+field2 Int64 NO++# Disable ident normalization+statement ok+set datafusion.sql_parser.enable_ident_normalization = false;++statement ok+CREATE TABLE TABLE_WITHOUT_NORMALIZATION(FIELD1 BIGINT, FIELD2 BIGINT) AS VALUES (1,2);++# Check table name is in uppercase+query CCCC+show create table TABLE_WITHOUT_NORMALIZATION+----+datafusion public TABLE_WITHOUT_NORMALIZATION NULL++# Check column name is in uppercase+query CCC+describe TABLE_WITHOUT_NORMALIZATION+----+FIELD1 Int64 YES+FIELD2 Int64 YES++query R+select 10000000000000000000.01+----+10000000000000000000++query C+select arrow_typeof(10000000000000000000.01)+----+Float64++statement ok+set datafusion.sql_parser.parse_float_as_decimal = true;++query R+select 10000000000000000000.01+----+10000000000000000000.01++query C+select arrow_typeof(10000000000000000000.01)+----+Decimal128(22, 2)++# Restore those to default value again+statement ok+set datafusion.sql_parser.parse_float_as_decimal = false;++statement ok+set datafusion.sql_parser.enable_ident_normalization = true;\ No newline at end of filediff --git a/datafusion/sql/src/expr/identifier.rs b/datafusion/sql/src/expr/identifier.rsindex 5a5c4004ef..a581d5f472 100644--- a/datafusion/sql/src/expr/identifier.rs+++ b/datafusion/sql/src/expr/identifier.rs@@ -70,7 +70,10 @@ impl<'a, S: ContextProvider> SqlToRel<'a, S> {Ok(Expr::ScalarVariable(ty, var_names))} else {// only support "schema.table" type identifiers here- let (name, relation) = match idents_to_table_reference(ids)? {+ let (name, relation) = match idents_to_table_reference(+ ids,+ self.options.enable_ident_normalization,+ )? {OwnedTableReference::Partial { schema, table } => (table, schema),r @ OwnedTableReference::Bare { .. }| r @ OwnedTableReference::Full { .. } => {diff --git a/datafusion/sql/src/planner.rs b/datafusion/sql/src/planner.rsindex 5ccbbc09f7..759a4940c6 100644--- a/datafusion/sql/src/planner.rs+++ b/datafusion/sql/src/planner.rs@@ -34,7 +34,7 @@ use datafusion_expr::utils::find_column_exprs;use datafusion_expr::TableSource;use datafusion_expr::{col, AggregateUDF, Expr, ScalarUDF, SubqueryAlias};-use crate::utils::{make_decimal_type, normalize_ident};+use crate::utils::make_decimal_type;/// The ContextProvider trait allows the query planner to obtain meta-data about tables and/// functions referenced in SQL statements@@ -53,9 +53,19 @@ pub trait ContextProvider {}/// SQL parser options-#[derive(Debug, Default)]+#[derive(Debug)]pub struct ParserOptions {pub parse_float_as_decimal: bool,+ pub enable_ident_normalization: bool,+}++impl Default for ParserOptions {+ fn default() -> Self {+ Self {+ parse_float_as_decimal: false,+ enable_ident_normalization: true,+ }+ }}#[derive(Debug, Clone)]@@ -124,7 +134,7 @@ impl<'a, S: ContextProvider> SqlToRel<'a, S> {.iter().any(|x| x.option == ColumnOption::Null);fields.push(Field::new(- normalize_ident(column.name),+ normalize_ident(column.name, self.options.enable_ident_normalization),data_type,allow_null,));@@ -141,7 +151,7 @@ impl<'a, S: ContextProvider> SqlToRel<'a, S> {) -> Result<LogicalPlan> {let apply_name_plan = LogicalPlan::SubqueryAlias(SubqueryAlias::try_new(plan,- normalize_ident(alias.name),+ normalize_ident(alias.name, self.options.enable_ident_normalization),)?);self.apply_expr_alias(apply_name_plan, alias.columns)@@ -164,7 +174,10 @@ impl<'a, S: ContextProvider> SqlToRel<'a, S> {let fields = plan.schema().fields().clone();LogicalPlanBuilder::from(plan).project(fields.iter().zip(idents.into_iter()).map(|(field, ident)| {- col(field.name()).alias(normalize_ident(ident))+ col(field.name()).alias(normalize_ident(+ ident,+ self.options.enable_ident_normalization,+ ))}))?.build()}@@ -323,23 +336,25 @@ impl<'a, S: ContextProvider> SqlToRel<'a, S> {/// ```pub fn object_name_to_table_reference(object_name: ObjectName,+ enable_normalization: bool,) -> Result<OwnedTableReference> {// use destructure to make it clear no fields on ObjectName are ignoredlet ObjectName(idents) = object_name;- idents_to_table_reference(idents)+ idents_to_table_reference(idents, enable_normalization)}/// Create a [`OwnedTableReference`] after normalizing the specified identifierpub(crate) fn idents_to_table_reference(idents: Vec<Ident>,+ enable_normalization: bool,) -> Result<OwnedTableReference> {struct IdentTaker(Vec<Ident>);/// take the next identifier from the back of idents, panic'ing if/// there are none leftimpl IdentTaker {- fn take(&mut self) -> String {+ fn take(&mut self, enable_normalization: bool) -> String {let ident = self.0.pop().expect("no more identifiers");- normalize_ident(ident)+ normalize_ident(ident, enable_normalization)}}@@ -347,18 +362,18 @@ pub(crate) fn idents_to_table_reference(match taker.0.len() {1 => {- let table = taker.take();+ let table = taker.take(enable_normalization);Ok(OwnedTableReference::Bare { table })}2 => {- let table = taker.take();- let schema = taker.take();+ let table = taker.take(enable_normalization);+ let schema = taker.take(enable_normalization);Ok(OwnedTableReference::Partial { schema, table })}3 => {- let table = taker.take();- let schema = taker.take();- let catalog = taker.take();+ let table = taker.take(enable_normalization);+ let schema = taker.take(enable_normalization);+ let catalog = taker.take(enable_normalization);Ok(OwnedTableReference::Full {catalog,schema,@@ -374,7 +389,10 @@ pub(crate) fn idents_to_table_reference(/// Construct a WHERE qualifier suitable for e.g. information_schema filtering/// from the provided object identifiers (catalog, schema and table names).-pub fn object_name_to_qualifier(sql_table_name: &ObjectName) -> String {+pub fn object_name_to_qualifier(+ sql_table_name: &ObjectName,+ enable_normalization: bool,+) -> String {let columns = vec!["table_name", "table_schema", "table_catalog"].into_iter();sql_table_name.0@@ -382,8 +400,20 @@ pub fn object_name_to_qualifier(sql_table_name: &ObjectName) -> String {.rev().zip(columns).map(|(ident, column_name)| {- format!(r#"{} = '{}'"#, column_name, normalize_ident(ident.clone()))+ format!(+ r#"{} = '{}'"#,+ column_name,+ normalize_ident(ident.clone(), enable_normalization)+ )}).collect::<Vec<_>>().join(" AND ")}++fn normalize_ident(id: Ident, enable_normalization: bool) -> String {+ if enable_normalization {+ return crate::utils::normalize_ident(id);+ }++ id.value+}diff --git a/datafusion/sql/src/relation/mod.rs b/datafusion/sql/src/relation/mod.rsindex 852e9afdbf..f0bba7f50e 100644--- a/datafusion/sql/src/relation/mod.rs+++ b/datafusion/sql/src/relation/mod.rs@@ -33,7 +33,10 @@ impl<'a, S: ContextProvider> SqlToRel<'a, S> {let (plan, alias) = match relation {TableFactor::Table { name, alias, .. } => {// normalize name and alias- let table_ref = object_name_to_table_reference(name)?;+ let table_ref = object_name_to_table_reference(+ name,+ self.options.enable_ident_normalization,+ )?;let table_name = table_ref.to_string();let cte = planner_context.ctes.get(&table_name);(diff --git a/datafusion/sql/src/statement.rs b/datafusion/sql/src/statement.rsindex 8fe3dfdbaf..92aefa0620 100644--- a/datafusion/sql/src/statement.rs+++ b/datafusion/sql/src/statement.rs@@ -158,7 +158,10 @@ impl<'a, S: ContextProvider> SqlToRel<'a, S> {};Ok(LogicalPlan::CreateMemoryTable(CreateMemoryTable {- name: object_name_to_table_reference(name)?,+ name: object_name_to_table_reference(+ name,+ self.options.enable_ident_normalization,+ )?,input: Arc::new(plan),if_not_exists,or_replace,@@ -176,7 +179,10 @@ impl<'a, S: ContextProvider> SqlToRel<'a, S> {plan = self.apply_expr_alias(plan, columns)?;Ok(LogicalPlan::CreateView(CreateView {- name: object_name_to_table_reference(name)?,+ name: object_name_to_table_reference(+ name,+ self.options.enable_ident_normalization,+ )?,input: Arc::new(plan),or_replace,definition: sql,@@ -221,7 +227,10 @@ impl<'a, S: ContextProvider> SqlToRel<'a, S> {// nor do we support multiple object nameslet name = match names.len() {0 => Err(ParserError("Missing table name.".to_string()).into()),- 1 => object_name_to_table_reference(names.pop().unwrap()),+ 1 => object_name_to_table_reference(+ names.pop().unwrap(),+ self.options.enable_ident_normalization,+ ),_ => {Err(ParserError("Multiple objects not supported".to_string()).into())@@ -412,7 +421,10 @@ impl<'a, S: ContextProvider> SqlToRel<'a, S> {statement: DescribeTableStmt,) -> Result<LogicalPlan> {let DescribeTableStmt { table_name } = statement;- let table_ref = object_name_to_table_reference(table_name)?;+ let table_ref = object_name_to_table_reference(+ table_name,+ self.options.enable_ident_normalization,+ )?;let table_source = self.schema_provider@@ -631,7 +643,10 @@ impl<'a, S: ContextProvider> SqlToRel<'a, S> {};// Do a table lookup to verify the table exists- let table_ref = object_name_to_table_reference(table_name.clone())?;+ let table_ref = object_name_to_table_reference(+ table_name.clone(),+ self.options.enable_ident_normalization,+ )?;let provider = self.schema_provider.get_table_provider((&table_ref).into())?;@@ -683,7 +698,10 @@ impl<'a, S: ContextProvider> SqlToRel<'a, S> {};// Do a table lookup to verify the table exists- let table_name = object_name_to_table_reference(table_name)?;+ let table_name = object_name_to_table_reference(+ table_name,+ self.options.enable_ident_normalization,+ )?;let provider = self.schema_provider.get_table_provider((&table_name).into())?;@@ -785,7 +803,10 @@ impl<'a, S: ContextProvider> SqlToRel<'a, S> {source: Box<Query>,) -> Result<LogicalPlan> {// Do a table lookup to verify the table exists- let table_name = object_name_to_table_reference(table_name)?;+ let table_name = object_name_to_table_reference(+ table_name,+ self.options.enable_ident_normalization,+ )?;let provider = self.schema_provider.get_table_provider((&table_name).into())?;@@ -887,10 +908,16 @@ impl<'a, S: ContextProvider> SqlToRel<'a, S> {));}// Figure out the where clause- let where_clause = object_name_to_qualifier(&sql_table_name);+ let where_clause = object_name_to_qualifier(+ &sql_table_name,+ self.options.enable_ident_normalization,+ );// Do a table lookup to verify the table exists- let table_ref = object_name_to_table_reference(sql_table_name)?;+ let table_ref = object_name_to_table_reference(+ sql_table_name,+ self.options.enable_ident_normalization,+ )?;let _ = self.schema_provider.get_table_provider((&table_ref).into())?;@@ -922,10 +949,16 @@ impl<'a, S: ContextProvider> SqlToRel<'a, S> {));}// Figure out the where clause- let where_clause = object_name_to_qualifier(&sql_table_name);+ let where_clause = object_name_to_qualifier(+ &sql_table_name,+ self.options.enable_ident_normalization,+ );// Do a table lookup to verify the table exists- let table_ref = object_name_to_table_reference(sql_table_name)?;+ let table_ref = object_name_to_table_reference(+ sql_table_name,+ self.options.enable_ident_normalization,+ )?;let _ = self.schema_provider.get_table_provider((&table_ref).into())?;diff --git a/datafusion/sql/tests/integration_test.rs b/datafusion/sql/tests/integration_test.rsindex 2707272591..bd596577bc 100644--- a/datafusion/sql/tests/integration_test.rs+++ b/datafusion/sql/tests/integration_test.rs@@ -58,11 +58,44 @@ fn parse_decimals() {&expected,ParserOptions {parse_float_as_decimal: true,+ enable_ident_normalization: false,},);}}+#[test]+fn parse_ident_normalization() {+ let test_data = [+ (+ "SELECT age FROM person",+ "Ok(Projection: person.age\n TableScan: person)",+ true,+ ),+ (+ "SELECT AGE FROM PERSON",+ "Ok(Projection: person.age\n TableScan: person)",+ true,+ ),+ (+ "SELECT AGE FROM PERSON",+ "Err(Plan(\"No table named: PERSON found\"))",+ false,+ ),+ ];++ for (sql, expected, enable_ident_normalization) in test_data {+ let plan = logical_plan_with_options(+ sql,+ ParserOptions {+ parse_float_as_decimal: false,+ enable_ident_normalization,+ },+ );+ assert_eq!(expected, format!("{plan:?}"));+ }+}+#[test]fn select_no_relation() {quick_test(