Apache DataFusion SQL Query Engine
fix: return no rows from SortExec with fetch=0 instead of panicking i… (#27000)
Reza Shahwaz852e55787a13
diff --git a/datafusion/physical-plan/src/sorts/sort.rs b/datafusion/physical-plan/src/sorts/sort.rsindex 8663515c07..53c2929d4a 100644--- a/datafusion/physical-plan/src/sorts/sort.rs+++ b/datafusion/physical-plan/src/sorts/sort.rs@@ -1794,6 +1794,11 @@ impl ExecutionPlan for SortExec {BaselineMetrics::new(&self.metrics_set, partition),))),(true, None) => Ok(input),+ // `TopK` requires `k > 0`. `LIMIT 0` is normally removed by the+ // logical optimizer, but a `SortExec` with `fetch = Some(0)` can+ // still reach execution, for example when the logical optimizer+ // is disabled or the plan is built directly.+ (false, Some(0)) => Ok(Box::pin(EmptyRecordBatchStream::new(self.schema()))),(false, Some(fetch)) => {let filter = self.filter.clone();let mut topk = TopK::try_new(diff --git a/datafusion/sqllogictest/test_files/limit.slt b/datafusion/sqllogictest/test_files/limit.sltindex 6d6cea4a83..a97ce9efab 100644--- a/datafusion/sqllogictest/test_files/limit.slt+++ b/datafusion/sqllogictest/test_files/limit.slt@@ -1299,3 +1299,35 @@ SET datafusion.optimizer.max_passes = 3;statement okDROP TABLE t23534;++# Regression test for https://github.com/apache/datafusion/issues/26431+# `LIMIT 0` over unsorted input must return no rows instead of panicking in+# TopK. With the logical optimizer disabled, `eliminate_limit` does not remove+# the limit, so the physical plan sorts with `fetch=0`.+statement ok+SET datafusion.optimizer.max_passes = 0;++statement ok+CREATE TABLE t26431 (c0 BIGINT) AS VALUES (3), (1), (2);++query TT+EXPLAIN SELECT c0 FROM t26431 ORDER BY c0 LIMIT 0;+----+logical_plan+01)Limit: skip=0, fetch=0+02)--Sort: t26431.c0 ASC NULLS LAST+03)----Projection: t26431.c0+04)------TableScan: t26431+physical_plan+01)SortExec: TopK(fetch=0), expr=[c0@0 ASC NULLS LAST], preserve_partitioning=[false]+02)--DataSourceExec: partitions=1, partition_sizes=[1]++query I+SELECT c0 FROM t26431 ORDER BY c0 LIMIT 0;+----++statement ok+SET datafusion.optimizer.max_passes = 3;++statement ok+DROP TABLE t26431;