Apache DataFusion SQL Query Engine
Implement a dialect-specific rule for unparsing an identifier with or without quotes (#10573)
Jax Liu7bd4b53ffa12
diff --git a/Cargo.toml b/Cargo.tomlindex e0edf30efa..339bbdf3d0 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -105,6 +105,7 @@ object_store = { version = "0.9.1", default-features = false }parking_lot = "0.12"parquet = { version = "51.0.0", default-features = false, features = ["arrow", "async", "object_store"] }rand = "0.8"+regex = "1.8"rstest = "0.19.0"serde_json = "1"sqlparser = { version = "0.45.0", features = ["visitor"] }diff --git a/datafusion-cli/Cargo.lock b/datafusion-cli/Cargo.lockindex db87f85e34..99af80bf9d 100644--- a/datafusion-cli/Cargo.lock+++ b/datafusion-cli/Cargo.lock@@ -1412,6 +1412,7 @@ dependencies = ["datafusion-common","datafusion-expr","log",+ "regex","sqlparser","strum 0.26.2",]diff --git a/datafusion-examples/examples/plan_to_sql.rs b/datafusion-examples/examples/plan_to_sql.rsindex 8ac6746a31..bd708fe52b 100644--- a/datafusion-examples/examples/plan_to_sql.rs+++ b/datafusion-examples/examples/plan_to_sql.rs@@ -49,7 +49,6 @@ use datafusion_sql::unparser::{plan_to_sql, Unparser};async fn main() -> Result<()> {// See how to evaluate expressionssimple_expr_to_sql_demo()?;- simple_expr_to_sql_demo_no_escape()?;simple_expr_to_sql_demo_escape_mysql_style()?;simple_plan_to_sql_demo().await?;round_trip_plan_to_sql_demo().await?;@@ -61,17 +60,6 @@ async fn main() -> Result<()> {fn simple_expr_to_sql_demo() -> Result<()> {let expr = col("a").lt(lit(5)).or(col("a").eq(lit(8)));let sql = expr_to_sql(&expr)?.to_string();- assert_eq!(sql, r#"(("a" < 5) OR ("a" = 8))"#);- Ok(())-}--/// DataFusion can convert expressions to SQL without escaping column names using-/// using a custom dialect and an explicit unparser-fn simple_expr_to_sql_demo_no_escape() -> Result<()> {- let expr = col("a").lt(lit(5)).or(col("a").eq(lit(8)));- let dialect = CustomDialect::new(None);- let unparser = Unparser::new(&dialect);- let sql = unparser.expr_to_sql(&expr)?.to_string();assert_eq!(sql, r#"((a < 5) OR (a = 8))"#);Ok(())}@@ -106,7 +94,7 @@ async fn simple_plan_to_sql_demo() -> Result<()> {assert_eq!(sql,- r#"SELECT "?table?"."id", "?table?"."int_col", "?table?"."double_col", "?table?"."date_string_col" FROM "?table?""#+ r#"SELECT "?table?".id, "?table?".int_col, "?table?".double_col, "?table?".date_string_col FROM "?table?""#);Ok(())@@ -145,7 +133,7 @@ async fn round_trip_plan_to_sql_demo() -> Result<()> {let sql = plan_to_sql(df.logical_plan())?.to_string();assert_eq!(sql,- r#"SELECT "alltypes_plain"."int_col", "alltypes_plain"."double_col", CAST("alltypes_plain"."date_string_col" AS VARCHAR) FROM "alltypes_plain" WHERE (("alltypes_plain"."id" > 1) AND ("alltypes_plain"."tinyint_col" < "alltypes_plain"."double_col"))"#+ r#"SELECT alltypes_plain.int_col, alltypes_plain.double_col, CAST(alltypes_plain.date_string_col AS VARCHAR) FROM alltypes_plain WHERE ((alltypes_plain.id > 1) AND (alltypes_plain.tinyint_col < alltypes_plain.double_col))"#);Ok(())diff --git a/datafusion/core/Cargo.toml b/datafusion/core/Cargo.tomlindex a0a525a149..a88cdfa274 100644--- a/datafusion/core/Cargo.toml+++ b/datafusion/core/Cargo.toml@@ -145,7 +145,7 @@ postgres-protocol = "0.6.4"postgres-types = { version = "0.2.4", features = ["derive", "with-chrono-0_4"] }rand = { workspace = true, features = ["small_rng"] }rand_distr = "0.4.3"-regex = "1.5.4"+regex = { workspace = true }rstest = { workspace = true }rust_decimal = { version = "1.27.0", features = ["tokio-pg"] }serde_json = { workspace = true }diff --git a/datafusion/functions/Cargo.toml b/datafusion/functions/Cargo.tomlindex ceb851a390..e4e99beee9 100644--- a/datafusion/functions/Cargo.toml+++ b/datafusion/functions/Cargo.toml@@ -80,7 +80,7 @@ itertools = { workspace = true }log = { workspace = true }md-5 = { version = "^0.10.0", optional = true }rand = { workspace = true }-regex = { version = "1.8", optional = true }+regex = { worksapce = true, optional = true }sha2 = { version = "^0.10.1", optional = true }unicode-segmentation = { version = "^1.7.1", optional = true }uuid = { version = "1.7", features = ["v4"], optional = true }diff --git a/datafusion/physical-expr/Cargo.toml b/datafusion/physical-expr/Cargo.tomlindex 798654206e..364940bdee 100644--- a/datafusion/physical-expr/Cargo.toml+++ b/datafusion/physical-expr/Cargo.toml@@ -66,7 +66,7 @@ itertools = { workspace = true, features = ["use_std"] }log = { workspace = true }paste = "^1.0"petgraph = "0.6.2"-regex = { version = "1.8", optional = true }+regex = { workspace = true, optional = true }[dev-dependencies]arrow = { workspace = true, features = ["test_utils"] }diff --git a/datafusion/sql/Cargo.toml b/datafusion/sql/Cargo.tomlindex ef3ed265c7..06bcdc9a1b 100644--- a/datafusion/sql/Cargo.toml+++ b/datafusion/sql/Cargo.toml@@ -47,6 +47,7 @@ arrow-schema = { workspace = true }datafusion-common = { workspace = true, default-features = true }datafusion-expr = { workspace = true }log = { workspace = true }+regex = { workspace = true }sqlparser = { workspace = true }strum = { version = "0.26.1", features = ["derive"] }diff --git a/datafusion/sql/src/unparser/dialect.rs b/datafusion/sql/src/unparser/dialect.rsindex ccbd388fc4..6a0df61ac1 100644--- a/datafusion/sql/src/unparser/dialect.rs+++ b/datafusion/sql/src/unparser/dialect.rs@@ -15,25 +15,38 @@// specific language governing permissions and limitations// under the License.-/// Dialect is used to capture dialect specific syntax.+use regex::Regex;+use sqlparser::keywords::ALL_KEYWORDS;++/// `Dialect` to use for Unparsing+///+/// The default dialect tries to avoid quoting identifiers unless necessary (e.g. `a` instead of `"a"`)+/// but this behavior can be overridden as needed/// Note: this trait will eventually be replaced by the Dialect in the SQLparser package////// See <https://github.com/sqlparser-rs/sqlparser-rs/pull/1170>pub trait Dialect {- fn identifier_quote_style(&self) -> Option<char>;+ fn identifier_quote_style(&self, _identifier: &str) -> Option<char>;}pub struct DefaultDialect {}impl Dialect for DefaultDialect {- fn identifier_quote_style(&self) -> Option<char> {- Some('"')+ fn identifier_quote_style(&self, identifier: &str) -> Option<char> {+ let identifier_regex = Regex::new(r"^[a-zA-Z_][a-zA-Z0-9_]*$").unwrap();+ if ALL_KEYWORDS.contains(&identifier.to_uppercase().as_str())+ || !identifier_regex.is_match(identifier)+ {+ Some('"')+ } else {+ None+ }}}pub struct PostgreSqlDialect {}impl Dialect for PostgreSqlDialect {- fn identifier_quote_style(&self) -> Option<char> {+ fn identifier_quote_style(&self, _: &str) -> Option<char> {Some('"')}}@@ -41,7 +54,7 @@ impl Dialect for PostgreSqlDialect {pub struct MySqlDialect {}impl Dialect for MySqlDialect {- fn identifier_quote_style(&self) -> Option<char> {+ fn identifier_quote_style(&self, _: &str) -> Option<char> {Some('`')}}@@ -49,7 +62,7 @@ impl Dialect for MySqlDialect {pub struct SqliteDialect {}impl Dialect for SqliteDialect {- fn identifier_quote_style(&self) -> Option<char> {+ fn identifier_quote_style(&self, _: &str) -> Option<char> {Some('`')}}@@ -67,7 +80,7 @@ impl CustomDialect {}impl Dialect for CustomDialect {- fn identifier_quote_style(&self) -> Option<char> {+ fn identifier_quote_style(&self, _: &str) -> Option<char> {self.identifier_quote_style}}diff --git a/datafusion/sql/src/unparser/expr.rs b/datafusion/sql/src/unparser/expr.rsindex 6209b409fa..5fe744e359 100644--- a/datafusion/sql/src/unparser/expr.rs+++ b/datafusion/sql/src/unparser/expr.rs@@ -74,7 +74,7 @@ impl Display for Unparsed {/// let expr = col("a").gt(lit(4));/// let sql = expr_to_sql(&expr).unwrap();///-/// assert_eq!(format!("{}", sql), "(\"a\" > 4)")+/// assert_eq!(format!("{}", sql), "(a > 4)")/// ```pub fn expr_to_sql(expr: &Expr) -> Result<ast::Expr> {let unparser = Unparser::default();@@ -492,10 +492,14 @@ impl Unparser<'_> {let mut id = table_ref.to_vec();id.push(col.name.to_string());return Ok(ast::Expr::CompoundIdentifier(- id.iter().map(|i| self.new_ident(i.to_string())).collect(),+ id.iter()+ .map(|i| self.new_ident_quoted_if_needs(i.to_string()))+ .collect(),));}- Ok(ast::Expr::Identifier(self.new_ident(col.name.to_string())))+ Ok(ast::Expr::Identifier(+ self.new_ident_quoted_if_needs(col.name.to_string()),+ ))}fn convert_bound(@@ -532,10 +536,12 @@ impl Unparser<'_> {.collect::<Result<Vec<_>>>()}- pub(super) fn new_ident(&self, str: String) -> ast::Ident {+ /// This function can create an identifier with or without quotes based on the dialect rules+ pub(super) fn new_ident_quoted_if_needs(&self, ident: String) -> ast::Ident {+ let quote_style = self.dialect.identifier_quote_style(&ident);ast::Ident {- value: str,- quote_style: self.dialect.identifier_quote_style(),+ value: ident,+ quote_style,}}@@ -977,67 +983,67 @@ mod tests {.build()?;let tests: Vec<(Expr, &str)> = vec![- ((col("a") + col("b")).gt(lit(4)), r#"(("a" + "b") > 4)"#),+ ((col("a") + col("b")).gt(lit(4)), r#"((a + b) > 4)"#),(Expr::Column(Column {relation: Some(TableReference::partial("a", "b")),name: "c".to_string(),}).gt(lit(4)),- r#"("a"."b"."c" > 4)"#,+ r#"(a.b.c > 4)"#,),(case(col("a")).when(lit(1), lit(true)).when(lit(0), lit(false)).otherwise(lit(ScalarValue::Null))?,- r#"CASE "a" WHEN 1 THEN true WHEN 0 THEN false ELSE NULL END"#,+ r#"CASE a WHEN 1 THEN true WHEN 0 THEN false ELSE NULL END"#,),(when(col("a").is_null(), lit(true)).otherwise(lit(false))?,- r#"CASE WHEN "a" IS NULL THEN true ELSE false END"#,+ r#"CASE WHEN a IS NULL THEN true ELSE false END"#,),(when(col("a").is_not_null(), lit(true)).otherwise(lit(false))?,- r#"CASE WHEN "a" IS NOT NULL THEN true ELSE false END"#,+ r#"CASE WHEN a IS NOT NULL THEN true ELSE false END"#,),(Expr::Cast(Cast {expr: Box::new(col("a")),data_type: DataType::Date64,}),- r#"CAST("a" AS DATETIME)"#,+ r#"CAST(a AS DATETIME)"#,),(Expr::Cast(Cast {expr: Box::new(col("a")),data_type: DataType::UInt32,}),- r#"CAST("a" AS INTEGER UNSIGNED)"#,+ r#"CAST(a AS INTEGER UNSIGNED)"#,),(col("a").in_list(vec![lit(1), lit(2), lit(3)], false),- r#""a" IN (1, 2, 3)"#,+ r#"a IN (1, 2, 3)"#,),(col("a").in_list(vec![lit(1), lit(2), lit(3)], true),- r#""a" NOT IN (1, 2, 3)"#,+ r#"a NOT IN (1, 2, 3)"#,),(ScalarUDF::new_from_impl(DummyUDF::new()).call(vec![col("a"), col("b")]),- r#"dummy_udf("a", "b")"#,+ r#"dummy_udf(a, b)"#,),(ScalarUDF::new_from_impl(DummyUDF::new()).call(vec![col("a"), col("b")]).is_null(),- r#"dummy_udf("a", "b") IS NULL"#,+ r#"dummy_udf(a, b) IS NULL"#,),(ScalarUDF::new_from_impl(DummyUDF::new()).call(vec![col("a"), col("b")]).is_not_null(),- r#"dummy_udf("a", "b") IS NOT NULL"#,+ r#"dummy_udf(a, b) IS NOT NULL"#,),(Expr::Like(Like {@@ -1047,7 +1053,7 @@ mod tests {escape_char: Some('o'),case_insensitive: true,}),- r#""a" NOT LIKE 'foo' ESCAPE 'o'"#,+ r#"a NOT LIKE 'foo' ESCAPE 'o'"#,),(Expr::SimilarTo(Like {@@ -1057,7 +1063,7 @@ mod tests {escape_char: Some('o'),case_insensitive: true,}),- r#""a" LIKE 'foo' ESCAPE 'o'"#,+ r#"a LIKE 'foo' ESCAPE 'o'"#,),(Expr::Literal(ScalarValue::Date64(Some(0))),@@ -1094,7 +1100,7 @@ mod tests {order_by: None,null_treatment: None,}),- r#"SUM("a")"#,+ r#"SUM(a)"#,),(Expr::AggregateFunction(AggregateFunction {@@ -1133,7 +1139,7 @@ mod tests {window_frame: WindowFrame::new(None),null_treatment: None,}),- r#"ROW_NUMBER("col") OVER (ROWS BETWEEN NULL PRECEDING AND NULL FOLLOWING)"#,+ r#"ROW_NUMBER(col) OVER (ROWS BETWEEN NULL PRECEDING AND NULL FOLLOWING)"#,),(Expr::WindowFunction(WindowFunction {@@ -1158,55 +1164,55 @@ mod tests {),null_treatment: None,}),- r#"COUNT(*) OVER (ORDER BY "a" DESC NULLS FIRST RANGE BETWEEN 6 PRECEDING AND 2 FOLLOWING)"#,+ r#"COUNT(*) OVER (ORDER BY a DESC NULLS FIRST RANGE BETWEEN 6 PRECEDING AND 2 FOLLOWING)"#,),- (col("a").is_not_null(), r#""a" IS NOT NULL"#),- (col("a").is_null(), r#""a" IS NULL"#),+ (col("a").is_not_null(), r#"a IS NOT NULL"#),+ (col("a").is_null(), r#"a IS NULL"#),((col("a") + col("b")).gt(lit(4)).is_true(),- r#"(("a" + "b") > 4) IS TRUE"#,+ r#"((a + b) > 4) IS TRUE"#,),((col("a") + col("b")).gt(lit(4)).is_not_true(),- r#"(("a" + "b") > 4) IS NOT TRUE"#,+ r#"((a + b) > 4) IS NOT TRUE"#,),((col("a") + col("b")).gt(lit(4)).is_false(),- r#"(("a" + "b") > 4) IS FALSE"#,+ r#"((a + b) > 4) IS FALSE"#,),((col("a") + col("b")).gt(lit(4)).is_not_false(),- r#"(("a" + "b") > 4) IS NOT FALSE"#,+ r#"((a + b) > 4) IS NOT FALSE"#,),((col("a") + col("b")).gt(lit(4)).is_unknown(),- r#"(("a" + "b") > 4) IS UNKNOWN"#,+ r#"((a + b) > 4) IS UNKNOWN"#,),((col("a") + col("b")).gt(lit(4)).is_not_unknown(),- r#"(("a" + "b") > 4) IS NOT UNKNOWN"#,+ r#"((a + b) > 4) IS NOT UNKNOWN"#,),- (not(col("a")), r#"NOT "a""#),+ (not(col("a")), r#"NOT a"#),(Expr::between(col("a"), lit(1), lit(7)),- r#"("a" BETWEEN 1 AND 7)"#,+ r#"(a BETWEEN 1 AND 7)"#,),- (Expr::Negative(Box::new(col("a"))), r#"-"a""#),+ (Expr::Negative(Box::new(col("a"))), r#"-a"#),(exists(Arc::new(dummy_logical_plan.clone())),- r#"EXISTS (SELECT "t"."a" FROM "t" WHERE ("t"."a" = 1))"#,+ r#"EXISTS (SELECT t.a FROM t WHERE (t.a = 1))"#,),(not_exists(Arc::new(dummy_logical_plan.clone())),- r#"NOT EXISTS (SELECT "t"."a" FROM "t" WHERE ("t"."a" = 1))"#,+ r#"NOT EXISTS (SELECT t.a FROM t WHERE (t.a = 1))"#,),(try_cast(col("a"), DataType::Date64),- r#"TRY_CAST("a" AS DATETIME)"#,+ r#"TRY_CAST(a AS DATETIME)"#,),(try_cast(col("a"), DataType::UInt32),- r#"TRY_CAST("a" AS INTEGER UNSIGNED)"#,+ r#"TRY_CAST(a AS INTEGER UNSIGNED)"#,),(Expr::ScalarVariable(Int8, vec![String::from("@a")]),@@ -1219,17 +1225,24 @@ mod tests {),r#"@root.foo"#,),- (col("x").eq(placeholder("$1")), r#"("x" = $1)"#),+ (col("x").eq(placeholder("$1")), r#"(x = $1)"#),(out_ref_col(DataType::Int32, "t.a").gt(lit(1)),- r#"("t"."a" > 1)"#,+ r#"(t.a > 1)"#,),(grouping_set(vec![vec![col("a"), col("b")], vec![col("a")]]),- r#"GROUPING SETS (("a", "b"), ("a"))"#,+ r#"GROUPING SETS ((a, b), (a))"#,+ ),+ (cube(vec![col("a"), col("b")]), r#"CUBE (a, b)"#),+ (rollup(vec![col("a"), col("b")]), r#"ROLLUP (a, b)"#),+ (col("table").eq(lit(1)), r#"("table" = 1)"#),+ (+ col("123_need_quoted").eq(lit(1)),+ r#"("123_need_quoted" = 1)"#,),- (cube(vec![col("a"), col("b")]), r#"CUBE ("a", "b")"#),- (rollup(vec![col("a"), col("b")]), r#"ROLLUP ("a", "b")"#),+ (col("need-quoted").eq(lit(1)), r#"("need-quoted" = 1)"#),+ (col("need quoted").eq(lit(1)), r#"("need quoted" = 1)"#),];for (expr, expected) in tests {@@ -1246,8 +1259,8 @@ mod tests {#[test]fn expr_to_unparsed_ok() -> Result<()> {let tests: Vec<(Expr, &str)> = vec![- ((col("a") + col("b")).gt(lit(4)), r#"(("a" + "b") > 4)"#),- (col("a").sort(true, true), r#""a" ASC NULLS FIRST"#),+ ((col("a") + col("b")).gt(lit(4)), r#"((a + b) > 4)"#),+ (col("a").sort(true, true), r#"a ASC NULLS FIRST"#),];for (expr, expected) in tests {diff --git a/datafusion/sql/src/unparser/plan.rs b/datafusion/sql/src/unparser/plan.rsindex 3373220a84..e23ee963ee 100644--- a/datafusion/sql/src/unparser/plan.rs+++ b/datafusion/sql/src/unparser/plan.rs@@ -52,7 +52,7 @@ use super::{/// .unwrap();/// let sql = plan_to_sql(&plan).unwrap();///-/// assert_eq!(format!("{}", sql), "SELECT \"table\".\"id\", \"table\".\"value\" FROM \"table\"")+/// assert_eq!(format!("{}", sql), "SELECT \"table\".id, \"table\".\"value\" FROM \"table\"")/// ```pub fn plan_to_sql(plan: &LogicalPlan) -> Result<ast::Statement> {let unparser = Unparser::default();@@ -141,9 +141,12 @@ impl Unparser<'_> {let mut builder = TableRelationBuilder::default();let mut table_parts = vec![];if let Some(schema_name) = scan.table_name.schema() {- table_parts.push(self.new_ident(schema_name.to_string()));+ table_parts+ .push(self.new_ident_quoted_if_needs(schema_name.to_string()));}- table_parts.push(self.new_ident(scan.table_name.table().to_string()));+ table_parts.push(+ self.new_ident_quoted_if_needs(scan.table_name.table().to_string()),+ );builder.name(ast::ObjectName(table_parts));relation.table(builder);@@ -416,7 +419,7 @@ impl Unparser<'_> {Ok(ast::SelectItem::ExprWithAlias {expr: inner,- alias: self.new_ident(name.to_string()),+ alias: self.new_ident_quoted_if_needs(name.to_string()),})}_ => {@@ -487,7 +490,7 @@ impl Unparser<'_> {fn new_table_alias(&self, alias: String) -> ast::TableAlias {ast::TableAlias {- name: self.new_ident(alias),+ name: self.new_ident_quoted_if_needs(alias),columns: Vec::new(),}}diff --git a/datafusion/sql/tests/sql_integration.rs b/datafusion/sql/tests/sql_integration.rsindex cca96b6eb9..e7da113e60 100644--- a/datafusion/sql/tests/sql_integration.rs+++ b/datafusion/sql/tests/sql_integration.rs@@ -4570,25 +4570,21 @@ impl TableSource for EmptyTable {#[test]fn roundtrip_expr() {let tests: Vec<(TableReference, &str, &str)> = vec![- (- TableReference::bare("person"),- "age > 35",- r#"("age" > 35)"#,- ),+ (TableReference::bare("person"), "age > 35", r#"(age > 35)"#),(TableReference::bare("person"),"id = '10'",- r#"("id" = '10')"#,+ r#"(id = '10')"#,),(TableReference::bare("person"),"CAST(id AS VARCHAR)",- r#"CAST("id" AS VARCHAR)"#,+ r#"CAST(id AS VARCHAR)"#,),(TableReference::bare("person"),"SUM((age * 2))",- r#"SUM(("age" * 2))"#,+ r#"SUM((age * 2))"#,),];