diff --git a/datafusion/core/tests/sql/unparser.rs b/datafusion/core/tests/sql/unparser.rs index e3674d8c387e1..edd11fea16081 100644 --- a/datafusion/core/tests/sql/unparser.rs +++ b/datafusion/core/tests/sql/unparser.rs @@ -30,15 +30,18 @@ use arrow::array::RecordBatch; use arrow::datatypes::{DataType, Field, Schema}; use datafusion::common::Result; use datafusion::datasource::empty::EmptyTable; +use datafusion::functions_aggregate::expr_fn::count; use datafusion::optimizer::{ OptimizerRule, single_distinct_to_groupby::SingleDistinctToGroupBy, }; -use datafusion::prelude::{ParquetReadOptions, SessionContext}; +use datafusion::prelude::{ParquetReadOptions, SessionContext, lit}; use datafusion_catalog::memory::MemorySchemaProvider; use datafusion_catalog::{CatalogProvider, MemoryCatalogProvider, SchemaProvider}; use datafusion_common::Column; use datafusion_expr::Expr; -use datafusion_sql::unparser::dialect::{DefaultDialect, DuckDBDialect, MySqlDialect}; +use datafusion_sql::unparser::dialect::{ + BigQueryDialect, DefaultDialect, DuckDBDialect, MySqlDialect, +}; use datafusion_sql::unparser::{Unparser, plan_to_sql}; use itertools::Itertools; use recursive::{set_minimum_stack_size, set_stack_allocation_size}; @@ -759,6 +762,57 @@ async fn optimized_filter_with_subquery_alias() -> Result<()> { Ok(()) } +#[tokio::test] +async fn optimized_count_over_filter_empty_projection() -> Result<()> { + let ctx = SessionContext::new(); + ctx.sql("create table t (id int)").await?.collect().await?; + let plan = ctx + .sql("select count(*) from t where id > 10") + .await? + .into_optimized_plan()?; + let sql = plan_to_sql(&plan)?.to_string(); + assert_eq!( + sql, + r#"SELECT count(1) AS "count(*)" FROM (SELECT 1 FROM t WHERE (t.id > 10))"# + ); + + let dialect = BigQueryDialect {}; + let unparser = Unparser::new(&dialect); + let sql = unparser.plan_to_sql(&plan)?.to_string(); + assert_eq!( + sql, + "SELECT count(1) AS `count_40_42_41` FROM (SELECT 1 FROM `t` WHERE (`t`.`id` > 10))" + ); + Ok(()) +} + +#[tokio::test] +async fn unparse_projection_without_columns_over_global_aggregate() -> Result<()> { + let ctx = SessionContext::new(); + ctx.sql("create table t (id int) as values (1), (5), (11)") + .await? + .collect() + .await?; + ctx.sql("create table empty (id int)") + .await? + .collect() + .await?; + + for table in ["t", "empty"] { + for projection in [vec![], vec![lit(1)]] { + let plan = ctx + .table(table) + .await? + .aggregate(vec![], vec![count(lit(1))])? + .select(projection)? + .into_unoptimized_plan(); + let sql = plan_to_sql(&plan)?.to_string(); + assert_eq!(ctx.sql(&sql).await?.count().await?, 1, "{sql}"); + } + } + Ok(()) +} + #[tokio::test] async fn optimized_filter_after_projection() -> Result<()> { let ctx = SessionContext::new(); diff --git a/datafusion/sql/src/unparser/plan.rs b/datafusion/sql/src/unparser/plan.rs index 564de3a2816f6..c2223bd3ff3aa 100644 --- a/datafusion/sql/src/unparser/plan.rs +++ b/datafusion/sql/src/unparser/plan.rs @@ -311,7 +311,7 @@ impl Unparser<'_> { select: &mut SelectBuilder, fully_absorbed: bool, ) -> Result { - let mut exprs = p.expr.clone(); + let mut exprs = self.projection_exprs_or_fallback(p); // If an Unnest node is found within the select, find and unproject the unnest column let flatten_alias = select.current_flatten_alias(); @@ -944,6 +944,29 @@ impl Unparser<'_> { ); } + // Without column references nothing in this SELECT carries a + // global aggregate, so absorbing it would return one row per + // input row instead of exactly one. + if p.expr.iter().all(|expr| expr.column_refs().is_empty()) + && find_agg_node_within_select(plan, true) + .is_some_and(|agg| agg.group_expr.is_empty()) + { + self.derive_with_dialect_alias( + "derived_projection", + p.input.as_ref(), + relation, + false, + vec![], + )?; + let items = self + .projection_exprs_or_fallback(p) + .iter() + .map(|expr| self.select_item_to_sql(expr)) + .collect::>>()?; + select.projection(items); + return Ok(()); + } + if let Some(scope) = Self::derived_input_scope(plan, select) { // The input is about to enter a new SQL scope. Preserve that // boundary explicitly and make the outer expressions resolve @@ -2928,6 +2951,14 @@ impl Unparser<'_> { } } + fn projection_exprs_or_fallback(&self, p: &Projection) -> Vec { + if p.expr.is_empty() { + self.empty_projection_fallback() + } else { + p.expr.clone() + } + } + /// Decides where extracted table-scan filters belong in the unparsed SQL: /// in the `JOIN ON` clause or in `WHERE`. /// diff --git a/datafusion/sql/tests/cases/plan_to_sql.rs b/datafusion/sql/tests/cases/plan_to_sql.rs index 2c08b5595ab74..e6421debbf16c 100644 --- a/datafusion/sql/tests/cases/plan_to_sql.rs +++ b/datafusion/sql/tests/cases/plan_to_sql.rs @@ -1490,6 +1490,106 @@ fn test_table_scan_with_empty_projection_and_filter_default_dialect() { ); } +fn filter_with_empty_projection_helper() -> LogicalPlan { + table_scan(Some("table"), &test_schema(), None) + .unwrap() + .filter(col("id").gt(lit(10))) + .unwrap() + .project(Vec::::new()) + .unwrap() + .build() + .unwrap() +} + +#[test] +fn test_empty_projection_with_filter_default_dialect() { + let plan = filter_with_empty_projection_helper(); + let unparser = Unparser::new(&UnparserDefaultDialect {}); + let sql = unparser.plan_to_sql(&plan).unwrap(); + assert_snapshot!( + sql, + @r#"SELECT 1 FROM "table" WHERE ("table".id > 10)"# + ); +} + +#[test] +fn test_empty_projection_with_filter_postgres() { + let plan = filter_with_empty_projection_helper(); + let unparser = Unparser::new(&UnparserPostgreSqlDialect {}); + let sql = unparser.plan_to_sql(&plan).unwrap(); + assert_snapshot!( + sql, + @r#"SELECT FROM "table" WHERE ("table"."id" > 10)"# + ); +} + +#[test] +fn test_empty_projection_with_filter_bigquery() { + let plan = filter_with_empty_projection_helper(); + let unparser = Unparser::new(&BigQueryDialect {}); + let sql = unparser.plan_to_sql(&plan).unwrap(); + assert_snapshot!( + sql, + @"SELECT 1 FROM `table` WHERE (`table`.`id` > 10)" + ); +} + +fn projection_over_aggregate_helper( + group_expr: Vec, + projection: Vec, +) -> LogicalPlan { + table_scan(Some("table"), &test_schema(), None) + .unwrap() + .aggregate(group_expr, vec![max(col("id"))]) + .unwrap() + .project(projection) + .unwrap() + .build() + .unwrap() +} + +#[test] +fn test_empty_projection_over_global_aggregate_default_dialect() { + let plan = projection_over_aggregate_helper(vec![], vec![]); + let unparser = Unparser::new(&UnparserDefaultDialect {}); + let sql = unparser.plan_to_sql(&plan).unwrap(); + assert_snapshot!( + sql, + @r#"SELECT 1 FROM (SELECT max("table".id) FROM "table")"# + ); +} + +#[test] +fn test_empty_projection_over_global_aggregate_postgres() { + let plan = projection_over_aggregate_helper(vec![], vec![]); + let unparser = Unparser::new(&UnparserPostgreSqlDialect {}); + let sql = unparser.plan_to_sql(&plan).unwrap(); + assert_snapshot!( + sql, + @r#"SELECT FROM (SELECT max("table"."id") FROM "table") AS "derived_projection""# + ); +} + +#[test] +fn test_constant_projection_over_global_aggregate() { + let plan = projection_over_aggregate_helper(vec![], vec![lit(1)]); + let sql = plan_to_sql(&plan).unwrap(); + assert_snapshot!( + sql, + @r#"SELECT 1 FROM (SELECT max("table".id) FROM "table")"# + ); +} + +#[test] +fn test_empty_projection_over_grouped_aggregate() { + let plan = projection_over_aggregate_helper(vec![col("value")], vec![]); + let sql = plan_to_sql(&plan).unwrap(); + assert_snapshot!( + sql, + @r#"SELECT 1 FROM "table" GROUP BY "table"."value""# + ); +} + fn table_scan_with_empty_projection_and_none_projection_helper( table_name: &str, table_schema: Schema,