Skip to content

Apache DataFusion SQL Query Engine

ARROW-9889: [Rust][DataFusion] Implement physical plan for EmptyRelation

alamb8290a5089179
diff --git a/rust/datafusion/src/execution/physical_plan/empty.rs b/rust/datafusion/src/execution/physical_plan/empty.rs
new file mode 100644
index 0000000000..6b057dc390
--- /dev/null
+++ b/rust/datafusion/src/execution/physical_plan/empty.rs
@@ -0,0 +1,139 @@
+// 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.
+
+//! EmptyRelation execution plan
+
+use std::sync::{Arc, Mutex};
+
+use crate::error::{ExecutionError, Result};
+use crate::execution::physical_plan::memory::MemoryIterator;
+use crate::execution::physical_plan::{Distribution, ExecutionPlan, Partitioning};
+use arrow::datatypes::SchemaRef;
+use arrow::record_batch::RecordBatchReader;
+
+/// Execution plan for empty relation (produces no rows)
+#[derive(Debug)]
+pub struct EmptyExec {
+ schema: SchemaRef,
+}
+
+impl EmptyExec {
+ /// Create a new EmptyExec
+ pub fn new(schema: SchemaRef) -> Self {
+ EmptyExec { schema }
+ }
+}
+
+impl ExecutionPlan for EmptyExec {
+ fn schema(&self) -> SchemaRef {
+ self.schema.clone()
+ }
+
+ fn children(&self) -> Vec<Arc<dyn ExecutionPlan>> {
+ vec![]
+ }
+
+ fn required_child_distribution(&self) -> Distribution {
+ Distribution::UnspecifiedDistribution
+ }
+
+ /// Get the output partitioning of this plan
+ fn output_partitioning(&self) -> Partitioning {
+ Partitioning::UnknownPartitioning(1)
+ }
+
+ fn with_new_children(
+ &self,
+ children: Vec<Arc<dyn ExecutionPlan>>,
+ ) -> Result<Arc<dyn ExecutionPlan>> {
+ match children.len() {
+ 0 => Ok(Arc::new(EmptyExec::new(self.schema.clone()))),
+ _ => Err(ExecutionError::General(
+ "EmptyExec wrong number of children".to_string(),
+ )),
+ }
+ }
+
+ fn execute(
+ &self,
+ partition: usize,
+ ) -> Result<Arc<Mutex<dyn RecordBatchReader + Send + Sync>>> {
+ // GlobalLimitExec has a single output partition
+ if 0 != partition {
+ return Err(ExecutionError::General(format!(
+ "EmptyExec invalid partition {} (expected 0)",
+ partition
+ )));
+ }
+
+ let data = vec![];
+ Ok(Arc::new(Mutex::new(MemoryIterator::try_new(
+ data,
+ self.schema.clone(),
+ None,
+ )?)))
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::execution::physical_plan::common;
+ use crate::test;
+
+ #[test]
+ fn empty() -> Result<()> {
+ let schema = test::aggr_test_schema();
+
+ let empty = EmptyExec::new(schema.clone());
+ assert_eq!(empty.schema(), schema);
+
+ // we should have no results
+ let iter = empty.execute(0)?;
+ let batches = common::collect(iter)?;
+ assert!(batches.is_empty());
+
+ Ok(())
+ }
+
+ #[test]
+ fn with_new_children() -> Result<()> {
+ let schema = test::aggr_test_schema();
+ let empty = EmptyExec::new(schema.clone());
+
+ let empty2 = empty.with_new_children(vec![])?;
+ assert_eq!(empty.schema(), empty2.schema());
+
+ let too_many_kids = vec![empty2];
+ assert!(
+ empty.with_new_children(too_many_kids).is_err(),
+ "expected error when providing list of kids"
+ );
+ Ok(())
+ }
+
+ #[test]
+ fn invalid_execute() -> Result<()> {
+ let schema = test::aggr_test_schema();
+ let empty = EmptyExec::new(schema.clone());
+
+ // ask for the wrong partition
+ assert!(empty.execute(1).is_err());
+ assert!(empty.execute(20).is_err());
+ Ok(())
+ }
+}
diff --git a/rust/datafusion/src/execution/physical_plan/explain.rs b/rust/datafusion/src/execution/physical_plan/explain.rs
index 6c48742d6b..959f1c4c3b 100644
--- a/rust/datafusion/src/execution/physical_plan/explain.rs
+++ b/rust/datafusion/src/execution/physical_plan/explain.rs
@@ -44,7 +44,7 @@ pub struct ExplainExec {
}
impl ExplainExec {
- /// Create a new MergeExec
+ /// Create a new ExplainExec
pub fn new(schema: SchemaRef, stringified_plans: Vec<StringifiedPlan>) -> Self {
ExplainExec {
schema,
diff --git a/rust/datafusion/src/execution/physical_plan/mod.rs b/rust/datafusion/src/execution/physical_plan/mod.rs
index 7a6ed865e3..c0af8e75a4 100644
--- a/rust/datafusion/src/execution/physical_plan/mod.rs
+++ b/rust/datafusion/src/execution/physical_plan/mod.rs
@@ -132,6 +132,7 @@ pub trait Accumulator: Debug {
pub mod common;
pub mod csv;
+pub mod empty;
pub mod explain;
pub mod expressions;
pub mod filter;
diff --git a/rust/datafusion/src/execution/physical_plan/planner.rs b/rust/datafusion/src/execution/physical_plan/planner.rs
index 84806ea074..7bb186efbb 100644
--- a/rust/datafusion/src/execution/physical_plan/planner.rs
+++ b/rust/datafusion/src/execution/physical_plan/planner.rs
@@ -19,7 +19,7 @@
use std::sync::Arc;
-use super::{expressions::binary, functions};
+use super::{empty::EmptyExec, expressions::binary, functions};
use crate::error::{ExecutionError, Result};
use crate::execution::context::ExecutionContextState;
use crate::execution::physical_plan::csv::{CsvExec, CsvReadOptions};
@@ -278,6 +278,9 @@ impl DefaultPhysicalPlanner {
ctx_state.config.concurrency,
)?))
}
+ LogicalPlan::EmptyRelation { schema } => {
+ Ok(Arc::new(EmptyExec::new(Arc::new(schema.as_ref().clone()))))
+ }
LogicalPlan::Limit { input, n, .. } => {
let limit = *n;
let input = self.create_physical_plan(input, ctx_state)?;
@@ -297,6 +300,15 @@ impl DefaultPhysicalPlanner {
ctx_state.config.concurrency,
)))
}
+ LogicalPlan::CreateExternalTable { .. } => {
+ // There is no default plan for "CREATE EXTERNAL
+ // TABLE" -- it must be handled at a higher level (so
+ // that the appropriate table can be registered with
+ // the context)
+ Err(ExecutionError::General(
+ "Unsupported logical plan: CreateExternalTable".to_string(),
+ ))
+ }
LogicalPlan::Explain {
verbose,
plan,
@@ -318,12 +330,9 @@ impl DefaultPhysicalPlanner {
format!("{:#?}", input),
));
}
- let schema_ref = Arc::new((**schema).clone());
+ let schema_ref = Arc::new(schema.as_ref().clone());
Ok(Arc::new(ExplainExec::new(schema_ref, stringified_plans)))
}
- _ => Err(ExecutionError::General(
- "Unsupported logical plan variant".to_string(),
- )),
}
}
diff --git a/rust/datafusion/tests/sql.rs b/rust/datafusion/tests/sql.rs
index daf37f409d..ed48c3f902 100644
--- a/rust/datafusion/tests/sql.rs
+++ b/rust/datafusion/tests/sql.rs
@@ -520,8 +520,9 @@ fn register_aggregate_csv_by_sql(ctx: &mut ExecutionContext) {
// TODO: The following c9 should be migrated to UInt32 and c10 should be UInt64 once
// unsigned is supported.
- ctx.sql(&format!(
- "
+ let df = ctx
+ .sql(&format!(
+ "
CREATE EXTERNAL TABLE aggregate_test_100 (
c1 VARCHAR NOT NULL,
c2 INT NOT NULL,
@@ -541,9 +542,17 @@ fn register_aggregate_csv_by_sql(ctx: &mut ExecutionContext) {
WITH HEADER ROW
LOCATION '{}/csv/aggregate_test_100.csv'
",
- testdata
- ))
- .unwrap();
+ testdata
+ ))
+ .expect("Creating dataframe for CREATE EXTERNAL TABLE");
+
+ // Mimic the CLI and execute the resulting plan -- even though it
+ // is effectively a no-op (returns zero rows)
+ let results = df.collect().expect("Executing CREATE EXTERNAL TABLE");
+ assert!(
+ results.is_empty(),
+ "Expected no rows from executing CREATE EXTERNAL TABLE"
+ );
}
fn register_aggregate_csv(ctx: &mut ExecutionContext) -> Result<()> {