Apache DataFusion SQL Query Engine
ARROW-11955: [Rust][DataFusion] Support Union
Heres, Daniel58cf719244d5
diff --git a/rust/datafusion/src/dataframe.rs b/rust/datafusion/src/dataframe.rsindex ceb5ca65f5..b3e561100c 100644--- a/rust/datafusion/src/dataframe.rs+++ b/rust/datafusion/src/dataframe.rs@@ -132,6 +132,20 @@ pub trait DataFrame: Send + Sync {/// ```fn limit(&self, n: usize) -> Result<Arc<dyn DataFrame>>;+ /// Calculate the union two [`DataFrame`]s. The two [`DataFrame`]s must have exactly the same schema+ ///+ /// ```+ /// # 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 df = df.union(df.clone())?;+ /// # Ok(())+ /// # }+ /// ```+ fn union(&self, dataframe: Arc<dyn DataFrame>) -> Result<Arc<dyn DataFrame>>;+/// Sort the DataFrame by the specified sorting expressions. Any expression can be turned into/// a sort expression by calling its [sort](../logical_plan/enum.Expr.html#method.sort) method.///diff --git a/rust/datafusion/src/execution/dataframe_impl.rs b/rust/datafusion/src/execution/dataframe_impl.rsindex 3a0931d8cc..7c3beb954d 100644--- a/rust/datafusion/src/execution/dataframe_impl.rs+++ b/rust/datafusion/src/execution/dataframe_impl.rs@@ -166,6 +166,13 @@ impl DataFrame for DataFrameImpl {let registry = self.ctx_state.lock().unwrap().clone();Arc::new(registry)}++ fn union(&self, dataframe: Arc<dyn DataFrame>) -> Result<Arc<dyn DataFrame>> {+ let plan = LogicalPlanBuilder::from(&self.plan)+ .union(dataframe.to_logical_plan())?+ .build()?;+ Ok(Arc::new(DataFrameImpl::new(self.ctx_state.clone(), &plan)))+ }}#[cfg(test)]diff --git a/rust/datafusion/src/logical_plan/builder.rs b/rust/datafusion/src/logical_plan/builder.rsindex 1f017b6f3c..58dfd0fa5d 100644--- a/rust/datafusion/src/logical_plan/builder.rs+++ b/rust/datafusion/src/logical_plan/builder.rs@@ -178,6 +178,29 @@ impl LogicalPlanBuilder {}))}+ /// Apply a union+ pub fn union(&self, plan: LogicalPlan) -> Result<Self> {+ let schema = self.plan.schema();++ if plan.schema() != schema {+ return Err(DataFusionError::Plan(+ "Schema's for union should be the same ".to_string(),+ ));+ }+ // Add plan to existing union if possible+ let mut inputs = match &self.plan {+ LogicalPlan::Union { inputs, .. } => inputs.clone(),+ _ => vec![self.plan.clone()],+ };+ inputs.push(plan);++ Ok(Self::from(&LogicalPlan::Union {+ inputs,+ schema: schema.clone(),+ alias: None,+ }))+ }+/// Apply a joinpub fn join(&self,@@ -413,6 +436,32 @@ mod tests {Ok(())}+ #[test]+ fn plan_builder_union_combined_single_union() -> Result<()> {+ let plan = LogicalPlanBuilder::scan_empty(+ "employee.csv",+ &employee_schema(),+ Some(vec![3, 4]),+ )?;++ let plan = plan+ .union(plan.build()?)?+ .union(plan.build()?)?+ .union(plan.build()?)?+ .build()?;++ // output has only one union+ let expected = "Union\+ \n TableScan: employee.csv projection=Some([3, 4])\+ \n TableScan: employee.csv projection=Some([3, 4])\+ \n TableScan: employee.csv projection=Some([3, 4])\+ \n TableScan: employee.csv projection=Some([3, 4])";++ assert_eq!(expected, format!("{:?}", plan));++ Ok(())+ }+#[test]fn projection_non_unique_names() -> Result<()> {let plan = LogicalPlanBuilder::scan_empty(@@ -425,9 +474,12 @@ mod tests {match plan {Err(DataFusionError::Plan(e)) => {- assert_eq!(e, "Projections require unique expression names \+ assert_eq!(+ e,+ "Projections require unique expression names \but the expression \"#id\" at position 0 and \"#first_name AS id\" at \- position 1 have the same name. Consider aliasing (\"AS\") one of them.");+ position 1 have the same name. Consider aliasing (\"AS\") one of them."+ );Ok(())}_ => Err(DataFusionError::Plan(@@ -448,9 +500,12 @@ mod tests {match plan {Err(DataFusionError::Plan(e)) => {- assert_eq!(e, "Aggregations require unique expression names \+ assert_eq!(+ e,+ "Aggregations require unique expression names \but the expression \"#state\" at position 0 and \"SUM(#salary) AS state\" at \- position 1 have the same name. Consider aliasing (\"AS\") one of them.");+ position 1 have the same name. Consider aliasing (\"AS\") one of them."+ );Ok(())}_ => Err(DataFusionError::Plan(diff --git a/rust/datafusion/src/logical_plan/plan.rs b/rust/datafusion/src/logical_plan/plan.rsindex 8aec9e668a..92110c8daf 100644--- a/rust/datafusion/src/logical_plan/plan.rs+++ b/rust/datafusion/src/logical_plan/plan.rs@@ -120,6 +120,15 @@ pub enum LogicalPlan {/// The partitioning schemepartitioning_scheme: Partitioning,},+ /// Union multiple inputs+ Union {+ /// Inputs to merge+ inputs: Vec<LogicalPlan>,+ /// Union schema. Should be the same for all inputs.+ schema: DFSchemaRef,+ /// Union output relation alias+ alias: Option<String>,+ },/// Produces rows from a table provider by reference or from the contextTableScan {/// The name of the table@@ -199,6 +208,7 @@ impl LogicalPlan {LogicalPlan::CreateExternalTable { schema, .. } => &schema,LogicalPlan::Explain { schema, .. } => &schema,LogicalPlan::Extension { node } => &node.schema(),+ LogicalPlan::Union { schema, .. } => &schema,}}@@ -225,6 +235,9 @@ impl LogicalPlan {schemas.insert(0, &schema);schemas}+ LogicalPlan::Union { schema, .. } => {+ vec![schema]+ }LogicalPlan::Extension { node } => vec![&node.schema()],LogicalPlan::Explain { schema, .. }| LogicalPlan::EmptyRelation { schema, .. }@@ -278,6 +291,9 @@ impl LogicalPlan {| LogicalPlan::Limit { .. }| LogicalPlan::CreateExternalTable { .. }| LogicalPlan::Explain { .. } => vec![],+ LogicalPlan::Union { .. } => {+ vec![]+ }}}@@ -293,6 +309,7 @@ impl LogicalPlan {LogicalPlan::Join { left, right, .. } => vec![left, right],LogicalPlan::Limit { input, .. } => vec![input],LogicalPlan::Extension { node } => node.inputs(),+ LogicalPlan::Union { inputs, .. } => inputs.iter().collect(),// plans without inputsLogicalPlan::TableScan { .. }| LogicalPlan::EmptyRelation { .. }@@ -382,6 +399,14 @@ impl LogicalPlan {LogicalPlan::Join { left, right, .. } => {left.accept(visitor)? && right.accept(visitor)?}+ LogicalPlan::Union { inputs, .. } => {+ for input in inputs {+ if !input.accept(visitor)? {+ return Ok(false);+ }+ }+ true+ }LogicalPlan::Limit { input, .. } => input.accept(visitor)?,LogicalPlan::Extension { node } => {for input in node.inputs() {@@ -671,6 +696,7 @@ impl LogicalPlan {write!(f, "CreateExternalTable: {:?}", name)}LogicalPlan::Explain { .. } => write!(f, "Explain"),+ LogicalPlan::Union { .. } => write!(f, "Union"),LogicalPlan::Extension { ref node } => node.fmt_for_explain(f),}}diff --git a/rust/datafusion/src/optimizer/constant_folding.rs b/rust/datafusion/src/optimizer/constant_folding.rsindex ab39daee27..ec4dfd4b01 100644--- a/rust/datafusion/src/optimizer/constant_folding.rs+++ b/rust/datafusion/src/optimizer/constant_folding.rs@@ -71,6 +71,7 @@ impl OptimizerRule for ConstantFolding {| LogicalPlan::Sort { .. }| LogicalPlan::Explain { .. }| LogicalPlan::Limit { .. }+ | LogicalPlan::Union { .. }| LogicalPlan::Join { .. } => {// apply the optimization to all inputs of the planlet inputs = plan.inputs();diff --git a/rust/datafusion/src/optimizer/hash_build_probe_order.rs b/rust/datafusion/src/optimizer/hash_build_probe_order.rsindex cb6d5c440e..f44050f0b7 100644--- a/rust/datafusion/src/optimizer/hash_build_probe_order.rs+++ b/rust/datafusion/src/optimizer/hash_build_probe_order.rs@@ -79,6 +79,10 @@ fn get_num_rows(logical_plan: &LogicalPlan) -> Option<usize> {// the following operators do not modify row count in any wayLogicalPlan::Projection { input, .. } => get_num_rows(input),LogicalPlan::Sort { input, .. } => get_num_rows(input),+ // Add number of rows of below plans+ LogicalPlan::Union { inputs, .. } => {+ inputs.iter().map(|plan| get_num_rows(plan)).sum()+ }}}@@ -145,6 +149,7 @@ impl OptimizerRule for HashBuildProbeOrder {| LogicalPlan::Sort { .. }| LogicalPlan::CreateExternalTable { .. }| LogicalPlan::Explain { .. }+ | LogicalPlan::Union { .. }| LogicalPlan::Extension { .. } => {let expr = plan.expressions();diff --git a/rust/datafusion/src/optimizer/limit_push_down.rs b/rust/datafusion/src/optimizer/limit_push_down.rsindex 67af69bc6b..fee03988c0 100644--- a/rust/datafusion/src/optimizer/limit_push_down.rs+++ b/rust/datafusion/src/optimizer/limit_push_down.rs@@ -39,8 +39,8 @@ fn limit_push_down(upper_limit: Option<usize>,plan: &LogicalPlan,) -> Result<LogicalPlan> {- match plan {- LogicalPlan::Limit { n, input } => {+ match (plan, upper_limit) {+ (LogicalPlan::Limit { n, input }, upper_limit) => {let smallest = upper_limit.map(|x| std::cmp::min(x, *n)).unwrap_or(*n);Ok(LogicalPlan::Limit {n: smallest,@@ -48,32 +48,34 @@ fn limit_push_down(input: Arc::new(limit_push_down(Some(smallest), input.as_ref())?),})}- LogicalPlan::TableScan {- table_name,- source,- projection,- filters,- limit,- projected_schema,- } => {- if let Some(n) = upper_limit {- Ok(LogicalPlan::TableScan {- table_name: table_name.clone(),- source: source.clone(),- projection: projection.clone(),- filters: filters.clone(),- limit: limit.map(|x| std::cmp::min(x, n)).or(Some(n)),- projected_schema: projected_schema.clone(),- })- } else {- Ok(plan.clone())- }- }- LogicalPlan::Projection {- expr,- input,- schema,- } => {+ (+ LogicalPlan::TableScan {+ table_name,+ source,+ projection,+ filters,+ limit,+ projected_schema,+ },+ Some(upper_limit),+ ) => Ok(LogicalPlan::TableScan {+ table_name: table_name.clone(),+ source: source.clone(),+ projection: projection.clone(),+ filters: filters.clone(),+ limit: limit+ .map(|x| std::cmp::min(x, upper_limit))+ .or(Some(upper_limit)),+ projected_schema: projected_schema.clone(),+ }),+ (+ LogicalPlan::Projection {+ expr,+ input,+ schema,+ },+ upper_limit,+ ) => {// Push down limit directly (projection doesn't change number of rows)Ok(LogicalPlan::Projection {expr: expr.clone(),@@ -81,6 +83,30 @@ fn limit_push_down(schema: schema.clone(),})}+ (+ LogicalPlan::Union {+ inputs,+ alias,+ schema,+ },+ Some(upper_limit),+ ) => {+ // Push down limit through UNION+ let new_inputs = inputs+ .iter()+ .map(|x| {+ Ok(LogicalPlan::Limit {+ n: upper_limit,+ input: Arc::new(limit_push_down(Some(upper_limit), x)?),+ })+ })+ .collect::<Result<_>>()?;+ Ok(LogicalPlan::Union {+ inputs: new_inputs,+ alias: alias.clone(),+ schema: schema.clone(),+ })+ }// For other nodes we can't push down the limit// But try to recurse and find other limit nodes to push down_ => {@@ -181,6 +207,28 @@ mod test {Ok(())}+ #[test]+ fn limit_should_push_down_union() -> Result<()> {+ let table_scan = test_table_scan()?;++ let plan = LogicalPlanBuilder::from(&table_scan)+ .union(LogicalPlanBuilder::from(&table_scan).build()?)?+ .limit(1000)?+ .build()?;++ // Limit should push down through union+ let expected = "Limit: 1000\+ \n Union\+ \n Limit: 1000\+ \n TableScan: test projection=None, limit=1000\+ \n Limit: 1000\+ \n TableScan: test projection=None, limit=1000";++ assert_optimized_plan_eq(&plan, expected);++ Ok(())+ }+#[test]fn multi_stage_limit_recurses_to_deeper_limit() -> Result<()> {let table_scan = test_table_scan()?;diff --git a/rust/datafusion/src/optimizer/projection_push_down.rs b/rust/datafusion/src/optimizer/projection_push_down.rsindex 59c7b10d15..8452321757 100644--- a/rust/datafusion/src/optimizer/projection_push_down.rs+++ b/rust/datafusion/src/optimizer/projection_push_down.rs@@ -269,6 +269,7 @@ fn optimize_plan(| LogicalPlan::EmptyRelation { .. }| LogicalPlan::Sort { .. }| LogicalPlan::CreateExternalTable { .. }+ | LogicalPlan::Union { .. }| LogicalPlan::Extension { .. } => {let expr = plan.expressions();// collect all required columns by this plandiff --git a/rust/datafusion/src/optimizer/utils.rs b/rust/datafusion/src/optimizer/utils.rsindex c2552d77d2..da21c58fee 100644--- a/rust/datafusion/src/optimizer/utils.rs+++ b/rust/datafusion/src/optimizer/utils.rs@@ -214,6 +214,11 @@ pub fn from_plan(LogicalPlan::Extension { node } => Ok(LogicalPlan::Extension {node: node.from_template(expr, inputs),}),+ LogicalPlan::Union { schema, alias, .. } => Ok(LogicalPlan::Union {+ inputs: inputs.to_vec(),+ schema: schema.clone(),+ alias: alias.clone(),+ }),LogicalPlan::EmptyRelation { .. }| LogicalPlan::TableScan { .. }| LogicalPlan::CreateExternalTable { .. }diff --git a/rust/datafusion/src/physical_plan/mod.rs b/rust/datafusion/src/physical_plan/mod.rsindex 7702ff2c4d..3d549ec932 100644--- a/rust/datafusion/src/physical_plan/mod.rs+++ b/rust/datafusion/src/physical_plan/mod.rs@@ -308,3 +308,4 @@ pub mod udaf;pub mod udf;#[cfg(feature = "unicode_expressions")]pub mod unicode_expressions;+pub mod union;diff --git a/rust/datafusion/src/physical_plan/planner.rs b/rust/datafusion/src/physical_plan/planner.rsindex ef1cb1160a..c6f321ca9b 100644--- a/rust/datafusion/src/physical_plan/planner.rs+++ b/rust/datafusion/src/physical_plan/planner.rs@@ -19,7 +19,9 @@use std::sync::Arc;-use super::{aggregates, empty::EmptyExec, expressions::binary, functions, udaf};+use super::{+ aggregates, empty::EmptyExec, expressions::binary, functions, udaf, union::UnionExec,+};use crate::error::{DataFusionError, Result};use crate::execution::context::ExecutionContextState;use crate::logical_plan::{@@ -268,6 +270,13 @@ impl DefaultPhysicalPlanner {self.create_physical_expr(predicate, &input_schema, ctx_state)?;Ok(Arc::new(FilterExec::try_new(runtime_expr, input)?))}+ LogicalPlan::Union { inputs, .. } => {+ let physical_plans = inputs+ .iter()+ .map(|input| self.create_physical_plan(input, ctx_state))+ .collect::<Result<Vec<_>>>()?;+ Ok(Arc::new(UnionExec::new(physical_plans)))+ }LogicalPlan::Repartition {input,partitioning_scheme,@@ -870,7 +879,8 @@ mod tests {};let plan = planner.create_physical_plan(&logical_plan, &ctx_state);- let expected_error = "No installed planner was able to convert the custom node to an execution plan: NoOp";+ let expected_error =+ "No installed planner was able to convert the custom node to an execution plan: NoOp";match plan {Ok(_) => panic!("Expected planning failure"),Err(e) => assert!(diff --git a/rust/datafusion/src/physical_plan/union.rs b/rust/datafusion/src/physical_plan/union.rsnew file mode 100644index 0000000000..cbab728a84--- /dev/null+++ b/rust/datafusion/src/physical_plan/union.rs@@ -0,0 +1,143 @@+// 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.++// Some of these functions reference the Postgres documentation+// or implementation to ensure compatibility and are subject to+// the Postgres license.++//! The Union operator combines multiple inputs with the same schema++use std::{any::Any, sync::Arc};++use arrow::datatypes::SchemaRef;++use super::{ExecutionPlan, Partitioning, SendableRecordBatchStream};+use crate::error::Result;+use async_trait::async_trait;++/// UNION ALL execution plan+#[derive(Debug)]+pub struct UnionExec {+ /// Input execution plan+ inputs: Vec<Arc<dyn ExecutionPlan>>,+}++impl UnionExec {+ /// Create a new UnionExec+ pub fn new(inputs: Vec<Arc<dyn ExecutionPlan>>) -> Self {+ UnionExec { inputs }+ }+}++#[async_trait]+impl ExecutionPlan for UnionExec {+ /// Return a reference to Any that can be used for downcasting+ fn as_any(&self) -> &dyn Any {+ self+ }++ fn schema(&self) -> SchemaRef {+ self.inputs[0].schema()+ }++ fn children(&self) -> Vec<Arc<dyn ExecutionPlan>> {+ self.inputs.clone()+ }++ /// Output of the union is the combination of all output partitions of the inputs+ fn output_partitioning(&self) -> Partitioning {+ // Sums all the output partitions+ let num_partitions = self+ .inputs+ .iter()+ .map(|plan| plan.output_partitioning().partition_count())+ .sum();+ // TODO: this loses partitioning info in case of same partitioning scheme (for example `Partitioning::Hash`)+ // https://issues.apache.org/jira/browse/ARROW-11991+ Partitioning::UnknownPartitioning(num_partitions)+ }++ fn with_new_children(+ &self,+ children: Vec<Arc<dyn ExecutionPlan>>,+ ) -> Result<Arc<dyn ExecutionPlan>> {+ Ok(Arc::new(UnionExec::new(children)))+ }++ async fn execute(&self, mut partition: usize) -> Result<SendableRecordBatchStream> {+ // find partition to execute+ for input in self.inputs.iter() {+ // Calculate whether partition belongs to the current partition+ if partition < input.output_partitioning().partition_count() {+ return input.execute(partition).await;+ } else {+ partition -= input.output_partitioning().partition_count();+ }+ }++ Err(crate::error::DataFusionError::Execution(format!(+ "Partition {} not found in Union",+ partition+ )))+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::physical_plan::{+ collect,+ csv::{CsvExec, CsvReadOptions},+ };+ use crate::test;+ use arrow::record_batch::RecordBatch;++ #[tokio::test]+ async fn test_union_partitions() -> Result<()> {+ let schema = test::aggr_test_schema();++ // Create csv's with different partitioning+ let path = test::create_partitioned_csv("aggregate_test_100.csv", 4)?;+ let path2 = test::create_partitioned_csv("aggregate_test_100.csv", 5)?;++ let csv = CsvExec::try_new(+ &path,+ CsvReadOptions::new().schema(&schema),+ None,+ 1024,+ None,+ )?;++ let csv2 = CsvExec::try_new(+ &path2,+ CsvReadOptions::new().schema(&schema),+ None,+ 1024,+ None,+ )?;++ let union_exec = Arc::new(UnionExec::new(vec![Arc::new(csv), Arc::new(csv2)]));++ // Should have 9 partitions and 9 output batches+ assert_eq!(union_exec.output_partitioning().partition_count(), 9);++ let result: Vec<RecordBatch> = collect(union_exec).await?;+ assert_eq!(result.len(), 9);++ Ok(())+ }+}diff --git a/rust/datafusion/src/sql/planner.rs b/rust/datafusion/src/sql/planner.rsindex f985b50653..31cea52a0f 100644--- a/rust/datafusion/src/sql/planner.rs+++ b/rust/datafusion/src/sql/planner.rs@@ -42,8 +42,8 @@ use arrow::datatypes::*;use crate::prelude::JoinType;use sqlparser::ast::{BinaryOperator, DataType as SQLDataType, DateTimeField, Expr as SQLExpr, FunctionArg,- Join, JoinConstraint, JoinOperator, Query, Select, SelectItem, SetExpr, TableFactor,- TableWithJoins, UnaryOperator, Value,+ Join, JoinConstraint, JoinOperator, Query, Select, SelectItem, SetExpr, SetOperator,+ TableFactor, TableWithJoins, UnaryOperator, Value,};use sqlparser::ast::{ColumnDef as SQLColumnDef, ColumnOption};use sqlparser::ast::{OrderByExpr, Statement};@@ -104,19 +104,75 @@ impl<'a, S: ContextProvider> SqlToRel<'a, S> {/// Generate a logic plan from an SQL querypub fn query_to_plan(&self, query: &Query) -> Result<LogicalPlan> {- let plan = match &query.body {- SetExpr::Select(s) => self.select_to_plan(s.as_ref()),- _ => Err(DataFusionError::NotImplemented(format!(- "Query {} not implemented yet",- query.body- ))),- }?;+ self.query_to_plan_with_alias(query, None)+ }++ /// Generate a logic plan from an SQL query with optional alias+ pub fn query_to_plan_with_alias(+ &self,+ query: &Query,+ alias: Option<String>,+ ) -> Result<LogicalPlan> {+ let set_expr = &query.body;+ let plan = self.set_expr_to_plan(set_expr, alias)?;let plan = self.order_by(&plan, &query.order_by)?;self.limit(&plan, &query.limit)}+ fn set_expr_to_plan(+ &self,+ set_expr: &SetExpr,+ alias: Option<String>,+ ) -> Result<LogicalPlan> {+ match set_expr {+ SetExpr::Select(s) => self.select_to_plan(s.as_ref()),+ SetExpr::SetOperation {+ op,+ left,+ right,+ all,+ } => match (op, all) {+ (SetOperator::Union, true) => {+ let left_plan = self.set_expr_to_plan(left.as_ref(), None)?;+ let right_plan = self.set_expr_to_plan(right.as_ref(), None)?;+ let inputs = vec![left_plan, right_plan]+ .into_iter()+ .flat_map(|p| match p {+ LogicalPlan::Union { inputs, .. } => inputs,+ x => vec![x],+ })+ .collect::<Vec<_>>();+ if inputs.is_empty() {+ return Err(DataFusionError::Plan(format!(+ "Empty UNION: {}",+ set_expr+ )));+ }+ if !inputs.iter().all(|s| s.schema() == inputs[0].schema()) {+ return Err(DataFusionError::Plan(+ "UNION ALL schemas are expected to be the same".to_string(),+ ));+ }+ Ok(LogicalPlan::Union {+ schema: inputs[0].schema().clone(),+ inputs,+ alias,+ })+ }+ _ => Err(DataFusionError::NotImplemented(format!(+ "Only UNION ALL is supported, found {}",+ op+ ))),+ },+ _ => Err(DataFusionError::NotImplemented(format!(+ "Query {} not implemented yet",+ set_expr+ ))),+ }+ }+/// Generate a logical plan from a CREATE EXTERNAL TABLE statementpub fn external_table_to_plan(&self,@@ -330,7 +386,12 @@ impl<'a, S: ContextProvider> SqlToRel<'a, S> {))),}}- TableFactor::Derived { subquery, .. } => self.query_to_plan(subquery),+ TableFactor::Derived {+ subquery, alias, ..+ } => self.query_to_plan_with_alias(+ subquery,+ alias.as_ref().map(|a| a.name.value.to_string()),+ ),TableFactor::NestedJoin(table_with_joins) => {self.plan_table_with_joins(table_with_joins)}@@ -2359,6 +2420,55 @@ mod tests {quick_test(sql, expected);}+ #[test]+ fn union() {+ let sql = "SELECT order_id from orders UNION ALL SELECT order_id FROM orders";+ let expected = "Union\+ \n Projection: #order_id\+ \n TableScan: orders projection=None\+ \n Projection: #order_id\+ \n TableScan: orders projection=None";+ quick_test(sql, expected);+ }++ #[test]+ fn union_4_combined_in_one() {+ let sql = "SELECT order_id from orders+ UNION ALL SELECT order_id FROM orders+ UNION ALL SELECT order_id FROM orders+ UNION ALL SELECT order_id FROM orders";+ let expected = "Union\+ \n Projection: #order_id\+ \n TableScan: orders projection=None\+ \n Projection: #order_id\+ \n TableScan: orders projection=None\+ \n Projection: #order_id\+ \n TableScan: orders projection=None\+ \n Projection: #order_id\+ \n TableScan: orders projection=None";+ quick_test(sql, expected);+ }++ #[test]+ fn union_schemas_should_be_same() {+ let sql = "SELECT order_id from orders UNION ALL SELECT customer_id FROM orders";+ let err = logical_plan(sql).expect_err("query should have failed");+ assert_eq!(+ "Plan(\"UNION ALL schemas are expected to be the same\")",+ format!("{:?}", err)+ );+ }++ #[test]+ fn only_union_all_supported() {+ let sql = "SELECT order_id from orders EXCEPT SELECT order_id FROM orders";+ let err = logical_plan(sql).expect_err("query should have failed");+ assert_eq!(+ "NotImplemented(\"Only UNION ALL is supported, found EXCEPT\")",+ format!("{:?}", err)+ );+ }+#[test]fn select_typedstring() {let sql = "SELECT date '2020-12-10' AS date FROM person";diff --git a/rust/datafusion/tests/sql.rs b/rust/datafusion/tests/sql.rsindex d7bea20abe..1bce3f7c07 100644--- a/rust/datafusion/tests/sql.rs+++ b/rust/datafusion/tests/sql.rs@@ -766,6 +766,27 @@ async fn csv_query_cast_literal() -> Result<()> {Ok(())}+#[tokio::test]+async fn union_all() -> Result<()> {+ let mut ctx = ExecutionContext::new();+ let sql = "SELECT 1 as x UNION ALL SELECT 2 as x";+ let actual = execute(&mut ctx, sql).await;+ let expected = vec![vec!["1"], vec!["2"]];+ assert_eq!(expected, actual);+ Ok(())+}++#[tokio::test]+async fn csv_union_all() -> Result<()> {+ let mut ctx = ExecutionContext::new();+ register_aggregate_csv(&mut ctx)?;+ let sql =+ "SELECT c1 FROM aggregate_test_100 UNION ALL SELECT c1 FROM aggregate_test_100";+ let actual = execute(&mut ctx, sql).await;+ assert_eq!(actual.len(), 200);+ Ok(())+}+#[tokio::test]async fn csv_query_limit() -> Result<()> {let mut ctx = ExecutionContext::new();