Apache DataFusion SQL Query Engine
ARROW-9464: [Rust] [DataFusion] Physical plan optimization rule to insert MergeExec when needed
Andy Grove8e20b3598ec4
diff --git a/rust/datafusion/src/execution/context.rs b/rust/datafusion/src/execution/context.rsindex 5a7adaa0c2..7b0c8e97c6 100644--- a/rust/datafusion/src/execution/context.rs+++ b/rust/datafusion/src/execution/context.rs@@ -339,7 +339,6 @@ impl ExecutionContext {_ => {// merge into a single partitionlet plan = MergeExec::new(- plan.schema().clone(),plan.clone(),self.state.lock()diff --git a/rust/datafusion/src/execution/physical_plan/csv.rs b/rust/datafusion/src/execution/physical_plan/csv.rsindex ca3525468c..2d9c05c94c 100644--- a/rust/datafusion/src/execution/physical_plan/csv.rs+++ b/rust/datafusion/src/execution/physical_plan/csv.rs@@ -103,7 +103,7 @@ impl<'a> CsvReadOptions<'a> {}/// Execution plan for scanning a CSV file-#[derive(Debug)]+#[derive(Debug, Clone)]pub struct CsvExec {/// Path to directory containing partitioned CSV files with the same schemapath: String,@@ -189,6 +189,25 @@ impl ExecutionPlan for CsvExec {Partitioning::UnknownPartitioning(self.filenames.len())}+ fn children(&self) -> Vec<Arc<dyn ExecutionPlan>> {+ // this is a leaf node and has no children+ vec![]+ }++ fn with_new_children(+ &self,+ children: Vec<Arc<dyn ExecutionPlan>>,+ ) -> Result<Arc<dyn ExecutionPlan>> {+ if children.is_empty() {+ Ok(Arc::new(self.clone()))+ } else {+ Err(ExecutionError::General(format!(+ "Children cannot be replaced in {:?}",+ self+ )))+ }+ }+fn execute(&self,partition: usize,diff --git a/rust/datafusion/src/execution/physical_plan/explain.rs b/rust/datafusion/src/execution/physical_plan/explain.rsindex b14fe5cf68..6c48742d6b 100644--- a/rust/datafusion/src/execution/physical_plan/explain.rs+++ b/rust/datafusion/src/execution/physical_plan/explain.rs@@ -17,7 +17,7 @@//! Defines the EXPLAIN operator-use crate::error::Result;+use crate::error::{ExecutionError, Result};use crate::{execution::physical_plan::{common::RecordBatchIterator, ExecutionPlan},logicalplan::StringifiedPlan,@@ -34,7 +34,7 @@ use std::sync::{Arc, Mutex};/// Explain execution plan operator. This operator contains the string/// values of the various plans it has when it is created, and passes/// them to its output.-#[derive(Debug)]+#[derive(Debug, Clone)]pub struct ExplainExec {/// The schema that this exec plan node outputsschema: SchemaRef,@@ -58,16 +58,39 @@ impl ExecutionPlan for ExplainExec {self.schema.clone()}+ fn children(&self) -> Vec<Arc<dyn ExecutionPlan>> {+ // this is a leaf node and has no children+ vec![]+ }+/// Get the output partitioning of this planfn output_partitioning(&self) -> Partitioning {Partitioning::UnknownPartitioning(1)}+ fn with_new_children(+ &self,+ children: Vec<Arc<dyn ExecutionPlan>>,+ ) -> Result<Arc<dyn ExecutionPlan>> {+ if children.is_empty() {+ Ok(Arc::new(self.clone()))+ } else {+ Err(ExecutionError::General(format!(+ "Children cannot be replaced in {:?}",+ self+ )))+ }+ }fn execute(&self,partition: usize,) -> Result<Arc<Mutex<dyn RecordBatchReader + Send + Sync>>> {- assert_eq!(0, partition);+ if 0 != partition {+ return Err(ExecutionError::General(format!(+ "ExplainExec invalid partition {}",+ partition+ )));+ }let mut type_builder = StringArray::builder(self.stringified_plans.len());let mut plan_builder = StringArray::builder(self.stringified_plans.len());diff --git a/rust/datafusion/src/execution/physical_plan/filter.rs b/rust/datafusion/src/execution/physical_plan/filter.rsindex c5f29b574b..8a5319dd71 100644--- a/rust/datafusion/src/execution/physical_plan/filter.rs+++ b/rust/datafusion/src/execution/physical_plan/filter.rs@@ -64,11 +64,30 @@ impl ExecutionPlan for FilterExec {self.input.schema()}+ fn children(&self) -> Vec<Arc<dyn ExecutionPlan>> {+ vec![self.input.clone()]+ }+/// Get the output partitioning of this planfn output_partitioning(&self) -> Partitioning {self.input.output_partitioning()}+ fn with_new_children(+ &self,+ children: Vec<Arc<dyn ExecutionPlan>>,+ ) -> Result<Arc<dyn ExecutionPlan>> {+ match children.len() {+ 1 => Ok(Arc::new(FilterExec::try_new(+ self.predicate.clone(),+ children[0].clone(),+ )?)),+ _ => Err(ExecutionError::General(+ "FilterExec wrong number of children".to_string(),+ )),+ }+ }+fn execute(&self,partition: usize,diff --git a/rust/datafusion/src/execution/physical_plan/hash_aggregate.rs b/rust/datafusion/src/execution/physical_plan/hash_aggregate.rsindex 0678121021..782786d42e 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, ExecutionPlan, Partitioning, PhysicalExpr,+ Accumulator, AggregateExpr, Distribution, ExecutionPlan, Partitioning, PhysicalExpr,};use arrow::array::{@@ -44,11 +44,21 @@ use crate::execution::physical_plan::expressions::col;use crate::logicalplan::ScalarValue;use fnv::FnvHashMap;+/// Hash aggregate modes+#[derive(Debug, Copy, Clone)]+pub enum AggregateMode {+ /// Partial aggregate that can be applied in parallel across input partitions+ Partial,+ /// Final aggregate that produces a single partition of output+ Final,+}+/// Hash aggregate execution plan#[derive(Debug)]pub struct HashAggregateExec {- group_expr: Vec<Arc<dyn PhysicalExpr>>,- aggr_expr: Vec<Arc<dyn AggregateExpr>>,+ mode: AggregateMode,+ group_expr: Vec<(Arc<dyn PhysicalExpr>, String)>,+ aggr_expr: Vec<(Arc<dyn AggregateExpr>, String)>,input: Arc<dyn ExecutionPlan>,schema: SchemaRef,}@@ -56,6 +66,7 @@ pub struct HashAggregateExec {impl HashAggregateExec {/// Create a new hash aggregate execution planpub fn try_new(+ mode: AggregateMode,group_expr: Vec<(Arc<dyn PhysicalExpr>, String)>,aggr_expr: Vec<(Arc<dyn AggregateExpr>, String)>,input: Arc<dyn ExecutionPlan>,@@ -80,8 +91,9 @@ impl HashAggregateExec {let schema = Arc::new(Schema::new(fields));Ok(HashAggregateExec {- group_expr: group_expr.iter().map(|x| x.0.clone()).collect(),- aggr_expr: aggr_expr.iter().map(|x| x.0.clone()).collect(),+ mode,+ group_expr,+ aggr_expr,input,schema,})@@ -99,7 +111,7 @@ impl HashAggregateExec {.collect();let final_aggr: Vec<Arc<dyn AggregateExpr>> = (0..self.aggr_expr.len())- .map(|i| self.aggr_expr[i].create_reducer(&agg_names[i]))+ .map(|i| self.aggr_expr[i].0.create_reducer(&agg_names[i])).collect();(final_group, final_aggr)@@ -111,6 +123,17 @@ impl ExecutionPlan for HashAggregateExec {self.schema.clone()}+ fn children(&self) -> Vec<Arc<dyn ExecutionPlan>> {+ vec![self.input.clone()]+ }++ fn required_child_distribution(&self) -> Distribution {+ match &self.mode {+ AggregateMode::Partial => Distribution::UnspecifiedDistribution,+ AggregateMode::Final => Distribution::SinglePartition,+ }+ }+/// Get the output partitioning of this planfn output_partitioning(&self) -> Partitioning {self.input.output_partitioning()@@ -121,21 +144,40 @@ impl ExecutionPlan for HashAggregateExec {partition: usize,) -> Result<Arc<Mutex<dyn RecordBatchReader + Send + Sync>>> {let input = self.input.execute(partition)?;+ let group_expr = self.group_expr.iter().map(|x| x.0.clone()).collect();+ let aggr_expr = self.aggr_expr.iter().map(|x| x.0.clone()).collect();if self.group_expr.is_empty() {Ok(Arc::new(Mutex::new(HashAggregateIterator::new(self.schema.clone(),- self.aggr_expr.clone(),+ aggr_expr,input,))))} else {Ok(Arc::new(Mutex::new(GroupedHashAggregateIterator::new(self.schema.clone(),- self.group_expr.clone(),- self.aggr_expr.clone(),+ group_expr,+ aggr_expr,input,))))}}++ fn with_new_children(+ &self,+ children: Vec<Arc<dyn ExecutionPlan>>,+ ) -> Result<Arc<dyn ExecutionPlan>> {+ match children.len() {+ 1 => Ok(Arc::new(HashAggregateExec::try_new(+ self.mode,+ self.group_expr.clone(),+ self.aggr_expr.clone(),+ children[0].clone(),+ )?)),+ _ => Err(ExecutionError::General(+ "HashAggregateExec wrong number of children".to_string(),+ )),+ }+ }}/// Create array from single accumulator value@@ -689,23 +731,23 @@ mod tests {let aggregates: Vec<(Arc<dyn AggregateExpr>, String)> =vec![(sum(col("c4")), "SUM(c4)".to_string())];- let partition_aggregate = Arc::new(HashAggregateExec::try_new(+ let partial_aggregate = Arc::new(HashAggregateExec::try_new(+ AggregateMode::Partial,groups.clone(),aggregates.clone(),Arc::new(csv),)?);- let schema = partition_aggregate.schema();-// construct the expressions for the final aggregation- let (final_group, final_aggr) = partition_aggregate.make_final_expr(+ let (final_group, final_aggr) = partial_aggregate.make_final_expr(groups.iter().map(|x| x.1.clone()).collect(),aggregates.iter().map(|x| x.1.clone()).collect(),);- let merge = Arc::new(MergeExec::new(schema.clone(), partition_aggregate, 2));+ let merge = Arc::new(MergeExec::new(partial_aggregate, 2));let merged_aggregate = Arc::new(HashAggregateExec::try_new(+ AggregateMode::Final,final_group.iter().enumerate()diff --git a/rust/datafusion/src/execution/physical_plan/limit.rs b/rust/datafusion/src/execution/physical_plan/limit.rsindex 862ac240e1..9ab5f90d17 100644--- a/rust/datafusion/src/execution/physical_plan/limit.rs+++ b/rust/datafusion/src/execution/physical_plan/limit.rs@@ -20,10 +20,8 @@use std::sync::{Arc, Mutex};use crate::error::{ExecutionError, Result};-use crate::execution::physical_plan::common::{self, RecordBatchIterator};use crate::execution::physical_plan::memory::MemoryIterator;-use crate::execution::physical_plan::merge::MergeExec;-use crate::execution::physical_plan::{ExecutionPlan, Partitioning};+use crate::execution::physical_plan::{Distribution, ExecutionPlan, Partitioning};use arrow::array::ArrayRef;use arrow::compute::limit;use arrow::datatypes::SchemaRef;@@ -32,9 +30,7 @@ use arrow::record_batch::{RecordBatch, RecordBatchReader};/// Limit execution plan#[derive(Debug)]pub struct GlobalLimitExec {- /// Input schema- schema: SchemaRef,- /// Input partitions+ /// Input execution planinput: Arc<dyn ExecutionPlan>,/// Maximum number of rows to returnlimit: usize,@@ -44,14 +40,8 @@ pub struct GlobalLimitExec {impl GlobalLimitExec {/// Create a new MergeExec- pub fn new(- schema: SchemaRef,- input: Arc<dyn ExecutionPlan>,- limit: usize,- concurrency: usize,- ) -> Self {+ pub fn new(input: Arc<dyn ExecutionPlan>, limit: usize, concurrency: usize) -> Self {GlobalLimitExec {- schema,input,limit,concurrency,@@ -61,7 +51,15 @@ impl GlobalLimitExec {impl ExecutionPlan for GlobalLimitExec {fn schema(&self) -> SchemaRef {- self.schema.clone()+ self.input.schema()+ }++ fn children(&self) -> Vec<Arc<dyn ExecutionPlan>> {+ vec![self.input.clone()]+ }++ fn required_child_distribution(&self) -> Distribution {+ Distribution::SinglePartition}/// Get the output partitioning of this plan@@ -69,68 +67,61 @@ impl ExecutionPlan for GlobalLimitExec {Partitioning::UnknownPartitioning(1)}+ fn with_new_children(+ &self,+ children: Vec<Arc<dyn ExecutionPlan>>,+ ) -> Result<Arc<dyn ExecutionPlan>> {+ match children.len() {+ 1 => Ok(Arc::new(GlobalLimitExec::new(+ children[0].clone(),+ self.limit,+ self.concurrency,+ ))),+ _ => Err(ExecutionError::General(+ "GlobalLimitExec wrong number of children".to_string(),+ )),+ }+ }+fn execute(&self,partition: usize,) -> Result<Arc<Mutex<dyn RecordBatchReader + Send + Sync>>> {- // GlobalLimitExec has a single partition- assert_eq!(0, partition);-- // apply limit in parallel across all input partitions- let local_limit = Arc::new(LocalLimitExec::new(- self.input.clone(),- self.schema.clone(),- self.limit,- ));-- // limit needs to collapse inputs down to a single partition- let merge = MergeExec::new(self.schema.clone(), local_limit, self.concurrency);- // MergeExec must always produce a single partition- assert_eq!(1, merge.output_partitioning().partition_count());- let it = merge.execute(0)?;- let batches = common::collect(it)?;-- // apply the limit to the output- let mut combined_results: Vec<Arc<RecordBatch>> = vec![];- let mut count = 0;- for batch in batches {- let capacity = self.limit - count;- if batch.num_rows() <= capacity {- count += batch.num_rows();- combined_results.push(Arc::new(batch.clone()))- } else {- let batch = truncate_batch(&batch, capacity)?;- count += batch.num_rows();- combined_results.push(Arc::new(batch.clone()))- }- if count == self.limit {- break;- }+ // GlobalLimitExec has a single output partition+ if 0 != partition {+ return Err(ExecutionError::General(format!(+ "GlobalLimitExec invalid partition {}",+ partition+ )));+ }++ // GlobalLimitExec requires a single input partition+ if 1 != self.input.output_partitioning().partition_count() {+ return Err(ExecutionError::General(+ "GlobalLimitExec requires a single input partition".to_owned(),+ ));}- Ok(Arc::new(Mutex::new(RecordBatchIterator::new(- self.schema.clone(),- combined_results,- ))))+ let it = self.input.execute(0)?;+ Ok(Arc::new(Mutex::new(MemoryIterator::try_new(+ collect_with_limit(it, self.limit)?,+ self.input.schema(),+ None,+ )?)))}}-/// LocalLimitExec applies a limit so a single partition+/// LocalLimitExec applies a limit to a single partition#[derive(Debug)]pub struct LocalLimitExec {input: Arc<dyn ExecutionPlan>,- schema: SchemaRef,limit: usize,}impl LocalLimitExec {/// Create a new LocalLimitExec partition- pub fn new(input: Arc<dyn ExecutionPlan>, schema: SchemaRef, limit: usize) -> Self {- Self {- input,- schema,- limit,- }+ pub fn new(input: Arc<dyn ExecutionPlan>, limit: usize) -> Self {+ Self { input, limit }}}@@ -139,10 +130,29 @@ impl ExecutionPlan for LocalLimitExec {self.input.schema()}+ fn children(&self) -> Vec<Arc<dyn ExecutionPlan>> {+ vec![self.input.clone()]+ }+fn output_partitioning(&self) -> Partitioning {self.input.output_partitioning()}+ fn with_new_children(+ &self,+ children: Vec<Arc<dyn ExecutionPlan>>,+ ) -> Result<Arc<dyn ExecutionPlan>> {+ match children.len() {+ 1 => Ok(Arc::new(LocalLimitExec::new(+ children[0].clone(),+ self.limit,+ ))),+ _ => Err(ExecutionError::General(+ "LocalLimitExec wrong number of children".to_string(),+ )),+ }+ }+fn execute(&self,partition: usize,@@ -150,7 +160,7 @@ impl ExecutionPlan for LocalLimitExec {let it = self.input.execute(partition)?;Ok(Arc::new(Mutex::new(MemoryIterator::try_new(collect_with_limit(it, self.limit)?,- self.schema.clone(),+ self.input.schema(),None,)?)))}@@ -207,6 +217,7 @@ mod tests {use super::*;use crate::execution::physical_plan::common;use crate::execution::physical_plan::csv::{CsvExec, CsvReadOptions};+ use crate::execution::physical_plan::merge::MergeExec;use crate::test;#[test]@@ -223,7 +234,8 @@ mod tests {// input should have 4 partitionsassert_eq!(csv.output_partitioning().partition_count(), num_partitions);- let limit = GlobalLimitExec::new(schema.clone(), Arc::new(csv), 7, 2);+ let limit =+ GlobalLimitExec::new(Arc::new(MergeExec::new(Arc::new(csv), 2)), 7, 2);// the result should contain 4 batches (one per input partition)let iter = limit.execute(0)?;diff --git a/rust/datafusion/src/execution/physical_plan/memory.rs b/rust/datafusion/src/execution/physical_plan/memory.rsindex 096cecb7eb..23338c0e60 100644--- a/rust/datafusion/src/execution/physical_plan/memory.rs+++ b/rust/datafusion/src/execution/physical_plan/memory.rs@@ -19,7 +19,7 @@use std::sync::{Arc, Mutex};-use crate::error::Result;+use crate::error::{ExecutionError, Result};use crate::execution::physical_plan::{ExecutionPlan, Partitioning};use arrow::datatypes::SchemaRef;use arrow::error::Result as ArrowResult;@@ -42,11 +42,26 @@ impl ExecutionPlan for MemoryExec {self.schema.clone()}+ fn children(&self) -> Vec<Arc<dyn ExecutionPlan>> {+ // this is a leaf node and has no children+ vec![]+ }+/// Get the output partitioning of this planfn output_partitioning(&self) -> Partitioning {Partitioning::UnknownPartitioning(self.partitions.len())}+ fn with_new_children(+ &self,+ _: Vec<Arc<dyn ExecutionPlan>>,+ ) -> Result<Arc<dyn ExecutionPlan>> {+ Err(ExecutionError::General(format!(+ "Children cannot be replaced in {:?}",+ self+ )))+ }+fn execute(&self,partition: usize,diff --git a/rust/datafusion/src/execution/physical_plan/merge.rs b/rust/datafusion/src/execution/physical_plan/merge.rsindex 9d36d6a3d5..e957a04f8f 100644--- a/rust/datafusion/src/execution/physical_plan/merge.rs+++ b/rust/datafusion/src/execution/physical_plan/merge.rs@@ -33,9 +33,7 @@ use arrow::record_batch::{RecordBatch, RecordBatchReader};/// partition. No guarantees are made about the order of the resulting partition.#[derive(Debug)]pub struct MergeExec {- /// Input schema- schema: SchemaRef,- /// Input partitions+ /// Input execution planinput: Arc<dyn ExecutionPlan>,/// Maximum number of concurrent threadsconcurrency: usize,@@ -43,13 +41,8 @@ pub struct MergeExec {impl MergeExec {/// Create a new MergeExec- pub fn new(- schema: SchemaRef,- input: Arc<dyn ExecutionPlan>,- max_concurrency: usize,- ) -> Self {+ pub fn new(input: Arc<dyn ExecutionPlan>, max_concurrency: usize) -> Self {MergeExec {- schema,input,concurrency: max_concurrency,}@@ -58,7 +51,11 @@ impl MergeExec {impl ExecutionPlan for MergeExec {fn schema(&self) -> SchemaRef {- self.schema.clone()+ self.input.schema()+ }++ fn children(&self) -> Vec<Arc<dyn ExecutionPlan>> {+ vec![self.input.clone()]}/// Get the output partitioning of this plan@@ -66,12 +63,32 @@ impl ExecutionPlan for MergeExec {Partitioning::UnknownPartitioning(1)}+ fn with_new_children(+ &self,+ children: Vec<Arc<dyn ExecutionPlan>>,+ ) -> Result<Arc<dyn ExecutionPlan>> {+ match children.len() {+ 1 => Ok(Arc::new(MergeExec::new(+ children[0].clone(),+ self.concurrency,+ ))),+ _ => Err(ExecutionError::General(+ "MergeExec wrong number of children".to_string(),+ )),+ }+ }+fn execute(&self,partition: usize,) -> Result<Arc<Mutex<dyn RecordBatchReader + Send + Sync>>> {// MergeExec produces a single partition- assert_eq!(0, partition);+ if 0 != partition {+ return Err(ExecutionError::General(format!(+ "MergeExec invalid partition {}",+ partition+ )));+ }let input_partitions = self.input.output_partitioning().partition_count();match input_partitions {@@ -110,7 +127,7 @@ impl ExecutionPlan for MergeExec {}Ok(Arc::new(Mutex::new(RecordBatchIterator::new(- self.schema.clone(),+ self.input.schema(),combined_results,))))}@@ -158,7 +175,7 @@ mod tests {// input should have 4 partitionsassert_eq!(csv.output_partitioning().partition_count(), num_partitions);- let merge = MergeExec::new(schema.clone(), Arc::new(csv), 2);+ let merge = MergeExec::new(Arc::new(csv), 2);// output of MergeExec should have a single partitionassert_eq!(merge.output_partitioning().partition_count(), 1);diff --git a/rust/datafusion/src/execution/physical_plan/mod.rs b/rust/datafusion/src/execution/physical_plan/mod.rsindex 80686f739d..f79907d2f0 100644--- a/rust/datafusion/src/execution/physical_plan/mod.rs+++ b/rust/datafusion/src/execution/physical_plan/mod.rs@@ -50,6 +50,20 @@ pub trait ExecutionPlan: Debug + Send + Sync {fn schema(&self) -> SchemaRef;/// Specifies the output partitioning scheme of this planfn output_partitioning(&self) -> Partitioning;+ /// Specifies the data distribution requirements of all the children for this operator+ fn required_child_distribution(&self) -> Distribution {+ Distribution::UnspecifiedDistribution+ }+ /// Get a list of child execution plans that provide the input for this plan. The returned list+ /// will be empty for leaf nodes, will contain a single value for unary nodes, or two+ /// values for binary nodes (such as joins).+ fn children(&self) -> Vec<Arc<dyn ExecutionPlan>>;+ /// Returns a new plan where all children were replaced by new plans.+ /// The size of `children` must be equal to the size of `ExecutionPlan::children()`.+ fn with_new_children(+ &self,+ children: Vec<Arc<dyn ExecutionPlan>>,+ ) -> Result<Arc<dyn ExecutionPlan>>;/// Execute one partition and return an iterator over RecordBatchfn execute(&self,@@ -74,6 +88,15 @@ impl Partitioning {}}+/// Distribution schemes+#[derive(Debug, Clone)]+pub enum Distribution {+ /// Unspecified distribution+ UnspecifiedDistribution,+ /// A single partition is required+ SinglePartition,+}+/// Expression that can be evaluated against a RecordBatch/// A Physical expression knows its type, nullability and how to evaluate itself.pub trait PhysicalExpr: Send + Sync + Display + Debug {diff --git a/rust/datafusion/src/execution/physical_plan/parquet.rs b/rust/datafusion/src/execution/physical_plan/parquet.rsindex 288856077f..3247090bea 100644--- a/rust/datafusion/src/execution/physical_plan/parquet.rs+++ b/rust/datafusion/src/execution/physical_plan/parquet.rs@@ -35,7 +35,7 @@ use fmt::Debug;use parquet::arrow::{ArrowReader, ParquetFileArrowReader};/// Execution plan for scanning a Parquet file-#[derive(Debug)]+#[derive(Debug, Clone)]pub struct ParquetExec {/// Path to directory containing partitioned Parquet files with the same schemafilenames: Vec<String>,@@ -91,11 +91,30 @@ impl ExecutionPlan for ParquetExec {self.schema.clone()}+ fn children(&self) -> Vec<Arc<dyn ExecutionPlan>> {+ // this is a leaf node and has no children+ vec![]+ }+/// Get the output partitioning of this planfn output_partitioning(&self) -> Partitioning {Partitioning::UnknownPartitioning(self.filenames.len())}+ fn with_new_children(+ &self,+ children: Vec<Arc<dyn ExecutionPlan>>,+ ) -> Result<Arc<dyn ExecutionPlan>> {+ if children.is_empty() {+ Ok(Arc::new(self.clone()))+ } else {+ Err(ExecutionError::General(format!(+ "Children cannot be replaced in {:?}",+ self+ )))+ }+ }+fn execute(&self,partition: usize,diff --git a/rust/datafusion/src/execution/physical_plan/planner.rs b/rust/datafusion/src/execution/physical_plan/planner.rsindex 7dace61823..18b86a0fe5 100644--- a/rust/datafusion/src/execution/physical_plan/planner.rs+++ b/rust/datafusion/src/execution/physical_plan/planner.rs@@ -24,19 +24,19 @@ use crate::error::{ExecutionError, Result};use crate::execution::context::ExecutionContextState;use crate::execution::physical_plan::csv::{CsvExec, CsvReadOptions};use crate::execution::physical_plan::explain::ExplainExec;-use crate::execution::physical_plan::expressions;use crate::execution::physical_plan::expressions::{Avg, Column, Count, Literal, Max, Min, PhysicalSortExpr, Sum,};use crate::execution::physical_plan::filter::FilterExec;-use crate::execution::physical_plan::hash_aggregate::HashAggregateExec;-use crate::execution::physical_plan::limit::GlobalLimitExec;+use crate::execution::physical_plan::hash_aggregate::{AggregateMode, HashAggregateExec};+use crate::execution::physical_plan::limit::{GlobalLimitExec, LocalLimitExec};use crate::execution::physical_plan::memory::MemoryExec;use crate::execution::physical_plan::merge::MergeExec;use crate::execution::physical_plan::parquet::ParquetExec;use crate::execution::physical_plan::projection::ProjectionExec;use crate::execution::physical_plan::sort::SortExec;use crate::execution::physical_plan::udf::ScalarFunctionExpr;+use crate::execution::physical_plan::{expressions, Distribution};use crate::execution::physical_plan::{AggregateExpr, ExecutionPlan, PhysicalExpr, PhysicalPlanner,};@@ -61,6 +61,55 @@ impl PhysicalPlanner for DefaultPhysicalPlanner {&self,logical_plan: &LogicalPlan,ctx_state: &ExecutionContextState,+ ) -> Result<Arc<dyn ExecutionPlan>> {+ let plan = self.create_initial_plan(logical_plan, ctx_state)?;+ self.optimize_plan(plan, ctx_state)+ }+}++impl DefaultPhysicalPlanner {+ /// Create a physical plan from a logical plan+ fn optimize_plan(+ &self,+ plan: Arc<dyn ExecutionPlan>,+ ctx_state: &ExecutionContextState,+ ) -> Result<Arc<dyn ExecutionPlan>> {+ let children = plan+ .children()+ .iter()+ .map(|child| self.optimize_plan(child.clone(), ctx_state))+ .collect::<Result<Vec<_>>>()?;++ if children.len() == 0 {+ // leaf node, children cannot be replaced+ Ok(plan.clone())+ } else {+ match plan.required_child_distribution() {+ Distribution::UnspecifiedDistribution => plan.with_new_children(children),+ Distribution::SinglePartition => plan.with_new_children(+ children+ .iter()+ .map(|child| {+ if child.output_partitioning().partition_count() == 1 {+ child.clone()+ } else {+ Arc::new(MergeExec::new(+ child.clone(),+ ctx_state.config.concurrency,+ ))+ }+ })+ .collect(),+ ),+ }+ }+ }++ /// Create a physical plan from a logical plan+ fn create_initial_plan(+ &self,+ logical_plan: &LogicalPlan,+ ctx_state: &ExecutionContextState,) -> Result<Arc<dyn ExecutionPlan>> {let batch_size = ctx_state.config.batch_size;@@ -153,26 +202,20 @@ impl PhysicalPlanner for DefaultPhysicalPlanner {.collect::<Result<Vec<_>>>()?;let initial_aggr = HashAggregateExec::try_new(+ AggregateMode::Partial,groups.clone(),aggregates.clone(),input,)?;- let schema = initial_aggr.schema();-if initial_aggr.output_partitioning().partition_count() == 1 {return Ok(Arc::new(initial_aggr));}- let initial_aggr = Arc::new(initial_aggr);- let merge = Arc::new(MergeExec::new(- schema.clone(),- initial_aggr.clone(),- ctx_state.config.concurrency,- ));+ let partial_aggr = Arc::new(initial_aggr);// construct the expressions for the final aggregation- let (final_group, final_aggr) = initial_aggr.make_final_expr(+ let (final_group, final_aggr) = partial_aggr.make_final_expr(groups.iter().map(|x| x.1.clone()).collect(),aggregates.iter().map(|x| x.1.clone()).collect(),);@@ -180,6 +223,7 @@ impl PhysicalPlanner for DefaultPhysicalPlanner {// construct a second aggregation, keeping the final column name equal to the first aggregation// and the expressions corresponding to the respective aggregateOk(Arc::new(HashAggregateExec::try_new(+ AggregateMode::Final,final_group.iter().enumerate()@@ -190,7 +234,7 @@ impl PhysicalPlanner for DefaultPhysicalPlanner {.enumerate().map(|(i, expr)| (expr.clone(), aggregates[i].1.clone())).collect(),- merge,+ partial_aggr,)?))}LogicalPlan::Filter {@@ -235,13 +279,21 @@ impl PhysicalPlanner for DefaultPhysicalPlanner {)?))}LogicalPlan::Limit { input, n, .. } => {+ let limit = *n;let input = self.create_physical_plan(input, ctx_state)?;- let input_schema = input.as_ref().schema().clone();++ // GlobalLimitExec requires a single partition for input+ let input = if input.output_partitioning().partition_count() == 1 {+ input+ } else {+ // Apply a LocalLimitExec to each partition. The optimizer will also insert+ // a MergeExec between the GlobalLimitExec and LocalLimitExec+ Arc::new(LocalLimitExec::new(input, limit))+ };Ok(Arc::new(GlobalLimitExec::new(- input_schema.clone(),input,- *n,+ limit,ctx_state.config.concurrency,)))}@@ -274,9 +326,7 @@ impl PhysicalPlanner for DefaultPhysicalPlanner {)),}}-}-impl DefaultPhysicalPlanner {/// Create a physical expression from a logical expressionpub fn create_physical_expr(&self,diff --git a/rust/datafusion/src/execution/physical_plan/projection.rs b/rust/datafusion/src/execution/physical_plan/projection.rsindex ce51e894e3..b469829fa3 100644--- a/rust/datafusion/src/execution/physical_plan/projection.rs+++ b/rust/datafusion/src/execution/physical_plan/projection.rs@@ -31,8 +31,8 @@ use arrow::record_batch::{RecordBatch, RecordBatchReader};/// Execution plan for a projection#[derive(Debug)]pub struct ProjectionExec {- /// The projection expressions- expr: Vec<Arc<dyn PhysicalExpr>>,+ /// The projection expressions stored as tuples of (expression, output column name)+ expr: Vec<(Arc<dyn PhysicalExpr>, String)>,/// The schema once the projection has been applied to the inputschema: SchemaRef,/// The input plan@@ -61,7 +61,7 @@ impl ProjectionExec {let schema = Arc::new(Schema::new(fields?));Ok(Self {- expr: expr.iter().map(|x| x.0.clone()).collect(),+ expr,schema,input: input.clone(),})@@ -74,18 +74,37 @@ impl ExecutionPlan for ProjectionExec {self.schema.clone()}+ fn children(&self) -> Vec<Arc<dyn ExecutionPlan>> {+ vec![self.input.clone()]+ }+/// Get the output partitioning of this planfn output_partitioning(&self) -> Partitioning {self.input.output_partitioning()}+ fn with_new_children(+ &self,+ children: Vec<Arc<dyn ExecutionPlan>>,+ ) -> Result<Arc<dyn ExecutionPlan>> {+ match children.len() {+ 1 => Ok(Arc::new(ProjectionExec::try_new(+ self.expr.clone(),+ children[0].clone(),+ )?)),+ _ => Err(ExecutionError::General(+ "ProjectionExec wrong number of children".to_string(),+ )),+ }+ }+fn execute(&self,partition: usize,) -> Result<Arc<Mutex<dyn RecordBatchReader + Send + Sync>>> {Ok(Arc::new(Mutex::new(ProjectionIterator {schema: self.schema.clone(),- expr: self.expr.clone(),+ expr: self.expr.iter().map(|x| x.0.clone()).collect(),input: self.input.execute(partition)?,})))}diff --git a/rust/datafusion/src/execution/physical_plan/sort.rs b/rust/datafusion/src/execution/physical_plan/sort.rsindex c6d20315b0..64836a9c30 100644--- a/rust/datafusion/src/execution/physical_plan/sort.rs+++ b/rust/datafusion/src/execution/physical_plan/sort.rs@@ -25,17 +25,19 @@ use arrow::compute::{concat, lexsort_to_indices, take, SortColumn, TakeOptions};use arrow::datatypes::SchemaRef;use arrow::record_batch::{RecordBatch, RecordBatchReader};-use crate::error::Result;+use crate::error::{ExecutionError, Result};use crate::execution::physical_plan::common::RecordBatchIterator;use crate::execution::physical_plan::expressions::PhysicalSortExpr;-use crate::execution::physical_plan::merge::MergeExec;-use crate::execution::physical_plan::{common, ExecutionPlan, Partitioning};+use crate::execution::physical_plan::{+ common, Distribution, ExecutionPlan, Partitioning,+};/// Sort execution plan#[derive(Debug)]pub struct SortExec {/// Input schemainput: Arc<dyn ExecutionPlan>,+ /// Sort expressionsexpr: Vec<PhysicalSortExpr>,/// Number of threads to execute input partitions on before combining into a single partitionconcurrency: usize,@@ -61,22 +63,53 @@ impl ExecutionPlan for SortExec {self.input.schema().clone()}+ fn children(&self) -> Vec<Arc<dyn ExecutionPlan>> {+ vec![self.input.clone()]+ }+/// Get the output partitioning of this planfn output_partitioning(&self) -> Partitioning {Partitioning::UnknownPartitioning(1)}+ fn required_child_distribution(&self) -> Distribution {+ Distribution::SinglePartition+ }++ fn with_new_children(+ &self,+ children: Vec<Arc<dyn ExecutionPlan>>,+ ) -> Result<Arc<dyn ExecutionPlan>> {+ match children.len() {+ 1 => Ok(Arc::new(SortExec::try_new(+ self.expr.clone(),+ children[0].clone(),+ self.concurrency,+ )?)),+ _ => Err(ExecutionError::General(+ "SortExec wrong number of children".to_string(),+ )),+ }+ }+fn execute(&self,partition: usize,) -> Result<Arc<Mutex<dyn RecordBatchReader + Send + Sync>>> {- assert_eq!(0, partition);+ if 0 != partition {+ return Err(ExecutionError::General(format!(+ "SortExec invalid partition {}",+ partition+ )));+ }// sort needs to operate on a single partition currently- let merge = MergeExec::new(self.schema(), self.input.clone(), self.concurrency);- // MergeExec must always produce a single partition- assert_eq!(1, merge.output_partitioning().partition_count());- let it = merge.execute(0)?;+ if 1 != self.input.output_partitioning().partition_count() {+ return Err(ExecutionError::General(+ "SortExec requires a single input partition".to_owned(),+ ));+ }+ let it = self.input.execute(0)?;let batches = common::collect(it)?;// combine all record batches into one for each column@@ -138,6 +171,7 @@ mod tests {use super::*;use crate::execution::physical_plan::csv::{CsvExec, CsvReadOptions};use crate::execution::physical_plan::expressions::col;+ use crate::execution::physical_plan::merge::MergeExec;use crate::test;use arrow::array::*;use arrow::datatypes::*;@@ -168,7 +202,7 @@ mod tests {options: SortOptions::default(),},],- Arc::new(csv),+ Arc::new(MergeExec::new(Arc::new(csv), 2)),2,)?);