Apache DataFusion SQL Query Engine
ARROW-10672: [Rust] [DataFusion] Made Limit be computed on the stream.
Jorge C. Leitao983ef4cfd056
diff --git a/rust/datafusion/src/physical_plan/limit.rs b/rust/datafusion/src/physical_plan/limit.rsindex b685ca43b6..c6b32fb53b 100644--- a/rust/datafusion/src/physical_plan/limit.rs+++ b/rust/datafusion/src/physical_plan/limit.rs@@ -18,18 +18,22 @@//! Defines the LIMIT planuse std::any::Any;+use std::pin::Pin;use std::sync::Arc;+use std::task::{Context, Poll};++use futures::stream::Stream;+use futures::stream::StreamExt;use crate::error::{DataFusionError, Result};-use crate::physical_plan::memory::MemoryStream;use crate::physical_plan::{Distribution, ExecutionPlan, Partitioning};use arrow::array::ArrayRef;use arrow::compute::limit;use arrow::datatypes::SchemaRef;+use arrow::error::Result as ArrowResult;use arrow::record_batch::RecordBatch;-use futures::StreamExt;-use super::SendableRecordBatchStream;+use super::{RecordBatchStream, SendableRecordBatchStream};use async_trait::async_trait;@@ -111,12 +115,8 @@ impl ExecutionPlan for GlobalLimitExec {));}- let mut it = self.input.execute(0).await?;- Ok(Box::pin(MemoryStream::try_new(- collect_with_limit(&mut it, self.limit).await?,- self.input.schema(),- None,- )?))+ let stream = self.input.execute(0).await?;+ Ok(Box::pin(LimitStream::new(stream, self.limit)))}}@@ -169,58 +169,72 @@ impl ExecutionPlan for LocalLimitExec {}async fn execute(&self, _: usize) -> Result<SendableRecordBatchStream> {- let mut it = self.input.execute(0).await?;- Ok(Box::pin(MemoryStream::try_new(- collect_with_limit(&mut it, self.limit).await?,- self.input.schema(),- None,- )?))+ let stream = self.input.execute(0).await?;+ Ok(Box::pin(LimitStream::new(stream, self.limit)))}}/// Truncate a RecordBatch to maximum of n rows-pub fn truncate_batch(batch: &RecordBatch, n: usize) -> Result<RecordBatch> {- let limited_columns: Result<Vec<ArrayRef>> = (0..batch.num_columns())- .map(|i| limit(batch.column(i), n).map_err(|error| DataFusionError::from(error)))+pub fn truncate_batch(batch: &RecordBatch, n: usize) -> RecordBatch {+ let limited_columns: Vec<ArrayRef> = (0..batch.num_columns())+ .map(|i| limit(batch.column(i), n)).collect();- Ok(RecordBatch::try_new(- batch.schema().clone(),- limited_columns?,- )?)+ RecordBatch::try_new(batch.schema().clone(), limited_columns).unwrap()}-/// Create a vector of record batches from an iterator-async fn collect_with_limit(- reader: &mut SendableRecordBatchStream,+/// A Limit stream limits the stream to up to `limit` rows.+struct LimitStream {limit: usize,-) -> Result<Vec<RecordBatch>> {- let mut count = 0;- let mut results: Vec<RecordBatch> = vec![];- loop {- match reader.as_mut().next().await {- Some(Ok(batch)) => {- let capacity = limit - count;- if batch.num_rows() <= capacity {- count += batch.num_rows();- results.push(batch);- } else {- let batch = truncate_batch(&batch, capacity)?;- count += batch.num_rows();- results.push(batch);- }- if count == limit {- return Ok(results);- }- }- None => {- return Ok(results);- }- Some(Err(e)) => return Err(DataFusionError::from(e)),+ input: SendableRecordBatchStream,+ // the current count+ current_len: usize,+}++impl LimitStream {+ fn new(input: SendableRecordBatchStream, limit: usize) -> Self {+ Self {+ limit,+ input,+ current_len: 0,+ }+ }++ fn stream_limit(&mut self, batch: RecordBatch) -> Option<RecordBatch> {+ if self.current_len == self.limit {+ return None;+ } else if self.current_len + batch.num_rows() <= self.limit {+ self.current_len += batch.num_rows();+ return Some(batch);+ } else {+ let batch_rows = self.limit - self.current_len;+ self.current_len = self.limit;+ Some(truncate_batch(&batch, batch_rows))}}}+impl Stream for LimitStream {+ type Item = ArrowResult<RecordBatch>;++ fn poll_next(+ mut self: Pin<&mut Self>,+ cx: &mut Context<'_>,+ ) -> Poll<Option<Self::Item>> {+ self.input.poll_next_unpin(cx).map(|x| match x {+ Some(Ok(batch)) => Ok(self.stream_limit(batch)).transpose(),+ other => other,+ })+ }+}++impl RecordBatchStream for LimitStream {+ /// Get the schema+ fn schema(&self) -> SchemaRef {+ self.input.schema().clone()+ }+}+#[cfg(test)]mod tests {