From e5fcb6a27b0371958c67e5622c99f52eb1b3dae8 Mon Sep 17 00:00:00 2001 From: Daniel Reverri Date: Mon, 19 Oct 2026 13:44:32 -0400 Subject: [PATCH 1/2] fix(unparser): apply empty projection fallback to Projection nodes A `Projection` with no expressions (as `optimize_projections` leaves under `count(*)` when a filter column is not otherwise needed) was unparsed as `SELECT FROM ...` regardless of `Dialect::supports_empty_select_list`. Only the `TableScan` path consulted the dialect, so e.g. BigQuery received SELECT COUNT(1) FROM (SELECT FROM `t` WHERE ...) and rejected it with "SELECT list must not be empty". `reconstruct_select_statement` now uses `empty_projection_fallback` for an empty projection, the same as the table scan path: `SELECT 1` for dialects without empty select lists, unchanged for PostgreSQL. Co-Authored-By: Claude Opus 5.5 --- datafusion/core/tests/sql/unparser.rs | 20 ++++++++ datafusion/sql/src/unparser/plan.rs | 10 +++- datafusion/sql/tests/cases/plan_to_sql.rs | 57 +++++++++++++++++++++++ 3 files changed, 86 insertions(+), 1 deletion(-) diff --git a/datafusion/core/tests/sql/unparser.rs b/datafusion/core/tests/sql/unparser.rs index e3674d8c387e1..ddc568c41b303 100644 --- a/datafusion/core/tests/sql/unparser.rs +++ b/datafusion/core/tests/sql/unparser.rs @@ -759,6 +759,26 @@ async fn optimized_filter_with_subquery_alias() -> Result<()> { Ok(()) } +/// `optimize_projections` prunes every column under `count(*)` when the +/// filter column isn't needed above the filter, leaving a `Projection` with +/// no expressions. Dialects without empty select list support must not +/// receive `SELECT FROM`. +#[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))"# + ); + 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..755b592638aa3 100644 --- a/datafusion/sql/src/unparser/plan.rs +++ b/datafusion/sql/src/unparser/plan.rs @@ -311,7 +311,15 @@ impl Unparser<'_> { select: &mut SelectBuilder, fully_absorbed: bool, ) -> Result { - let mut exprs = p.expr.clone(); + // A projection of no columns (e.g. under `count(*)` once + // `optimize_projections` has pruned every input column) gets the + // same fallback as an empty table scan projection, so dialects + // that reject `SELECT FROM` receive `SELECT 1 FROM`. + let mut exprs = if p.expr.is_empty() { + self.empty_projection_fallback() + } else { + p.expr.clone() + }; // If an Unnest node is found within the select, find and unproject the unnest column let flatten_alias = select.current_flatten_alias(); diff --git a/datafusion/sql/tests/cases/plan_to_sql.rs b/datafusion/sql/tests/cases/plan_to_sql.rs index 2c08b5595ab74..b63a98e5dd6e4 100644 --- a/datafusion/sql/tests/cases/plan_to_sql.rs +++ b/datafusion/sql/tests/cases/plan_to_sql.rs @@ -1490,6 +1490,63 @@ fn test_table_scan_with_empty_projection_and_filter_default_dialect() { ); } +/// A `Projection` node with no expressions, as `optimize_projections` +/// leaves under `count(*)` when the filter column isn't otherwise needed. +/// +/// For `select count(*) from t where id > 10`, the optimized plan is: +/// +/// ```text +/// Projection: count(Int64(1)) AS count(*) +/// Aggregate: groupBy=[[]], aggr=[[count(Int64(1))]] +/// Projection: <-- empty +/// Filter: t.id > Int32(10) +/// TableScan: t projection=[id] +/// ``` +/// +/// See also `optimized_count_over_filter_empty_projection` in +/// `datafusion/core/tests/sql/unparser.rs`. +fn filter_with_empty_projection_helper() -> LogicalPlanBuilder { + table_scan(Some("table"), &test_schema(), None) + .unwrap() + .filter(col("id").gt(lit(10))) + .unwrap() + .project(Vec::::new()) + .unwrap() +} + +#[test] +fn test_empty_projection_node_default_dialect() { + let plan = filter_with_empty_projection_helper().build().unwrap(); + 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_node_postgres() { + let plan = filter_with_empty_projection_helper().build().unwrap(); + 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_node_bigquery() { + let plan = filter_with_empty_projection_helper().build().unwrap(); + 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 table_scan_with_empty_projection_and_none_projection_helper( table_name: &str, table_schema: Schema, From 95a69c2921f2cf97f4ba3d7dd75227fc099e5ec5 Mon Sep 17 00:00:00 2001 From: Daniel Reverri Date: Thu, 3 Dec 2026 00:03:01 -0500 Subject: [PATCH 2/2] fix(unparser): keep global aggregates under projections without columns A Projection whose expressions reference no columns, such as the empty projection the fallback now emits as `SELECT 1`, was absorbed into the SELECT of a global Aggregate below it. Nothing in that SELECT referenced the aggregate and there was no GROUP BY, so the SQL returned one row per input row instead of exactly one. Keep the aggregate in a derived table in that case. Also unparse the optimized plan from #27332 with BigQueryDialect. Co-Authored-By: Claude Opus 5.5 --- datafusion/core/tests/sql/unparser.rs | 46 ++++++++++-- datafusion/sql/src/unparser/plan.rs | 41 ++++++++--- datafusion/sql/tests/cases/plan_to_sql.rs | 87 +++++++++++++++++------ 3 files changed, 137 insertions(+), 37 deletions(-) diff --git a/datafusion/core/tests/sql/unparser.rs b/datafusion/core/tests/sql/unparser.rs index ddc568c41b303..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,10 +762,6 @@ async fn optimized_filter_with_subquery_alias() -> Result<()> { Ok(()) } -/// `optimize_projections` prunes every column under `count(*)` when the -/// filter column isn't needed above the filter, leaving a `Projection` with -/// no expressions. Dialects without empty select list support must not -/// receive `SELECT FROM`. #[tokio::test] async fn optimized_count_over_filter_empty_projection() -> Result<()> { let ctx = SessionContext::new(); @@ -776,6 +775,41 @@ async fn optimized_count_over_filter_empty_projection() -> Result<()> { 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(()) } diff --git a/datafusion/sql/src/unparser/plan.rs b/datafusion/sql/src/unparser/plan.rs index 755b592638aa3..c2223bd3ff3aa 100644 --- a/datafusion/sql/src/unparser/plan.rs +++ b/datafusion/sql/src/unparser/plan.rs @@ -311,15 +311,7 @@ impl Unparser<'_> { select: &mut SelectBuilder, fully_absorbed: bool, ) -> Result { - // A projection of no columns (e.g. under `count(*)` once - // `optimize_projections` has pruned every input column) gets the - // same fallback as an empty table scan projection, so dialects - // that reject `SELECT FROM` receive `SELECT 1 FROM`. - let mut exprs = if p.expr.is_empty() { - self.empty_projection_fallback() - } else { - 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(); @@ -952,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 @@ -2936,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 b63a98e5dd6e4..e6421debbf16c 100644 --- a/datafusion/sql/tests/cases/plan_to_sql.rs +++ b/datafusion/sql/tests/cases/plan_to_sql.rs @@ -1490,33 +1490,20 @@ fn test_table_scan_with_empty_projection_and_filter_default_dialect() { ); } -/// A `Projection` node with no expressions, as `optimize_projections` -/// leaves under `count(*)` when the filter column isn't otherwise needed. -/// -/// For `select count(*) from t where id > 10`, the optimized plan is: -/// -/// ```text -/// Projection: count(Int64(1)) AS count(*) -/// Aggregate: groupBy=[[]], aggr=[[count(Int64(1))]] -/// Projection: <-- empty -/// Filter: t.id > Int32(10) -/// TableScan: t projection=[id] -/// ``` -/// -/// See also `optimized_count_over_filter_empty_projection` in -/// `datafusion/core/tests/sql/unparser.rs`. -fn filter_with_empty_projection_helper() -> LogicalPlanBuilder { +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_node_default_dialect() { - let plan = filter_with_empty_projection_helper().build().unwrap(); +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!( @@ -1526,8 +1513,8 @@ fn test_empty_projection_node_default_dialect() { } #[test] -fn test_empty_projection_node_postgres() { - let plan = filter_with_empty_projection_helper().build().unwrap(); +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!( @@ -1537,8 +1524,8 @@ fn test_empty_projection_node_postgres() { } #[test] -fn test_empty_projection_node_bigquery() { - let plan = filter_with_empty_projection_helper().build().unwrap(); +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!( @@ -1547,6 +1534,62 @@ fn test_empty_projection_node_bigquery() { ); } +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,