Apache DataFusion SQL Query Engine
fix: support scalar function nested in get_field in Unparser (#16610)
Chen Chongchen17f1c9d4f84d
diff --git a/datafusion/sql/src/unparser/expr.rs b/datafusion/sql/src/unparser/expr.rsindex 1e39d7186d..729c6f235b 100644--- a/datafusion/sql/src/unparser/expr.rs+++ b/datafusion/sql/src/unparser/expr.rs@@ -621,27 +621,43 @@ impl Unparser<'_> {return internal_err!("get_field must have exactly 2 arguments");}- let mut id = match &args[0] {- Expr::Column(col) => match self.col_to_sql(col)? {- ast::Expr::Identifier(ident) => vec![ident],- ast::Expr::CompoundIdentifier(idents) => idents,- other => return internal_err!("expected col_to_sql to return an Identifier or CompoundIdentifier, but received: {:?}", other),- },- _ => return internal_err!("get_field expects first argument to be column, but received: {:?}", &args[0]),- };-let field = match &args[1] {Expr::Literal(lit, _) => self.new_ident_quoted_if_needs(lit.to_string()),_ => {return internal_err!("get_field expects second argument to be a string, but received: {:?}",- &args[0]+ &args[1])}};- id.push(field);- Ok(ast::Expr::CompoundIdentifier(id))+ match &args[0] {+ Expr::Column(col) => {+ let mut id = match self.col_to_sql(col)? {+ ast::Expr::Identifier(ident) => vec![ident],+ ast::Expr::CompoundIdentifier(idents) => idents,+ other => return internal_err!("expected col_to_sql to return an Identifier or CompoundIdentifier, but received: {:?}", other),+ };+ id.push(field);+ Ok(ast::Expr::CompoundIdentifier(id))+ }+ Expr::ScalarFunction(struct_expr) => {+ let root = self+ .scalar_function_to_sql(struct_expr.func.name(), &struct_expr.args)?;+ Ok(ast::Expr::CompoundFieldAccess {+ root: Box::new(root),+ access_chain: vec![ast::AccessExpr::Dot(ast::Expr::Identifier(+ field,+ ))],+ })+ }+ _ => {+ internal_err!(+ "get_field expects first argument to be column or scalar function, but received: {:?}",+ &args[0]+ )+ }+ }}fn map_to_sql(&self, args: &[Expr]) -> Result<ast::Expr> {diff --git a/datafusion/sql/tests/cases/plan_to_sql.rs b/datafusion/sql/tests/cases/plan_to_sql.rsindex d1af54a6f4..22924540ba 100644--- a/datafusion/sql/tests/cases/plan_to_sql.rs+++ b/datafusion/sql/tests/cases/plan_to_sql.rs@@ -307,7 +307,8 @@ macro_rules! roundtrip_statement_with_dialect_helper {.with_aggregate_function(max_udaf()).with_aggregate_function(min_udaf()).with_expr_planner(Arc::new(CoreFunctionPlanner::default()))- .with_expr_planner(Arc::new(NestedFunctionPlanner));+ .with_expr_planner(Arc::new(NestedFunctionPlanner))+ .with_expr_planner(Arc::new(FieldAccessPlanner));let context = MockContextProvider { state };let sql_to_rel = SqlToRel::new(&context);@@ -1337,7 +1338,10 @@ where.with_aggregate_function(grouping_udaf()).with_window_function(rank_udwf()).with_scalar_function(Arc::new(unicode::substr().as_ref().clone()))- .with_scalar_function(make_array_udf()),+ .with_scalar_function(make_array_udf())+ .with_expr_planner(Arc::new(CoreFunctionPlanner::default()))+ .with_expr_planner(Arc::new(NestedFunctionPlanner))+ .with_expr_planner(Arc::new(FieldAccessPlanner)),};let sql_to_rel = SqlToRel::new(&context);let plan = sql_to_rel.sql_statement_to_plan(statement).unwrap();@@ -2596,3 +2600,60 @@ fn test_not_ilike_filter_with_escape() {@"SELECT person.first_name FROM person WHERE person.first_name NOT ILIKE 'A!_%' ESCAPE '!'");}++#[test]+fn test_struct_expr() {+ let statement = generate_round_trip_statement(+ GenericDialect {},+ r#"WITH test AS (SELECT STRUCT(STRUCT('Product Name' as name) as product) AS metadata) SELECT metadata.product FROM test WHERE metadata.product.name = 'Product Name'"#,+ );+ assert_snapshot!(+ statement,+ @r#"SELECT test."metadata".product FROM (SELECT {product: {"name": 'Product Name'}} AS "metadata") AS test WHERE (test."metadata".product."name" = 'Product Name')"#+ );++ let statement = generate_round_trip_statement(+ GenericDialect {},+ r#"WITH test AS (SELECT STRUCT(STRUCT('Product Name' as name) as product) AS metadata) SELECT metadata.product FROM test WHERE metadata['product']['name'] = 'Product Name'"#,+ );+ assert_snapshot!(+ statement,+ @r#"SELECT test."metadata".product FROM (SELECT {product: {"name": 'Product Name'}} AS "metadata") AS test WHERE (test."metadata".product."name" = 'Product Name')"#+ );+}++#[test]+fn test_struct_expr2() {+ let statement = generate_round_trip_statement(+ GenericDialect {},+ r#"SELECT STRUCT(STRUCT('Product Name' as name) as product)['product']['name'] = 'Product Name';"#,+ );+ assert_snapshot!(+ statement,+ @r#"SELECT ({product: {"name": 'Product Name'}}.product."name" = 'Product Name')"#+ );+}++#[test]+fn test_struct_expr3() {+ let statement = generate_round_trip_statement(+ GenericDialect {},+ r#"WITH+ test AS (+ SELECT+ STRUCT (+ STRUCT (+ STRUCT ('Product Name' as name) as product+ ) AS metadata+ ) AS c1+ )+ SELECT+ c1.metadata.product.name+ FROM+ test"#,+ );+ assert_snapshot!(+ statement,+ @r#"SELECT test.c1."metadata".product."name" FROM (SELECT {"metadata": {product: {"name": 'Product Name'}}} AS c1) AS test"#+ );+}