Skip to content

Apache DataFusion SQL Query Engine

ARROW-9911: [Rust][DataFusion] SELECT <expression> with no FROM clause should produce a single row of output

waynec385dc7ed7d4
diff --git a/rust/datafusion/src/execution/context.rs b/rust/datafusion/src/execution/context.rs
index af10a18fb2..feebe04c0e 100644
--- a/rust/datafusion/src/execution/context.rs
+++ b/rust/datafusion/src/execution/context.rs
@@ -142,12 +142,12 @@ impl ExecutionContext {
.schema(&schema)
.has_header(*has_header),
)?;
- let plan = LogicalPlanBuilder::empty().build()?;
+ let plan = LogicalPlanBuilder::empty(false).build()?;
Ok(Arc::new(DataFrameImpl::new(self.state.clone(), &plan)))
}
FileType::Parquet => {
self.register_parquet(name, location)?;
- let plan = LogicalPlanBuilder::empty().build()?;
+ let plan = LogicalPlanBuilder::empty(false).build()?;
Ok(Arc::new(DataFrameImpl::new(self.state.clone(), &plan)))
}
_ => Err(DataFusionError::NotImplemented(format!(
diff --git a/rust/datafusion/src/logical_plan/builder.rs b/rust/datafusion/src/logical_plan/builder.rs
index d17b547670..32e5303928 100644
--- a/rust/datafusion/src/logical_plan/builder.rs
+++ b/rust/datafusion/src/logical_plan/builder.rs
@@ -41,9 +41,12 @@ impl LogicalPlanBuilder {
Self { plan: plan.clone() }
}
- /// Create an empty relation
- pub fn empty() -> Self {
+ /// Create an empty relation.
+ ///
+ /// `produce_one_row` set to true means this empty node needs to produce a placeholder row.
+ pub fn empty(produce_one_row: bool) -> Self {
Self::from(&LogicalPlan::EmptyRelation {
+ produce_one_row,
schema: SchemaRef::new(Schema::empty()),
})
}
diff --git a/rust/datafusion/src/logical_plan/plan.rs b/rust/datafusion/src/logical_plan/plan.rs
index 6f93a7a0ea..ced13fa89c 100644
--- a/rust/datafusion/src/logical_plan/plan.rs
+++ b/rust/datafusion/src/logical_plan/plan.rs
@@ -146,6 +146,8 @@ pub enum LogicalPlan {
},
/// Produces no rows: An empty relation with an empty schema
EmptyRelation {
+ /// Whether to produce a placeholder row
+ produce_one_row: bool,
/// The schema description of the output
schema: SchemaRef,
},
@@ -192,7 +194,7 @@ impl LogicalPlan {
/// Get a reference to the logical plan's schema
pub fn schema(&self) -> &SchemaRef {
match self {
- LogicalPlan::EmptyRelation { schema } => &schema,
+ LogicalPlan::EmptyRelation { schema, .. } => &schema,
LogicalPlan::InMemoryScan {
projected_schema, ..
} => &projected_schema,
diff --git a/rust/datafusion/src/optimizer/utils.rs b/rust/datafusion/src/optimizer/utils.rs
index 3b83fcbd93..b4c4e890ba 100644
--- a/rust/datafusion/src/optimizer/utils.rs
+++ b/rust/datafusion/src/optimizer/utils.rs
@@ -320,7 +320,7 @@ mod tests {
fn test_optimize_explain() -> Result<()> {
let mut optimizer = TestOptimizer {};
- let empty_plan = LogicalPlanBuilder::empty().build()?;
+ let empty_plan = LogicalPlanBuilder::empty(false).build()?;
let schema = LogicalPlan::explain_schema();
let optimized_explain = optimize_explain(
diff --git a/rust/datafusion/src/physical_plan/empty.rs b/rust/datafusion/src/physical_plan/empty.rs
index ecdbeba9ee..129970fb26 100644
--- a/rust/datafusion/src/physical_plan/empty.rs
+++ b/rust/datafusion/src/physical_plan/empty.rs
@@ -23,7 +23,9 @@ use std::sync::Arc;
use crate::error::{DataFusionError, Result};
use crate::physical_plan::memory::MemoryStream;
use crate::physical_plan::{Distribution, ExecutionPlan, Partitioning};
-use arrow::datatypes::SchemaRef;
+use arrow::array::NullArray;
+use arrow::datatypes::{DataType, Field, Schema, SchemaRef};
+use arrow::record_batch::RecordBatch;
use super::SendableRecordBatchStream;
@@ -32,13 +34,17 @@ use async_trait::async_trait;
/// Execution plan for empty relation (produces no rows)
#[derive(Debug)]
pub struct EmptyExec {
+ produce_one_row: bool,
schema: SchemaRef,
}
impl EmptyExec {
/// Create a new EmptyExec
- pub fn new(schema: SchemaRef) -> Self {
- EmptyExec { schema }
+ pub fn new(produce_one_row: bool, schema: SchemaRef) -> Self {
+ EmptyExec {
+ produce_one_row,
+ schema,
+ }
}
}
@@ -71,7 +77,7 @@ impl ExecutionPlan for EmptyExec {
children: Vec<Arc<dyn ExecutionPlan>>,
) -> Result<Arc<dyn ExecutionPlan>> {
match children.len() {
- 0 => Ok(Arc::new(EmptyExec::new(self.schema.clone()))),
+ 0 => Ok(Arc::new(EmptyExec::new(false, self.schema.clone()))),
_ => Err(DataFusionError::Internal(
"EmptyExec wrong number of children".to_string(),
)),
@@ -87,7 +93,20 @@ impl ExecutionPlan for EmptyExec {
)));
}
- let data = vec![];
+ // Makes a stream only contains one null element if needed
+ let data = if self.produce_one_row {
+ vec![RecordBatch::try_new(
+ Arc::new(Schema::new(vec![Field::new(
+ "placeholder",
+ DataType::Null,
+ true,
+ )])),
+ vec![Arc::new(NullArray::new(1))],
+ )?]
+ } else {
+ vec![]
+ };
+
Ok(Box::pin(MemoryStream::try_new(
data,
self.schema.clone(),
@@ -106,7 +125,7 @@ mod tests {
async fn empty() -> Result<()> {
let schema = test::aggr_test_schema();
- let empty = EmptyExec::new(schema.clone());
+ let empty = EmptyExec::new(false, schema.clone());
assert_eq!(empty.schema(), schema);
// we should have no results
@@ -120,7 +139,7 @@ mod tests {
#[test]
fn with_new_children() -> Result<()> {
let schema = test::aggr_test_schema();
- let empty = EmptyExec::new(schema.clone());
+ let empty = EmptyExec::new(false, schema.clone());
let empty2 = empty.with_new_children(vec![])?;
assert_eq!(empty.schema(), empty2.schema());
@@ -136,11 +155,25 @@ mod tests {
#[tokio::test]
async fn invalid_execute() -> Result<()> {
let schema = test::aggr_test_schema();
- let empty = EmptyExec::new(schema.clone());
+ let empty = EmptyExec::new(false, schema.clone());
// ask for the wrong partition
assert!(empty.execute(1).await.is_err());
assert!(empty.execute(20).await.is_err());
Ok(())
}
+
+ #[tokio::test]
+ async fn produce_one_row() -> Result<()> {
+ let schema = test::aggr_test_schema();
+ let empty = EmptyExec::new(true, schema);
+
+ let iter = empty.execute(0).await?;
+ let batches = common::collect(iter).await?;
+
+ // should have one item
+ assert_eq!(batches.len(), 1);
+
+ Ok(())
+ }
}
diff --git a/rust/datafusion/src/physical_plan/planner.rs b/rust/datafusion/src/physical_plan/planner.rs
index 1303fa4b0f..4740a5dde1 100644
--- a/rust/datafusion/src/physical_plan/planner.rs
+++ b/rust/datafusion/src/physical_plan/planner.rs
@@ -287,9 +287,13 @@ impl DefaultPhysicalPlanner {
ctx_state.config.concurrency,
)?))
}
- LogicalPlan::EmptyRelation { schema } => {
- Ok(Arc::new(EmptyExec::new(Arc::new(schema.as_ref().clone()))))
- }
+ LogicalPlan::EmptyRelation {
+ produce_one_row,
+ schema,
+ } => Ok(Arc::new(EmptyExec::new(
+ *produce_one_row,
+ Arc::new(schema.as_ref().clone()),
+ ))),
LogicalPlan::Limit { input, n, .. } => {
let limit = *n;
let input = self.create_physical_plan(input, ctx_state)?;
diff --git a/rust/datafusion/src/physical_plan/projection.rs b/rust/datafusion/src/physical_plan/projection.rs
index e15a264e5c..65b2828ca9 100644
--- a/rust/datafusion/src/physical_plan/projection.rs
+++ b/rust/datafusion/src/physical_plan/projection.rs
@@ -18,7 +18,7 @@
//! Defines the projection execution plan. A projection determines which columns or expressions
//! are returned from a query. The SQL statement `SELECT a, b, a+b FROM t1` is an example
//! of a projection on table `t1` where the expressions `a`, `b`, and `a+b` are the
-//! projection expressions.
+//! projection expressions. `SELECT` without `FROM` will only evaluate expressions.
use std::any::Any;
use std::pin::Pin;
diff --git a/rust/datafusion/src/sql/planner.rs b/rust/datafusion/src/sql/planner.rs
index fc138dfbc8..0d275391ca 100644
--- a/rust/datafusion/src/sql/planner.rs
+++ b/rust/datafusion/src/sql/planner.rs
@@ -209,7 +209,7 @@ impl<'a, S: SchemaProvider> SqlToRel<'a, S> {
fn from_join_to_plan(&self, from: &Vec<TableWithJoins>) -> Result<LogicalPlan> {
if from.len() == 0 {
- return Ok(LogicalPlanBuilder::empty().build()?);
+ return Ok(LogicalPlanBuilder::empty(true).build()?);
}
if from.len() != 1 {
return Err(DataFusionError::NotImplemented(
diff --git a/rust/datafusion/tests/sql.rs b/rust/datafusion/tests/sql.rs
index 8dd7afa1d7..ca8a6cc4f0 100644
--- a/rust/datafusion/tests/sql.rs
+++ b/rust/datafusion/tests/sql.rs
@@ -1399,3 +1399,22 @@ async fn query_on_string_dictionary() -> Result<()> {
Ok(())
}
+
+#[tokio::test]
+async fn query_without_from() -> Result<()> {
+ // Test for SELECT <expression> without FROM.
+ // Should evaluate expressions in project position.
+ let mut ctx = ExecutionContext::new();
+
+ let sql = "SELECT 1";
+ let actual = execute(&mut ctx, sql).await;
+ let expected = vec![vec!["1"]];
+ assert_eq!(expected, actual);
+
+ let sql = "SELECT 1+2, 3/4, cos(0)";
+ let actual = execute(&mut ctx, sql).await;
+ let expected = vec![vec!["3", "0", "1"]];
+ assert_eq!(expected, actual);
+
+ Ok(())
+}