Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
58 changes: 56 additions & 2 deletions datafusion/core/tests/sql/unparser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};
Expand Down Expand Up @@ -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();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Non-blocking: Could we also unparse this optimized plan using BigQueryDialect to cover the complete nested query reported in #27332?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added in 95a69c2: optimized_count_over_filter_empty_projection now also unparses the optimized plan with BigQueryDialect, which gives SELECT count(1) AS `count_40_42_41` FROM (SELECT 1 FROM `t` WHERE (`t`.`id` > 10)). The alias is BigQuery's usual escaping of count(*).

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();
Expand Down
33 changes: 32 additions & 1 deletion datafusion/sql/src/unparser/plan.rs

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Does SELECT 1 preserve the meaning of a zero-column projection outside count(*), such as EXISTS or a UNION with zero columns?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The optimize_projections step should only produce an empty Projection when it can prove that the parent node needs only the row count of its input, not any column values. In the PR's example, select count(*) from t where id > 10, the aggregate count(Int64(1)) reads no columns. The filter below it still needs id, so the optimizer keeps id for the filter and inserts an empty Projection above it:

Projection: count(Int64(1)) AS count(*)
  Aggregate: groupBy=[[]], aggr=[[count(Int64(1))]]
    Projection:                          <-- empty
      Filter: t.id > Int32(10)
        TableScan: t projection=[id]

Because the parent was planned against a zero-column input, nothing above the empty Projection can reference a column, including the 1 the unparser adds. SELECT 1 FROM ... returns the same rows as SELECT FROM ..., so the result is unchanged.

To check the cases you mentioned, I ran zero-column queries in DataFusion and PostgreSQL 17, and ran the default-dialect unparser output for the same plans, which is the same query with SELECT FROM replaced by SELECT 1, back through DataFusion. t has id values 1, 5, 11, 12, 20.

Query (zero-column form) DataFusion PostgreSQL DataFusion, unparsed (SELECT 1)
SELECT t.id FROM t WHERE EXISTS (SELECT FROM t WHERE t.id > 10) ORDER BY t.id 5 rows 5 rows 5 rows
SELECT t.id FROM t WHERE EXISTS (SELECT FROM t WHERE t.id > 100) ORDER BY t.id 0 rows 0 rows 0 rows
SELECT t.id FROM t WHERE NOT EXISTS (SELECT FROM t WHERE t.id > 10) ORDER BY t.id 0 rows 0 rows 0 rows
SELECT count(1) AS n FROM (SELECT FROM t WHERE t.id > 10 UNION ALL SELECT FROM t WHERE t.id < 6) s n = 5 n = 5 n = 5
SELECT count(1) AS n FROM (SELECT FROM t WHERE t.id > 10 UNION SELECT FROM t WHERE t.id < 6) s n = 1 n = 1 n = 1
SELECT count(1) AS n FROM (SELECT FROM t WHERE t.id > 100 UNION SELECT FROM t WHERE t.id > 100) s n = 0 n = 0 n = 0

The one visible difference is when the empty projection is the root of the plan, e.g. a user explicitly asks for zero columns. Then the SQL returns one constant column instead of zero. That's the same trade-off TableScan has had since #19221, and it only applies to dialects with supports_empty_select_list() == false, where SELECT FROM isn't valid anyway. PostgreSQL still gets SELECT FROM.

This PR also fixes a union case. Before it, an empty TableScan input and an empty Projection input unparsed as SELECT 1 FROM t UNION ALL SELECT FROM t WHERE ..., which fails with UNION queries have different number of columns. Both inputs now use the same fallback.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Following up: a review found that the global aggregate case did change cardinality; that's fixed in 95a69c2.

Original file line number Diff line number Diff line change
Expand Up @@ -311,7 +311,7 @@ impl Unparser<'_> {
select: &mut SelectBuilder,
fully_absorbed: bool,
) -> Result<bool> {
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();
Expand Down Expand Up @@ -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::<Result<Vec<_>>>()?;
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
Expand Down Expand Up @@ -2928,6 +2951,14 @@ impl Unparser<'_> {
}
}

fn projection_exprs_or_fallback(&self, p: &Projection) -> Vec<Expr> {
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`.
///
Expand Down
100 changes: 100 additions & 0 deletions datafusion/sql/tests/cases/plan_to_sql.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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::<Expr>::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<Expr>,
projection: Vec<Expr>,
) -> 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,
Expand Down