Apache DataFusion SQL Query Engine
ARROW-10582: [Rust] [DataFusion] Implement "repartition" operator
Andy Grove91f49b0b625c
diff --git a/rust/benchmarks/src/bin/tpch.rs b/rust/benchmarks/src/bin/tpch.rsindex 6c5d06cf37..8a6fca7893 100644--- a/rust/benchmarks/src/bin/tpch.rs+++ b/rust/benchmarks/src/bin/tpch.rs@@ -18,7 +18,6 @@//! Benchmark derived from TPC-H. This is not an official TPC-H benchmark.use std::path::{Path, PathBuf};-use std::sync::Arc;use std::time::Instant;use arrow::datatypes::{DataType, DateUnit, Field, Schema};@@ -28,7 +27,6 @@ use datafusion::datasource::{CsvFile, MemTable, TableProvider};use datafusion::error::{DataFusionError, Result};use datafusion::logical_plan::LogicalPlan;use datafusion::physical_plan::collect;-use datafusion::physical_plan::csv::CsvExec;use datafusion::prelude::*;use parquet::basic::Compression;@@ -87,6 +85,10 @@ struct ConvertOpt {/// Compression to use when writing Parquet files#[structopt(short = "c", long = "compression", default_value = "snappy")]compression: String,++ /// Number of partitions to produce+ #[structopt(short = "p", long = "partitions", default_value = "1")]+ partitions: usize,}#[derive(Debug, StructOpt)]@@ -1017,8 +1019,21 @@ async fn convert_tbl(opt: ConvertOpt) -> Result<()> {.delimiter(b'|').file_extension(".tbl");- let ctx = ExecutionContext::new();- let csv = Arc::new(CsvExec::try_new(&input_path, options, None, 4096)?);+ let mut ctx = ExecutionContext::new();++ // build plan to read the TBL file+ let mut csv = ctx.read_csv(&input_path, options)?;++ // optionally, repartition the file+ if opt.partitions > 1 {+ csv = csv.repartition(Partitioning::RoundRobinBatch(opt.partitions))?+ }++ // create the physical plan+ let csv = csv.to_logical_plan();+ let csv = ctx.optimize(&csv)?;+ let csv = ctx.create_physical_plan(&csv)?;+let output_path = output_root_path.join(table);let output_path = output_path.to_str().unwrap().to_owned();diff --git a/rust/datafusion/src/dataframe.rs b/rust/datafusion/src/dataframe.rsindex 6cab9299f4..1e3c1f1744 100644--- a/rust/datafusion/src/dataframe.rs+++ b/rust/datafusion/src/dataframe.rs@@ -19,7 +19,9 @@use crate::arrow::record_batch::RecordBatch;use crate::error::Result;-use crate::logical_plan::{DFSchema, Expr, FunctionRegistry, JoinType, LogicalPlan};+use crate::logical_plan::{+ DFSchema, Expr, FunctionRegistry, JoinType, LogicalPlan, Partitioning,+};use std::sync::Arc;use async_trait::async_trait;@@ -172,6 +174,23 @@ pub trait DataFrame {right_cols: &[&str],) -> Result<Arc<dyn DataFrame>>;+ /// Repartition a DataFrame based on a logical partitioning scheme.+ ///+ /// ```+ /// # use datafusion::prelude::*;+ /// # use datafusion::error::Result;+ /// # fn main() -> Result<()> {+ /// let mut ctx = ExecutionContext::new();+ /// let df = ctx.read_csv("tests/example.csv", CsvReadOptions::new())?;+ /// let df1 = df.repartition(Partitioning::RoundRobinBatch(4))?;+ /// # Ok(())+ /// # }+ /// ```+ fn repartition(+ &self,+ partitioning_scheme: Partitioning,+ ) -> Result<Arc<dyn DataFrame>>;+/// Executes this DataFrame and collects all results into a vector of RecordBatch.////// ```diff --git a/rust/datafusion/src/execution/dataframe_impl.rs b/rust/datafusion/src/execution/dataframe_impl.rsindex 3badb4fc38..22be551322 100644--- a/rust/datafusion/src/execution/dataframe_impl.rs+++ b/rust/datafusion/src/execution/dataframe_impl.rs@@ -24,6 +24,7 @@ use crate::error::Result;use crate::execution::context::{ExecutionContext, ExecutionContextState};use crate::logical_plan::{col, DFSchema, Expr, FunctionRegistry, JoinType, LogicalPlan, LogicalPlanBuilder,+ Partitioning,};use crate::{arrow::record_batch::RecordBatch, physical_plan::collect};@@ -111,6 +112,16 @@ impl DataFrame for DataFrameImpl {Ok(Arc::new(DataFrameImpl::new(self.ctx_state.clone(), &plan)))}+ fn repartition(+ &self,+ partitioning_scheme: Partitioning,+ ) -> Result<Arc<dyn DataFrame>> {+ let plan = LogicalPlanBuilder::from(&self.plan)+ .repartition(partitioning_scheme)?+ .build()?;+ Ok(Arc::new(DataFrameImpl::new(self.ctx_state.clone(), &plan)))+ }+/// Convert to logical planfn to_logical_plan(&self) -> LogicalPlan {self.plan.clone()diff --git a/rust/datafusion/src/logical_plan/builder.rs b/rust/datafusion/src/logical_plan/builder.rsindex 3a98f67632..23bf2c5ac3 100644--- a/rust/datafusion/src/logical_plan/builder.rs+++ b/rust/datafusion/src/logical_plan/builder.rs@@ -35,7 +35,7 @@ use super::dfschema::ToDFSchema;use super::{col, exprlist_to_fields, Expr, JoinType, LogicalPlan, PlanType, StringifiedPlan,};-use crate::logical_plan::{DFField, DFSchema, DFSchemaRef};+use crate::logical_plan::{DFField, DFSchema, DFSchemaRef, Partitioning};use std::collections::HashSet;/// Builder for logical plans@@ -207,6 +207,14 @@ impl LogicalPlanBuilder {}}+ /// Repartition+ pub fn repartition(&self, partitioning_scheme: Partitioning) -> Result<Self> {+ Ok(Self::from(&LogicalPlan::Repartition {+ input: Arc::new(self.plan.clone()),+ partitioning_scheme,+ }))+ }+/// Apply an aggregatepub fn aggregate(&self, group_expr: Vec<Expr>, aggr_expr: Vec<Expr>) -> Result<Self> {let mut all_expr: Vec<Expr> = group_expr.clone();diff --git a/rust/datafusion/src/logical_plan/mod.rs b/rust/datafusion/src/logical_plan/mod.rsindex 4cd4d99587..f810b0162c 100644--- a/rust/datafusion/src/logical_plan/mod.rs+++ b/rust/datafusion/src/logical_plan/mod.rs@@ -41,5 +41,7 @@ pub use expr::{};pub use extension::UserDefinedLogicalNode;pub use operators::Operator;-pub use plan::{JoinType, LogicalPlan, PlanType, PlanVisitor, StringifiedPlan};+pub use plan::{+ JoinType, LogicalPlan, Partitioning, PlanType, PlanVisitor, StringifiedPlan,+};pub use registry::FunctionRegistry;diff --git a/rust/datafusion/src/logical_plan/plan.rs b/rust/datafusion/src/logical_plan/plan.rsindex 957f2bb3e4..b228402ca1 100644--- a/rust/datafusion/src/logical_plan/plan.rs+++ b/rust/datafusion/src/logical_plan/plan.rs@@ -110,6 +110,13 @@ pub enum LogicalPlan {/// The output schema, containing fields from the left and right inputsschema: DFSchemaRef,},+ /// Repartition the plan based on a partitioning scheme.+ Repartition {+ /// The incoming logical plan+ input: Arc<LogicalPlan>,+ /// The partitioning scheme+ partitioning_scheme: Partitioning,+ },/// Produces rows from a table provider by reference or from the contextTableScan {/// The name of the table@@ -182,6 +189,7 @@ impl LogicalPlan {LogicalPlan::Aggregate { schema, .. } => &schema,LogicalPlan::Sort { input, .. } => input.schema(),LogicalPlan::Join { schema, .. } => &schema,+ LogicalPlan::Repartition { input, .. } => input.schema(),LogicalPlan::Limit { input, .. } => input.schema(),LogicalPlan::CreateExternalTable { schema, .. } => &schema,LogicalPlan::Explain { schema, .. } => &schema,@@ -198,6 +206,17 @@ impl LogicalPlan {}}+/// Logical partitioning schemes supported by the repartition operator.+#[derive(Debug, Clone)]+pub enum Partitioning {+ /// Allocate batches using a round-robin algorithm and the specified number of partitions+ RoundRobinBatch(usize),+ /// Allocate rows based on a hash of one of more expressions and the specified number+ /// of partitions.+ /// This partitioning scheme is not yet fully supported. See https://issues.apache.org/jira/browse/ARROW-11011+ Hash(Vec<Expr>, usize),+}+/// Trait that implements the [Visitor/// pattern](https://en.wikipedia.org/wiki/Visitor_pattern) for a/// depth first walk of `LogicalPlan` nodes. `pre_visit` is called@@ -261,6 +280,7 @@ impl LogicalPlan {let recurse = match self {LogicalPlan::Projection { input, .. } => input.accept(visitor)?,LogicalPlan::Filter { input, .. } => input.accept(visitor)?,+ LogicalPlan::Repartition { input, .. } => input.accept(visitor)?,LogicalPlan::Aggregate { input, .. } => input.accept(visitor)?,LogicalPlan::Sort { input, .. } => input.accept(visitor)?,LogicalPlan::Join { left, right, .. } => {@@ -464,7 +484,7 @@ impl LogicalPlan {struct Wrapper<'a>(&'a LogicalPlan);impl<'a> fmt::Display for Wrapper<'a> {fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {- match *self.0 {+ match &*self.0 {LogicalPlan::EmptyRelation { .. } => write!(f, "EmptyRelation"),LogicalPlan::TableScan {ref table_name,@@ -523,6 +543,28 @@ impl LogicalPlan {keys.iter().map(|(l, r)| format!("{} = {}", l, r)).collect();write!(f, "Join: {}", join_expr.join(", "))}+ LogicalPlan::Repartition {+ partitioning_scheme,+ ..+ } => match partitioning_scheme {+ Partitioning::RoundRobinBatch(n) => {+ write!(+ f,+ "Repartition: RoundRobinBatch partition_count={}",+ n+ )+ }+ Partitioning::Hash(expr, n) => {+ let hash_expr: Vec<String> =+ expr.iter().map(|e| format!("{:?}", e)).collect();+ write!(+ f,+ "Repartition: Hash({}) partition_count={}",+ hash_expr.join(", "),+ n+ )+ }+ },LogicalPlan::Limit { ref n, .. } => write!(f, "Limit: {}", n),LogicalPlan::CreateExternalTable { ref name, .. } => {write!(f, "CreateExternalTable: {:?}", name)diff --git a/rust/datafusion/src/optimizer/hash_build_probe_order.rs b/rust/datafusion/src/optimizer/hash_build_probe_order.rsindex df05076bc3..179149b489 100644--- a/rust/datafusion/src/optimizer/hash_build_probe_order.rs+++ b/rust/datafusion/src/optimizer/hash_build_probe_order.rs@@ -117,6 +117,7 @@ impl OptimizerRule for HashBuildProbeOrder {| LogicalPlan::TableScan { .. }| LogicalPlan::Limit { .. }| LogicalPlan::Filter { .. }+ | LogicalPlan::Repartition { .. }| LogicalPlan::EmptyRelation { .. }| LogicalPlan::Sort { .. }| LogicalPlan::CreateExternalTable { .. }diff --git a/rust/datafusion/src/optimizer/projection_push_down.rs b/rust/datafusion/src/optimizer/projection_push_down.rsindex 92236b97c6..bb87ed823d 100644--- a/rust/datafusion/src/optimizer/projection_push_down.rs+++ b/rust/datafusion/src/optimizer/projection_push_down.rs@@ -275,6 +275,7 @@ fn optimize_plan(// expressions in this node to the list of required columnsLogicalPlan::Limit { .. }| LogicalPlan::Filter { .. }+ | LogicalPlan::Repartition { .. }| LogicalPlan::EmptyRelation { .. }| LogicalPlan::Sort { .. }| LogicalPlan::CreateExternalTable { .. }diff --git a/rust/datafusion/src/optimizer/utils.rs b/rust/datafusion/src/optimizer/utils.rsindex da13b73ae7..2e950fd2be 100644--- a/rust/datafusion/src/optimizer/utils.rs+++ b/rust/datafusion/src/optimizer/utils.rs@@ -24,7 +24,7 @@ use arrow::datatypes::Schema;use super::optimizer::OptimizerRule;use crate::error::{DataFusionError, Result};use crate::logical_plan::{- Expr, LogicalPlan, Operator, PlanType, StringifiedPlan, ToDFSchema,+ Expr, LogicalPlan, Operator, Partitioning, PlanType, StringifiedPlan, ToDFSchema,};use crate::prelude::{col, lit};use crate::scalar::ScalarValue;@@ -140,6 +140,13 @@ pub fn expressions(plan: &LogicalPlan) -> Vec<Expr> {match plan {LogicalPlan::Projection { expr, .. } => expr.clone(),LogicalPlan::Filter { predicate, .. } => vec![predicate.clone()],+ LogicalPlan::Repartition {+ partitioning_scheme,+ ..+ } => match partitioning_scheme {+ Partitioning::Hash(expr, _) => expr.clone(),+ _ => vec![],+ },LogicalPlan::Aggregate {group_expr,aggr_expr,@@ -168,6 +175,7 @@ pub fn inputs(plan: &LogicalPlan) -> Vec<&LogicalPlan> {match plan {LogicalPlan::Projection { input, .. } => vec![input],LogicalPlan::Filter { input, .. } => vec![input],+ LogicalPlan::Repartition { input, .. } => vec![input],LogicalPlan::Aggregate { input, .. } => vec![input],LogicalPlan::Sort { input, .. } => vec![input],LogicalPlan::Join { left, right, .. } => vec![left, right],@@ -197,6 +205,19 @@ pub fn from_plan(predicate: expr[0].clone(),input: Arc::new(inputs[0].clone()),}),+ LogicalPlan::Repartition {+ partitioning_scheme,+ ..+ } => match partitioning_scheme {+ Partitioning::RoundRobinBatch(n) => Ok(LogicalPlan::Repartition {+ partitioning_scheme: Partitioning::RoundRobinBatch(*n),+ input: Arc::new(inputs[0].clone()),+ }),+ Partitioning::Hash(_, n) => Ok(LogicalPlan::Repartition {+ partitioning_scheme: Partitioning::Hash(expr.to_owned(), *n),+ input: Arc::new(inputs[0].clone()),+ }),+ },LogicalPlan::Aggregate {group_expr, schema, ..} => Ok(LogicalPlan::Aggregate {diff --git a/rust/datafusion/src/physical_plan/mod.rs b/rust/datafusion/src/physical_plan/mod.rsindex 1a8d1ccf45..d0dcede78d 100644--- a/rust/datafusion/src/physical_plan/mod.rs+++ b/rust/datafusion/src/physical_plan/mod.rs@@ -107,7 +107,13 @@ pub async fn collect(plan: Arc<dyn ExecutionPlan>) -> Result<Vec<RecordBatch>> {/// Partitioning schemes supported by operators.#[derive(Debug, Clone)]pub enum Partitioning {- /// Unknown partitioning scheme+ /// Allocate batches using a round-robin algorithm and the specified number of partitions+ RoundRobinBatch(usize),+ /// Allocate rows based on a hash of one of more expressions and the specified+ /// number of partitions+ /// This partitioning scheme is not yet fully supported. See https://issues.apache.org/jira/browse/ARROW-11011+ Hash(Vec<Arc<dyn PhysicalExpr>>, usize),+ /// Unknown partitioning scheme with a known number of partitionsUnknownPartitioning(usize),}@@ -116,6 +122,8 @@ impl Partitioning {pub fn partition_count(&self) -> usize {use Partitioning::*;match self {+ RoundRobinBatch(n) => *n,+ Hash(_, n) => *n,UnknownPartitioning(n) => *n,}}@@ -260,6 +268,7 @@ pub mod merge;pub mod parquet;pub mod planner;pub mod projection;+pub mod repartition;pub mod sort;pub mod string_expressions;pub mod type_coercion;diff --git a/rust/datafusion/src/physical_plan/planner.rs b/rust/datafusion/src/physical_plan/planner.rsindex 1d3a479ea0..310f07b3d3 100644--- a/rust/datafusion/src/physical_plan/planner.rs+++ b/rust/datafusion/src/physical_plan/planner.rs@@ -23,21 +23,22 @@ use super::{aggregates, empty::EmptyExec, expressions::binary, functions, udaf};use crate::error::{DataFusionError, Result};use crate::execution::context::ExecutionContextState;use crate::logical_plan::{- DFSchema, Expr, LogicalPlan, Operator, PlanType, StringifiedPlan,- UserDefinedLogicalNode,+ DFSchema, Expr, LogicalPlan, Operator, Partitioning as LogicalPartitioning, PlanType,+ StringifiedPlan, UserDefinedLogicalNode,};use crate::physical_plan::explain::ExplainExec;use crate::physical_plan::expressions::{CaseExpr, Column, Literal, PhysicalSortExpr};use crate::physical_plan::filter::FilterExec;use crate::physical_plan::hash_aggregate::{AggregateMode, HashAggregateExec};use crate::physical_plan::hash_join::HashJoinExec;-use crate::physical_plan::hash_utils;use crate::physical_plan::limit::{GlobalLimitExec, LocalLimitExec};use crate::physical_plan::merge::MergeExec;use crate::physical_plan::projection::ProjectionExec;+use crate::physical_plan::repartition::RepartitionExec;use crate::physical_plan::sort::SortExec;use crate::physical_plan::udf;use crate::physical_plan::{expressions, Distribution};+use crate::physical_plan::{hash_utils, Partitioning};use crate::physical_plan::{AggregateExpr, ExecutionPlan, PhysicalExpr, PhysicalPlanner};use crate::prelude::JoinType;use crate::variable::VarType;@@ -228,6 +229,31 @@ impl DefaultPhysicalPlanner {self.create_physical_expr(predicate, &input_schema, ctx_state)?;Ok(Arc::new(FilterExec::try_new(runtime_expr, input)?))}+ LogicalPlan::Repartition {+ input,+ partitioning_scheme,+ } => {+ let input = self.create_physical_plan(input, ctx_state)?;+ let input_schema = input.schema();+ let physical_partitioning = match partitioning_scheme {+ LogicalPartitioning::RoundRobinBatch(n) => {+ Partitioning::RoundRobinBatch(*n)+ }+ LogicalPartitioning::Hash(expr, n) => {+ let runtime_expr = expr+ .iter()+ .map(|e| {+ self.create_physical_expr(e, &input_schema, &ctx_state)+ })+ .collect::<Result<Vec<_>>>()?;+ Partitioning::Hash(runtime_expr, *n)+ }+ };+ Ok(Arc::new(RepartitionExec::try_new(+ input,+ physical_partitioning,+ )?))+ }LogicalPlan::Sort { expr, input, .. } => {let input = self.create_physical_plan(input, ctx_state)?;let input_schema = input.as_ref().schema();diff --git a/rust/datafusion/src/physical_plan/repartition.rs b/rust/datafusion/src/physical_plan/repartition.rsnew file mode 100644index 0000000000..fb975034a3--- /dev/null+++ b/rust/datafusion/src/physical_plan/repartition.rs@@ -0,0 +1,335 @@+// Licensed to the Apache Software Foundation (ASF) under one+// or more contributor license agreements. See the NOTICE file+// distributed with this work for additional information+// regarding copyright ownership. The ASF licenses this file+// to you under the Apache License, Version 2.0 (the+// "License"); you may not use this file except in compliance+// with the License. You may obtain a copy of the License at+//+// http://www.apache.org/licenses/LICENSE-2.0+//+// Unless required by applicable law or agreed to in writing,+// software distributed under the License is distributed on an+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+// KIND, either express or implied. See the License for the+// specific language governing permissions and limitations+// under the License.++//! The repartition operator maps N input partitions to M output partitions based on a+//! partitioning scheme.++use std::any::Any;+use std::pin::Pin;+use std::sync::Arc;+use std::task::{Context, Poll};++use crate::error::{DataFusionError, Result};+use crate::physical_plan::{ExecutionPlan, Partitioning};+use arrow::datatypes::SchemaRef;+use arrow::error::Result as ArrowResult;+use arrow::record_batch::RecordBatch;++use super::{RecordBatchStream, SendableRecordBatchStream};+use async_trait::async_trait;++use crossbeam::channel::{unbounded, Receiver, Sender};+use futures::stream::Stream;+use futures::StreamExt;+use tokio::sync::Mutex;+use tokio::task::JoinHandle;++type MaybeBatch = Option<ArrowResult<RecordBatch>>;++/// The repartition operator maps N input partitions to M output partitions based on a+/// partitioning scheme. No guarantees are made about the order of the resulting partitions.+#[derive(Debug)]+pub struct RepartitionExec {+ /// Input execution plan+ input: Arc<dyn ExecutionPlan>,+ /// Partitioning scheme to use+ partitioning: Partitioning,+ /// Channels for sending batches from input partitions to output partitions+ /// there is one entry in this Vec for each output partition+ channels: Arc<Mutex<Vec<(Sender<MaybeBatch>, Receiver<MaybeBatch>)>>>,+}++#[async_trait]+impl ExecutionPlan for RepartitionExec {+ /// Return a reference to Any that can be used for downcasting+ fn as_any(&self) -> &dyn Any {+ self+ }++ /// Get the schema for this execution plan+ fn schema(&self) -> SchemaRef {+ self.input.schema()+ }++ fn children(&self) -> Vec<Arc<dyn ExecutionPlan>> {+ vec![self.input.clone()]+ }++ fn with_new_children(+ &self,+ children: Vec<Arc<dyn ExecutionPlan>>,+ ) -> Result<Arc<dyn ExecutionPlan>> {+ match children.len() {+ 1 => Ok(Arc::new(RepartitionExec::try_new(+ children[0].clone(),+ self.partitioning.clone(),+ )?)),+ _ => Err(DataFusionError::Internal(+ "RepartitionExec wrong number of children".to_string(),+ )),+ }+ }++ fn output_partitioning(&self) -> Partitioning {+ self.partitioning.clone()+ }++ async fn execute(&self, partition: usize) -> Result<SendableRecordBatchStream> {+ // lock mutexes+ let mut channels = self.channels.lock().await;++ let num_input_partitions = self.input.output_partitioning().partition_count();+ let num_output_partitions = self.partitioning.partition_count();++ // if this is the first partition to be invoked then we need to set up initial state+ if channels.is_empty() {+ // create one channel per *output* partition+ for _ in 0..num_output_partitions {+ // Note that this operator uses unbounded channels to avoid deadlocks because+ // the output partitions can be read in any order and this could cause input+ // partitions to be blocked when sending data to output receivers that are not+ // being read yet. This may cause high memory usage if the next operator is+ // reading output partitions in order rather than concurrently. One workaround+ // for this would be to add spill-to-disk capabilities.+ let (sender, receiver) = unbounded::<Option<ArrowResult<RecordBatch>>>();+ channels.push((sender, receiver));+ }+ // launch one async task per *input* partition+ for i in 0..num_input_partitions {+ let input = self.input.clone();+ let mut channels = channels.clone();+ let partitioning = self.partitioning.clone();+ let _: JoinHandle<Result<()>> = tokio::spawn(async move {+ let mut stream = input.execute(i).await?;+ let mut counter = 0;+ while let Some(result) = stream.next().await {+ match partitioning {+ Partitioning::RoundRobinBatch(_) => {+ let output_partition = counter % num_output_partitions;+ let tx = &mut channels[output_partition].0;+ tx.send(Some(result)).map_err(|e| {+ DataFusionError::Execution(e.to_string())+ })?;+ }+ other => {+ // this should be unreachable as long as the validation logic+ // in the constructor is kept up-to-date+ return Err(DataFusionError::NotImplemented(format!(+ "Unsupported repartitioning scheme {:?}",+ other+ )));+ }+ }+ counter += 1;+ }++ // notify each output partition that this input partition has no more data+ for i in 0..num_output_partitions {+ let tx = &mut channels[i].0;+ tx.send(None)+ .map_err(|e| DataFusionError::Execution(e.to_string()))?;+ }+ Ok(())+ });+ }+ }++ // now return stream for the specified *output* partition which will+ // read from the channel+ Ok(Box::pin(RepartitionStream {+ num_input_partitions,+ num_input_partitions_processed: 0,+ schema: self.input.schema(),+ input: channels[partition].1.clone(),+ }))+ }+}++impl RepartitionExec {+ /// Create a new RepartitionExec+ pub fn try_new(+ input: Arc<dyn ExecutionPlan>,+ partitioning: Partitioning,+ ) -> Result<Self> {+ match &partitioning {+ Partitioning::RoundRobinBatch(_) => Ok(RepartitionExec {+ input,+ partitioning,+ channels: Arc::new(Mutex::new(vec![])),+ }),+ other => Err(DataFusionError::NotImplemented(format!(+ "Partitioning scheme not supported yet: {:?}",+ other+ ))),+ }+ }+}++struct RepartitionStream {+ /// Number of input partitions that will be sending batches to this output channel+ num_input_partitions: usize,+ /// Number of input partitions that have finished sending batches to this output channel+ num_input_partitions_processed: usize,+ /// Schema+ schema: SchemaRef,+ /// channel containing the repartitioned batches+ input: Receiver<Option<ArrowResult<RecordBatch>>>,+}++impl Stream for RepartitionStream {+ type Item = ArrowResult<RecordBatch>;++ fn poll_next(+ mut self: Pin<&mut Self>,+ cx: &mut Context<'_>,+ ) -> Poll<Option<Self::Item>> {+ match self.input.recv() {+ Ok(Some(batch)) => Poll::Ready(Some(batch)),+ // End of results from one input partition+ Ok(None) => {+ self.num_input_partitions_processed += 1;+ if self.num_input_partitions == self.num_input_partitions_processed {+ // all input partitions have finished sending batches+ Poll::Ready(None)+ } else {+ // other partitions still have data to send+ self.poll_next(cx)+ }+ }+ // RecvError means receiver has exited and closed the channel+ Err(_) => Poll::Ready(None),+ }+ }+}++impl RecordBatchStream for RepartitionStream {+ /// Get the schema+ fn schema(&self) -> SchemaRef {+ self.schema.clone()+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::physical_plan::memory::MemoryExec;+ use arrow::array::UInt32Array;+ use arrow::datatypes::{DataType, Field, Schema};+ use arrow::record_batch::RecordBatch;++ #[tokio::test(threaded_scheduler)]+ async fn one_to_many_round_robin() -> Result<()> {+ // define input partitions+ let schema = test_schema();+ let partition = create_vec_batches(&schema, 50)?;+ let partitions = vec![partition];++ // repartition from 1 input to 4 output+ let output_partitions =+ repartition(&schema, partitions, Partitioning::RoundRobinBatch(4)).await?;++ assert_eq!(4, output_partitions.len());+ assert_eq!(13, output_partitions[0].len());+ assert_eq!(13, output_partitions[1].len());+ assert_eq!(12, output_partitions[2].len());+ assert_eq!(12, output_partitions[3].len());++ Ok(())+ }++ #[tokio::test(threaded_scheduler)]+ async fn many_to_one_round_robin() -> Result<()> {+ // define input partitions+ let schema = test_schema();+ let partition = create_vec_batches(&schema, 50)?;+ let partitions = vec![partition.clone(), partition.clone(), partition.clone()];++ // repartition from 3 input to 1 output+ let output_partitions =+ repartition(&schema, partitions, Partitioning::RoundRobinBatch(1)).await?;++ assert_eq!(1, output_partitions.len());+ assert_eq!(150, output_partitions[0].len());++ Ok(())+ }++ #[tokio::test(threaded_scheduler)]+ async fn many_to_many_round_robin() -> Result<()> {+ // define input partitions+ let schema = test_schema();+ let partition = create_vec_batches(&schema, 50)?;+ let partitions = vec![partition.clone(), partition.clone(), partition.clone()];++ // repartition from 3 input to 5 output+ let output_partitions =+ repartition(&schema, partitions, Partitioning::RoundRobinBatch(5)).await?;++ assert_eq!(5, output_partitions.len());+ assert_eq!(30, output_partitions[0].len());+ assert_eq!(30, output_partitions[1].len());+ assert_eq!(30, output_partitions[2].len());+ assert_eq!(30, output_partitions[3].len());+ assert_eq!(30, output_partitions[4].len());++ Ok(())+ }++ fn test_schema() -> Arc<Schema> {+ Arc::new(Schema::new(vec![Field::new("c0", DataType::UInt32, false)]))+ }++ fn create_vec_batches(schema: &Arc<Schema>, n: usize) -> Result<Vec<RecordBatch>> {+ let batch = create_batch(schema);+ let mut vec = Vec::with_capacity(n);+ for _ in 0..n {+ vec.push(batch.clone());+ }+ Ok(vec)+ }++ fn create_batch(schema: &Arc<Schema>) -> RecordBatch {+ RecordBatch::try_new(+ schema.clone(),+ vec![Arc::new(UInt32Array::from(vec![1, 2, 3, 4, 5, 6, 7, 8]))],+ )+ .unwrap()+ }++ async fn repartition(+ schema: &SchemaRef,+ input_partitions: Vec<Vec<RecordBatch>>,+ partitioning: Partitioning,+ ) -> Result<Vec<Vec<RecordBatch>>> {+ // create physical plan+ let exec = MemoryExec::try_new(&input_partitions, schema.clone(), None)?;+ let exec = RepartitionExec::try_new(Arc::new(exec), partitioning)?;++ // execute and collect results+ let mut output_partitions = vec![];+ for i in 0..exec.partitioning.partition_count() {+ // execute this *output* partition and collect all batches+ let mut stream = exec.execute(i).await?;+ let mut batches = vec![];+ while let Some(result) = stream.next().await {+ batches.push(result?);+ }+ output_partitions.push(batches);+ }+ Ok(output_partitions)+ }+}diff --git a/rust/datafusion/src/prelude.rs b/rust/datafusion/src/prelude.rsindex 20bbbe47c9..309b75bc6b 100644--- a/rust/datafusion/src/prelude.rs+++ b/rust/datafusion/src/prelude.rs@@ -29,5 +29,6 @@ pub use crate::dataframe::DataFrame;pub use crate::execution::context::{ExecutionConfig, ExecutionContext};pub use crate::logical_plan::{array, avg, col, concat, count, create_udf, length, lit, max, min, sum, JoinType,+ Partitioning,};pub use crate::physical_plan::csv::CsvReadOptions;