Apache DataFusion SQL Query Engine
ARROW-8559: [Rust] Consolidate Record Batch reader traits in main arrow crate
Paddy Horane000af2c50e5
diff --git a/rust/datafusion/src/datasource/csv.rs b/rust/datafusion/src/datasource/csv.rsindex 0835579d31..a419286e30 100644--- a/rust/datafusion/src/datasource/csv.rs+++ b/rust/datafusion/src/datasource/csv.rs@@ -36,8 +36,9 @@use std::fs::File;use arrow::csv;-use arrow::datatypes::{Field, Schema};-use arrow::record_batch::RecordBatch;+use arrow::datatypes::{Field, Schema, SchemaRef};+use arrow::error::Result as ArrowResult;+use arrow::record_batch::{RecordBatch, RecordBatchReader};use std::string::String;use std::sync::Arc;@@ -45,12 +46,12 @@ use crate::datasource::{ScanResult, TableProvider};use crate::error::Result;use crate::execution::physical_plan::csv::CsvExec;pub use crate::execution::physical_plan::csv::CsvReadOptions;-use crate::execution::physical_plan::{BatchIterator, ExecutionPlan};+use crate::execution::physical_plan::ExecutionPlan;/// Represents a CSV file with a provided schemapub struct CsvFile {filename: String,- schema: Arc<Schema>,+ schema: SchemaRef,has_header: bool,delimiter: u8,}@@ -73,7 +74,7 @@ impl CsvFile {}impl TableProvider for CsvFile {- fn schema(&self) -> Arc<Schema> {+ fn schema(&self) -> SchemaRef {self.schema.clone()}@@ -103,7 +104,7 @@ impl TableProvider for CsvFile {/// Iterator over CSV batches// TODO: usage example (rather than documenting `new()`)pub struct CsvBatchIterator {- schema: Arc<Schema>,+ schema: SchemaRef,reader: csv::Reader<File>,}@@ -111,7 +112,7 @@ impl CsvBatchIterator {#[allow(missing_docs)]pub fn try_new(filename: &str,- schema: Arc<Schema>,+ schema: SchemaRef,has_header: bool,delimiter: Option<u8>,projection: &Option<Vec<usize>>,@@ -144,12 +145,12 @@ impl CsvBatchIterator {}}-impl BatchIterator for CsvBatchIterator {- fn schema(&self) -> Arc<Schema> {+impl RecordBatchReader for CsvBatchIterator {+ fn schema(&self) -> SchemaRef {self.schema.clone()}- fn next(&mut self) -> Result<Option<RecordBatch>> {- Ok(self.reader.next()?)+ fn next_batch(&mut self) -> ArrowResult<Option<RecordBatch>> {+ self.reader.next()}}diff --git a/rust/datafusion/src/datasource/datasource.rs b/rust/datafusion/src/datasource/datasource.rsindex 48f5219667..9d83023a1f 100644--- a/rust/datafusion/src/datasource/datasource.rs+++ b/rust/datafusion/src/datasource/datasource.rs@@ -19,19 +19,19 @@use std::sync::{Arc, Mutex};-use arrow::datatypes::Schema;+use arrow::datatypes::SchemaRef;+use arrow::record_batch::RecordBatchReader;use crate::error::Result;-use crate::execution::physical_plan::BatchIterator;-/// Returned by implementors of `Table#scan`, this `BatchIterator` is wrapped with+/// Returned by implementors of `Table#scan`, this `SendableRecordBatchReader` is wrapped with/// an `Arc` and `Mutex` so that it can be shared across threads as it is used.-pub type ScanResult = Arc<Mutex<dyn BatchIterator>>;+pub type ScanResult = Arc<Mutex<dyn RecordBatchReader + Send + Sync>>;/// Source tablepub trait TableProvider {/// Get a reference to the schema for this table- fn schema(&self) -> Arc<Schema>;+ fn schema(&self) -> SchemaRef;/// Perform a scan of a table and return a sequence of iterators over the data (one/// iterator per partition)diff --git a/rust/datafusion/src/datasource/memory.rs b/rust/datafusion/src/datasource/memory.rsindex 53ca7e961f..5f2a5b7501 100644--- a/rust/datafusion/src/datasource/memory.rs+++ b/rust/datafusion/src/datasource/memory.rs@@ -21,7 +21,7 @@use std::sync::Arc;-use arrow::datatypes::{Field, Schema};+use arrow::datatypes::{Field, Schema, SchemaRef};use arrow::record_batch::RecordBatch;use crate::datasource::{ScanResult, TableProvider};@@ -31,13 +31,13 @@ use crate::execution::physical_plan::ExecutionPlan;/// In-memory tablepub struct MemTable {- schema: Arc<Schema>,+ schema: SchemaRef,batches: Vec<Vec<RecordBatch>>,}impl MemTable {/// Create a new in-memory table from the provided schema and record batches- pub fn new(schema: Arc<Schema>, partitions: Vec<Vec<RecordBatch>>) -> Result<Self> {+ pub fn new(schema: SchemaRef, partitions: Vec<Vec<RecordBatch>>) -> Result<Self> {if partitions.iter().all(|partition| {partition.iter()@@ -62,7 +62,7 @@ impl MemTable {let mut data: Vec<Vec<RecordBatch>> = Vec::with_capacity(partitions.len());for it in &partitions {let mut partition = vec![];- while let Ok(Some(batch)) = it.lock().unwrap().next() {+ while let Ok(Some(batch)) = it.lock().unwrap().next_batch() {partition.push(batch);}data.push(partition);@@ -73,7 +73,7 @@ impl MemTable {}impl TableProvider for MemTable {- fn schema(&self) -> Arc<Schema> {+ fn schema(&self) -> SchemaRef {self.schema.clone()}@@ -151,7 +151,7 @@ mod tests {// scan with projectionlet partitions = provider.scan(&Some(vec![2, 1]), 1024).unwrap();- let batch2 = partitions[0].lock().unwrap().next().unwrap().unwrap();+ let batch2 = partitions[0].lock().unwrap().next_batch().unwrap().unwrap();assert_eq!(2, batch2.schema().fields().len());assert_eq!("c", batch2.schema().field(0).name());assert_eq!("b", batch2.schema().field(1).name());@@ -179,7 +179,7 @@ mod tests {let provider = MemTable::new(schema, vec![vec![batch]]).unwrap();let partitions = provider.scan(&None, 1024).unwrap();- let batch1 = partitions[0].lock().unwrap().next().unwrap().unwrap();+ let batch1 = partitions[0].lock().unwrap().next_batch().unwrap().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 8fa585ee11..ff32327052 100644--- a/rust/datafusion/src/datasource/parquet.rs+++ b/rust/datafusion/src/datasource/parquet.rs@@ -18,7 +18,6 @@//! Parquet data sourceuse std::string::String;-use std::sync::Arc;use arrow::datatypes::*;@@ -27,14 +26,14 @@ use crate::error::Result;use crate::execution::physical_plan::parquet::ParquetExec;use crate::execution::physical_plan::ExecutionPlan;-/// Table-based representation of a `ParquetFile`+/// Table-based representation of a `ParquetFile`.pub struct ParquetTable {path: String,- schema: Arc<Schema>,+ schema: SchemaRef,}impl ParquetTable {- /// Attempt to initialize a new `ParquetTable` from a file path+ /// Attempt to initialize a new `ParquetTable` from a file path.pub fn try_new(path: &str) -> Result<Self> {let parquet_exec = ParquetExec::try_new(path, None, 0)?;let schema = parquet_exec.schema();@@ -46,13 +45,13 @@ impl ParquetTable {}impl TableProvider for ParquetTable {- /// Get the schema for this parquet file- fn schema(&self) -> Arc<Schema> {+ /// Get the schema for this parquet file.+ fn schema(&self) -> SchemaRef {self.schema.clone()}/// Scan the file(s), using the provided projection, and return one BatchIterator per- /// partition+ /// partition.fn scan(&self,projection: &Option<Vec<usize>>,@@ -89,7 +88,7 @@ mod tests {let mut it = scan[0].lock().unwrap();let mut count = 0;- while let Some(batch) = it.next().unwrap() {+ while let Some(batch) = it.next_batch().unwrap() {assert_eq!(11, batch.num_columns());assert_eq!(2, batch.num_rows());count += 1;@@ -128,7 +127,7 @@ mod tests {let projection = None;let scan = table.scan(&projection, 1024).unwrap();let mut it = scan[0].lock().unwrap();- let batch = it.next().unwrap().unwrap();+ let batch = it.next_batch().unwrap().unwrap();assert_eq!(11, batch.num_columns());assert_eq!(8, batch.num_rows());@@ -141,7 +140,7 @@ mod tests {let projection = Some(vec![1]);let scan = table.scan(&projection, 1024).unwrap();let mut it = scan[0].lock().unwrap();- let batch = it.next().unwrap().unwrap();+ let batch = it.next_batch().unwrap().unwrap();assert_eq!(1, batch.num_columns());assert_eq!(8, batch.num_rows());@@ -169,7 +168,7 @@ mod tests {let projection = Some(vec![0]);let scan = table.scan(&projection, 1024).unwrap();let mut it = scan[0].lock().unwrap();- let batch = it.next().unwrap().unwrap();+ let batch = it.next_batch().unwrap().unwrap();assert_eq!(1, batch.num_columns());assert_eq!(8, batch.num_rows());@@ -194,7 +193,7 @@ mod tests {let projection = Some(vec![10]);let scan = table.scan(&projection, 1024).unwrap();let mut it = scan[0].lock().unwrap();- let batch = it.next().unwrap().unwrap();+ let batch = it.next_batch().unwrap().unwrap();assert_eq!(1, batch.num_columns());assert_eq!(8, batch.num_rows());@@ -219,8 +218,7 @@ mod tests {let projection = Some(vec![6]);let scan = table.scan(&projection, 1024).unwrap();let mut it = scan[0].lock().unwrap();- let batch = it.next().unwrap().unwrap();-+ let batch = it.next_batch().unwrap().unwrap();assert_eq!(1, batch.num_columns());assert_eq!(8, batch.num_rows());@@ -247,7 +245,7 @@ mod tests {let projection = Some(vec![7]);let scan = table.scan(&projection, 1024).unwrap();let mut it = scan[0].lock().unwrap();- let batch = it.next().unwrap().unwrap();+ let batch = it.next_batch().unwrap().unwrap();assert_eq!(1, batch.num_columns());assert_eq!(8, batch.num_rows());@@ -275,7 +273,7 @@ mod tests {let projection = Some(vec![9]);let scan = table.scan(&projection, 1024).unwrap();let mut it = scan[0].lock().unwrap();- let batch = it.next().unwrap().unwrap();+ let batch = it.next_batch().unwrap().unwrap();assert_eq!(1, batch.num_columns());assert_eq!(8, batch.num_rows());diff --git a/rust/datafusion/src/error.rs b/rust/datafusion/src/error.rsindex 80c0ad4aee..4ecb30c92c 100644--- a/rust/datafusion/src/error.rs+++ b/rust/datafusion/src/error.rs@@ -54,6 +54,13 @@ pub enum ExecutionError {ExecutionError(String),}+impl ExecutionError {+ /// Wraps this `ExecutionError` in arrow's `ExternalError` variant.+ pub fn into_arrow_external_error(self) -> ArrowError {+ ArrowError::from_external_error(Box::new(self))+ }+}+impl From<Error> for ExecutionError {fn from(e: Error) -> Self {ExecutionError::IoError(e)diff --git a/rust/datafusion/src/execution/context.rs b/rust/datafusion/src/execution/context.rsindex d142b0dd18..1cb3c5f577 100644--- a/rust/datafusion/src/execution/context.rs+++ b/rust/datafusion/src/execution/context.rs@@ -616,15 +616,15 @@ impl ExecutionContext {let path = Path::new(&path).join(&filename);let file = fs::File::create(path)?;let mut writer = csv::Writer::new(file);- let it = p.execute()?;- let mut it = it.lock().unwrap();+ let reader = p.execute()?;+ let mut reader = reader.lock().unwrap();loop {- match it.next() {+ match reader.next_batch() {Ok(Some(batch)) => {writer.write(&batch)?;}Ok(None) => break,- Err(e) => return Err(e),+ Err(e) => return Err(ExecutionError::from(e)),}}Ok(())@@ -648,7 +648,7 @@ struct ExecutionContextSchemaProvider<'a> {}impl SchemaProvider for ExecutionContextSchemaProvider<'_> {- fn get_table_meta(&self, name: &str) -> Option<Arc<Schema>> {+ fn get_table_meta(&self, name: &str) -> Option<SchemaRef> {self.datasources.get(name).map(|ds| ds.schema().clone())}diff --git a/rust/datafusion/src/execution/physical_plan/common.rs b/rust/datafusion/src/execution/physical_plan/common.rsindex 6cfa0a7123..f418012b03 100644--- a/rust/datafusion/src/execution/physical_plan/common.rs+++ b/rust/datafusion/src/execution/physical_plan/common.rs@@ -22,23 +22,23 @@ use std::fs::metadata;use std::sync::{Arc, Mutex};use crate::error::{ExecutionError, Result};-use crate::execution::physical_plan::BatchIterator;use crate::logicalplan::ScalarValue;use arrow::array::{self, ArrayRef};-use arrow::datatypes::{DataType, Schema};-use arrow::record_batch::RecordBatch;+use arrow::datatypes::{DataType, SchemaRef};+use arrow::error::Result as ArrowResult;+use arrow::record_batch::{RecordBatch, RecordBatchReader};/// Iterator over a vector of record batchespub struct RecordBatchIterator {- schema: Arc<Schema>,+ schema: SchemaRef,batches: Vec<Arc<RecordBatch>>,index: usize,}impl RecordBatchIterator {/// Create a new RecordBatchIterator- pub fn new(schema: Arc<Schema>, batches: Vec<Arc<RecordBatch>>) -> Self {+ pub fn new(schema: SchemaRef, batches: Vec<Arc<RecordBatch>>) -> Self {RecordBatchIterator {schema,index: 0,@@ -47,12 +47,12 @@ impl RecordBatchIterator {}}-impl BatchIterator for RecordBatchIterator {- fn schema(&self) -> Arc<Schema> {+impl RecordBatchReader for RecordBatchIterator {+ fn schema(&self) -> SchemaRef {self.schema.clone()}- fn next(&mut self) -> Result<Option<RecordBatch>> {+ fn next_batch(&mut self) -> ArrowResult<Option<RecordBatch>> {if self.index < self.batches.len() {self.index += 1;Ok(Some(self.batches[self.index - 1].as_ref().clone()))@@ -63,11 +63,13 @@ impl BatchIterator for RecordBatchIterator {}/// Create a vector of record batches from an iterator-pub fn collect(it: Arc<Mutex<dyn BatchIterator>>) -> Result<Vec<RecordBatch>> {- let mut it = it.lock().unwrap();+pub 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 it.next() {+ match reader.next_batch() {Ok(Some(batch)) => {results.push(batch);}@@ -75,7 +77,7 @@ pub fn collect(it: Arc<Mutex<dyn BatchIterator>>) -> Result<Vec<RecordBatch>> {// end of result setreturn Ok(results);}- Err(e) => return Err(e),+ Err(e) => return Err(ExecutionError::from(e)),}}}diff --git a/rust/datafusion/src/execution/physical_plan/csv.rs b/rust/datafusion/src/execution/physical_plan/csv.rsindex 6b0fd3e9c2..0ed49c5781 100644--- a/rust/datafusion/src/execution/physical_plan/csv.rs+++ b/rust/datafusion/src/execution/physical_plan/csv.rs@@ -22,10 +22,11 @@ use std::sync::{Arc, Mutex};use crate::error::{ExecutionError, Result};use crate::execution::physical_plan::common;-use crate::execution::physical_plan::{BatchIterator, ExecutionPlan, Partition};+use crate::execution::physical_plan::{ExecutionPlan, Partition};use arrow::csv;-use arrow::datatypes::Schema;-use arrow::record_batch::RecordBatch;+use arrow::datatypes::{Schema, SchemaRef};+use arrow::error::Result as ArrowResult;+use arrow::record_batch::{RecordBatch, RecordBatchReader};/// CSV file read option#[derive(Copy, Clone)]@@ -96,7 +97,7 @@ pub struct CsvExec {/// Path to directory containing partitioned CSV files with the same schemapath: String,/// Schema representing the CSV file- schema: Arc<Schema>,+ schema: SchemaRef,/// Does the CSV file have a header?has_header: bool,/// An optional column delimiter. Defaults to `b','`@@ -104,7 +105,7 @@ pub struct CsvExec {/// Optional projection for which columns to loadprojection: Option<Vec<usize>>,/// Schema after the projection has been applied- projected_schema: Arc<Schema>,+ projected_schema: SchemaRef,/// Batch sizebatch_size: usize,}@@ -157,7 +158,7 @@ impl CsvExec {impl ExecutionPlan for CsvExec {/// Get the schema for this execution plan- fn schema(&self) -> Arc<Schema> {+ fn schema(&self) -> SchemaRef {self.projected_schema.clone()}@@ -187,7 +188,7 @@ struct CsvPartition {/// Path to the CSV Filepath: String,/// Schema representing the CSV file- schema: Arc<Schema>,+ schema: SchemaRef,/// Does the CSV file have a header?has_header: bool,/// An optional column delimiter. Defaults to `b','`@@ -201,7 +202,7 @@ struct CsvPartition {impl CsvPartition {fn new(path: &str,- schema: Arc<Schema>,+ schema: SchemaRef,has_header: bool,delimiter: Option<u8>,projection: Option<Vec<usize>>,@@ -220,7 +221,7 @@ impl CsvPartition {impl Partition for CsvPartition {/// Execute this partition and return an iterator over RecordBatch- fn execute(&self) -> Result<Arc<Mutex<dyn BatchIterator>>> {+ fn execute(&self) -> Result<Arc<Mutex<dyn RecordBatchReader + Send + Sync>>> {Ok(Arc::new(Mutex::new(CsvIterator::try_new(&self.path,self.schema.clone(),@@ -242,7 +243,7 @@ impl CsvIterator {/// Create an iterator for a CSV filepub fn try_new(filename: &str,- schema: Arc<Schema>,+ schema: SchemaRef,has_header: bool,delimiter: Option<u8>,projection: &Option<Vec<usize>>,@@ -262,14 +263,14 @@ impl CsvIterator {}}-impl BatchIterator for CsvIterator {+impl RecordBatchReader for CsvIterator {/// Get the schema- fn schema(&self) -> Arc<Schema> {+ fn schema(&self) -> SchemaRef {self.reader.schema()}/// Get the next RecordBatch- fn next(&mut self) -> Result<Option<RecordBatch>> {+ fn next_batch(&mut self) -> ArrowResult<Option<RecordBatch>> {Ok(self.reader.next()?)}}@@ -297,7 +298,7 @@ mod tests {let partitions = csv.partitions()?;let results = partitions[0].execute()?;let mut it = results.lock().unwrap();- let batch = it.next()?.unwrap();+ let batch = it.next_batch()?.unwrap();assert_eq!(3, batch.num_columns());let batch_schema = batch.schema();assert_eq!(3, batch_schema.fields().len());@@ -321,7 +322,7 @@ mod tests {let partitions = csv.partitions()?;let results = partitions[0].execute()?;let mut it = results.lock().unwrap();- let batch = it.next()?.unwrap();+ let batch = it.next_batch()?.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/execution/physical_plan/datasource.rs b/rust/datafusion/src/execution/physical_plan/datasource.rsindex a34e96ed64..4545dc024b 100644--- a/rust/datafusion/src/execution/physical_plan/datasource.rs+++ b/rust/datafusion/src/execution/physical_plan/datasource.rs@@ -20,27 +20,28 @@use std::sync::{Arc, Mutex};use crate::error::Result;-use crate::execution::physical_plan::{BatchIterator, ExecutionPlan, Partition};-use arrow::datatypes::Schema;+use crate::execution::physical_plan::{ExecutionPlan, Partition};+use arrow::datatypes::SchemaRef;+use arrow::record_batch::RecordBatchReader;/// Datasource execution planpub struct DatasourceExec {- schema: Arc<Schema>,- partitions: Vec<Arc<Mutex<dyn BatchIterator>>>,+ schema: SchemaRef,+ partitions: Vec<Arc<Mutex<dyn RecordBatchReader + Send + Sync>>>,}impl DatasourceExec {/// Create a new data source execution planpub fn new(- schema: Arc<Schema>,- partitions: Vec<Arc<Mutex<dyn BatchIterator>>>,+ schema: SchemaRef,+ partitions: Vec<Arc<Mutex<dyn RecordBatchReader + Send + Sync>>>,) -> Self {Self { schema, partitions }}}impl ExecutionPlan for DatasourceExec {- fn schema(&self) -> Arc<Schema> {+ fn schema(&self) -> SchemaRef {self.schema.clone()}@@ -55,19 +56,19 @@ impl ExecutionPlan for DatasourceExec {}}-/// Wrapper to convert a BatchIterator into a Partition+/// Wrapper to convert a `SendableRecordBatchReader` into a `Partition`.pub struct DatasourcePartition {- batch_iter: Arc<Mutex<dyn BatchIterator>>,+ batch_iter: Arc<Mutex<dyn RecordBatchReader + Send + Sync>>,}impl DatasourcePartition {- fn new(batch_iter: Arc<Mutex<dyn BatchIterator>>) -> Self {+ fn new(batch_iter: Arc<Mutex<dyn RecordBatchReader + Send + Sync>>) -> Self {Self { batch_iter }}}impl Partition for DatasourcePartition {- fn execute(&self) -> Result<Arc<Mutex<dyn BatchIterator>>> {+ fn execute(&self) -> Result<Arc<Mutex<dyn RecordBatchReader + Send + Sync>>> {Ok(self.batch_iter.clone())}}diff --git a/rust/datafusion/src/execution/physical_plan/expressions.rs b/rust/datafusion/src/execution/physical_plan/expressions.rsindex d26d050c52..e3e1ea847f 100644--- a/rust/datafusion/src/execution/physical_plan/expressions.rs+++ b/rust/datafusion/src/execution/physical_plan/expressions.rs@@ -2004,7 +2004,7 @@ mod tests {}fn apply_arithmetic<T: ArrowNumericType>(- schema: Arc<Schema>,+ schema: SchemaRef,data: Vec<ArrayRef>,op: Operator,expected: PrimitiveArray<T>,diff --git a/rust/datafusion/src/execution/physical_plan/hash_aggregate.rs b/rust/datafusion/src/execution/physical_plan/hash_aggregate.rsindex ef14b0e178..441681ad0b 100644--- a/rust/datafusion/src/execution/physical_plan/hash_aggregate.rs+++ b/rust/datafusion/src/execution/physical_plan/hash_aggregate.rs@@ -23,7 +23,7 @@ use std::sync::{Arc, Mutex};use crate::error::{ExecutionError, Result};use crate::execution::physical_plan::{- Accumulator, AggregateExpr, BatchIterator, ExecutionPlan, Partition, PhysicalExpr,+ Accumulator, AggregateExpr, ExecutionPlan, Partition, PhysicalExpr,};use arrow::array::{@@ -35,8 +35,9 @@ use arrow::array::{Int8Builder, StringBuilder, UInt16Builder, UInt32Builder, UInt64Builder,UInt8Builder,};-use arrow::datatypes::{DataType, Field, Schema};-use arrow::record_batch::RecordBatch;+use arrow::datatypes::{DataType, Field, Schema, SchemaRef};+use arrow::error::Result as ArrowResult;+use arrow::record_batch::{RecordBatch, RecordBatchReader};use crate::execution::physical_plan::expressions::Column;use crate::logicalplan::ScalarValue;@@ -47,7 +48,7 @@ pub struct HashAggregateExec {group_expr: Vec<Arc<dyn PhysicalExpr>>,aggr_expr: Vec<Arc<dyn AggregateExpr>>,input: Arc<dyn ExecutionPlan>,- schema: Arc<Schema>,+ schema: SchemaRef,}impl HashAggregateExec {@@ -102,7 +103,7 @@ impl HashAggregateExec {}impl ExecutionPlan for HashAggregateExec {- fn schema(&self) -> Arc<Schema> {+ fn schema(&self) -> SchemaRef {self.schema.clone()}@@ -130,7 +131,7 @@ struct HashAggregatePartition {group_expr: Vec<Arc<dyn PhysicalExpr>>,aggr_expr: Vec<Arc<dyn AggregateExpr>>,input: Arc<dyn Partition>,- schema: Arc<Schema>,+ schema: SchemaRef,}impl HashAggregatePartition {@@ -139,7 +140,7 @@ impl HashAggregatePartition {group_expr: Vec<Arc<dyn PhysicalExpr>>,aggr_expr: Vec<Arc<dyn AggregateExpr>>,input: Arc<dyn Partition>,- schema: Arc<Schema>,+ schema: SchemaRef,) -> Self {HashAggregatePartition {group_expr,@@ -151,7 +152,7 @@ impl HashAggregatePartition {}impl Partition for HashAggregatePartition {- fn execute(&self) -> Result<Arc<Mutex<dyn BatchIterator>>> {+ fn execute(&self) -> Result<Arc<Mutex<dyn RecordBatchReader + Send + Sync>>> {if self.group_expr.is_empty() {Ok(Arc::new(Mutex::new(HashAggregateIterator::new(self.schema.clone(),@@ -198,7 +199,12 @@ macro_rules! aggr_array_from_map_entries {let mut builder = $BUILDER::new($MAP.len());let mut err = false;for v in $MAP.values() {- match v[$COL_INDEX].as_ref().borrow().get_value()? {+ match v[$COL_INDEX]+ .as_ref()+ .borrow()+ .get_value()+ .map_err(ExecutionError::into_arrow_external_error)?+ {Some(ScalarValue::$TY(n)) => builder.append_value(n as $TY2).unwrap(),None => builder.append_null().unwrap(),_ => err = true,@@ -243,20 +249,20 @@ struct MapEntry {}struct GroupedHashAggregateIterator {- schema: Arc<Schema>,+ schema: SchemaRef,group_expr: Vec<Arc<dyn PhysicalExpr>>,aggr_expr: Vec<Arc<dyn AggregateExpr>>,- input: Arc<Mutex<dyn BatchIterator>>,+ input: Arc<Mutex<dyn RecordBatchReader + Send + Sync>>,finished: bool,}impl GroupedHashAggregateIterator {/// Create a new HashAggregateIteratorpub fn new(- schema: Arc<Schema>,+ schema: SchemaRef,group_expr: Vec<Arc<dyn PhysicalExpr>>,aggr_expr: Vec<Arc<dyn AggregateExpr>>,- input: Arc<Mutex<dyn BatchIterator>>,+ input: Arc<Mutex<dyn RecordBatchReader + Send + Sync>>,) -> Self {GroupedHashAggregateIterator {schema,@@ -278,18 +284,20 @@ macro_rules! update_accumulators {if $ARRAY.is_valid(row) {let value = Some($SCALAR_TY(primitive_array.value(row)));let mut accum = $ACCUM[row][$COL].borrow_mut();- accum.accumulate_scalar(value)?;+ accum+ .accumulate_scalar(value)+ .map_err(ExecutionError::into_arrow_external_error)?;}}}};}-impl BatchIterator for GroupedHashAggregateIterator {- fn schema(&self) -> Arc<Schema> {+impl RecordBatchReader for GroupedHashAggregateIterator {+ fn schema(&self) -> SchemaRef {self.schema.clone()}- fn next(&mut self) -> Result<Option<RecordBatch>> {+ fn next_batch(&mut self) -> ArrowResult<Option<RecordBatch>> {if self.finished {return Ok(None);}@@ -304,20 +312,26 @@ impl BatchIterator for GroupedHashAggregateIterator {let mut input = self.input.lock().unwrap();// iterate over input and perform aggregation- while let Some(batch) = input.next()? {+ while let Some(batch) = input.next_batch()? {// evaluate the grouping expressions for this batchlet group_values = self.group_expr.iter()- .map(|expr| expr.evaluate(&batch))- .collect::<Result<Vec<_>>>()?;+ .map(|expr| {+ expr.evaluate(&batch)+ .map_err(ExecutionError::into_arrow_external_error)+ })+ .collect::<ArrowResult<Vec<_>>>()?;// evaluate the inputs to the aggregate expressions for this batchlet aggr_input_values = self.aggr_expr.iter()- .map(|expr| expr.evaluate_input(&batch))- .collect::<Result<Vec<_>>>()?;+ .map(|expr| {+ expr.evaluate_input(&batch)+ .map_err(ExecutionError::into_arrow_external_error)+ })+ .collect::<ArrowResult<Vec<_>>>()?;// create vector large enough to hold the grouping keylet mut key = Vec::with_capacity(group_values.len());@@ -331,7 +345,8 @@ impl BatchIterator for GroupedHashAggregateIterator {for row in 0..batch.num_rows() {// create grouping key for this row- create_key(&group_values, row, &mut key)?;+ create_key(&group_values, row, &mut key)+ .map_err(ExecutionError::into_arrow_external_error)?;if let Some(accumulator_set) = map.get(&key) {accumulators.push(accumulator_set.clone());@@ -429,7 +444,7 @@ impl BatchIterator for GroupedHashAggregateIterator {return Err(ExecutionError::ExecutionError(format!("Unsupported data type {:?} for result of aggregate expression",other- )));+ )).into_arrow_external_error());}};}@@ -444,7 +459,8 @@ impl BatchIterator for GroupedHashAggregateIterator {// grouping valuesfor i in 0..self.group_expr.len() {let array: Result<ArrayRef> = match self.group_expr[i]- .data_type(&input_schema)?+ .data_type(&input_schema)+ .map_err(ExecutionError::into_arrow_external_error)?{DataType::UInt8 => {group_array_from_map_entries!(UInt8Builder, UInt8, map, i)@@ -478,7 +494,8 @@ impl BatchIterator for GroupedHashAggregateIterator {_ => {return Err(ExecutionError::ExecutionError("Unexpected value for Utf8 group column".to_string(),- ))+ )+ .into_arrow_external_error())}}}@@ -488,11 +505,13 @@ impl BatchIterator for GroupedHashAggregateIterator {"Unsupported group by expr".to_string(),)),};- result_arrays.push(array?);+ result_arrays.push(array.map_err(ExecutionError::into_arrow_external_error)?);// aggregate valuesfor i in 0..self.aggr_expr.len() {- let aggr_data_type = self.aggr_expr[i].data_type(&input_schema)?;+ let aggr_data_type = self.aggr_expr[i]+ .data_type(&input_schema)+ .map_err(ExecutionError::into_arrow_external_error)?;let array = match aggr_data_type {DataType::UInt8 => {aggr_array_from_map_entries!(UInt64Builder, UInt8, u64, map, i)@@ -528,7 +547,8 @@ impl BatchIterator for GroupedHashAggregateIterator {"Unsupported aggregate expr".to_string(),)),};- result_arrays.push(array?);+ result_arrays+ .push(array.map_err(ExecutionError::into_arrow_external_error)?);}}@@ -538,18 +558,18 @@ impl BatchIterator for GroupedHashAggregateIterator {}struct HashAggregateIterator {- schema: Arc<Schema>,+ schema: SchemaRef,aggr_expr: Vec<Arc<dyn AggregateExpr>>,- input: Arc<Mutex<dyn BatchIterator>>,+ input: Arc<Mutex<dyn RecordBatchReader + Send + Sync>>,finished: bool,}impl HashAggregateIterator {/// Create a new HashAggregateIteratorpub fn new(- schema: Arc<Schema>,+ schema: SchemaRef,aggr_expr: Vec<Arc<dyn AggregateExpr>>,- input: Arc<Mutex<dyn BatchIterator>>,+ input: Arc<Mutex<dyn RecordBatchReader + Send + Sync>>,) -> Self {HashAggregateIterator {schema,@@ -560,12 +580,12 @@ impl HashAggregateIterator {}}-impl BatchIterator for HashAggregateIterator {- fn schema(&self) -> Arc<Schema> {+impl RecordBatchReader for HashAggregateIterator {+ fn schema(&self) -> SchemaRef {self.schema.clone()}- fn next(&mut self) -> Result<Option<RecordBatch>> {+ fn next_batch(&mut self) -> ArrowResult<Option<RecordBatch>> {if self.finished {return Ok(None);}@@ -582,20 +602,28 @@ impl BatchIterator for HashAggregateIterator {let mut input = self.input.lock().unwrap();// iterate over input and perform aggregation- while let Some(batch) = input.next()? {+ while let Some(batch) = input.next_batch()? {// evaluate the inputs to the aggregate expressions for this batchlet aggr_input_values = self.aggr_expr.iter()- .map(|expr| expr.evaluate_input(&batch))- .collect::<Result<Vec<_>>>()?;+ .map(|expr| {+ expr.evaluate_input(&batch)+ .map_err(ExecutionError::into_arrow_external_error)+ })+ .collect::<ArrowResult<Vec<_>>>()?;// iterate over each row in the batchlet _ = accumulators.iter().zip(aggr_input_values.iter())- .map(|(accum, input)| accum.borrow_mut().accumulate_batch(input))- .collect::<Result<Vec<_>>>()?;+ .map(|(accum, input)| {+ accum+ .borrow_mut()+ .accumulate_batch(input)+ .map_err(ExecutionError::into_arrow_external_error)+ })+ .collect::<ArrowResult<Vec<_>>>()?;}let input_schema = input.schema();@@ -605,8 +633,13 @@ impl BatchIterator for HashAggregateIterator {// aggregate valuesfor i in 0..self.aggr_expr.len() {- let aggr_data_type = self.aggr_expr[i].data_type(&input_schema)?;- let value = accumulators[i].borrow_mut().get_value()?;+ let aggr_data_type = self.aggr_expr[i]+ .data_type(&input_schema)+ .map_err(ExecutionError::into_arrow_external_error)?;+ let value = accumulators[i]+ .borrow_mut()+ .get_value()+ .map_err(ExecutionError::into_arrow_external_error)?;let array = match aggr_data_type {DataType::UInt8 => {aggr_array_from_accumulator!(UInt64Builder, UInt8, u64, value)@@ -642,7 +675,7 @@ impl BatchIterator for HashAggregateIterator {"Unsupported aggregate expr".to_string(),)),};- result_arrays.push(array?);+ result_arrays.push(array.map_err(ExecutionError::into_arrow_external_error)?);}let batch = RecordBatch::try_new(self.schema.clone(), result_arrays)?;diff --git a/rust/datafusion/src/execution/physical_plan/limit.rs b/rust/datafusion/src/execution/physical_plan/limit.rsindex 93dba721ab..7b10ff259e 100644--- a/rust/datafusion/src/execution/physical_plan/limit.rs+++ b/rust/datafusion/src/execution/physical_plan/limit.rs@@ -20,11 +20,11 @@use crate::error::{ExecutionError, Result};use crate::execution::physical_plan::common::RecordBatchIterator;use crate::execution::physical_plan::ExecutionPlan;-use crate::execution::physical_plan::{BatchIterator, Partition};+use crate::execution::physical_plan::Partition;use arrow::array::ArrayRef;use arrow::compute::limit;-use arrow::datatypes::Schema;-use arrow::record_batch::RecordBatch;+use arrow::datatypes::SchemaRef;+use arrow::record_batch::{RecordBatch, RecordBatchReader};use std::sync::{Arc, Mutex};use std::thread;use std::thread::JoinHandle;@@ -32,7 +32,7 @@ use std::thread::JoinHandle;/// Limit execution planpub struct LimitExec {/// Input schema- schema: Arc<Schema>,+ schema: SchemaRef,/// Input partitionspartitions: Vec<Arc<dyn Partition>>,/// Maximum number of rows to return@@ -42,7 +42,7 @@ pub struct LimitExec {impl LimitExec {/// Create a new MergeExecpub fn new(- schema: Arc<Schema>,+ schema: SchemaRef,partitions: Vec<Arc<dyn Partition>>,limit: usize,) -> Self {@@ -55,7 +55,7 @@ impl LimitExec {}impl ExecutionPlan for LimitExec {- fn schema(&self) -> Arc<Schema> {+ fn schema(&self) -> SchemaRef {self.schema.clone()}@@ -70,7 +70,7 @@ impl ExecutionPlan for LimitExec {struct LimitPartition {/// Input schema- schema: Arc<Schema>,+ schema: SchemaRef,/// Input partitionspartitions: Vec<Arc<dyn Partition>>,/// Maximum number of rows to return@@ -78,7 +78,7 @@ struct LimitPartition {}impl Partition for LimitPartition {- fn execute(&self) -> Result<Arc<Mutex<dyn BatchIterator>>> {+ fn execute(&self) -> Result<Arc<Mutex<dyn RecordBatchReader + Send + Sync>>> {// collect up to "limit" rows on each partitionlet threads: Vec<JoinHandle<Result<Vec<RecordBatch>>>> = self.partitions@@ -136,14 +136,14 @@ pub fn truncate_batch(batch: &RecordBatch, n: usize) -> Result<RecordBatch> {/// Create a vector of record batches from an iteratorfn collect_with_limit(- it: Arc<Mutex<dyn BatchIterator>>,+ reader: Arc<Mutex<dyn RecordBatchReader + Send + Sync>>,limit: usize,) -> Result<Vec<RecordBatch>> {let mut count = 0;- let mut it = it.lock().unwrap();+ let mut reader = reader.lock().unwrap();let mut results: Vec<RecordBatch> = vec![];loop {- match it.next() {+ match reader.next_batch() {Ok(Some(batch)) => {let capacity = limit - count;if batch.num_rows() <= capacity {@@ -162,7 +162,7 @@ fn collect_with_limit(// end of result setreturn Ok(results);}- Err(e) => return Err(e),+ Err(e) => return Err(ExecutionError::from(e)),}}}diff --git a/rust/datafusion/src/execution/physical_plan/memory.rs b/rust/datafusion/src/execution/physical_plan/memory.rsindex b045e9f52f..b6ff75d0ac 100644--- a/rust/datafusion/src/execution/physical_plan/memory.rs+++ b/rust/datafusion/src/execution/physical_plan/memory.rs@@ -20,23 +20,24 @@use std::sync::{Arc, Mutex};use crate::error::Result;-use crate::execution::physical_plan::{BatchIterator, ExecutionPlan, Partition};-use arrow::datatypes::Schema;-use arrow::record_batch::RecordBatch;+use crate::execution::physical_plan::{ExecutionPlan, Partition};+use arrow::datatypes::SchemaRef;+use arrow::error::Result as ArrowResult;+use arrow::record_batch::{RecordBatch, RecordBatchReader};/// Execution plan for reading in-memory batches of datapub struct MemoryExec {/// The partitions to querypartitions: Vec<Vec<RecordBatch>>,/// Schema representing the data after the optional projection is applied- schema: Arc<Schema>,+ schema: SchemaRef,/// Optional projectionprojection: Option<Vec<usize>>,}impl ExecutionPlan for MemoryExec {/// Get the schema for this execution plan- fn schema(&self) -> Arc<Schema> {+ fn schema(&self) -> SchemaRef {self.schema.clone()}@@ -61,7 +62,7 @@ impl MemoryExec {/// Create a new execution plan for reading in-memory record batchespub fn try_new(partitions: &Vec<Vec<RecordBatch>>,- schema: Arc<Schema>,+ schema: SchemaRef,projection: Option<Vec<usize>>,) -> Result<Self> {Ok(Self {@@ -77,7 +78,7 @@ struct MemoryPartition {/// Vector of record batchesdata: Vec<RecordBatch>,/// Schema representing the data- schema: Arc<Schema>,+ schema: SchemaRef,/// Optional projectionprojection: Option<Vec<usize>>,}@@ -86,7 +87,7 @@ impl MemoryPartition {/// Create a new in-memory partitionfn new(data: Vec<RecordBatch>,- schema: Arc<Schema>,+ schema: SchemaRef,projection: Option<Vec<usize>>,) -> Self {Self {@@ -99,7 +100,7 @@ impl MemoryPartition {impl Partition for MemoryPartition {/// Execute this partition and return an iterator over RecordBatch- fn execute(&self) -> Result<Arc<Mutex<dyn BatchIterator>>> {+ fn execute(&self) -> Result<Arc<Mutex<dyn RecordBatchReader + Send + Sync>>> {Ok(Arc::new(Mutex::new(MemoryIterator::try_new(self.data.clone(),self.schema.clone(),@@ -113,7 +114,7 @@ struct MemoryIterator {/// Vector of record batchesdata: Vec<RecordBatch>,/// Schema representing the data- schema: Arc<Schema>,+ schema: SchemaRef,/// Optional projection for which columns to loadprojection: Option<Vec<usize>>,/// Index into the data@@ -124,7 +125,7 @@ impl MemoryIterator {/// Create an iterator for a vector of record batchespub fn try_new(data: Vec<RecordBatch>,- schema: Arc<Schema>,+ schema: SchemaRef,projection: Option<Vec<usize>>,) -> Result<Self> {Ok(Self {@@ -136,14 +137,14 @@ impl MemoryIterator {}}-impl BatchIterator for MemoryIterator {+impl RecordBatchReader for MemoryIterator {/// Get the schema- fn schema(&self) -> Arc<Schema> {+ fn schema(&self) -> SchemaRef {self.schema.clone()}/// Get the next RecordBatch- fn next(&mut self) -> Result<Option<RecordBatch>> {+ fn next_batch(&mut self) -> ArrowResult<Option<RecordBatch>> {if self.index < self.data.len() {self.index += 1;let batch = &self.data[self.index - 1];diff --git a/rust/datafusion/src/execution/physical_plan/merge.rs b/rust/datafusion/src/execution/physical_plan/merge.rsindex ea7921bb5f..b6b7cef099 100644--- a/rust/datafusion/src/execution/physical_plan/merge.rs+++ b/rust/datafusion/src/execution/physical_plan/merge.rs@@ -20,10 +20,10 @@use crate::error::Result;use crate::execution::physical_plan::common::RecordBatchIterator;+use crate::execution::physical_plan::Partition;use crate::execution::physical_plan::{common, ExecutionPlan};-use crate::execution::physical_plan::{BatchIterator, Partition};-use arrow::datatypes::Schema;-use arrow::record_batch::RecordBatch;+use arrow::datatypes::SchemaRef;+use arrow::record_batch::{RecordBatch, RecordBatchReader};use std::sync::{Arc, Mutex};use std::thread;use std::thread::JoinHandle;@@ -32,20 +32,20 @@ use std::thread::JoinHandle;/// partition. No guarantees are made about the order of the resulting partition.pub struct MergeExec {/// Input schema- schema: Arc<Schema>,+ schema: SchemaRef,/// Input partitionspartitions: Vec<Arc<dyn Partition>>,}impl MergeExec {/// Create a new MergeExec- pub fn new(schema: Arc<Schema>, partitions: Vec<Arc<dyn Partition>>) -> Self {+ pub fn new(schema: SchemaRef, partitions: Vec<Arc<dyn Partition>>) -> Self {MergeExec { schema, partitions }}}impl ExecutionPlan for MergeExec {- fn schema(&self) -> Arc<Schema> {+ fn schema(&self) -> SchemaRef {self.schema.clone()}@@ -59,13 +59,13 @@ impl ExecutionPlan for MergeExec {struct MergePartition {/// Input schema- schema: Arc<Schema>,+ schema: SchemaRef,/// Input partitionspartitions: Vec<Arc<dyn Partition>>,}impl Partition for MergePartition {- fn execute(&self) -> Result<Arc<Mutex<dyn BatchIterator>>> {+ fn execute(&self) -> Result<Arc<Mutex<dyn RecordBatchReader + Send + Sync>>> {let threads: Vec<JoinHandle<Result<Vec<RecordBatch>>>> = self.partitions.iter()diff --git a/rust/datafusion/src/execution/physical_plan/mod.rs b/rust/datafusion/src/execution/physical_plan/mod.rsindex b7da5e15fd..a3b32eb80c 100644--- a/rust/datafusion/src/execution/physical_plan/mod.rs+++ b/rust/datafusion/src/execution/physical_plan/mod.rs@@ -24,13 +24,13 @@ use std::sync::{Arc, Mutex};use crate::error::Result;use crate::logicalplan::ScalarValue;use arrow::array::ArrayRef;-use arrow::datatypes::{DataType, Field, Schema};-use arrow::record_batch::RecordBatch;+use arrow::datatypes::{DataType, Field, Schema, SchemaRef};+use arrow::record_batch::{RecordBatch, RecordBatchReader};/// Partition-aware execution plan for a relationpub trait ExecutionPlan {/// Get the schema for this execution plan- fn schema(&self) -> Arc<Schema>;+ fn schema(&self) -> SchemaRef;/// Get the partitions for this execution plan. Each partition can be executed in parallel.fn partitions(&self) -> Result<Vec<Arc<dyn Partition>>>;}@@ -38,15 +38,7 @@ pub trait ExecutionPlan {/// Represents a partition of an execution plan that can be executed on a threadpub trait Partition: Send + Sync {/// Execute this partition and return an iterator over RecordBatch- fn execute(&self) -> Result<Arc<Mutex<dyn BatchIterator>>>;-}--/// Iterator over RecordBatch that can be sent between threads-pub trait BatchIterator: Send + Sync {- /// Get the schema for the batches returned by this iterator- fn schema(&self) -> Arc<Schema>;- /// Get the next RecordBatch- fn next(&mut self) -> Result<Option<RecordBatch>>;+ fn execute(&self) -> Result<Arc<Mutex<dyn RecordBatchReader + Send + Sync>>>;}/// Expression that can be evaluated against a RecordBatch@@ -69,7 +61,7 @@ pub trait PhysicalExpr: Send + Sync {}}-/// Agggregate expression that can be evaluated against a RecordBatch+/// Aggregate expression that can be evaluated against a RecordBatchpub trait AggregateExpr: Send + Sync {/// Get the name to use in a schema to represent the result of this expressionfn name(&self) -> String;diff --git a/rust/datafusion/src/execution/physical_plan/parquet.rs b/rust/datafusion/src/execution/physical_plan/parquet.rsindex 88d5880cd4..16bd43880f 100644--- a/rust/datafusion/src/execution/physical_plan/parquet.rs+++ b/rust/datafusion/src/execution/physical_plan/parquet.rs@@ -24,8 +24,9 @@ use std::thread;use crate::error::{ExecutionError, Result};use crate::execution::physical_plan::common;-use crate::execution::physical_plan::{BatchIterator, ExecutionPlan, Partition};-use arrow::datatypes::Schema;+use crate::execution::physical_plan::{ExecutionPlan, Partition};+use arrow::datatypes::{Schema, SchemaRef};+use arrow::error::{ArrowError, Result as ArrowResult};use arrow::record_batch::{RecordBatch, RecordBatchReader};use parquet::file::reader::SerializedFileReader;@@ -37,7 +38,7 @@ pub struct ParquetExec {/// Path to directory containing partitioned Parquet files with the same schemafilenames: Vec<String>,/// Schema after projection is applied- schema: Arc<Schema>,+ schema: SchemaRef,/// Projection for which columns to loadprojection: Vec<usize>,/// Batch size@@ -84,7 +85,7 @@ impl ParquetExec {}impl ExecutionPlan for ParquetExec {- fn schema(&self) -> Arc<Schema> {+ fn schema(&self) -> SchemaRef {self.schema.clone()}@@ -106,7 +107,7 @@ impl ExecutionPlan for ParquetExec {}struct ParquetPartition {- iterator: Arc<Mutex<dyn BatchIterator>>,+ iterator: Arc<Mutex<dyn RecordBatchReader + Send + Sync>>,}impl ParquetPartition {@@ -114,15 +115,15 @@ impl ParquetPartition {pub fn new(filename: &str,projection: Vec<usize>,- schema: Arc<Schema>,+ schema: SchemaRef,batch_size: usize,) -> Self {// because the parquet implementation is not thread-safe, it is necessary to execute// on a thread and communicate with channelslet (request_tx, request_rx): (Sender<()>, Receiver<()>) = unbounded();let (response_tx, response_rx): (- Sender<Result<Option<RecordBatch>>>,- Receiver<Result<Option<RecordBatch>>>,+ Sender<ArrowResult<Option<RecordBatch>>>,+ Receiver<ArrowResult<Option<RecordBatch>>>,) = unbounded();let filename = filename.to_string();@@ -153,7 +154,7 @@ impl ParquetPartition {}Err(e) => {response_tx- .send(Err(ExecutionError::General(format!(+ .send(Err(ArrowError::ParquetError(format!("{:?}",e))))@@ -166,7 +167,7 @@ impl ParquetPartition {Err(e) => {response_tx- .send(Err(ExecutionError::General(format!("{:?}", e))))+ .send(Err(ArrowError::ParquetError(format!("{:?}", e)))).unwrap();}}@@ -174,7 +175,7 @@ impl ParquetPartition {Err(e) => {response_tx- .send(Err(ExecutionError::General(format!("{:?}", e))))+ .send(Err(ArrowError::ParquetError(format!("{:?}", e)))).unwrap();}}@@ -191,23 +192,23 @@ impl ParquetPartition {}impl Partition for ParquetPartition {- fn execute(&self) -> Result<Arc<Mutex<dyn BatchIterator>>> {+ fn execute(&self) -> Result<Arc<Mutex<dyn RecordBatchReader + Send + Sync>>> {Ok(self.iterator.clone())}}struct ParquetIterator {- schema: Arc<Schema>,+ schema: SchemaRef,request_tx: Sender<()>,- response_rx: Receiver<Result<Option<RecordBatch>>>,+ response_rx: Receiver<ArrowResult<Option<RecordBatch>>>,}-impl BatchIterator for ParquetIterator {- fn schema(&self) -> Arc<Schema> {+impl RecordBatchReader for ParquetIterator {+ fn schema(&self) -> SchemaRef {self.schema.clone()}- fn next(&mut self) -> Result<Option<RecordBatch>> {+ fn next_batch(&mut self) -> ArrowResult<Option<RecordBatch>> {match self.request_tx.send(()) {Ok(_) => match self.response_rx.recv() {Ok(batch) => batch,@@ -236,26 +237,23 @@ mod tests {let results = partitions[0].execute()?;let mut results = results.lock().unwrap();- let batch = results.next()?.unwrap();+ let batch = results.next_batch()?.unwrap();assert_eq!(8, batch.num_rows());assert_eq!(3, batch.num_columns());- let field_names: Vec<&str> = batch- .schema()- .fields()- .iter()- .map(|f| f.name().as_str())- .collect();+ let schema = batch.schema();+ let field_names: Vec<&str> =+ schema.fields().iter().map(|f| f.name().as_str()).collect();assert_eq!(vec!["id", "bool_col", "tinyint_col"], field_names);- let batch = results.next()?;+ let batch = results.next_batch()?;assert!(batch.is_none());- let batch = results.next()?;+ let batch = results.next_batch()?;assert!(batch.is_none());- let batch = results.next()?;+ let batch = results.next_batch()?;assert!(batch.is_none());Ok(())diff --git a/rust/datafusion/src/execution/physical_plan/projection.rs b/rust/datafusion/src/execution/physical_plan/projection.rsindex f1d778548e..7f39deda49 100644--- a/rust/datafusion/src/execution/physical_plan/projection.rs+++ b/rust/datafusion/src/execution/physical_plan/projection.rs@@ -22,19 +22,18 @@use std::sync::{Arc, Mutex};-use crate::error::Result;-use crate::execution::physical_plan::{- BatchIterator, ExecutionPlan, Partition, PhysicalExpr,-};-use arrow::datatypes::Schema;-use arrow::record_batch::RecordBatch;+use crate::error::{ExecutionError, Result};+use crate::execution::physical_plan::{ExecutionPlan, Partition, PhysicalExpr};+use arrow::datatypes::{Schema, SchemaRef};+use arrow::error::Result as ArrowResult;+use arrow::record_batch::{RecordBatch, RecordBatchReader};/// Execution plan for a projectionpub struct ProjectionExec {/// The projection expressionsexpr: Vec<Arc<dyn PhysicalExpr>>,/// The schema once the projection has been applied to the input- schema: Arc<Schema>,+ schema: SchemaRef,/// The input planinput: Arc<dyn ExecutionPlan>,}@@ -64,7 +63,7 @@ impl ProjectionExec {impl ExecutionPlan for ProjectionExec {/// Get the schema for this execution plan- fn schema(&self) -> Arc<Schema> {+ fn schema(&self) -> SchemaRef {self.schema.clone()}@@ -91,14 +90,14 @@ impl ExecutionPlan for ProjectionExec {/// Represents a single partition of a projection execution planstruct ProjectionPartition {- schema: Arc<Schema>,+ schema: SchemaRef,expr: Vec<Arc<dyn PhysicalExpr>>,input: Arc<dyn Partition>,}impl Partition for ProjectionPartition {/// Execute the projection- fn execute(&self) -> Result<Arc<Mutex<dyn BatchIterator>>> {+ fn execute(&self) -> Result<Arc<Mutex<dyn RecordBatchReader + Send + Sync>>> {Ok(Arc::new(Mutex::new(ProjectionIterator {schema: self.schema.clone(),expr: self.expr.clone(),@@ -109,25 +108,28 @@ impl Partition for ProjectionPartition {/// Projection iteratorstruct ProjectionIterator {- schema: Arc<Schema>,+ schema: SchemaRef,expr: Vec<Arc<dyn PhysicalExpr>>,- input: Arc<Mutex<dyn BatchIterator>>,+ input: Arc<Mutex<dyn RecordBatchReader + Send + Sync>>,}-impl BatchIterator for ProjectionIterator {+impl RecordBatchReader for ProjectionIterator {/// Get the schema- fn schema(&self) -> Arc<Schema> {+ fn schema(&self) -> SchemaRef {self.schema.clone()}/// Get the next batch- fn next(&mut self) -> Result<Option<RecordBatch>> {+ fn next_batch(&mut self) -> ArrowResult<Option<RecordBatch>> {let mut input = self.input.lock().unwrap();- match input.next()? {+ 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?)?))+ Ok(Some(RecordBatch::try_new(+ self.schema.clone(),+ arrays.map_err(ExecutionError::into_arrow_external_error)?,+ )?))}None => Ok(None),}@@ -165,7 +167,7 @@ mod tests {partition_count += 1;let iterator = partition.execute()?;let mut iterator = iterator.lock().unwrap();- while let Some(batch) = iterator.next()? {+ while let Some(batch) = iterator.next_batch()? {assert_eq!(1, batch.num_columns());row_count += batch.num_rows();}diff --git a/rust/datafusion/src/execution/physical_plan/selection.rs b/rust/datafusion/src/execution/physical_plan/selection.rsindex 5998aa4320..b8efe421d9 100644--- a/rust/datafusion/src/execution/physical_plan/selection.rs+++ b/rust/datafusion/src/execution/physical_plan/selection.rs@@ -20,13 +20,12 @@use std::sync::{Arc, Mutex};use crate::error::{ExecutionError, Result};-use crate::execution::physical_plan::{- BatchIterator, ExecutionPlan, Partition, PhysicalExpr,-};+use crate::execution::physical_plan::{ExecutionPlan, Partition, PhysicalExpr};use arrow::array::BooleanArray;use arrow::compute::filter;-use arrow::datatypes::Schema;-use arrow::record_batch::RecordBatch;+use arrow::datatypes::SchemaRef;+use arrow::error::Result as ArrowResult;+use arrow::record_batch::{RecordBatch, RecordBatchReader};/// Execution plan for a Selectionpub struct SelectionExec {@@ -51,7 +50,7 @@ impl SelectionExec {impl ExecutionPlan for SelectionExec {/// Get the schema for this execution plan- fn schema(&self) -> Arc<Schema> {+ fn schema(&self) -> SchemaRef {// The selection operator does not make any changes to the schema of its inputself.input.schema()}@@ -80,14 +79,14 @@ impl ExecutionPlan for SelectionExec {/// Represents a single partition of a Selection execution planstruct SelectionPartition {- schema: Arc<Schema>,+ schema: SchemaRef,expr: Arc<dyn PhysicalExpr>,input: Arc<dyn Partition>,}impl Partition for SelectionPartition {/// Execute the Selection- fn execute(&self) -> Result<Arc<Mutex<dyn BatchIterator>>> {+ fn execute(&self) -> Result<Arc<Mutex<dyn RecordBatchReader + Send + Sync>>> {Ok(Arc::new(Mutex::new(SelectionIterator {schema: self.schema.clone(),expr: self.expr.clone(),@@ -98,24 +97,27 @@ impl Partition for SelectionPartition {/// Selection iteratorstruct SelectionIterator {- schema: Arc<Schema>,+ schema: SchemaRef,expr: Arc<dyn PhysicalExpr>,- input: Arc<Mutex<dyn BatchIterator>>,+ input: Arc<Mutex<dyn RecordBatchReader + Send + Sync>>,}-impl BatchIterator for SelectionIterator {+impl RecordBatchReader for SelectionIterator {/// Get the schema- fn schema(&self) -> Arc<Schema> {+ fn schema(&self) -> SchemaRef {self.schema.clone()}/// Get the next batch- fn next(&mut self) -> Result<Option<RecordBatch>> {+ fn next_batch(&mut self) -> ArrowResult<Option<RecordBatch>> {let mut input = self.input.lock().unwrap();- match input.next()? {+ match input.next_batch()? {Some(batch) => {// evaluate the selection predicate to get a boolean array- let predicate_result = self.expr.evaluate(&batch)?;+ let predicate_result = self+ .expr+ .evaluate(&batch)+ .map_err(ExecutionError::into_arrow_external_error)?;if let Some(f) = predicate_result.as_any().downcast_ref::<BooleanArray>(){@@ -133,7 +135,8 @@ impl BatchIterator for SelectionIterator {} else {Err(ExecutionError::InternalError("Predicate evaluated to non-boolean value".to_string(),- ))+ )+ .into_arrow_external_error())}}None => Ok(None),diff --git a/rust/datafusion/src/execution/physical_plan/sort.rs b/rust/datafusion/src/execution/physical_plan/sort.rsindex 7f022ee51e..7017e8a036 100644--- a/rust/datafusion/src/execution/physical_plan/sort.rs+++ b/rust/datafusion/src/execution/physical_plan/sort.rs@@ -24,13 +24,13 @@ use std::thread::JoinHandle;use arrow::array::ArrayRef;pub use arrow::compute::SortOptions;use arrow::compute::{concat, lexsort_to_indices, take, SortColumn, TakeOptions};-use arrow::datatypes::Schema;-use arrow::record_batch::RecordBatch;+use arrow::datatypes::SchemaRef;+use arrow::record_batch::{RecordBatch, RecordBatchReader};use crate::error::Result;use crate::execution::physical_plan::common::RecordBatchIterator;use crate::execution::physical_plan::expressions::PhysicalSortExpr;-use crate::execution::physical_plan::{common, BatchIterator, ExecutionPlan, Partition};+use crate::execution::physical_plan::{common, ExecutionPlan, Partition};/// Sort execution planpub struct SortExec {@@ -50,7 +50,7 @@ impl SortExec {}impl ExecutionPlan for SortExec {- fn schema(&self) -> Arc<Schema> {+ fn schema(&self) -> SchemaRef {self.input.schema().clone()}@@ -67,14 +67,14 @@ impl ExecutionPlan for SortExec {/// Represents a single partition of a Sort execution planstruct SortPartition {- schema: Arc<Schema>,+ schema: SchemaRef,expr: Vec<PhysicalSortExpr>,input: Vec<Arc<dyn Partition>>,}impl Partition for SortPartition {/// Execute the sort- fn execute(&self) -> Result<Arc<Mutex<dyn BatchIterator>>> {+ fn execute(&self) -> Result<Arc<Mutex<dyn RecordBatchReader + Send + Sync>>> {let threads: Vec<JoinHandle<Result<Vec<RecordBatch>>>> = self.input.iter()diff --git a/rust/datafusion/src/sql/planner.rs b/rust/datafusion/src/sql/planner.rsindex 3a25f25736..5c9570638b 100644--- a/rust/datafusion/src/sql/planner.rs+++ b/rust/datafusion/src/sql/planner.rs@@ -33,7 +33,7 @@ use sqlparser::sqlast::*;/// functions referenced in SQL statementspub trait SchemaProvider {/// Getter for a field description- fn get_table_meta(&self, name: &str) -> Option<Arc<Schema>>;+ fn get_table_meta(&self, name: &str) -> Option<SchemaRef>;/// Getter for a UDF descriptionfn get_function_meta(&self, name: &str) -> Option<Arc<FunctionMeta>>;}@@ -698,7 +698,7 @@ mod tests {struct MockSchemaProvider {}impl SchemaProvider for MockSchemaProvider {- fn get_table_meta(&self, name: &str) -> Option<Arc<Schema>> {+ fn get_table_meta(&self, name: &str) -> Option<SchemaRef> {match name {"person" => Some(Arc::new(Schema::new(vec![Field::new("id", DataType::UInt32, false),diff --git a/rust/datafusion/src/test/mod.rs b/rust/datafusion/src/test/mod.rsindex ecda07dda8..317c14564f 100644--- a/rust/datafusion/src/test/mod.rs+++ b/rust/datafusion/src/test/mod.rs@@ -22,7 +22,7 @@ use crate::execution::context::ExecutionContext;use crate::execution::physical_plan::ExecutionPlan;use crate::logicalplan::{Expr, LogicalPlan, LogicalPlanBuilder};use arrow::array;-use arrow::datatypes::{DataType, Field, Schema};+use arrow::datatypes::{DataType, Field, Schema, SchemaRef};use arrow::record_batch::RecordBatch;use std::env;use std::fs::File;@@ -87,7 +87,7 @@ pub fn create_partitioned_csv(filename: &str, partitions: usize) -> Result<Strin}/// Get the schema for the aggregate_test_* csv files-pub fn aggr_test_schema() -> Arc<Schema> {+pub fn aggr_test_schema() -> SchemaRef {Arc::new(Schema::new(vec![Field::new("c1", DataType::Utf8, false),Field::new("c2", DataType::UInt32, false),diff --git a/rust/datafusion/tests/sql.rs b/rust/datafusion/tests/sql.rsindex 44ddca2713..47f60fa205 100644--- a/rust/datafusion/tests/sql.rs+++ b/rust/datafusion/tests/sql.rs@@ -22,7 +22,7 @@ extern crate arrow;extern crate datafusion;use arrow::array::*;-use arrow::datatypes::{DataType, Field, Schema};+use arrow::datatypes::{DataType, Field, Schema, SchemaRef};use arrow::record_batch::RecordBatch;use datafusion::datasource::csv::CsvReadOptions;@@ -394,7 +394,7 @@ fn csv_query_count_one() {assert_eq!(expected, actual);}-fn aggr_test_schema() -> Arc<Schema> {+fn aggr_test_schema() -> SchemaRef {Arc::new(Schema::new(vec![Field::new("c1", DataType::Utf8, false),Field::new("c2", DataType::UInt32, false),