Apache DataFusion SQL Query Engine
ARROW-10046: [Rust] [DataFusion] Made `RecordBatchReader` implement Iterator
Jorge C. Leitaoa019055e009d
diff --git a/rust/datafusion/examples/flight_client.rs b/rust/datafusion/examples/flight_client.rsindex 3bc2a04a49..64103445a9 100644--- a/rust/datafusion/examples/flight_client.rs+++ b/rust/datafusion/examples/flight_client.rs@@ -63,7 +63,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {while let Some(flight_data) = stream.message().await? {// the unwrap is infallible and thus safelet record_batch =- flight_data_to_arrow_batch(&flight_data, schema.clone())?.unwrap();+ flight_data_to_arrow_batch(&flight_data, schema.clone()).unwrap()?;results.push(record_batch);}diff --git a/rust/datafusion/src/datasource/memory.rs b/rust/datafusion/src/datasource/memory.rsindex 4f0f846828..fcff7d61ac 100644--- a/rust/datafusion/src/datasource/memory.rs+++ b/rust/datafusion/src/datasource/memory.rs@@ -22,6 +22,7 @@use std::sync::Arc;use arrow::datatypes::{Field, Schema, SchemaRef};+use arrow::error::Result as ArrowResult;use arrow::record_batch::RecordBatch;use crate::datasource::TableProvider;@@ -64,10 +65,7 @@ impl MemTable {for partition in 0..exec.output_partitioning().partition_count() {let it = exec.execute(partition).await?;let mut it = it.lock().unwrap();- let mut partition_batches = vec![];- while let Ok(Some(batch)) = it.next_batch() {- partition_batches.push(batch);- }+ let partition_batches = it.into_iter().collect::<ArrowResult<Vec<_>>>()?;data.push(partition_batches);}@@ -148,7 +146,7 @@ mod tests {// scan with projectionlet exec = provider.scan(&Some(vec![2, 1]), 1024)?;let it = exec.execute(0).await?;- let batch2 = it.lock().expect("mutex lock").next_batch()?.unwrap();+ let batch2 = it.lock().expect("mutex lock").next().unwrap()?;assert_eq!(2, batch2.schema().fields().len());assert_eq!("c", batch2.schema().field(0).name());assert_eq!("b", batch2.schema().field(1).name());@@ -178,7 +176,7 @@ mod tests {let exec = provider.scan(&None, 1024)?;let it = exec.execute(0).await?;- let batch1 = it.lock().expect("mutex lock").next_batch()?.unwrap();+ let batch1 = it.lock().expect("mutex lock").next().unwrap()?;assert_eq!(3, batch1.schema().fields().len());assert_eq!(3, batch1.num_columns());diff --git a/rust/datafusion/src/datasource/parquet.rs b/rust/datafusion/src/datasource/parquet.rsindex cdefaad645..9f11372b14 100644--- a/rust/datafusion/src/datasource/parquet.rs+++ b/rust/datafusion/src/datasource/parquet.rs@@ -85,12 +85,14 @@ mod tests {let it = exec.execute(0).await?;let mut it = it.lock().unwrap();- let mut count = 0;- while let Some(batch) = it.next_batch()? {- assert_eq!(11, batch.num_columns());- assert_eq!(2, batch.num_rows());- count += 1;- }+ let count = it+ .into_iter()+ .map(|batch| {+ let batch = batch.unwrap();+ assert_eq!(11, batch.num_columns());+ assert_eq!(2, batch.num_rows());+ })+ .count();// we should have seen 4 batches of 2 rowsassert_eq!(4, count);@@ -304,8 +306,8 @@ mod tests {let exec = table.scan(projection, 1024)?;let it = exec.execute(0).await?;let mut it = it.lock().expect("failed to lock mutex");- Ok(it- .next_batch()?- .expect("should have received at least one batch"))+ it.next()+ .expect("should have received at least one batch")+ .map_err(|e| e.into())}}diff --git a/rust/datafusion/src/execution/context.rs b/rust/datafusion/src/execution/context.rsindex 7bc2d123b0..3df5e80f4b 100644--- a/rust/datafusion/src/execution/context.rs+++ b/rust/datafusion/src/execution/context.rs@@ -25,6 +25,7 @@ use std::sync::Arc;use arrow::csv;use arrow::datatypes::*;+use arrow::error::Result as ArrowResult;use arrow::record_batch::RecordBatch;use crate::datasource::csv::CsvFile;@@ -363,15 +364,13 @@ impl ExecutionContext {let mut writer = csv::Writer::new(file);let reader = plan.execute(i).await.unwrap();let mut reader = reader.lock().unwrap();- loop {- match reader.next_batch() {- Ok(Some(batch)) => writer.write(&batch).unwrap(),- Ok(None) => break,- Err(e) => return Err(ExecutionError::from(e)),- }- }- }+ reader+ .into_iter()+ .map(|batch| writer.write(&batch?))+ .collect::<ArrowResult<_>>()+ .map_err(|e| ExecutionError::from(e))?+ }Ok(())}diff --git a/rust/datafusion/src/physical_plan/common.rs b/rust/datafusion/src/physical_plan/common.rsindex e13e64c2f5..3008d9b1bc 100644--- a/rust/datafusion/src/physical_plan/common.rs+++ b/rust/datafusion/src/physical_plan/common.rs@@ -54,39 +54,34 @@ impl RecordBatchIterator {}}-impl RecordBatchReader for RecordBatchIterator {- fn schema(&self) -> SchemaRef {- self.schema.clone()- }+impl Iterator for RecordBatchIterator {+ type Item = ArrowResult<RecordBatch>;- fn next_batch(&mut self) -> ArrowResult<Option<RecordBatch>> {+ fn next(&mut self) -> Option<Self::Item> {if self.index < self.batches.len() {self.index += 1;- Ok(Some(self.batches[self.index - 1].as_ref().clone()))+ Some(Ok(self.batches[self.index - 1].as_ref().clone()))} else {- Ok(None)+ None}}}+impl RecordBatchReader for RecordBatchIterator {+ fn schema(&self) -> SchemaRef {+ self.schema.clone()+ }+}+/// Create a vector of record batches from an iteratorpub fn collect(it: Arc<Mutex<dyn RecordBatchReader + Send + Sync>>,) -> Result<Vec<RecordBatch>> {- let mut reader = it.lock().unwrap();- let mut results: Vec<RecordBatch> = vec![];- loop {- match reader.next_batch() {- Ok(Some(batch)) => {- results.push(batch);- }- Ok(None) => {- // end of result set- return Ok(results);- }- Err(e) => return Err(ExecutionError::from(e)),- }- }+ it.lock()+ .unwrap()+ .into_iter()+ .collect::<ArrowResult<Vec<_>>>()+ .map_err(|e| ExecutionError::from(e))}/// Recursively build a list of files in a directory with a given extensiondiff --git a/rust/datafusion/src/physical_plan/csv.rs b/rust/datafusion/src/physical_plan/csv.rsindex 436f5c4b64..acbf92d87b 100644--- a/rust/datafusion/src/physical_plan/csv.rs+++ b/rust/datafusion/src/physical_plan/csv.rs@@ -262,16 +262,19 @@ impl CsvIterator {}}+impl Iterator for CsvIterator {+ type Item = ArrowResult<RecordBatch>;++ fn next(&mut self) -> Option<Self::Item> {+ self.reader.next()+ }+}+impl RecordBatchReader for CsvIterator {/// Get the schemafn schema(&self) -> SchemaRef {self.reader.schema()}-- /// Get the next RecordBatch- fn next_batch(&mut self) -> ArrowResult<Option<RecordBatch>> {- Ok(self.reader.next()?)- }}#[cfg(test)]@@ -296,7 +299,7 @@ mod tests {assert_eq!(3, csv.schema().fields().len());let it = csv.execute(0).await?;let mut it = it.lock().unwrap();- let batch = it.next_batch()?.unwrap();+ let batch = it.next().unwrap()?;assert_eq!(3, batch.num_columns());let batch_schema = batch.schema();assert_eq!(3, batch_schema.fields().len());@@ -319,7 +322,7 @@ mod tests {assert_eq!(13, csv.schema().fields().len());let it = csv.execute(0).await?;let mut it = it.lock().unwrap();- let batch = it.next_batch()?.unwrap();+ let batch = it.next().unwrap()?;assert_eq!(13, batch.num_columns());let batch_schema = batch.schema();assert_eq!(13, batch_schema.fields().len());diff --git a/rust/datafusion/src/physical_plan/filter.rs b/rust/datafusion/src/physical_plan/filter.rsindex ffc9fa5ff6..26c04cb8d1 100644--- a/rust/datafusion/src/physical_plan/filter.rs+++ b/rust/datafusion/src/physical_plan/filter.rs@@ -120,48 +120,58 @@ struct FilterExecIter {input: Arc<Mutex<dyn RecordBatchReader + Send + Sync>>,}-impl RecordBatchReader for FilterExecIter {- /// Get the schema- fn schema(&self) -> SchemaRef {- self.schema.clone()- }+impl Iterator for FilterExecIter {+ type Item = ArrowResult<RecordBatch>;/// Get the next batch- fn next_batch(&mut self) -> ArrowResult<Option<RecordBatch>> {+ fn next(&mut self) -> Option<ArrowResult<RecordBatch>> {let mut input = self.input.lock().unwrap();- match input.next_batch()? {- Some(batch) => {+ match input.next() {+ Some(Ok(batch)) => {// evaluate the filter predicate to get a boolean array indicating which rows// to include in the output- let result = self- .predicate- .evaluate(&batch)- .map_err(ExecutionError::into_arrow_external_error)?;-- if let Some(f) = result.as_any().downcast_ref::<BooleanArray>() {- // filter each array- let mut filtered_arrays = Vec::with_capacity(batch.num_columns());- for i in 0..batch.num_columns() {- let array = batch.column(i);- let filtered_array = filter(array.as_ref(), f)?;- filtered_arrays.push(filtered_array);- }- Ok(Some(RecordBatch::try_new(- batch.schema().clone(),- filtered_arrays,- )?))- } else {- Err(ExecutionError::InternalError(- "Filter predicate evaluated to non-boolean value".to_string(),- )- .into_arrow_external_error())- }+ Some(+ self.predicate+ .evaluate(&batch)+ .map_err(ExecutionError::into_arrow_external_error)+ .and_then(|array| {+ array+ .as_any()+ .downcast_ref::<BooleanArray>()+ .ok_or(+ ExecutionError::InternalError(+ "Filter predicate evaluated to non-boolean value"+ .to_string(),+ )+ .into_arrow_external_error(),+ )+ // apply predicate to each column+ .and_then(|predicate| {+ batch+ .columns()+ .iter()+ .map(|column| filter(column.as_ref(), predicate))+ .collect::<ArrowResult<Vec<_>>>()+ })+ })+ // build RecordBatch+ .and_then(|columns| {+ RecordBatch::try_new(batch.schema().clone(), columns)+ }),+ )}- None => Ok(None),+ other => other,}}}+impl RecordBatchReader for FilterExecIter {+ /// Get the schema+ fn schema(&self) -> SchemaRef {+ self.schema.clone()+ }+}+#[cfg(test)]mod tests {diff --git a/rust/datafusion/src/physical_plan/hash_aggregate.rs b/rust/datafusion/src/physical_plan/hash_aggregate.rsindex 8bb679b3f3..5420135812 100644--- a/rust/datafusion/src/physical_plan/hash_aggregate.rs+++ b/rust/datafusion/src/physical_plan/hash_aggregate.rs@@ -240,26 +240,124 @@ impl GroupedHashAggregateIterator {finished: false,}}++ fn aggregate_batch(+ &self,+ batch: &RecordBatch,+ accumulators: &mut FnvHashMap<+ Vec<GroupByScalar>,+ (AccumulatorSet, Box<Vec<u32>>),+ >,+ aggregate_expressions: &Vec<Vec<Arc<dyn PhysicalExpr>>>,+ ) -> Result<()> {+ // evaluate the grouping expressions+ let group_values = evaluate(&self.group_expr, batch)?;++ // evaluate the aggregation expressions.+ // We could evaluate them after the `take`, but since we need to evaluate all+ // of them anyways, it is more performant to do it while they are together.+ let aggr_input_values = evaluate_many(aggregate_expressions, &batch)?;++ // create vector large enough to hold the grouping key+ // this is an optimization to avoid allocating `key` on every row.+ // it will be overwritten on every iteration of the loop below+ let mut key = Vec::with_capacity(group_values.len());+ for _ in 0..group_values.len() {+ key.push(GroupByScalar::UInt32(0));+ }++ // 1.1 construct the key from the group values+ // 1.2 construct the mapping key if it does not exist+ // 1.3 add the row' index to `indices`+ for row in 0..batch.num_rows() {+ // 1.1+ create_key(&group_values, row, &mut key)+ .map_err(ExecutionError::into_arrow_external_error)?;++ match accumulators.get_mut(&key) {+ // 1.2+ None => {+ let accumulator_set = create_accumulators(&self.aggr_expr)+ .map_err(ExecutionError::into_arrow_external_error)?;++ accumulators.insert(+ key.clone(),+ (accumulator_set, Box::new(vec![row as u32])),+ );+ }+ // 1.3+ Some((_, v)) => v.push(row as u32),+ }+ }++ // 2.1 for each key+ // 2.2 for each aggregation+ // 2.3 `take` from each of its arrays the keys' values+ // 2.4 update / merge the accumulator with the values+ // 2.5 clear indices+ accumulators+ .iter_mut()+ // 2.1+ .map(|(_, (accumulator_set, indices))| {+ // 2.2+ accumulator_set+ .iter()+ .zip(&aggr_input_values)+ .into_iter()+ .map(|(accumulator, aggr_array)| {+ (+ accumulator,+ aggr_array+ .iter()+ .map(|array| {+ // 2.3+ compute::take(+ array,+ &UInt32Array::from(*indices.clone()),+ None, // None: no index check+ )+ .unwrap()+ })+ .collect::<Vec<ArrayRef>>(),+ )+ })+ // 2.4+ .map(|(accumulator, values)| match self.mode {+ AggregateMode::Partial => {+ accumulator.borrow_mut().update_batch(&values)+ }+ AggregateMode::Final => {+ // note: the aggregation here is over states, not values, thus the merge+ accumulator.borrow_mut().merge_batch(&values)+ }+ })+ .collect::<Result<()>>()+ // 2.5+ .and(Ok(indices.clear()))+ })+ .collect::<Result<()>>()+ }}type AccumulatorSet = Vec<Rc<RefCell<dyn Accumulator>>>;-impl RecordBatchReader for GroupedHashAggregateIterator {- fn schema(&self) -> SchemaRef {- self.schema.clone()- }+impl Iterator for GroupedHashAggregateIterator {+ type Item = ArrowResult<RecordBatch>;- fn next_batch(&mut self) -> ArrowResult<Option<RecordBatch>> {+ fn next(&mut self) -> Option<Self::Item> {if self.finished {- return Ok(None);+ return None;}// return single batchself.finished = true;// the expressions to evaluate the batch, one vec of expressions per aggregation- let aggregate_expressions = aggregate_expressions(&self.aggr_expr, &self.mode)- .map_err(ExecutionError::into_arrow_external_error)?;+ let aggregate_expressions =+ match aggregate_expressions(&self.aggr_expr, &self.mode) {+ Ok(e) => e,+ Err(e) => return Some(Err(ExecutionError::into_arrow_external_error(e))),+ };// mapping key -> (set of accumulators, indices of the key in the batch)// * the indexes are updated at each row@@ -271,110 +369,36 @@ impl RecordBatchReader for GroupedHashAggregateIterator {> = FnvHashMap::default();// iterate over all input batches and update the accumulators- let mut input = self.input.lock().unwrap();-- // iterate over input and perform aggregation- while let Some(batch) = &input.next_batch()? {- // evaluate the grouping expressions- let group_values = evaluate(&self.group_expr, batch)- .map_err(ExecutionError::into_arrow_external_error)?;-- // evaluate the aggregation expressions.- // We could evaluate them after the `take`, but since we need to evaluate all- // of them anyways, it is more performant to do it while they are together.- let aggr_input_values = evaluate_many(&aggregate_expressions, &batch)- .map_err(ExecutionError::into_arrow_external_error)?;-- // create vector large enough to hold the grouping key- // this is an optimization to avoid allocating `key` on every row.- // it will be overwritten on every iteration of the loop below- let mut key = Vec::with_capacity(group_values.len());- for _ in 0..group_values.len() {- key.push(GroupByScalar::UInt32(0));- }-- // 1.1 construct the key from the group values- // 1.2 construct the mapping key if it does not exist- // 1.3 add the row' index to `indices`- for row in 0..batch.num_rows() {- // 1.1- create_key(&group_values, row, &mut key)- .map_err(ExecutionError::into_arrow_external_error)?;-- match accumulators.get_mut(&key) {- // 1.2- None => {- let accumulator_set = create_accumulators(&self.aggr_expr)- .map_err(ExecutionError::into_arrow_external_error)?;-- accumulators.insert(- key.clone(),- (accumulator_set, Box::new(vec![row as u32])),- );- }- // 1.3- Some((_, v)) => v.push(row as u32),- }- }-- // 2.1 for each key- // 2.2 for each aggregation- // 2.3 `take` from each of its arrays the keys' values- // 2.4 update / merge the accumulator with the values- // 2.5 clear indices- accumulators- .iter_mut()- // 2.1- .map(|(_, (accumulator_set, indices))| {- // 2.2- accumulator_set- .iter()- .zip(&aggr_input_values)- .into_iter()- .map(|(accumulator, aggr_array)| {- (- accumulator,- aggr_array- .iter()- .map(|array| {- // 2.3- compute::take(- array,- &UInt32Array::from(*indices.clone()),- None, // None: no index check- )- .unwrap()- })- .collect::<Vec<ArrayRef>>(),- )- })- // 2.4- .map(|(accumulator, values)| match self.mode {- AggregateMode::Partial => {- accumulator.borrow_mut().update_batch(&values)- }- AggregateMode::Final => {- // note: the aggregation here is over states, not values, thus the merge- accumulator.borrow_mut().merge_batch(&values)- }- })- .collect::<Result<()>>()- // 2.5- .and(Ok(indices.clear()))- })- .collect::<Result<()>>()- .map_err(ExecutionError::into_arrow_external_error)?;+ match self+ .input+ .lock()+ .unwrap()+ .into_iter()+ .map(|batch| {+ self.aggregate_batch(&batch?, &mut accumulators, &aggregate_expressions)+ .map_err(ExecutionError::into_arrow_external_error)+ })+ .collect::<ArrowResult<()>>()+ {+ Err(e) => return Some(Err(e)),+ Ok(_) => {}}- let batch = create_batch_from_map(- &self.mode,- &accumulators,- self.group_expr.len(),- &self.schema,+ Some(+ create_batch_from_map(+ &self.mode,+ &accumulators,+ self.group_expr.len(),+ &self.schema,+ )+ .map_err(ExecutionError::into_arrow_external_error),)- .map_err(ExecutionError::into_arrow_external_error)?;+ }+}- Ok(Some(batch))+impl RecordBatchReader for GroupedHashAggregateIterator {+ fn schema(&self) -> SchemaRef {+ self.schema.clone()}}@@ -456,62 +480,87 @@ impl HashAggregateIterator {finished: false,}}-}-impl RecordBatchReader for HashAggregateIterator {- fn schema(&self) -> SchemaRef {- self.schema.clone()+ fn aggregate_batch(+ &self,+ batch: &RecordBatch,+ accumulators: &AccumulatorSet,+ expressions: &Vec<Vec<Arc<dyn PhysicalExpr>>>,+ ) -> Result<()> {+ // 1.1 iterate accumulators and respective expressions together+ // 1.2 evaluate expressions+ // 1.3 update / merge accumulators with the expressions' values++ // 1.1+ accumulators+ .iter()+ .zip(expressions)+ .map(|(accum, expr)| {+ // 1.2+ let values = &expr+ .iter()+ .map(|e| e.evaluate(batch))+ .collect::<Result<Vec<_>>>()?;++ // 1.3+ match self.mode {+ AggregateMode::Partial => accum.borrow_mut().update_batch(values),+ AggregateMode::Final => accum.borrow_mut().merge_batch(values),+ }+ })+ .collect::<Result<()>>()}+}++impl Iterator for HashAggregateIterator {+ type Item = ArrowResult<RecordBatch>;- fn next_batch(&mut self) -> ArrowResult<Option<RecordBatch>> {+ fn next(&mut self) -> Option<Self::Item> {if self.finished {- return Ok(None);+ return None;}// return single batchself.finished = true;- let accumulators = create_accumulators(&self.aggr_expr)- .map_err(ExecutionError::into_arrow_external_error)?;-- let expressions = aggregate_expressions(&self.aggr_expr, &self.mode)- .map_err(ExecutionError::into_arrow_external_error)?;-- let mut input = self.input.lock().unwrap();-- // 1 for each batch:- // 1.1 iterate accumulators and respective expressions together- // 1.2 evaluate expressions- // 1.3 update / merge accumulators with the expressions' values- // 2 convert values to a record batch- while let Some(batch) = input.next_batch()? {- // 1.1- accumulators- .iter()- .zip(&expressions)- .map(|(accum, expr)| {- // 1.2- let values = &expr- .iter()- .map(|e| e.evaluate(&batch))- .collect::<Result<Vec<_>>>()?;-- // 1.3- match self.mode {- AggregateMode::Partial => accum.borrow_mut().update_batch(values),- AggregateMode::Final => accum.borrow_mut().merge_batch(values),- }- })- .collect::<Result<()>>()- .map_err(ExecutionError::into_arrow_external_error)?;+ let accumulators = match create_accumulators(&self.aggr_expr) {+ Ok(e) => e,+ Err(e) => return Some(Err(ExecutionError::into_arrow_external_error(e))),+ };++ let expressions = match aggregate_expressions(&self.aggr_expr, &self.mode) {+ Ok(e) => e,+ Err(e) => return Some(Err(ExecutionError::into_arrow_external_error(e))),+ };++ // 1 for each batch, update / merge accumulators with the expressions' values+ match self+ .input+ .lock()+ .unwrap()+ .into_iter()+ .map(|batch| {+ self.aggregate_batch(&batch?, &accumulators, &expressions)+ .map_err(ExecutionError::into_arrow_external_error)+ })+ .collect::<ArrowResult<()>>()+ {+ Err(e) => return Some(Err(e)),+ Ok(_) => {}}- // 2- let columns = finalize_aggregation(&accumulators, &self.mode)- .map_err(ExecutionError::into_arrow_external_error)?;+ // 2 convert values to a record batch+ Some(+ finalize_aggregation(&accumulators, &self.mode)+ .map_err(ExecutionError::into_arrow_external_error)+ .and_then(|columns| RecordBatch::try_new(self.schema.clone(), columns)),+ )+ }+}- let batch = RecordBatch::try_new(self.schema.clone(), columns)?;- Ok(Some(batch))+impl RecordBatchReader for HashAggregateIterator {+ fn schema(&self) -> SchemaRef {+ self.schema.clone()}}diff --git a/rust/datafusion/src/physical_plan/limit.rs b/rust/datafusion/src/physical_plan/limit.rsindex a42140e9ca..fee774f133 100644--- a/rust/datafusion/src/physical_plan/limit.rs+++ b/rust/datafusion/src/physical_plan/limit.rs@@ -202,8 +202,8 @@ fn collect_with_limit(let mut reader = reader.lock().unwrap();let mut results: Vec<RecordBatch> = vec![];loop {- match reader.next_batch() {- Ok(Some(batch)) => {+ match reader.next() {+ Some(Ok(batch)) => {let capacity = limit - count;if batch.num_rows() <= capacity {count += batch.num_rows();@@ -217,11 +217,10 @@ fn collect_with_limit(return Ok(results);}}- Ok(None) => {- // end of result set+ None => {return Ok(results);}- Err(e) => return Err(ExecutionError::from(e)),+ Some(Err(e)) => return Err(ExecutionError::from(e)),}}}diff --git a/rust/datafusion/src/physical_plan/memory.rs b/rust/datafusion/src/physical_plan/memory.rsindex fd86006885..b64976f4ea 100644--- a/rust/datafusion/src/physical_plan/memory.rs+++ b/rust/datafusion/src/physical_plan/memory.rs@@ -126,27 +126,30 @@ impl MemoryIterator {}}-impl RecordBatchReader for MemoryIterator {- /// Get the schema- fn schema(&self) -> SchemaRef {- self.schema.clone()- }+impl Iterator for MemoryIterator {+ type Item = ArrowResult<RecordBatch>;- /// Get the next RecordBatch- fn next_batch(&mut self) -> ArrowResult<Option<RecordBatch>> {+ fn next(&mut self) -> Option<Self::Item> {if self.index < self.data.len() {self.index += 1;let batch = &self.data[self.index - 1];// apply projectionmatch &self.projection {- Some(columns) => Ok(Some(RecordBatch::try_new(+ Some(columns) => Some(RecordBatch::try_new(self.schema.clone(),columns.iter().map(|i| batch.column(*i).clone()).collect(),- )?)),- None => Ok(Some(batch.clone())),+ )),+ None => Some(Ok(batch.clone())),}} else {- Ok(None)+ None}}}++impl RecordBatchReader for MemoryIterator {+ /// Get the schema+ fn schema(&self) -> SchemaRef {+ self.schema.clone()+ }+}diff --git a/rust/datafusion/src/physical_plan/parquet.rs b/rust/datafusion/src/physical_plan/parquet.rsindex ddffdf8d60..83525f9364 100644--- a/rust/datafusion/src/physical_plan/parquet.rs+++ b/rust/datafusion/src/physical_plan/parquet.rs@@ -131,8 +131,8 @@ impl ExecutionPlan for ParquetExec {// because the parquet implementation is not thread-safe, it is necessary to execute// on a thread and communicate with channelslet (response_tx, response_rx): (- Sender<ArrowResult<Option<RecordBatch>>>,- Receiver<ArrowResult<Option<RecordBatch>>>,+ Sender<Option<ArrowResult<RecordBatch>>>,+ Receiver<Option<ArrowResult<RecordBatch>>>,) = bounded(2);let filename = self.filenames[partition].clone();@@ -155,8 +155,8 @@ impl ExecutionPlan for ParquetExec {}fn send_result(- response_tx: &Sender<ArrowResult<Option<RecordBatch>>>,- result: ArrowResult<Option<RecordBatch>>,+ response_tx: &Sender<Option<ArrowResult<RecordBatch>>>,+ result: Option<ArrowResult<RecordBatch>>,) -> Result<()> {response_tx.send(result)@@ -168,7 +168,7 @@ fn read_file(filename: &str,projection: Vec<usize>,batch_size: usize,- response_tx: Sender<ArrowResult<Option<RecordBatch>>>,+ response_tx: Sender<Option<ArrowResult<RecordBatch>>>,) -> Result<()> {let file = File::open(&filename)?;let file_reader = Rc::new(SerializedFileReader::new(file)?);@@ -176,20 +176,20 @@ fn read_file(let mut batch_reader =arrow_reader.get_record_reader_by_columns(projection.clone(), batch_size)?;loop {- match batch_reader.next_batch() {- Ok(Some(batch)) => send_result(&response_tx, Ok(Some(batch)))?,- Ok(None) => {+ match batch_reader.next() {+ Some(Ok(batch)) => send_result(&response_tx, Some(Ok(batch)))?,+ None => {// finished reading file- send_result(&response_tx, Ok(None))?;+ send_result(&response_tx, None)?;break;}- Err(e) => {+ Some(Err(e)) => {let err_msg =format!("Error reading batch from {}: {}", filename, e.to_string());// send error to operatorsend_result(&response_tx,- Err(ArrowError::ParquetError(err_msg.clone())),+ Some(Err(ArrowError::ParquetError(err_msg.clone()))),)?;// terminate thread with errorreturn Err(ExecutionError::ExecutionError(err_msg));@@ -201,23 +201,27 @@ fn read_file(struct ParquetIterator {schema: SchemaRef,- response_rx: Receiver<ArrowResult<Option<RecordBatch>>>,+ response_rx: Receiver<Option<ArrowResult<RecordBatch>>>,}-impl RecordBatchReader for ParquetIterator {- fn schema(&self) -> SchemaRef {- self.schema.clone()- }+impl Iterator for ParquetIterator {+ type Item = ArrowResult<RecordBatch>;- fn next_batch(&mut self) -> ArrowResult<Option<RecordBatch>> {+ fn next(&mut self) -> Option<Self::Item> {match self.response_rx.recv() {Ok(batch) => batch,// RecvError means receiver has exited and closed the channel- Err(RecvError) => Ok(None),+ Err(RecvError) => None,}}}+impl RecordBatchReader for ParquetIterator {+ fn schema(&self) -> SchemaRef {+ self.schema.clone()+ }+}+#[cfg(test)]mod tests {use super::*;@@ -233,7 +237,7 @@ mod tests {let results = parquet_exec.execute(0).await?;let mut results = results.lock().unwrap();- let batch = results.next_batch()?.unwrap();+ let batch = results.next().unwrap()?;assert_eq!(8, batch.num_rows());assert_eq!(3, batch.num_columns());@@ -243,13 +247,13 @@ mod tests {schema.fields().iter().map(|f| f.name().as_str()).collect();assert_eq!(vec!["id", "bool_col", "tinyint_col"], field_names);- let batch = results.next_batch()?;+ let batch = results.next();assert!(batch.is_none());- let batch = results.next_batch()?;+ let batch = results.next();assert!(batch.is_none());- let batch = results.next_batch()?;+ let batch = results.next();assert!(batch.is_none());Ok(())diff --git a/rust/datafusion/src/physical_plan/projection.rs b/rust/datafusion/src/physical_plan/projection.rsindex 43f60510b6..9c74dbd91a 100644--- a/rust/datafusion/src/physical_plan/projection.rs+++ b/rust/datafusion/src/physical_plan/projection.rs@@ -126,27 +126,32 @@ struct ProjectionIterator {input: Arc<Mutex<dyn RecordBatchReader + Send + Sync>>,}+impl Iterator for ProjectionIterator {+ type Item = ArrowResult<RecordBatch>;++ fn next(&mut self) -> Option<Self::Item> {+ let mut input = self.input.lock().unwrap();+ match input.next() {+ Some(Ok(batch)) => Some(+ self.expr+ .iter()+ .map(|expr| expr.evaluate(&batch))+ .collect::<Result<Vec<_>>>()+ .map_or_else(+ |e| Err(ExecutionError::into_arrow_external_error(e)),+ |arrays| RecordBatch::try_new(self.schema.clone(), arrays),+ ),+ ),+ other => other,+ }+ }+}+impl RecordBatchReader for ProjectionIterator {/// Get the schemafn schema(&self) -> SchemaRef {self.schema.clone()}-- /// Get the next batch- fn next_batch(&mut self) -> ArrowResult<Option<RecordBatch>> {- let mut input = self.input.lock().unwrap();- match input.next_batch()? {- Some(batch) => {- let arrays: Result<Vec<_>> =- self.expr.iter().map(|expr| expr.evaluate(&batch)).collect();- Ok(Some(RecordBatch::try_new(- self.schema.clone(),- arrays.map_err(ExecutionError::into_arrow_external_error)?,- )?))- }- None => Ok(None),- }- }}#[cfg(test)]@@ -177,10 +182,15 @@ mod tests {partition_count += 1;let iterator = projection.execute(partition).await?;let mut iterator = iterator.lock().unwrap();- while let Some(batch) = iterator.next_batch()? {- assert_eq!(1, batch.num_columns());- row_count += batch.num_rows();- }++ row_count += iterator+ .into_iter()+ .map(|batch| {+ let batch = batch.unwrap();+ assert_eq!(1, batch.num_columns());+ batch.num_rows()+ })+ .sum::<usize>();}assert_eq!(partitions, partition_count);assert_eq!(100, row_count);diff --git a/rust/datafusion/tests/user_defined_plan.rs b/rust/datafusion/tests/user_defined_plan.rsindex aa55238c16..03bc173b2b 100644--- a/rust/datafusion/tests/user_defined_plan.rs+++ b/rust/datafusion/tests/user_defined_plan.rs@@ -59,7 +59,6 @@//!use arrow::{- array::StringBuilder,array::{Int64Array, PrimitiveArrayOps, StringArray},datatypes::SchemaRef,error::ArrowError,@@ -450,73 +449,69 @@ impl TopKReader {self.top_values.remove(&smallest_revenue);}}-}-impl RecordBatchReader for TopKReader {- fn schema(&self) -> SchemaRef {- self.input.lock().expect("locked input reader").schema()+ // how we process a whole batch+ fn accumulate_batch(&mut self, input_batch: &RecordBatch) -> Result<()> {+ let num_rows = input_batch.num_rows();+ // Assuming the input columns are+ // column[0]: customer_id / UTF8+ // column[1]: revenue: Int64+ let customer_id = input_batch+ .column(0)+ .as_any()+ .downcast_ref::<StringArray>()+ .expect("Column 0 is not customer_id");++ let revenue = input_batch+ .column(1)+ .as_any()+ .downcast_ref::<Int64Array>()+ .expect("Column 1 is not revenue");++ for row in 0..num_rows {+ self.add_row(customer_id.value(row), revenue.value(row));+ }+ Ok(())}+}++impl Iterator for TopKReader {+ type Item = std::result::Result<RecordBatch, ArrowError>;/// Reads the next `RecordBatch`.- fn next_batch(&mut self) -> std::result::Result<Option<RecordBatch>, ArrowError> {+ fn next(&mut self) -> Option<Self::Item> {if self.done {- return Ok(None);+ return None;}- // use a loop so that we release the mutex once we have read each input_batch- loop {- let input_batch = self- .input- .lock()- .expect("locked input mutex")- .next_batch()?;-- match input_batch {- Some(input_batch) => {- println!("Got an input batch");- let num_rows = input_batch.num_rows();-- // Assuming the input columns are- // column[0]: customer_id / UTF8- // column[1]: revenue: Int64- let customer_id = input_batch- .column(0)- .as_any()- .downcast_ref::<StringArray>()- .expect("Column 0 is not customer_id");-- let revenue = input_batch- .column(1)- .as_any()- .downcast_ref::<Int64Array>()- .expect("Column 1 is not revenue");-- for row in 0..num_rows {- self.add_row(customer_id.value(row), revenue.value(row));- }- }- None => break,- }- }-- let mut revenue_builder = Int64Array::builder(self.top_values.len());- let mut customer_id_builder = StringBuilder::new(self.top_values.len());+ self.input+ .clone()+ .lock()+ .unwrap()+ .into_iter()+ .map(|batch| self.accumulate_batch(&batch?))+ .collect::<Result<()>>()+ .unwrap();// make output by walking over the map backwards (so values are descending)- for (revenue, customer_id) in self.top_values.iter().rev() {- revenue_builder.append_value(*revenue)?;- customer_id_builder.append_value(customer_id)?;- }+ let (revenue, customer): (Vec<i64>, Vec<&String>) =+ self.top_values.iter().rev().unzip();++ let customer: Vec<&str> = customer.iter().map(|&s| &**s).collect();- let record_batch = RecordBatch::try_new(+ self.done = true;+ Some(RecordBatch::try_new(self.schema().clone(),vec![- Arc::new(customer_id_builder.finish()),- Arc::new(revenue_builder.finish()),+ Arc::new(StringArray::from(customer)),+ Arc::new(Int64Array::from(revenue)),],- )?;+ ))+ }+}- self.done = true;- Ok(Some(record_batch))+impl RecordBatchReader for TopKReader {+ fn schema(&self) -> SchemaRef {+ self.input.lock().expect("locked input reader").schema()}}