Skip to content

Apache DataFusion SQL Query Engine

ARROW-9753: [Rust] [DataFusion] Replaced Arc<Mutex<>> by Box<>

Jorge C. Leitao12b288933f6f
diff --git a/rust/datafusion/src/datasource/memory.rs b/rust/datafusion/src/datasource/memory.rs
index fcff7d61ac..8ab22a3dbe 100644
--- a/rust/datafusion/src/datasource/memory.rs
+++ b/rust/datafusion/src/datasource/memory.rs
@@ -64,7 +64,6 @@ impl MemTable {
Vec::with_capacity(exec.output_partitioning().partition_count());
for partition in 0..exec.output_partitioning().partition_count() {
let it = exec.execute(partition).await?;
- let mut it = it.lock().unwrap();
let partition_batches = it.into_iter().collect::<ArrowResult<Vec<_>>>()?;
data.push(partition_batches);
}
@@ -145,8 +144,8 @@ mod tests {
// scan with projection
let exec = provider.scan(&Some(vec![2, 1]), 1024)?;
- let it = exec.execute(0).await?;
- let batch2 = it.lock().expect("mutex lock").next().unwrap()?;
+ let mut it = exec.execute(0).await?;
+ let batch2 = it.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());
@@ -175,8 +174,8 @@ mod tests {
let provider = MemTable::new(schema, vec![vec![batch]])?;
let exec = provider.scan(&None, 1024)?;
- let it = exec.execute(0).await?;
- let batch1 = it.lock().expect("mutex lock").next().unwrap()?;
+ let mut it = exec.execute(0).await?;
+ let batch1 = it.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.rs
index 9f11372b14..5308246b4f 100644
--- a/rust/datafusion/src/datasource/parquet.rs
+++ b/rust/datafusion/src/datasource/parquet.rs
@@ -83,7 +83,6 @@ mod tests {
let projection = None;
let exec = table.scan(&projection, 2)?;
let it = exec.execute(0).await?;
- let mut it = it.lock().unwrap();
let count = it
.into_iter()
@@ -304,8 +303,7 @@ mod tests {
projection: &Option<Vec<usize>>,
) -> Result<RecordBatch> {
let exec = table.scan(projection, 1024)?;
- let it = exec.execute(0).await?;
- let mut it = it.lock().expect("failed to lock mutex");
+ let mut it = exec.execute(0).await?;
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.rs
index 3df5e80f4b..2b7470f6ed 100644
--- a/rust/datafusion/src/execution/context.rs
+++ b/rust/datafusion/src/execution/context.rs
@@ -360,10 +360,9 @@ impl ExecutionContext {
let plan = plan.clone();
let filename = format!("part-{}.csv", i);
let path = Path::new(&path).join(&filename);
- let file = fs::File::create(path).unwrap();
+ let file = fs::File::create(path)?;
let mut writer = csv::Writer::new(file);
- let reader = plan.execute(i).await.unwrap();
- let mut reader = reader.lock().unwrap();
+ let reader = plan.execute(i).await?;
reader
.into_iter()
diff --git a/rust/datafusion/src/physical_plan/common.rs b/rust/datafusion/src/physical_plan/common.rs
index 3008d9b1bc..a59bcc8256 100644
--- a/rust/datafusion/src/physical_plan/common.rs
+++ b/rust/datafusion/src/physical_plan/common.rs
@@ -19,8 +19,9 @@
use std::fs;
use std::fs::metadata;
-use std::sync::{Arc, Mutex};
+use std::sync::Arc;
+use super::Source;
use crate::error::{ExecutionError, Result};
use array::{
@@ -74,12 +75,8 @@ impl RecordBatchReader for RecordBatchIterator {
}
/// Create a vector of record batches from an iterator
-pub fn collect(
- it: Arc<Mutex<dyn RecordBatchReader + Send + Sync>>,
-) -> Result<Vec<RecordBatch>> {
- it.lock()
- .unwrap()
- .into_iter()
+pub fn collect(it: Source) -> Result<Vec<RecordBatch>> {
+ it.into_iter()
.collect::<ArrowResult<Vec<_>>>()
.map_err(|e| ExecutionError::from(e))
}
diff --git a/rust/datafusion/src/physical_plan/csv.rs b/rust/datafusion/src/physical_plan/csv.rs
index acbf92d87b..4356417b89 100644
--- a/rust/datafusion/src/physical_plan/csv.rs
+++ b/rust/datafusion/src/physical_plan/csv.rs
@@ -19,7 +19,7 @@
use std::any::Any;
use std::fs::File;
-use std::sync::{Arc, Mutex};
+use std::sync::Arc;
use crate::error::{ExecutionError, Result};
use crate::physical_plan::ExecutionPlan;
@@ -29,6 +29,7 @@ use arrow::datatypes::{Schema, SchemaRef};
use arrow::error::Result as ArrowResult;
use arrow::record_batch::{RecordBatch, RecordBatchReader};
+use super::Source;
use async_trait::async_trait;
/// CSV file read option
@@ -217,18 +218,15 @@ impl ExecutionPlan for CsvExec {
}
}
- async fn execute(
- &self,
- partition: usize,
- ) -> Result<Arc<Mutex<dyn RecordBatchReader + Send + Sync>>> {
- Ok(Arc::new(Mutex::new(CsvIterator::try_new(
+ async fn execute(&self, partition: usize) -> Result<Source> {
+ Ok(Box::new(CsvIterator::try_new(
&self.filenames[partition],
self.schema.clone(),
self.has_header,
self.delimiter,
&self.projection,
self.batch_size,
- )?)))
+ )?))
}
}
@@ -297,8 +295,7 @@ mod tests {
assert_eq!(13, csv.schema.fields().len());
assert_eq!(3, csv.projected_schema.fields().len());
assert_eq!(3, csv.schema().fields().len());
- let it = csv.execute(0).await?;
- let mut it = it.lock().unwrap();
+ let mut it = csv.execute(0).await?;
let batch = it.next().unwrap()?;
assert_eq!(3, batch.num_columns());
let batch_schema = batch.schema();
@@ -320,8 +317,7 @@ mod tests {
assert_eq!(13, csv.schema.fields().len());
assert_eq!(13, csv.projected_schema.fields().len());
assert_eq!(13, csv.schema().fields().len());
- let it = csv.execute(0).await?;
- let mut it = it.lock().unwrap();
+ let mut it = csv.execute(0).await?;
let batch = it.next().unwrap()?;
assert_eq!(13, batch.num_columns());
let batch_schema = batch.schema();
diff --git a/rust/datafusion/src/physical_plan/empty.rs b/rust/datafusion/src/physical_plan/empty.rs
index 7e39eef70b..27c3fdc441 100644
--- a/rust/datafusion/src/physical_plan/empty.rs
+++ b/rust/datafusion/src/physical_plan/empty.rs
@@ -18,13 +18,14 @@
//! EmptyRelation execution plan
use std::any::Any;
-use std::sync::{Arc, Mutex};
+use std::sync::Arc;
use crate::error::{ExecutionError, Result};
use crate::physical_plan::memory::MemoryIterator;
use crate::physical_plan::{Distribution, ExecutionPlan, Partitioning};
use arrow::datatypes::SchemaRef;
-use arrow::record_batch::RecordBatchReader;
+
+use super::Source;
use async_trait::async_trait;
@@ -77,10 +78,7 @@ impl ExecutionPlan for EmptyExec {
}
}
- async fn execute(
- &self,
- partition: usize,
- ) -> Result<Arc<Mutex<dyn RecordBatchReader + Send + Sync>>> {
+ async fn execute(&self, partition: usize) -> Result<Source> {
// GlobalLimitExec has a single output partition
if 0 != partition {
return Err(ExecutionError::General(format!(
@@ -90,11 +88,11 @@ impl ExecutionPlan for EmptyExec {
}
let data = vec![];
- Ok(Arc::new(Mutex::new(MemoryIterator::try_new(
+ Ok(Box::new(MemoryIterator::try_new(
data,
self.schema.clone(),
None,
- )?)))
+ )?))
}
}
diff --git a/rust/datafusion/src/physical_plan/explain.rs b/rust/datafusion/src/physical_plan/explain.rs
index 4e3957f71c..b5d92a5feb 100644
--- a/rust/datafusion/src/physical_plan/explain.rs
+++ b/rust/datafusion/src/physical_plan/explain.rs
@@ -18,21 +18,18 @@
//! Defines the EXPLAIN operator
use std::any::Any;
-use std::sync::{Arc, Mutex};
+use std::sync::Arc;
use crate::error::{ExecutionError, Result};
use crate::{
logical_plan::StringifiedPlan,
physical_plan::{common::RecordBatchIterator, ExecutionPlan},
};
-use arrow::{
- array::StringBuilder,
- datatypes::SchemaRef,
- record_batch::{RecordBatch, RecordBatchReader},
-};
+use arrow::{array::StringBuilder, datatypes::SchemaRef, record_batch::RecordBatch};
use crate::physical_plan::Partitioning;
+use super::Source;
use async_trait::async_trait;
/// Explain execution plan operator. This operator contains the string
@@ -91,10 +88,8 @@ impl ExecutionPlan for ExplainExec {
)))
}
}
- async fn execute(
- &self,
- partition: usize,
- ) -> Result<Arc<Mutex<dyn RecordBatchReader + Send + Sync>>> {
+
+ async fn execute(&self, partition: usize) -> Result<Source> {
if 0 != partition {
return Err(ExecutionError::General(format!(
"ExplainExec invalid partition {}",
@@ -118,9 +113,9 @@ impl ExecutionPlan for ExplainExec {
],
)?;
- Ok(Arc::new(Mutex::new(RecordBatchIterator::new(
+ Ok(Box::new(RecordBatchIterator::new(
self.schema.clone(),
vec![Arc::new(record_batch)],
- ))))
+ )))
}
}
diff --git a/rust/datafusion/src/physical_plan/filter.rs b/rust/datafusion/src/physical_plan/filter.rs
index 26c04cb8d1..5c7f638420 100644
--- a/rust/datafusion/src/physical_plan/filter.rs
+++ b/rust/datafusion/src/physical_plan/filter.rs
@@ -19,8 +19,9 @@
//! include in its output batches.
use std::any::Any;
-use std::sync::{Arc, Mutex};
+use std::sync::Arc;
+use super::Source;
use crate::error::{ExecutionError, Result};
use crate::physical_plan::{ExecutionPlan, Partitioning, PhysicalExpr};
use arrow::array::BooleanArray;
@@ -97,15 +98,12 @@ impl ExecutionPlan for FilterExec {
}
}
- async fn execute(
- &self,
- partition: usize,
- ) -> Result<Arc<Mutex<dyn RecordBatchReader + Send + Sync>>> {
- Ok(Arc::new(Mutex::new(FilterExecIter {
+ async fn execute(&self, partition: usize) -> Result<Source> {
+ Ok(Box::new(FilterExecIter {
schema: self.input.schema().clone(),
predicate: self.predicate.clone(),
input: self.input.execute(partition).await?,
- })))
+ }))
}
}
@@ -117,7 +115,7 @@ struct FilterExecIter {
/// The expression to filter on. This expression must evaluate to a boolean value.
predicate: Arc<dyn PhysicalExpr>,
/// The input partition to filter.
- input: Arc<Mutex<dyn RecordBatchReader + Send + Sync>>,
+ input: Source,
}
impl Iterator for FilterExecIter {
@@ -125,8 +123,7 @@ impl Iterator for FilterExecIter {
/// Get the next batch
fn next(&mut self) -> Option<ArrowResult<RecordBatch>> {
- let mut input = self.input.lock().unwrap();
- match input.next() {
+ match self.input.next() {
Some(Ok(batch)) => {
// evaluate the filter predicate to get a boolean array indicating which rows
// to include in the output
diff --git a/rust/datafusion/src/physical_plan/hash_aggregate.rs b/rust/datafusion/src/physical_plan/hash_aggregate.rs
index 5420135812..1698577021 100644
--- a/rust/datafusion/src/physical_plan/hash_aggregate.rs
+++ b/rust/datafusion/src/physical_plan/hash_aggregate.rs
@@ -20,7 +20,7 @@
use std::any::Any;
use std::cell::RefCell;
use std::rc::Rc;
-use std::sync::{Arc, Mutex};
+use std::sync::Arc;
use crate::error::{ExecutionError, Result};
use crate::physical_plan::{Accumulator, AggregateExpr};
@@ -40,7 +40,7 @@ use arrow::{
use fnv::FnvHashMap;
-use super::{common, expressions::Column};
+use super::{common, expressions::Column, Source};
use async_trait::async_trait;
@@ -145,28 +145,25 @@ impl ExecutionPlan for HashAggregateExec {
self.input.output_partitioning()
}
- async fn execute(
- &self,
- partition: usize,
- ) -> Result<Arc<Mutex<dyn RecordBatchReader + Send + Sync>>> {
+ async fn execute(&self, partition: usize) -> Result<Source> {
let input = self.input.execute(partition).await?;
let group_expr = self.group_expr.iter().map(|x| x.0.clone()).collect();
if self.group_expr.is_empty() {
- Ok(Arc::new(Mutex::new(HashAggregateIterator::new(
+ Ok(Box::new(HashAggregateIterator::new(
self.mode,
self.schema.clone(),
self.aggr_expr.clone(),
input,
- ))))
+ )))
} else {
- Ok(Arc::new(Mutex::new(GroupedHashAggregateIterator::new(
+ Ok(Box::new(GroupedHashAggregateIterator::new(
self.mode.clone(),
self.schema.clone(),
group_expr,
self.aggr_expr.clone(),
input,
- ))))
+ )))
}
}
@@ -218,10 +215,104 @@ struct GroupedHashAggregateIterator {
schema: SchemaRef,
group_expr: Vec<Arc<dyn PhysicalExpr>>,
aggr_expr: Vec<Arc<dyn AggregateExpr>>,
- input: Arc<Mutex<dyn RecordBatchReader + Send + Sync>>,
+ input: Source,
finished: bool,
}
+fn group_aggregate_batch(
+ mode: &AggregateMode,
+ group_expr: &Vec<Arc<dyn PhysicalExpr>>,
+ aggr_expr: &Vec<Arc<dyn AggregateExpr>>,
+ 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(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(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 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<()>>()
+}
+
impl GroupedHashAggregateIterator {
/// Create a new HashAggregateIterator
pub fn new(
@@ -229,7 +320,7 @@ impl GroupedHashAggregateIterator {
schema: SchemaRef,
group_expr: Vec<Arc<dyn PhysicalExpr>>,
aggr_expr: Vec<Arc<dyn AggregateExpr>>,
- input: Arc<Mutex<dyn RecordBatchReader + Send + Sync>>,
+ input: Source,
) -> Self {
GroupedHashAggregateIterator {
mode,
@@ -240,103 +331,6 @@ 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>>>;
@@ -352,12 +346,15 @@ impl Iterator for GroupedHashAggregateIterator {
// return single batch
self.finished = true;
+ let mode = &self.mode;
+ let group_expr = &self.group_expr;
+ let aggr_expr = &self.aggr_expr;
+
// the expressions to evaluate the batch, one vec of expressions per aggregation
- 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))),
- };
+ let aggregate_expressions = match aggregate_expressions(&aggr_expr, &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
@@ -371,12 +368,18 @@ impl Iterator for GroupedHashAggregateIterator {
// iterate over all input batches and update the accumulators
match self
.input
- .lock()
- .unwrap()
+ .as_mut()
.into_iter()
.map(|batch| {
- self.aggregate_batch(&batch?, &mut accumulators, &aggregate_expressions)
- .map_err(ExecutionError::into_arrow_external_error)
+ group_aggregate_batch(
+ &mode,
+ &group_expr,
+ &aggr_expr,
+ &batch?,
+ &mut accumulators,
+ &aggregate_expressions,
+ )
+ .map_err(ExecutionError::into_arrow_external_error)
})
.collect::<ArrowResult<()>>()
{
@@ -460,7 +463,7 @@ struct HashAggregateIterator {
mode: AggregateMode,
schema: SchemaRef,
aggr_expr: Vec<Arc<dyn AggregateExpr>>,
- input: Arc<Mutex<dyn RecordBatchReader + Send + Sync>>,
+ input: Source,
finished: bool,
}
@@ -470,7 +473,7 @@ impl HashAggregateIterator {
mode: AggregateMode,
schema: SchemaRef,
aggr_expr: Vec<Arc<dyn AggregateExpr>>,
- input: Arc<Mutex<dyn RecordBatchReader + Send + Sync>>,
+ input: Source,
) -> Self {
HashAggregateIterator {
mode,
@@ -480,36 +483,36 @@ impl HashAggregateIterator {
finished: false,
}
}
+}
- 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
+fn aggregate_batch(
+ mode: &AggregateMode,
+ 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<()>>()
- }
+ // 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 mode {
+ AggregateMode::Partial => accum.borrow_mut().update_batch(values),
+ AggregateMode::Final => accum.borrow_mut().merge_batch(values),
+ }
+ })
+ .collect::<Result<()>>()
}
impl Iterator for HashAggregateIterator {
@@ -533,14 +536,16 @@ impl Iterator for HashAggregateIterator {
Err(e) => return Some(Err(ExecutionError::into_arrow_external_error(e))),
};
+ let mode = self.mode;
+ let schema = self.schema();
+
// 1 for each batch, update / merge accumulators with the expressions' values
match self
.input
- .lock()
- .unwrap()
+ .as_mut()
.into_iter()
.map(|batch| {
- self.aggregate_batch(&batch?, &accumulators, &expressions)
+ aggregate_batch(&mode, &batch?, &accumulators, &expressions)
.map_err(ExecutionError::into_arrow_external_error)
})
.collect::<ArrowResult<()>>()
@@ -551,9 +556,9 @@ impl Iterator for HashAggregateIterator {
// 2 convert values to a record batch
Some(
- finalize_aggregation(&accumulators, &self.mode)
+ finalize_aggregation(&accumulators, &mode)
.map_err(ExecutionError::into_arrow_external_error)
- .and_then(|columns| RecordBatch::try_new(self.schema.clone(), columns)),
+ .and_then(|columns| RecordBatch::try_new(schema.clone(), columns)),
)
}
}
diff --git a/rust/datafusion/src/physical_plan/limit.rs b/rust/datafusion/src/physical_plan/limit.rs
index fee774f133..e10805c3d4 100644
--- a/rust/datafusion/src/physical_plan/limit.rs
+++ b/rust/datafusion/src/physical_plan/limit.rs
@@ -18,7 +18,7 @@
//! Defines the LIMIT plan
use std::any::Any;
-use std::sync::{Arc, Mutex};
+use std::sync::Arc;
use crate::error::{ExecutionError, Result};
use crate::physical_plan::memory::MemoryIterator;
@@ -26,7 +26,9 @@ use crate::physical_plan::{Distribution, ExecutionPlan, Partitioning};
use arrow::array::ArrayRef;
use arrow::compute::limit;
use arrow::datatypes::SchemaRef;
-use arrow::record_batch::{RecordBatch, RecordBatchReader};
+use arrow::record_batch::RecordBatch;
+
+use super::Source;
use async_trait::async_trait;
@@ -92,10 +94,7 @@ impl ExecutionPlan for GlobalLimitExec {
}
}
- async fn execute(
- &self,
- partition: usize,
- ) -> Result<Arc<Mutex<dyn RecordBatchReader + Send + Sync>>> {
+ async fn execute(&self, partition: usize) -> Result<Source> {
// GlobalLimitExec has a single output partition
if 0 != partition {
return Err(ExecutionError::General(format!(
@@ -111,12 +110,12 @@ impl ExecutionPlan for GlobalLimitExec {
));
}
- let it = self.input.execute(0).await?;
- Ok(Arc::new(Mutex::new(MemoryIterator::try_new(
- collect_with_limit(it, self.limit)?,
+ let mut it = self.input.execute(0).await?;
+ Ok(Box::new(MemoryIterator::try_new(
+ collect_with_limit(&mut it, self.limit)?,
self.input.schema(),
None,
- )?)))
+ )?))
}
}
@@ -168,16 +167,13 @@ impl ExecutionPlan for LocalLimitExec {
}
}
- async fn execute(
- &self,
- partition: usize,
- ) -> Result<Arc<Mutex<dyn RecordBatchReader + Send + Sync>>> {
- let it = self.input.execute(partition).await?;
- Ok(Arc::new(Mutex::new(MemoryIterator::try_new(
- collect_with_limit(it, self.limit)?,
+ async fn execute(&self, _: usize) -> Result<Source> {
+ let mut it = self.input.execute(0).await?;
+ Ok(Box::new(MemoryIterator::try_new(
+ collect_with_limit(&mut it, self.limit)?,
self.input.schema(),
None,
- )?)))
+ )?))
}
}
@@ -194,15 +190,11 @@ pub fn truncate_batch(batch: &RecordBatch, n: usize) -> Result<RecordBatch> {
}
/// Create a vector of record batches from an iterator
-fn collect_with_limit(
- reader: Arc<Mutex<dyn RecordBatchReader + Send + Sync>>,
- limit: usize,
-) -> Result<Vec<RecordBatch>> {
+fn collect_with_limit(reader: &mut Source, limit: usize) -> Result<Vec<RecordBatch>> {
let mut count = 0;
- let mut reader = reader.lock().unwrap();
let mut results: Vec<RecordBatch> = vec![];
loop {
- match reader.next() {
+ match reader.as_mut().next() {
Some(Ok(batch)) => {
let capacity = limit - count;
if batch.num_rows() <= capacity {
diff --git a/rust/datafusion/src/physical_plan/memory.rs b/rust/datafusion/src/physical_plan/memory.rs
index b64976f4ea..79f213231f 100644
--- a/rust/datafusion/src/physical_plan/memory.rs
+++ b/rust/datafusion/src/physical_plan/memory.rs
@@ -18,7 +18,7 @@
//! Execution plan for reading in-memory batches of data
use std::any::Any;
-use std::sync::{Arc, Mutex};
+use std::sync::Arc;
use crate::error::{ExecutionError, Result};
use crate::physical_plan::{ExecutionPlan, Partitioning};
@@ -26,6 +26,7 @@ use arrow::datatypes::SchemaRef;
use arrow::error::Result as ArrowResult;
use arrow::record_batch::{RecordBatch, RecordBatchReader};
+use super::Source;
use async_trait::async_trait;
/// Execution plan for reading in-memory batches of data
@@ -71,15 +72,12 @@ impl ExecutionPlan for MemoryExec {
)))
}
- async fn execute(
- &self,
- partition: usize,
- ) -> Result<Arc<Mutex<dyn RecordBatchReader + Send + Sync>>> {
- Ok(Arc::new(Mutex::new(MemoryIterator::try_new(
+ async fn execute(&self, partition: usize) -> Result<Source> {
+ Ok(Box::new(MemoryIterator::try_new(
self.partitions[partition].clone(),
self.schema.clone(),
self.projection.clone(),
- )?)))
+ )?))
}
}
diff --git a/rust/datafusion/src/physical_plan/merge.rs b/rust/datafusion/src/physical_plan/merge.rs
index 5c8a25a216..1a2357e543 100644
--- a/rust/datafusion/src/physical_plan/merge.rs
+++ b/rust/datafusion/src/physical_plan/merge.rs
@@ -19,7 +19,7 @@
//! into a single partition
use std::any::Any;
-use std::sync::{Arc, Mutex};
+use std::sync::Arc;
use crate::error::{ExecutionError, Result};
use crate::physical_plan::common::RecordBatchIterator;
@@ -27,7 +27,9 @@ use crate::physical_plan::Partitioning;
use crate::physical_plan::{common, ExecutionPlan};
use arrow::datatypes::SchemaRef;
-use arrow::record_batch::{RecordBatch, RecordBatchReader};
+use arrow::record_batch::RecordBatch;
+
+use super::Source;
use async_trait::async_trait;
use tokio::task::{self, JoinHandle};
@@ -87,10 +89,7 @@ impl ExecutionPlan for MergeExec {
}
}
- async fn execute(
- &self,
- partition: usize,
- ) -> Result<Arc<Mutex<dyn RecordBatchReader + Send + Sync>>> {
+ async fn execute(&self, partition: usize) -> Result<Source> {
// MergeExec produces a single partition
if 0 != partition {
return Err(ExecutionError::General(format!(
@@ -122,9 +121,10 @@ impl ExecutionPlan for MergeExec {
let mut batches: Vec<Arc<RecordBatch>> = vec![];
for partition in chunk {
let it = input.execute(partition).await?;
- common::collect(it)?
- .iter()
- .for_each(|b| batches.push(Arc::new(b.clone())));
+ common::collect(it).iter().for_each(|b| {
+ b.iter()
+ .for_each(|b| batches.push(Arc::new(b.clone())))
+ });
}
Ok(batches)
});
@@ -140,10 +140,10 @@ impl ExecutionPlan for MergeExec {
}
}
- Ok(Arc::new(Mutex::new(RecordBatchIterator::new(
+ Ok(Box::new(RecordBatchIterator::new(
self.input.schema(),
combined_results,
- ))))
+ )))
}
}
}
diff --git a/rust/datafusion/src/physical_plan/mod.rs b/rust/datafusion/src/physical_plan/mod.rs
index 243014519e..3565610ca9 100644
--- a/rust/datafusion/src/physical_plan/mod.rs
+++ b/rust/datafusion/src/physical_plan/mod.rs
@@ -21,7 +21,7 @@ use std::any::Any;
use std::cell::RefCell;
use std::fmt::{Debug, Display};
use std::rc::Rc;
-use std::sync::{Arc, Mutex};
+use std::sync::Arc;
use crate::execution::context::ExecutionContextState;
use crate::logical_plan::LogicalPlan;
@@ -31,6 +31,7 @@ use arrow::record_batch::{RecordBatch, RecordBatchReader};
use arrow::{array::ArrayRef, datatypes::Field};
use async_trait::async_trait;
+type Source = Box<dyn RecordBatchReader + Send>;
/// Physical query planner that converts a `LogicalPlan` to an
/// `ExecutionPlan` suitable for execution.
@@ -67,11 +68,9 @@ pub trait ExecutionPlan: Debug + Send + Sync {
&self,
children: Vec<Arc<dyn ExecutionPlan>>,
) -> Result<Arc<dyn ExecutionPlan>>;
- /// Execute one partition and return an iterator over RecordBatch
- async fn execute(
- &self,
- partition: usize,
- ) -> Result<Arc<Mutex<dyn RecordBatchReader + Send + Sync>>>;
+
+ /// creates an iterator
+ async fn execute(&self, partition: usize) -> Result<Source>;
}
/// Partitioning schemes supported by operators.
diff --git a/rust/datafusion/src/physical_plan/parquet.rs b/rust/datafusion/src/physical_plan/parquet.rs
index 83525f9364..6b6d475160 100644
--- a/rust/datafusion/src/physical_plan/parquet.rs
+++ b/rust/datafusion/src/physical_plan/parquet.rs
@@ -20,7 +20,7 @@
use std::any::Any;
use std::fs::File;
use std::rc::Rc;
-use std::sync::{Arc, Mutex};
+use std::sync::Arc;
use std::{fmt, thread};
use crate::error::{ExecutionError, Result};
@@ -35,6 +35,7 @@ use crossbeam::channel::{bounded, Receiver, RecvError, Sender};
use fmt::Debug;
use parquet::arrow::{ArrowReader, ParquetFileArrowReader};
+use super::Source;
use async_trait::async_trait;
/// Execution plan for scanning a Parquet file
@@ -124,10 +125,7 @@ impl ExecutionPlan for ParquetExec {
}
}
- async fn execute(
- &self,
- partition: usize,
- ) -> Result<Arc<Mutex<dyn RecordBatchReader + Send + Sync>>> {
+ async fn execute(&self, partition: usize) -> Result<Source> {
// because the parquet implementation is not thread-safe, it is necessary to execute
// on a thread and communicate with channels
let (response_tx, response_rx): (
@@ -145,10 +143,10 @@ impl ExecutionPlan for ParquetExec {
}
});
- let iterator = Arc::new(Mutex::new(ParquetIterator {
+ let iterator = Box::new(ParquetIterator {
schema: self.schema.clone(),
response_rx,
- }));
+ });
Ok(iterator)
}
@@ -235,8 +233,7 @@ mod tests {
let parquet_exec = ParquetExec::try_new(&filename, Some(vec![0, 1, 2]), 1024)?;
assert_eq!(parquet_exec.output_partitioning().partition_count(), 1);
- let results = parquet_exec.execute(0).await?;
- let mut results = results.lock().unwrap();
+ let mut results = parquet_exec.execute(0).await?;
let batch = results.next().unwrap()?;
assert_eq!(8, batch.num_rows());
diff --git a/rust/datafusion/src/physical_plan/planner.rs b/rust/datafusion/src/physical_plan/planner.rs
index 3335f93854..d899046bdd 100644
--- a/rust/datafusion/src/physical_plan/planner.rs
+++ b/rust/datafusion/src/physical_plan/planner.rs
@@ -546,16 +546,16 @@ impl ExtensionPlanner for DefaultExtensionPlanner {
#[cfg(test)]
mod tests {
use super::*;
- use crate::logical_plan::{col, lit, sum, LogicalPlanBuilder};
use crate::physical_plan::{csv::CsvReadOptions, expressions, Partitioning};
- use crate::{prelude::ExecutionConfig, test::arrow_testdata_path};
- use arrow::{
- datatypes::{DataType, Field, SchemaRef},
- record_batch::RecordBatchReader,
+ use crate::{
+ logical_plan::{col, lit, sum, LogicalPlanBuilder},
+ physical_plan::Source,
};
+ use crate::{prelude::ExecutionConfig, test::arrow_testdata_path};
+ use arrow::datatypes::{DataType, Field, SchemaRef};
use async_trait::async_trait;
use fmt::Debug;
- use std::{any::Any, collections::HashMap, fmt, sync::Mutex};
+ use std::{any::Any, collections::HashMap, fmt};
fn make_ctx_state() -> ExecutionContextState {
ExecutionContextState {
@@ -800,11 +800,7 @@ mod tests {
unimplemented!("NoOpExecutionPlan::with_new_children");
}
- /// Execute one partition and return an iterator over RecordBatch
- async fn execute(
- &self,
- _partition: usize,
- ) -> Result<Arc<Mutex<dyn RecordBatchReader + Send + Sync>>> {
+ async fn execute(&self, _partition: usize) -> Result<Source> {
unimplemented!("NoOpExecutionPlan::execute");
}
}
diff --git a/rust/datafusion/src/physical_plan/projection.rs b/rust/datafusion/src/physical_plan/projection.rs
index 9c74dbd91a..dc3e0799d1 100644
--- a/rust/datafusion/src/physical_plan/projection.rs
+++ b/rust/datafusion/src/physical_plan/projection.rs
@@ -21,7 +21,7 @@
//! projection expressions.
use std::any::Any;
-use std::sync::{Arc, Mutex};
+use std::sync::Arc;
use crate::error::{ExecutionError, Result};
use crate::physical_plan::{ExecutionPlan, Partitioning, PhysicalExpr};
@@ -29,6 +29,7 @@ use arrow::datatypes::{Field, Schema, SchemaRef};
use arrow::error::Result as ArrowResult;
use arrow::record_batch::{RecordBatch, RecordBatchReader};
+use super::Source;
use async_trait::async_trait;
/// Execution plan for a projection
@@ -107,15 +108,12 @@ impl ExecutionPlan for ProjectionExec {
}
}
- async fn execute(
- &self,
- partition: usize,
- ) -> Result<Arc<Mutex<dyn RecordBatchReader + Send + Sync>>> {
- Ok(Arc::new(Mutex::new(ProjectionIterator {
+ async fn execute(&self, partition: usize) -> Result<Source> {
+ Ok(Box::new(ProjectionIterator {
schema: self.schema.clone(),
expr: self.expr.iter().map(|x| x.0.clone()).collect(),
input: self.input.execute(partition).await?,
- })))
+ }))
}
}
@@ -123,15 +121,14 @@ impl ExecutionPlan for ProjectionExec {
struct ProjectionIterator {
schema: SchemaRef,
expr: Vec<Arc<dyn PhysicalExpr>>,
- input: Arc<Mutex<dyn RecordBatchReader + Send + Sync>>,
+ input: Source,
}
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() {
+ match self.input.next() {
Some(Ok(batch)) => Some(
self.expr
.iter()
@@ -181,7 +178,6 @@ mod tests {
for partition in 0..projection.output_partitioning().partition_count() {
partition_count += 1;
let iterator = projection.execute(partition).await?;
- let mut iterator = iterator.lock().unwrap();
row_count += iterator
.into_iter()
diff --git a/rust/datafusion/src/physical_plan/sort.rs b/rust/datafusion/src/physical_plan/sort.rs
index 139bb4285e..0eb3b08894 100644
--- a/rust/datafusion/src/physical_plan/sort.rs
+++ b/rust/datafusion/src/physical_plan/sort.rs
@@ -18,19 +18,20 @@
//! Defines the SORT plan
use std::any::Any;
-use std::sync::{Arc, Mutex};
+use std::sync::Arc;
use arrow::array::ArrayRef;
pub use arrow::compute::SortOptions;
use arrow::compute::{concat, lexsort_to_indices, take, SortColumn, TakeOptions};
use arrow::datatypes::SchemaRef;
-use arrow::record_batch::{RecordBatch, RecordBatchReader};
+use arrow::record_batch::RecordBatch;
use crate::error::{ExecutionError, Result};
use crate::physical_plan::common::RecordBatchIterator;
use crate::physical_plan::expressions::PhysicalSortExpr;
use crate::physical_plan::{common, Distribution, ExecutionPlan, Partitioning};
+use super::Source;
use async_trait::async_trait;
/// Sort execution plan
@@ -99,10 +100,7 @@ impl ExecutionPlan for SortExec {
}
}
- async fn execute(
- &self,
- partition: usize,
- ) -> Result<Arc<Mutex<dyn RecordBatchReader + Send + Sync>>> {
+ async fn execute(&self, partition: usize) -> Result<Source> {
if 0 != partition {
return Err(ExecutionError::General(format!(
"SortExec invalid partition {}",
@@ -166,10 +164,10 @@ impl ExecutionPlan for SortExec {
.collect::<Result<Vec<ArrayRef>>>()?,
)?;
- Ok(Arc::new(Mutex::new(RecordBatchIterator::new(
+ Ok(Box::new(RecordBatchIterator::new(
self.schema(),
vec![Arc::new(sorted_batch)],
- ))))
+ )))
}
}
diff --git a/rust/datafusion/tests/user_defined_plan.rs b/rust/datafusion/tests/user_defined_plan.rs
index 03bc173b2b..71957f2197 100644
--- a/rust/datafusion/tests/user_defined_plan.rs
+++ b/rust/datafusion/tests/user_defined_plan.rs
@@ -78,12 +78,7 @@ use datafusion::{
prelude::{ExecutionConfig, ExecutionContext},
};
use fmt::Debug;
-use std::{
- any::Any,
- collections::BTreeMap,
- fmt,
- sync::{Arc, Mutex},
-};
+use std::{any::Any, collections::BTreeMap, fmt, sync::Arc};
use async_trait::async_trait;
@@ -400,7 +395,7 @@ impl ExecutionPlan for TopKExec {
async fn execute(
&self,
partition: usize,
- ) -> Result<Arc<Mutex<dyn RecordBatchReader + Send + Sync>>> {
+ ) -> Result<Box<dyn RecordBatchReader + Send>> {
if 0 != partition {
return Err(ExecutionError::General(format!(
"TopKExec invalid partition {}",
@@ -408,71 +403,74 @@ impl ExecutionPlan for TopKExec {
)));
}
- Ok(Arc::new(Mutex::new(TopKReader {
+ Ok(Box::new(TopKReader {
input: self.input.execute(partition).await?,
k: self.k,
- top_values: BTreeMap::new(),
done: false,
- })))
+ }))
}
}
// A very specialized TopK implementation
struct TopKReader {
/// The input to read data from
- input: Arc<Mutex<dyn RecordBatchReader + Send + Sync>>,
+ input: Box<dyn RecordBatchReader + Send>,
/// Maximum number of output values
k: usize,
- /// Hard coded implementation for sales / customer_id example
- top_values: BTreeMap<i64, String>,
/// Have we produced the output yet?
done: bool,
}
-impl TopKReader {
- /// Keeps track of the revenue from customer_id and stores if it
- /// is the top values we have seen so far.
- fn add_row(&mut self, customer_id: &str, revenue: i64) {
- self.top_values.insert(revenue, customer_id.into());
- // only keep top k
- while self.top_values.len() > self.k {
- self.remove_lowest_value()
- }
+/// Keeps track of the revenue from customer_id and stores if it
+/// is the top values we have seen so far.
+fn add_row(
+ top_values: &mut BTreeMap<i64, String>,
+ customer_id: &str,
+ revenue: i64,
+ k: &usize,
+) {
+ top_values.insert(revenue, customer_id.into());
+ // only keep top k
+ while top_values.len() > *k {
+ remove_lowest_value(top_values)
}
+}
- fn remove_lowest_value(&mut self) {
- if !self.top_values.is_empty() {
- let smallest_revenue = {
- let (revenue, _) = self.top_values.iter().next().unwrap();
- *revenue
- };
- self.top_values.remove(&smallest_revenue);
- }
+fn remove_lowest_value(top_values: &mut BTreeMap<i64, String>) {
+ if !top_values.is_empty() {
+ let smallest_revenue = {
+ let (revenue, _) = top_values.iter().next().unwrap();
+ *revenue
+ };
+ top_values.remove(&smallest_revenue);
}
+}
- // 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(())
+fn accumulate_batch(
+ input_batch: &RecordBatch,
+ top_values: &mut BTreeMap<i64, String>,
+ k: &usize,
+) -> 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 {
+ add_row(top_values, customer_id.value(row), revenue.value(row), k);
}
+ Ok(())
}
impl Iterator for TopKReader {
@@ -484,18 +482,22 @@ impl Iterator for TopKReader {
return None;
}
+ // Hard coded implementation for sales / customer_id example
+ let mut top_values: BTreeMap<i64, String> = BTreeMap::new();
+
+ // take this as immutable
+ let k = &self.k;
+
self.input
- .clone()
- .lock()
- .unwrap()
+ .as_mut()
.into_iter()
- .map(|batch| self.accumulate_batch(&batch?))
+ .map(|batch| accumulate_batch(&batch?, &mut top_values, k))
.collect::<Result<()>>()
.unwrap();
// make output by walking over the map backwards (so values are descending)
let (revenue, customer): (Vec<i64>, Vec<&String>) =
- self.top_values.iter().rev().unzip();
+ top_values.iter().rev().unzip();
let customer: Vec<&str> = customer.iter().map(|&s| &**s).collect();
@@ -512,6 +514,6 @@ impl Iterator for TopKReader {
impl RecordBatchReader for TopKReader {
fn schema(&self) -> SchemaRef {
- self.input.lock().expect("locked input reader").schema()
+ self.input.schema()
}
}