Apache DataFusion SQL Query Engine
ARROW-9005: [Rust] [Datafusion] support sort expression
Qingping Hou4096d15963f0
diff --git a/rust/datafusion/Cargo.toml b/rust/datafusion/Cargo.tomlindex 6a77c21ec3..c83eb3ac76 100644--- a/rust/datafusion/Cargo.toml+++ b/rust/datafusion/Cargo.toml@@ -47,7 +47,7 @@ cli = ["rustyline"]fnv = "1.0"arrow = { path = "../arrow", version = "1.0.0-SNAPSHOT" }parquet = { path = "../parquet", version = "1.0.0-SNAPSHOT" }-sqlparser = "0.2.5"+sqlparser = "0.2.6"clap = "2.33"prettytable-rs = "0.8.0"rustyline = {version = "6.0", optional = true}diff --git a/rust/datafusion/src/execution/context.rs b/rust/datafusion/src/execution/context.rsindex c94364668e..f7fb1a31d1 100644--- a/rust/datafusion/src/execution/context.rs+++ b/rust/datafusion/src/execution/context.rs@@ -36,7 +36,8 @@ use crate::execution::physical_plan::common;use crate::execution::physical_plan::csv::{CsvExec, CsvReadOptions};use crate::execution::physical_plan::datasource::DatasourceExec;use crate::execution::physical_plan::expressions::{- Alias, Avg, BinaryExpr, CastExpr, Column, Count, Literal, Max, Min, Sum,+ Alias, Avg, BinaryExpr, CastExpr, Column, Count, Literal, Max, Min, PhysicalSortExpr,+ Sum,};use crate::execution::physical_plan::hash_aggregate::HashAggregateExec;use crate::execution::physical_plan::limit::LimitExec;@@ -46,6 +47,7 @@ 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::selection::SelectionExec;+use crate::execution::physical_plan::sort::{SortExec, SortOptions};use crate::execution::physical_plan::udf::{ScalarFunction, ScalarFunctionExpr};use crate::execution::physical_plan::{AggregateExpr, ExecutionPlan, PhysicalExpr};use crate::execution::table_impl::TableImpl;@@ -394,6 +396,33 @@ impl ExecutionContext {let runtime_expr = self.create_physical_expr(expr, &input_schema)?;Ok(Arc::new(SelectionExec::try_new(runtime_expr, input)?))}+ LogicalPlan::Sort { expr, input, .. } => {+ let input = self.create_physical_plan(input, batch_size)?;+ let input_schema = input.as_ref().schema().clone();++ let sort_expr = expr+ .iter()+ .map(|e| match e {+ Expr::Sort {+ expr,+ asc,+ nulls_first,+ } => self.create_physical_sort_expr(+ expr,+ &input_schema,+ SortOptions {+ descending: !*asc,+ nulls_first: *nulls_first,+ },+ ),+ _ => Err(ExecutionError::ExecutionError(+ "Sort only accepts sort expressions".to_string(),+ )),+ })+ .collect::<Result<Vec<_>>>()?;++ Ok(Arc::new(SortExec::try_new(sort_expr, input)?))+ }LogicalPlan::Limit { input, expr, .. } => {let input = self.create_physical_plan(input, batch_size)?;let input_schema = input.as_ref().schema().clone();@@ -530,6 +559,19 @@ impl ExecutionContext {}}+ /// Create an aggregate expression from a logical expression+ pub fn create_physical_sort_expr(+ &self,+ e: &Expr,+ input_schema: &Schema,+ options: SortOptions,+ ) -> Result<PhysicalSortExpr> {+ Ok(PhysicalSortExpr {+ expr: self.create_physical_expr(e, input_schema)?,+ options: options,+ })+ }+/// Execute a physical plan and collect the results in memorypub fn collect(&self, plan: &dyn ExecutionPlan) -> Result<Vec<RecordBatch>> {let partitions = plan.partitions()?;@@ -778,6 +820,23 @@ mod tests {Ok(())}+ #[test]+ fn sort() -> Result<()> {+ let results = execute("SELECT c1, c2 FROM test ORDER BY c1 DESC, c2 ASC", 4)?;+ assert_eq!(results.len(), 1);++ let batch = &results[0];+ let expected: Vec<&str> = vec![+ "3,1", "3,2", "3,3", "3,4", "3,5", "3,6", "3,7", "3,8", "3,9", "3,10", "2,1",+ "2,2", "2,3", "2,4", "2,5", "2,6", "2,7", "2,8", "2,9", "2,10", "1,1", "1,2",+ "1,3", "1,4", "1,5", "1,6", "1,7", "1,8", "1,9", "1,10", "0,1", "0,2", "0,3",+ "0,4", "0,5", "0,6", "0,7", "0,8", "0,9", "0,10",+ ];+ assert_eq!(test::format_batch(batch), expected);++ Ok(())+ }+#[test]fn aggregate() -> Result<()> {let results = execute("SELECT SUM(c1), SUM(c2) FROM test", 4)?;diff --git a/rust/datafusion/src/execution/physical_plan/expressions.rs b/rust/datafusion/src/execution/physical_plan/expressions.rsindex 9969eeddf1..73882fa31f 100644--- a/rust/datafusion/src/execution/physical_plan/expressions.rs+++ b/rust/datafusion/src/execution/physical_plan/expressions.rs@@ -43,6 +43,7 @@ use arrow::compute::kernels::comparison::{eq, gt, gt_eq, lt, lt_eq, neq};use arrow::compute::kernels::comparison::{eq_utf8, gt_eq_utf8, gt_utf8, like_utf8, lt_eq_utf8, lt_utf8, neq_utf8, nlike_utf8,};+use arrow::compute::kernels::sort::{SortColumn, SortOptions};use arrow::datatypes::{DataType, Schema, TimeUnit};use arrow::record_batch::RecordBatch;@@ -1264,6 +1265,25 @@ pub fn lit(value: ScalarValue) -> Arc<dyn PhysicalExpr> {Arc::new(Literal::new(value))}+/// Represents Sort operation for a column in a RecordBatch+#[derive(Clone)]+pub struct PhysicalSortExpr {+ /// Physical expression representing the column to sort+ pub expr: Arc<dyn PhysicalExpr>,+ /// Option to specify how the given column should be sorted+ pub options: SortOptions,+}++impl PhysicalSortExpr {+ /// evaluate the sort expression into SortColumn that can be passed into arrow sort kernel+ pub fn evaluate_to_sort_column(&self, batch: &RecordBatch) -> Result<SortColumn> {+ Ok(SortColumn {+ values: self.expr.evaluate(batch)?,+ options: Some(self.options),+ })+ }+}+#[cfg(test)]mod tests {use super::*;diff --git a/rust/datafusion/src/execution/physical_plan/mod.rs b/rust/datafusion/src/execution/physical_plan/mod.rsindex 9afe9aa8e0..92e425e94a 100644--- a/rust/datafusion/src/execution/physical_plan/mod.rs+++ b/rust/datafusion/src/execution/physical_plan/mod.rs@@ -97,4 +97,5 @@ pub mod merge;pub mod parquet;pub mod projection;pub mod selection;+pub mod sort;pub mod udf;diff --git a/rust/datafusion/src/execution/physical_plan/projection.rs b/rust/datafusion/src/execution/physical_plan/projection.rsindex 9c8e5170de..a0c588db45 100644--- a/rust/datafusion/src/execution/physical_plan/projection.rs+++ b/rust/datafusion/src/execution/physical_plan/projection.rs@@ -75,10 +75,9 @@ impl ExecutionPlan for ProjectionExec {.partitions()?.iter().map(|p| {- let expr = self.expr.clone();let projection: Arc<dyn Partition> = Arc::new(ProjectionPartition {schema: self.schema.clone(),- expr,+ expr: self.expr.clone(),input: p.clone() as Arc<dyn Partition>,});diff --git a/rust/datafusion/src/execution/physical_plan/sort.rs b/rust/datafusion/src/execution/physical_plan/sort.rsnew file mode 100644index 0000000000..7f022ee51e--- /dev/null+++ b/rust/datafusion/src/execution/physical_plan/sort.rs@@ -0,0 +1,211 @@+// 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.++//! Defines the SORT plan++use std::sync::{Arc, Mutex};+use std::thread;+use std::thread::JoinHandle;++use arrow::array::ArrayRef;+pub use arrow::compute::SortOptions;+use arrow::compute::{concat, lexsort_to_indices, take, SortColumn, TakeOptions};+use arrow::datatypes::Schema;+use arrow::record_batch::RecordBatch;++use crate::error::Result;+use crate::execution::physical_plan::common::RecordBatchIterator;+use crate::execution::physical_plan::expressions::PhysicalSortExpr;+use crate::execution::physical_plan::{common, BatchIterator, ExecutionPlan, Partition};++/// Sort execution plan+pub struct SortExec {+ /// Input schema+ input: Arc<dyn ExecutionPlan>,+ expr: Vec<PhysicalSortExpr>,+}++impl SortExec {+ /// Create a new sort execution plan+ pub fn try_new(+ expr: Vec<PhysicalSortExpr>,+ input: Arc<dyn ExecutionPlan>,+ ) -> Result<Self> {+ Ok(Self { expr, input })+ }+}++impl ExecutionPlan for SortExec {+ fn schema(&self) -> Arc<Schema> {+ self.input.schema().clone()+ }++ fn partitions(&self) -> Result<Vec<Arc<dyn Partition>>> {+ Ok(vec![+ (Arc::new(SortPartition {+ input: self.input.partitions()?,+ expr: self.expr.clone(),+ schema: self.schema(),+ })),+ ])+ }+}++/// Represents a single partition of a Sort execution plan+struct SortPartition {+ schema: Arc<Schema>,+ expr: Vec<PhysicalSortExpr>,+ input: Vec<Arc<dyn Partition>>,+}++impl Partition for SortPartition {+ /// Execute the sort+ fn execute(&self) -> Result<Arc<Mutex<dyn BatchIterator>>> {+ let threads: Vec<JoinHandle<Result<Vec<RecordBatch>>>> = self+ .input+ .iter()+ .map(|p| {+ let p = p.clone();+ thread::spawn(move || {+ let it = p.execute()?;+ common::collect(it)+ })+ })+ .collect();++ // generate record batches from input in parallel+ let mut all_batches: Vec<Arc<RecordBatch>> = vec![];+ for thread in threads {+ let join = thread.join().expect("Failed to join thread");+ let result = join?;+ result+ .iter()+ .for_each(|batch| all_batches.push(Arc::new(batch.clone())));+ }++ // combine all record batches into one for each column+ let combined_batch = RecordBatch::try_new(+ self.schema.clone(),+ self.schema+ .fields()+ .iter()+ .enumerate()+ .map(|(i, _)| -> Result<ArrayRef> {+ Ok(concat(+ &all_batches+ .iter()+ .map(|batch| batch.columns()[i].clone())+ .collect::<Vec<ArrayRef>>(),+ )?)+ })+ .collect::<Result<Vec<ArrayRef>>>()?,+ )?;++ // sort combined record batch+ let indices = lexsort_to_indices(+ &self+ .expr+ .iter()+ .map(|e| e.evaluate_to_sort_column(&combined_batch))+ .collect::<Result<Vec<SortColumn>>>()?,+ )?;++ // reorder all rows based on sorted indices+ let sorted_batch = RecordBatch::try_new(+ self.schema.clone(),+ combined_batch+ .columns()+ .iter()+ .map(|column| -> Result<ArrayRef> {+ Ok(take(+ column,+ &indices,+ // disable bound check overhead since indices are already generated from+ // the same record batch+ Some(TakeOptions {+ check_bounds: false,+ }),+ )?)+ })+ .collect::<Result<Vec<ArrayRef>>>()?,+ )?;++ Ok(Arc::new(Mutex::new(RecordBatchIterator::new(+ self.schema.clone(),+ vec![Arc::new(sorted_batch)],+ ))))+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::execution::physical_plan::csv::{CsvExec, CsvReadOptions};+ use crate::execution::physical_plan::expressions::col;+ use crate::test;+ use arrow::array::*;+ use arrow::datatypes::*;++ #[test]+ fn test_sort() -> Result<()> {+ let schema = test::aggr_test_schema();+ let partitions = 4;+ let path = test::create_partitioned_csv("aggregate_test_100.csv", partitions)?;+ let csv =+ CsvExec::try_new(&path, CsvReadOptions::new().schema(&schema), None, 1024)?;++ let sort_exec = SortExec::try_new(+ vec![+ // c1 string column+ PhysicalSortExpr {+ expr: col(0, schema.as_ref()),+ options: SortOptions::default(),+ },+ // c2 uin32 column+ PhysicalSortExpr {+ expr: col(1, schema.as_ref()),+ options: SortOptions::default(),+ },+ // c7 uin8 column+ PhysicalSortExpr {+ expr: col(6, schema.as_ref()),+ options: SortOptions::default(),+ },+ ],+ Arc::new(csv),+ )?;++ let result: Vec<RecordBatch> = test::execute(&sort_exec)?;+ assert_eq!(result.len(), 1);++ let columns = result[0].columns();++ let c1 = as_string_array(&columns[0]);+ assert_eq!(c1.value(0), "a");+ assert_eq!(c1.value(c1.len() - 1), "e");++ let c2 = as_primitive_array::<UInt32Type>(&columns[1]);+ assert_eq!(c2.value(0), 1);+ assert_eq!(c2.value(c2.len() - 1), 5,);++ let c7 = as_primitive_array::<UInt8Type>(&columns[6]);+ assert_eq!(c7.value(0), 15);+ assert_eq!(c7.value(c7.len() - 1), 254,);++ Ok(())+ }+}diff --git a/rust/datafusion/src/logicalplan.rs b/rust/datafusion/src/logicalplan.rsindex 704c548254..3384b93a40 100644--- a/rust/datafusion/src/logicalplan.rs+++ b/rust/datafusion/src/logicalplan.rs@@ -218,6 +218,8 @@ pub enum Expr {expr: Box<Expr>,/// The direction of the sortasc: bool,+ /// Whether to put Nulls before all other data values+ nulls_first: bool,},/// scalar functionScalarFunction {@@ -444,11 +446,20 @@ impl fmt::Debug for Expr {Expr::BinaryExpr { left, op, right } => {write!(f, "{:?} {:?} {:?}", left, op, right)}- Expr::Sort { expr, asc } => {+ Expr::Sort {+ expr,+ asc,+ nulls_first,+ } => {if *asc {- write!(f, "{:?} ASC", expr)+ write!(f, "{:?} ASC", expr)?;+ } else {+ write!(f, "{:?} DESC", expr)?;+ }+ if *nulls_first {+ write!(f, " NULLS FIRST")} else {- write!(f, "{:?} DESC", expr)+ write!(f, " NULLS LAST")}}Expr::ScalarFunction { name, ref args, .. } => {@@ -1014,6 +1025,36 @@ mod tests {Ok(())}+ #[test]+ fn plan_builder_sort() -> Result<()> {+ let plan = LogicalPlanBuilder::scan(+ "default",+ "employee.csv",+ &employee_schema(),+ Some(vec![3, 4]),+ )?+ .sort(vec![+ Expr::Sort {+ expr: Box::new(col("state")),+ asc: true,+ nulls_first: true,+ },+ Expr::Sort {+ expr: Box::new(col("total_salary")),+ asc: false,+ nulls_first: false,+ },+ ])?+ .build()?;++ let expected = "Sort: #state ASC NULLS FIRST, #total_salary DESC NULLS LAST\+ \n TableScan: employee.csv projection=Some([3, 4])";++ assert_eq!(expected, format!("{:?}", plan));++ Ok(())+ }+fn employee_schema() -> Schema {Schema::new(vec![Field::new("id", DataType::Int32, false),diff --git a/rust/datafusion/src/optimizer/projection_push_down.rs b/rust/datafusion/src/optimizer/projection_push_down.rsindex 10e60adf78..7fa40664ae 100644--- a/rust/datafusion/src/optimizer/projection_push_down.rs+++ b/rust/datafusion/src/optimizer/projection_push_down.rs@@ -226,9 +226,14 @@ impl ProjectionPushDown {expr: Box::new(self.rewrite_expr(expr, mapping)?),data_type: data_type.clone(),}),- Expr::Sort { expr, asc } => Ok(Expr::Sort {+ Expr::Sort {+ expr,+ asc,+ nulls_first,+ } => Ok(Expr::Sort {expr: Box::new(self.rewrite_expr(expr, mapping)?),asc: *asc,+ nulls_first: *nulls_first,}),Expr::AggregateFunction {name,diff --git a/rust/datafusion/src/optimizer/resolve_columns.rs b/rust/datafusion/src/optimizer/resolve_columns.rsindex 5a7f249b07..61b2e81736 100644--- a/rust/datafusion/src/optimizer/resolve_columns.rs+++ b/rust/datafusion/src/optimizer/resolve_columns.rs@@ -55,13 +55,16 @@ impl OptimizerRule for ResolveColumnsRule {rewrite_expr_list(aggr_expr, &input.schema())?,)?.build()?),- LogicalPlan::Sort { input, expr, .. } => Ok(LogicalPlanBuilder::from(input)- .sort(rewrite_expr_list(expr, &input.schema())?)?- .build()?),+ LogicalPlan::Sort { input, expr, .. } => {+ Ok(LogicalPlanBuilder::from(&self.optimize(input)?)+ .sort(rewrite_expr_list(expr, &input.schema())?)?+ .build()?)+ }_ => Ok(plan.clone()),}}}+fn rewrite_expr_list(expr: &[Expr], schema: &Schema) -> Result<Vec<Expr>> {Ok(expr.iter()@@ -87,9 +90,14 @@ fn rewrite_expr(expr: &Expr, schema: &Schema) -> Result<Expr> {expr: Box::new(rewrite_expr(&expr, schema)?),data_type: data_type.clone(),}),- Expr::Sort { expr, asc } => Ok(Expr::Sort {+ Expr::Sort {+ expr,+ asc,+ nulls_first,+ } => Ok(Expr::Sort {expr: Box::new(rewrite_expr(&expr, schema)?),asc: asc.clone(),+ nulls_first: nulls_first.clone(),}),Expr::ScalarFunction {name,diff --git a/rust/datafusion/src/optimizer/type_coercion.rs b/rust/datafusion/src/optimizer/type_coercion.rsindex 03a85ba4c8..7639b5bc12 100644--- a/rust/datafusion/src/optimizer/type_coercion.rs+++ b/rust/datafusion/src/optimizer/type_coercion.rs@@ -172,11 +172,8 @@ impl<'a> OptimizerRule for TypeCoercionRule<'a> {LogicalPlan::CsvScan { .. } => Ok(plan.clone()),LogicalPlan::EmptyRelation { .. } => Ok(plan.clone()),LogicalPlan::Limit { .. } => Ok(plan.clone()),+ LogicalPlan::Sort { .. } => Ok(plan.clone()),LogicalPlan::CreateExternalTable { .. } => Ok(plan.clone()),- other => Err(ExecutionError::NotImplemented(format!(- "Type coercion optimizer rule does not support relation: {:?}",- other- ))),}}}diff --git a/rust/datafusion/src/sql/planner.rs b/rust/datafusion/src/sql/planner.rsindex a51aa41e02..3a25f25736 100644--- a/rust/datafusion/src/sql/planner.rs+++ b/rust/datafusion/src/sql/planner.rs@@ -247,6 +247,8 @@ impl<S: SchemaProvider> SqlToRel<S> {self.sql_to_rex(&e.expr, &input_schema).unwrap(),),asc: e.asc,+ // by default nulls first to be consistent with spark+ nulls_first: e.nulls_first.unwrap_or(true),})}).collect();@@ -618,7 +620,7 @@ mod tests {#[test]fn select_order_by() {let sql = "SELECT id FROM person ORDER BY id";- let expected = "Sort: #0 ASC\+ let expected = "Sort: #0 ASC NULLS FIRST\\n Projection: #0\\n TableScan: person projection=None";quick_test(sql, expected);@@ -627,12 +629,29 @@ mod tests {#[test]fn select_order_by_desc() {let sql = "SELECT id FROM person ORDER BY id DESC";- let expected = "Sort: #0 DESC\+ let expected = "Sort: #0 DESC NULLS FIRST\\n Projection: #0\\n TableScan: person projection=None";quick_test(sql, expected);}+ #[test]+ fn select_order_by_nulls_last() {+ quick_test(+ "SELECT id FROM person ORDER BY id DESC NULLS LAST",+ "Sort: #0 DESC NULLS LAST\+ \n Projection: #0\+ \n TableScan: person projection=None",+ );++ quick_test(+ "SELECT id FROM person ORDER BY id NULLS LAST",+ "Sort: #0 ASC NULLS LAST\+ \n Projection: #0\+ \n TableScan: person projection=None",+ );+ }+#[test]fn select_group_by() {let sql = "SELECT state FROM person GROUP BY state";