Apache DataFusion SQL Query Engine
ARROW-11323: [Rust][DataFusion] Allow sort queries to return no results
Andrew Lamb49c0dc37f46f
diff --git a/rust/datafusion/src/execution/context.rs b/rust/datafusion/src/execution/context.rsindex b4b715bacb..5a036935ec 100644--- a/rust/datafusion/src/execution/context.rs+++ b/rust/datafusion/src/execution/context.rs@@ -853,6 +853,19 @@ mod tests {Ok(())}+ #[tokio::test]+ async fn sort_empty() -> Result<()> {+ // The predicate on this query purposely generates no results+ let results = execute(+ "SELECT c1, c2 FROM test WHERE c1 > 100000 ORDER BY c1 DESC, c2 ASC",+ 4,+ )+ .await+ .unwrap();+ assert_eq!(results.len(), 0);+ Ok(())+ }+#[tokio::test]async fn aggregate() -> Result<()> {let results = execute("SELECT SUM(c1), SUM(c2) FROM test", 4).await?;@@ -870,6 +883,24 @@ mod tests {Ok(())}+ #[tokio::test]+ async fn aggregate_empty() -> Result<()> {+ // The predicate on this query purposely generates no results+ let results = execute("SELECT SUM(c1), SUM(c2) FROM test where c1 > 100000", 4)+ .await+ .unwrap();++ assert_eq!(results.len(), 1);+ let batch = &results[0];++ let expected: Vec<&str> = vec!["NULL,NULL"];+ let mut rows = test::format_batch(&batch);+ rows.sort();+ assert_eq!(rows, expected);++ Ok(())+ }+#[tokio::test]async fn aggregate_avg() -> Result<()> {let results = execute("SELECT AVG(c1), AVG(c2) FROM test", 4).await?;diff --git a/rust/datafusion/src/physical_plan/sort.rs b/rust/datafusion/src/physical_plan/sort.rsindex 85655401c9..03e9d6a420 100644--- a/rust/datafusion/src/physical_plan/sort.rs+++ b/rust/datafusion/src/physical_plan/sort.rs@@ -141,7 +141,10 @@ fn sort_batches(batches: &Vec<RecordBatch>,schema: &SchemaRef,expr: &[PhysicalSortExpr],-) -> ArrowResult<RecordBatch> {+) -> ArrowResult<Option<RecordBatch>> {+ if batches.is_empty() {+ return Ok(None);+ }// combine all record batches into one for each columnlet combined_batch = RecordBatch::try_new(schema.clone(),@@ -170,7 +173,7 @@ fn sort_batches()?;// reorder all rows based on sorted indices- RecordBatch::try_new(+ let sorted_batch = RecordBatch::try_new(schema.clone(),combined_batch.columns()@@ -187,13 +190,14 @@ fn sort_batches()}).collect::<ArrowResult<Vec<ArrayRef>>>()?,- )+ );+ sorted_batch.map(Some)}pin_project! {struct SortStream {#[pin]- output: futures::channel::oneshot::Receiver<ArrowResult<RecordBatch>>,+ output: futures::channel::oneshot::Receiver<ArrowResult<Option<RecordBatch>>>,finished: bool,schema: SchemaRef,}@@ -240,10 +244,10 @@ impl Stream for SortStream {// check for error in receiving channel and unwrap actual resultlet result = match result {- Err(e) => Err(ArrowError::ExternalError(Box::new(e))), // error receiving- Ok(result) => result,+ Err(e) => Some(Err(ArrowError::ExternalError(Box::new(e)))), // error receiving+ Ok(result) => result.transpose(),};- Poll::Ready(Some(result))+ Poll::Ready(result)}Poll::Pending => Poll::Pending,}