Apache DataFusion SQL Query Engine
Implement physical planner support for DATE +/- INTERVAL (#2357)
Andy Grove98ce80fe77ae
diff --git a/datafusion/core/src/optimizer/simplify_expressions.rs b/datafusion/core/src/optimizer/simplify_expressions.rsindex 4572246190..4dfbb6eb65 100644--- a/datafusion/core/src/optimizer/simplify_expressions.rs+++ b/datafusion/core/src/optimizer/simplify_expressions.rs@@ -294,7 +294,7 @@ impl<'a> ExprRewriter for ConstEvaluator<'a> {// if this expr is not ok to evaluate, mark entire parent// stack as not ok (as all parents have at least one child or- // descendant that is non evaluateable+ // descendant that can not be evaluatedif !Self::can_evaluate(expr) {// walk back up stack, marking first parent that is not mutable@@ -738,7 +738,7 @@ mod tests {use arrow::array::{ArrayRef, Int32Array};use chrono::{DateTime, TimeZone, Utc};- use datafusion_expr::BuiltinScalarFunction;+ use datafusion_expr::{BuiltinScalarFunction, ExprSchemable};use super::*;use crate::assert_contains;@@ -1907,4 +1907,36 @@ mod tests {assert_eq!(expected, actual);}++ #[test]+ fn select_date_plus_interval() {+ let table_scan = test_table_scan();++ let ts_string = "2020-09-08T12:05:00+00:00";+ let time = chrono::Utc.timestamp_nanos(1599566400000000000i64);++ // now() < cast(to_timestamp(...) as int) + 5000000000+ let schema = table_scan.schema();++ let date_plus_interval_expr = to_timestamp_expr(ts_string)+ .cast_to(&DataType::Date32, schema)+ .unwrap()+ + Expr::Literal(ScalarValue::IntervalDayTime(Some(123)));++ let plan = LogicalPlanBuilder::from(table_scan.clone())+ .project(vec![date_plus_interval_expr])+ .unwrap()+ .build()+ .unwrap();++ println!("{:?}", plan);++ // Note that constant folder runs and folds the entire+ // expression down to a single constant (true)+ let expected = "Projection: Date32(\"18636\") AS CAST(totimestamp(Utf8(\"2020-09-08T12:05:00+00:00\")) AS Date32) + IntervalDayTime(\"123\")\+ \n TableScan: test projection=None";+ let actual = get_optimized_plan_formatted(&plan, &time);++ assert_eq!(expected, actual);+ }}diff --git a/datafusion/core/src/physical_plan/planner.rs b/datafusion/core/src/physical_plan/planner.rsindex 4cca768c7a..c02e1732a8 100644--- a/datafusion/core/src/physical_plan/planner.rs+++ b/datafusion/core/src/physical_plan/planner.rs@@ -62,6 +62,7 @@ use arrow::compute::SortOptions;use arrow::datatypes::{Schema, SchemaRef};use arrow::{compute::can_cast_types, datatypes::DataType};use async_trait::async_trait;+use datafusion_physical_expr::expressions::DateIntervalExpr;use futures::future::BoxFuture;use futures::{FutureExt, StreamExt, TryStreamExt};use log::{debug, trace};@@ -964,7 +965,27 @@ pub fn create_physical_expr(input_schema,execution_props,)?;- binary(lhs, *op, rhs, input_schema)+ match (+ lhs.data_type(input_schema)?,+ op,+ rhs.data_type(input_schema)?,+ ) {+ (+ DataType::Date32 | DataType::Date64,+ Operator::Plus | Operator::Minus,+ DataType::Interval(_),+ ) => Ok(Arc::new(DateIntervalExpr::try_new(+ lhs,+ *op,+ rhs,+ input_schema,+ )?)),+ _ => {+ // assume that we can coerce both sides into a common type+ // and then perform a binary operation+ binary(lhs, *op, rhs, input_schema)+ }+ }}Expr::Case {expr,diff --git a/datafusion/physical-expr/src/expressions/datetime.rs b/datafusion/physical-expr/src/expressions/datetime.rsnew file mode 100644index 0000000000..df186121ac--- /dev/null+++ b/datafusion/physical-expr/src/expressions/datetime.rs@@ -0,0 +1,150 @@+// 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.++use crate::PhysicalExpr;+use arrow::datatypes::{DataType, Schema};+use arrow::record_batch::RecordBatch;+use datafusion_common::Result;+use datafusion_common::{DataFusionError, ScalarValue};+use datafusion_expr::{ColumnarValue, Operator};+use std::any::Any;+use std::fmt::{Display, Formatter};+use std::sync::Arc;++/// Perform DATE +/ INTERVAL math+#[derive(Debug)]+pub struct DateIntervalExpr {+ lhs: Arc<dyn PhysicalExpr>,+ op: Operator,+ rhs: Arc<dyn PhysicalExpr>,+}++impl DateIntervalExpr {+ /// Create a new instance of DateIntervalExpr+ pub fn try_new(+ lhs: Arc<dyn PhysicalExpr>,+ op: Operator,+ rhs: Arc<dyn PhysicalExpr>,+ input_schema: &Schema,+ ) -> Result<Self> {+ match lhs.data_type(input_schema)? {+ DataType::Date32 | DataType::Date64 => match rhs.data_type(input_schema)? {+ DataType::Interval(_) => match &op {+ Operator::Plus | Operator::Minus => Ok(Self { lhs, op, rhs }),+ _ => Err(DataFusionError::Execution(format!(+ "Invalid operator '{}' for DateIntervalExpr",+ op+ ))),+ },+ other => Err(DataFusionError::Execution(format!(+ "Invalid rhs type '{}' for DateIntervalExpr",+ other+ ))),+ },+ other => Err(DataFusionError::Execution(format!(+ "Invalid lhs type '{}' for DateIntervalExpr",+ other+ ))),+ }+ }+}++impl Display for DateIntervalExpr {+ fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {+ write!(f, "{} {} {}", self.lhs, self.op, self.rhs)+ }+}++impl PhysicalExpr for DateIntervalExpr {+ fn as_any(&self) -> &dyn Any {+ self+ }++ fn data_type(&self, input_schema: &Schema) -> datafusion_common::Result<DataType> {+ self.lhs.data_type(input_schema)+ }++ fn nullable(&self, input_schema: &Schema) -> datafusion_common::Result<bool> {+ self.lhs.nullable(input_schema)+ }++ fn evaluate(&self, batch: &RecordBatch) -> datafusion_common::Result<ColumnarValue> {+ let dates = self.lhs.evaluate(batch)?;+ let intervals = self.rhs.evaluate(batch)?;++ let interval = match intervals {+ ColumnarValue::Scalar(interval) => match interval {+ ScalarValue::IntervalDayTime(Some(interval)) => interval as i32,+ other => {+ return Err(DataFusionError::Execution(format!(+ "DateIntervalExpr does not support interval {}",+ other+ )))+ }+ },+ _ => {+ return Err(DataFusionError::Execution(+ "Columnar execution is not yet supported for DateIntervalExpr"+ .to_string(),+ ))+ }+ };++ match dates {+ ColumnarValue::Scalar(scalar) => match scalar {+ ScalarValue::Date32(Some(date)) => match &self.op {+ Operator::Plus => Ok(ColumnarValue::Scalar(ScalarValue::Date32(+ Some(date + interval),+ ))),+ Operator::Minus => Ok(ColumnarValue::Scalar(ScalarValue::Date32(+ Some(date - interval),+ ))),+ _ => {+ // this should be unreachable because we check the operators in `try_new`+ Err(DataFusionError::Execution(+ "Invalid operator for DateIntervalExpr".to_string(),+ ))+ }+ },+ ScalarValue::Date64(Some(date)) => match &self.op {+ Operator::Plus => Ok(ColumnarValue::Scalar(ScalarValue::Date64(+ Some(date + interval as i64),+ ))),+ Operator::Minus => Ok(ColumnarValue::Scalar(ScalarValue::Date64(+ Some(date - interval as i64),+ ))),+ _ => {+ // this should be unreachable because we check the operators in `try_new`+ Err(DataFusionError::Execution(+ "Invalid operator for DateIntervalExpr".to_string(),+ ))+ }+ },+ _ => {+ // this should be unreachable because we check the types in `try_new`+ Err(DataFusionError::Execution(+ "Invalid lhs type for DateIntervalExpr".to_string(),+ ))+ }+ },+ _ => Err(DataFusionError::Execution(+ "Columnar execution is not yet supported for DateIntervalExpr"+ .to_string(),+ )),+ }+ }+}diff --git a/datafusion/physical-expr/src/expressions/mod.rs b/datafusion/physical-expr/src/expressions/mod.rsindex 3190f680fa..2cdceab6cc 100644--- a/datafusion/physical-expr/src/expressions/mod.rs+++ b/datafusion/physical-expr/src/expressions/mod.rs@@ -22,6 +22,7 @@ mod binary;mod case;mod cast;mod column;+mod datetime;mod get_indexed_field;mod in_list;mod is_not_null;@@ -68,6 +69,7 @@ pub use cast::{cast, cast_column, cast_with_options, CastExpr, DEFAULT_DATAFUSION_CAST_OPTIONS,};pub use column::{col, Column};+pub use datetime::DateIntervalExpr;pub use get_indexed_field::GetIndexedFieldExpr;pub use in_list::{in_list, InListExpr};pub use is_not_null::{is_not_null, IsNotNullExpr};