Apache DataFusion SQL Query Engine
cp_solver, Duration vs Interval cases (#7475)
Berkay Şahine83b75f65b04
diff --git a/datafusion/core/src/physical_optimizer/join_selection.rs b/datafusion/core/src/physical_optimizer/join_selection.rsindex 342e33f16c..628cc1da3b 100644--- a/datafusion/core/src/physical_optimizer/join_selection.rs+++ b/datafusion/core/src/physical_optimizer/join_selection.rs@@ -1175,7 +1175,7 @@ mod tests_statistical {mod util_tests {use datafusion_expr::Operator;use datafusion_physical_expr::expressions::{BinaryExpr, Column, NegativeExpr};- use datafusion_physical_expr::intervals::check_support;+ use datafusion_physical_expr::intervals::utils::check_support;use datafusion_physical_expr::PhysicalExpr;use std::sync::Arc;diff --git a/datafusion/core/src/physical_optimizer/pipeline_checker.rs b/datafusion/core/src/physical_optimizer/pipeline_checker.rsindex 9736eb381c..44679647b5 100644--- a/datafusion/core/src/physical_optimizer/pipeline_checker.rs+++ b/datafusion/core/src/physical_optimizer/pipeline_checker.rs@@ -27,7 +27,7 @@ use crate::physical_plan::{with_new_children_if_necessary, ExecutionPlan};use datafusion_common::config::OptimizerOptions;use datafusion_common::tree_node::{Transformed, TreeNode, VisitRecursion};use datafusion_common::{plan_err, DataFusionError};-use datafusion_physical_expr::intervals::{check_support, is_datatype_supported};+use datafusion_physical_expr::intervals::utils::{check_support, is_datatype_supported};use std::sync::Arc;/// The PipelineChecker rule rejects non-runnable query plans that usediff --git a/datafusion/core/src/physical_plan/filter.rs b/datafusion/core/src/physical_plan/filter.rsindex 779fa16c7a..5c8cb1abc4 100644--- a/datafusion/core/src/physical_plan/filter.rs+++ b/datafusion/core/src/physical_plan/filter.rs@@ -41,7 +41,7 @@ use datafusion_common::{plan_err, DataFusionError, Result};use datafusion_execution::TaskContext;use datafusion_expr::Operator;use datafusion_physical_expr::expressions::BinaryExpr;-use datafusion_physical_expr::intervals::check_support;+use datafusion_physical_expr::intervals::utils::check_support;use datafusion_physical_expr::{analyze, split_conjunction, AnalysisContext, ExprBoundaries,OrderingEquivalenceProperties, PhysicalExpr,diff --git a/datafusion/physical-expr/src/aggregate/min_max.rs b/datafusion/physical-expr/src/aggregate/min_max.rsindex a9028e6840..db72c91ee1 100644--- a/datafusion/physical-expr/src/aggregate/min_max.rs+++ b/datafusion/physical-expr/src/aggregate/min_max.rs@@ -662,6 +662,30 @@ macro_rules! min_max {ScalarValue::IntervalMonthDayNano(_),) => {interval_min_max!($OP, $VALUE, $DELTA)+ }+ (+ ScalarValue::DurationSecond(lhs),+ ScalarValue::DurationSecond(rhs),+ ) => {+ typed_min_max!(lhs, rhs, DurationSecond, $OP)+ }+ (+ ScalarValue::DurationMillisecond(lhs),+ ScalarValue::DurationMillisecond(rhs),+ ) => {+ typed_min_max!(lhs, rhs, DurationMillisecond, $OP)+ }+ (+ ScalarValue::DurationMicrosecond(lhs),+ ScalarValue::DurationMicrosecond(rhs),+ ) => {+ typed_min_max!(lhs, rhs, DurationMicrosecond, $OP)+ }+ (+ ScalarValue::DurationNanosecond(lhs),+ ScalarValue::DurationNanosecond(rhs),+ ) => {+ typed_min_max!(lhs, rhs, DurationNanosecond, $OP)}e => {return internal_err!(diff --git a/datafusion/physical-expr/src/expressions/binary.rs b/datafusion/physical-expr/src/expressions/binary.rsindex ac33cdcc4e..f235ea9fcd 100644--- a/datafusion/physical-expr/src/expressions/binary.rs+++ b/datafusion/physical-expr/src/expressions/binary.rs@@ -363,9 +363,10 @@ impl PhysicalExpr for BinaryExpr {interval: &Interval,children: &[&Interval],) -> Result<Vec<Option<Interval>>> {- // Get children intervals. Graph brings+ // Get children intervals.let left_interval = children[0];let right_interval = children[1];+let (left, right) = if self.op.is_logic_operator() {// TODO: Currently, this implementation only supports the AND operator// and does not require any further propagation. In the future,@@ -617,8 +618,7 @@ pub fn binary(#[cfg(test)]mod tests {use super::*;- use crate::expressions::{col, lit};- use crate::expressions::{try_cast, Literal};+ use crate::expressions::{col, lit, try_cast, Literal};use arrow::datatypes::{ArrowNumericType, Decimal128Type, Field, Int32Type, SchemaRef,};diff --git a/datafusion/physical-expr/src/intervals/cp_solver.rs b/datafusion/physical-expr/src/intervals/cp_solver.rsindex edf1507c70..6573242664 100644--- a/datafusion/physical-expr/src/intervals/cp_solver.rs+++ b/datafusion/physical-expr/src/intervals/cp_solver.rs@@ -21,24 +21,25 @@ use std::collections::HashSet;use std::fmt::{Display, Formatter};use std::sync::Arc;+use super::utils::{+ convert_duration_type_to_interval, convert_interval_type_to_duration, get_inverse_op,+};+use super::IntervalBound;+use crate::expressions::Literal;+use crate::intervals::interval_aritmetic::{apply_operator, Interval};+use crate::utils::{build_dag, ExprTreeNode};+use crate::PhysicalExpr;+use arrow_schema::DataType;-use datafusion_common::{Result, ScalarValue};+use datafusion_common::{DataFusionError, Result, ScalarValue};use datafusion_expr::type_coercion::binary::get_result_type;use datafusion_expr::Operator;+use petgraph::graph::NodeIndex;use petgraph::stable_graph::{DefaultIx, StableGraph};use petgraph::visit::{Bfs, Dfs, DfsPostOrder, EdgeRef};use petgraph::Outgoing;-use crate::expressions::{BinaryExpr, CastExpr, Column, Literal};-use crate::intervals::interval_aritmetic::{- apply_operator, is_operator_supported, Interval,-};-use crate::utils::{build_dag, ExprTreeNode};-use crate::PhysicalExpr;--use super::IntervalBound;-// Interval arithmetic provides a way to perform mathematical operations on// intervals, which represent a range of possible values rather than a single// point value. This allows for the propagation of ranges through mathematical@@ -203,15 +204,6 @@ impl PartialEq for ExprIntervalGraphNode {}}-// This function returns the inverse operator of the given operator.-fn get_inverse_op(op: Operator) -> Operator {- match op {- Operator::Plus => Operator::Minus,- Operator::Minus => Operator::Plus,- _ => unreachable!(),- }-}-/// This function refines intervals `left_child` and `right_child` by applying/// constraint propagation through `parent` via operation. The main idea is/// that we can shrink ranges of variables x and y using parent interval p.@@ -231,22 +223,45 @@ pub fn propagate_arithmetic(right_child: &Interval,) -> Result<(Option<Interval>, Option<Interval>)> {let inverse_op = get_inverse_op(*op);- // First, propagate to the left:- match apply_operator(&inverse_op, parent, right_child)?.intersect(left_child)? {- // Left is feasible:- Some(value) => {- // Propagate to the right using the new left.- let right = match op {- Operator::Minus => apply_operator(op, &value, parent),- Operator::Plus => apply_operator(&inverse_op, parent, &value),- _ => unreachable!(),- }?- .intersect(right_child)?;- // Return intervals for both children:- Ok((Some(value), right))+ match (left_child.get_datatype()?, right_child.get_datatype()?) {+ // If we have a child whose type is a time interval (i.e. DataType::Interval), we need special handling+ // since timestamp differencing results in a Duration type.+ (DataType::Timestamp(..), DataType::Interval(_)) => {+ propagate_time_interval_at_right(+ left_child,+ right_child,+ parent,+ op,+ &inverse_op,+ )+ }+ (DataType::Interval(_), DataType::Timestamp(..)) => {+ propagate_time_interval_at_left(+ left_child,+ right_child,+ parent,+ op,+ &inverse_op,+ )+ }+ _ => {+ // First, propagate to the left:+ match apply_operator(&inverse_op, parent, right_child)?+ .intersect(left_child)?+ {+ // Left is feasible:+ Some(value) => {+ // Propagate to the right using the new left.+ let right =+ propagate_right(&value, parent, right_child, op, &inverse_op)?;++ // Return intervals for both children:+ Ok((Some(value), right))+ }+ // If the left child is infeasible, short-circuit.+ None => Ok((None, None)),+ }}- // If the left child is infeasible, short-circuit.- None => Ok((None, None)),}}@@ -288,12 +303,28 @@ pub fn propagate_comparison(left_child: &Interval,right_child: &Interval,) -> Result<(Option<Interval>, Option<Interval>)> {- let parent = comparison_operator_target(- &left_child.get_datatype()?,- op,- &right_child.get_datatype()?,- )?;- propagate_arithmetic(&Operator::Minus, &parent, left_child, right_child)+ let left_type = left_child.get_datatype()?;+ let right_type = right_child.get_datatype()?;+ let parent = comparison_operator_target(&left_type, op, &right_type)?;+ match (&left_type, &right_type) {+ // We can not compare a Duration type with a time interval type+ // without a reference timestamp unless the latter has a zero month field.+ (DataType::Interval(_), DataType::Duration(_)) => {+ propagate_comparison_to_time_interval_at_left(+ left_child,+ &parent,+ right_child,+ )+ }+ (DataType::Duration(_), DataType::Interval(_)) => {+ propagate_comparison_to_time_interval_at_left(+ left_child,+ &parent,+ right_child,+ )+ }+ _ => propagate_arithmetic(&Operator::Minus, &parent, left_child, right_child),+ }}impl ExprIntervalGraph {@@ -542,20 +573,112 @@ impl ExprIntervalGraph {}}-/// Indicates whether interval arithmetic is supported for the given expression.-/// Currently, we do not support all [`PhysicalExpr`]s for interval calculations.-/// We do not support every type of [`Operator`]s either. Over time, this check-/// will relax as more types of `PhysicalExpr`s and `Operator`s are supported.-/// Currently, [`CastExpr`], [`BinaryExpr`], [`Column`] and [`Literal`] are supported.-pub fn check_support(expr: &Arc<dyn PhysicalExpr>) -> bool {- let expr_any = expr.as_any();- let expr_supported = if let Some(binary_expr) = expr_any.downcast_ref::<BinaryExpr>()- {- is_operator_supported(binary_expr.op())+/// During the propagation of [`Interval`] values on an [`ExprIntervalGraph`], if there exists a `timestamp - timestamp`+/// operation, the result would be of type `Duration`. However, we may encounter a situation where a time interval+/// is involved in an arithmetic operation with a `Duration` type. This function offers special handling for such cases,+/// where the time interval resides on the left side of the operation.+fn propagate_time_interval_at_left(+ left_child: &Interval,+ right_child: &Interval,+ parent: &Interval,+ op: &Operator,+ inverse_op: &Operator,+) -> Result<(Option<Interval>, Option<Interval>)> {+ // We check if the child's time interval(s) has a non-zero month or day field(s).+ // If so, we return it as is without propagating. Otherwise, we first convert+ // the time intervals to the Duration type, then propagate, and then convert the bounds to time intervals again.+ if let Some(duration) = convert_interval_type_to_duration(left_child) {+ match apply_operator(inverse_op, parent, right_child)?.intersect(duration)? {+ Some(value) => {+ let right = propagate_right(&value, parent, right_child, op, inverse_op)?;+ let new_interval = convert_duration_type_to_interval(&value);+ Ok((new_interval, right))+ }+ None => Ok((None, None)),+ }+ } else {+ let right = propagate_right(left_child, parent, right_child, op, inverse_op)?;+ Ok((Some(left_child.clone()), right))+ }+}++/// During the propagation of [`Interval`] values on an [`ExprIntervalGraph`], if there exists a `timestamp - timestamp`+/// operation, the result would be of type `Duration`. However, we may encounter a situation where a time interval+/// is involved in an arithmetic operation with a `Duration` type. This function offers special handling for such cases,+/// where the time interval resides on the right side of the operation.+fn propagate_time_interval_at_right(+ left_child: &Interval,+ right_child: &Interval,+ parent: &Interval,+ op: &Operator,+ inverse_op: &Operator,+) -> Result<(Option<Interval>, Option<Interval>)> {+ // We check if the child's time interval(s) has a non-zero month or day field(s).+ // If so, we return it as is without propagating. Otherwise, we first convert+ // the time intervals to the Duration type, then propagate, and then convert the bounds to time intervals again.+ if let Some(duration) = convert_interval_type_to_duration(right_child) {+ match apply_operator(inverse_op, parent, &duration)?.intersect(left_child)? {+ Some(value) => {+ let right =+ propagate_right(left_child, parent, &duration, op, inverse_op)?;+ let right =+ right.and_then(|right| convert_duration_type_to_interval(&right));+ Ok((Some(value), right))+ }+ None => Ok((None, None)),+ }} else {- expr_any.is::<Column>() || expr_any.is::<Literal>() || expr_any.is::<CastExpr>()- };- expr_supported && expr.children().iter().all(check_support)+ match apply_operator(inverse_op, parent, right_child)?.intersect(left_child)? {+ Some(value) => Ok((Some(value), Some(right_child.clone()))),+ None => Ok((None, None)),+ }+ }+}++/// This is a subfunction of the `propagate_arithmetic` function that propagates to the right child.+fn propagate_right(+ left: &Interval,+ parent: &Interval,+ right: &Interval,+ op: &Operator,+ inverse_op: &Operator,+) -> Result<Option<Interval>> {+ match op {+ Operator::Minus => apply_operator(op, left, parent),+ Operator::Plus => apply_operator(inverse_op, parent, left),+ _ => unreachable!(),+ }?+ .intersect(right)+}++/// Converts the `time interval` (as the left child) to duration, then performs the propagation rule for comparison operators.+pub fn propagate_comparison_to_time_interval_at_left(+ left_child: &Interval,+ parent: &Interval,+ right_child: &Interval,+) -> Result<(Option<Interval>, Option<Interval>)> {+ if let Some(converted) = convert_interval_type_to_duration(left_child) {+ propagate_arithmetic(&Operator::Minus, parent, &converted, right_child)+ } else {+ Err(DataFusionError::Internal(+ "Interval type has a non-zero month field, cannot compare with a Duration type".to_string(),+ ))+ }+}++/// Converts the `time interval` (as the right child) to duration, then performs the propagation rule for comparison operators.+pub fn propagate_comparison_to_time_interval_at_right(+ left_child: &Interval,+ parent: &Interval,+ right_child: &Interval,+) -> Result<(Option<Interval>, Option<Interval>)> {+ if let Some(converted) = convert_interval_type_to_duration(right_child) {+ propagate_arithmetic(&Operator::Minus, parent, left_child, &converted)+ } else {+ Err(DataFusionError::Internal(+ "Interval type has a non-zero month field, cannot compare with a Duration type".to_string(),+ ))+ }}#[cfg(test)]@@ -1125,4 +1248,170 @@ mod tests {assert_eq!(prev_node_count, final_node_count);Ok(())}++ #[test]+ fn test_propagate_constraints_singleton_interval_at_right() -> Result<()> {+ let expression = BinaryExpr::new(+ Arc::new(Column::new("ts_column", 0)),+ Operator::Plus,+ Arc::new(Literal::new(ScalarValue::new_interval_mdn(0, 1, 321))),+ );+ let parent = Interval::new(+ IntervalBound::new(+ // 15.10.2020 - 10:11:12.000_000_321 AM+ ScalarValue::TimestampNanosecond(Some(1_602_756_672_000_000_321), None),+ false,+ ),+ IntervalBound::new(+ // 16.10.2020 - 10:11:12.000_000_321 AM+ ScalarValue::TimestampNanosecond(Some(1_602_843_072_000_000_321), None),+ false,+ ),+ );+ let left_child = Interval::new(+ IntervalBound::new(+ // 10.10.2020 - 10:11:12 AM+ ScalarValue::TimestampNanosecond(Some(1_602_324_672_000_000_000), None),+ false,+ ),+ IntervalBound::new(+ // 20.10.2020 - 10:11:12 AM+ ScalarValue::TimestampNanosecond(Some(1_603_188_672_000_000_000), None),+ false,+ ),+ );+ let right_child = Interval::new(+ IntervalBound::new(+ // 1 day 321 ns+ ScalarValue::IntervalMonthDayNano(Some(0x1_0000_0000_0000_0141)),+ false,+ ),+ IntervalBound::new(+ // 1 day 321 ns+ ScalarValue::IntervalMonthDayNano(Some(0x1_0000_0000_0000_0141)),+ false,+ ),+ );+ let children = vec![&left_child, &right_child];+ let result = expression.propagate_constraints(&parent, &children)?;++ assert_eq!(+ Some(Interval::new(+ // 14.10.2020 - 10:11:12 AM+ IntervalBound::new(+ ScalarValue::TimestampNanosecond(+ Some(1_602_670_272_000_000_000),+ None+ ),+ false,+ ),+ // 15.10.2020 - 10:11:12 AM+ IntervalBound::new(+ ScalarValue::TimestampNanosecond(+ Some(1_602_756_672_000_000_000),+ None+ ),+ false,+ ),+ )),+ result[0]+ );+ assert_eq!(+ Some(Interval::new(+ // 1 day 321 ns in Duration type+ IntervalBound::new(+ ScalarValue::IntervalMonthDayNano(Some(0x1_0000_0000_0000_0141)),+ false,+ ),+ // 1 day 321 ns in Duration type+ IntervalBound::new(+ ScalarValue::IntervalMonthDayNano(Some(0x1_0000_0000_0000_0141)),+ false,+ ),+ )),+ result[1]+ );++ Ok(())+ }++ #[test]+ fn test_propagate_constraints_column_interval_at_left() -> Result<()> {+ let expression = BinaryExpr::new(+ Arc::new(Column::new("interval_column", 1)),+ Operator::Plus,+ Arc::new(Column::new("ts_column", 0)),+ );+ let parent = Interval::new(+ IntervalBound::new(+ // 15.10.2020 - 10:11:12 AM+ ScalarValue::TimestampMillisecond(Some(1_602_756_672_000), None),+ false,+ ),+ IntervalBound::new(+ // 16.10.2020 - 10:11:12 AM+ ScalarValue::TimestampMillisecond(Some(1_602_843_072_000), None),+ false,+ ),+ );+ let right_child = Interval::new(+ IntervalBound::new(+ // 10.10.2020 - 10:11:12 AM+ ScalarValue::TimestampMillisecond(Some(1_602_324_672_000), None),+ false,+ ),+ IntervalBound::new(+ // 20.10.2020 - 10:11:12 AM+ ScalarValue::TimestampMillisecond(Some(1_603_188_672_000), None),+ false,+ ),+ );+ let left_child = Interval::new(+ IntervalBound::new(+ // 2 days+ ScalarValue::IntervalDayTime(Some(172_800_000)),+ false,+ ),+ IntervalBound::new(+ // 10 days+ ScalarValue::IntervalDayTime(Some(864_000_000)),+ false,+ ),+ );+ let children = vec![&left_child, &right_child];+ let result = expression.propagate_constraints(&parent, &children)?;++ assert_eq!(+ Some(Interval::new(+ // 10.10.2020 - 10:11:12 AM+ IntervalBound::new(+ ScalarValue::TimestampMillisecond(Some(1_602_324_672_000), None),+ false,+ ),+ // 14.10.2020 - 10:11:12 AM+ IntervalBound::new(+ ScalarValue::TimestampMillisecond(Some(1_602_670_272_000), None),+ false,+ )+ )),+ result[1]+ );+ assert_eq!(+ Some(Interval::new(+ IntervalBound::new(+ // 2 days+ ScalarValue::IntervalDayTime(Some(172_800_000)),+ false,+ ),+ IntervalBound::new(+ // 6 days+ ScalarValue::IntervalDayTime(Some(518_400_000)),+ false,+ ),+ )),+ result[0]+ );++ Ok(())+ }}diff --git a/datafusion/physical-expr/src/intervals/interval_aritmetic.rs b/datafusion/physical-expr/src/intervals/interval_aritmetic.rsindex 659a47da15..5e4710116c 100644--- a/datafusion/physical-expr/src/intervals/interval_aritmetic.rs+++ b/datafusion/physical-expr/src/intervals/interval_aritmetic.rs@@ -617,38 +617,6 @@ pub fn cardinality_ratio(Ok(final_interval.cardinality()? as f64 / initial_interval.cardinality()? as f64)}-/// Indicates whether interval arithmetic is supported for the given operator.-pub fn is_operator_supported(op: &Operator) -> bool {- matches!(- op,- &Operator::Plus- | &Operator::Minus- | &Operator::And- | &Operator::Gt- | &Operator::GtEq- | &Operator::Lt- | &Operator::LtEq- | &Operator::Eq- )-}--/// Indicates whether interval arithmetic is supported for the given data type.-pub fn is_datatype_supported(data_type: &DataType) -> bool {- matches!(- data_type,- &DataType::Int64- | &DataType::Int32- | &DataType::Int16- | &DataType::Int8- | &DataType::UInt64- | &DataType::UInt32- | &DataType::UInt16- | &DataType::UInt8- | &DataType::Float64- | &DataType::Float32- )-}-pub fn apply_operator(op: &Operator, lhs: &Interval, rhs: &Interval) -> Result<Interval> {match *op {Operator::Eq => Ok(lhs.equal(rhs)),diff --git a/datafusion/physical-expr/src/intervals/mod.rs b/datafusion/physical-expr/src/intervals/mod.rsindex a9255752fe..b89d1c59dc 100644--- a/datafusion/physical-expr/src/intervals/mod.rs+++ b/datafusion/physical-expr/src/intervals/mod.rs@@ -20,7 +20,8 @@pub mod cp_solver;pub mod interval_aritmetic;pub mod rounding;-pub mod test_utils;-pub use cp_solver::{check_support, ExprIntervalGraph};+pub mod utils;++pub use cp_solver::ExprIntervalGraph;pub use interval_aritmetic::*;diff --git a/datafusion/physical-expr/src/intervals/utils.rs b/datafusion/physical-expr/src/intervals/utils.rsnew file mode 100644index 0000000000..be3b177713--- /dev/null+++ b/datafusion/physical-expr/src/intervals/utils.rs@@ -0,0 +1,192 @@+// 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.++//! Utility functions for the interval arithmetic library++use std::sync::Arc;++use super::{Interval, IntervalBound};+use crate::{+ expressions::{BinaryExpr, CastExpr, Column, Literal},+ PhysicalExpr,+};++use arrow_schema::DataType;+use datafusion_common::{DataFusionError, Result, ScalarValue};+use datafusion_expr::Operator;++const MDN_DAY_MASK: i128 = 0xFFFF_FFFF_0000_0000_0000_0000;+const MDN_NS_MASK: i128 = 0xFFFF_FFFF_FFFF_FFFF;+const DT_MS_MASK: i64 = 0xFFFF_FFFF;++/// Indicates whether interval arithmetic is supported for the given expression.+/// Currently, we do not support all [`PhysicalExpr`]s for interval calculations.+/// We do not support every type of [`Operator`]s either. Over time, this check+/// will relax as more types of `PhysicalExpr`s and `Operator`s are supported.+/// Currently, [`CastExpr`], [`BinaryExpr`], [`Column`] and [`Literal`] are supported.+pub fn check_support(expr: &Arc<dyn PhysicalExpr>) -> bool {+ let expr_any = expr.as_any();+ let expr_supported = if let Some(binary_expr) = expr_any.downcast_ref::<BinaryExpr>()+ {+ is_operator_supported(binary_expr.op())+ } else {+ expr_any.is::<Column>() || expr_any.is::<Literal>() || expr_any.is::<CastExpr>()+ };+ expr_supported && expr.children().iter().all(check_support)+}++// This function returns the inverse operator of the given operator.+pub fn get_inverse_op(op: Operator) -> Operator {+ match op {+ Operator::Plus => Operator::Minus,+ Operator::Minus => Operator::Plus,+ _ => unreachable!(),+ }+}++/// Indicates whether interval arithmetic is supported for the given operator.+pub fn is_operator_supported(op: &Operator) -> bool {+ matches!(+ op,+ &Operator::Plus+ | &Operator::Minus+ | &Operator::And+ | &Operator::Gt+ | &Operator::GtEq+ | &Operator::Lt+ | &Operator::LtEq+ | &Operator::Eq+ )+}++/// Indicates whether interval arithmetic is supported for the given data type.+pub fn is_datatype_supported(data_type: &DataType) -> bool {+ matches!(+ data_type,+ &DataType::Int64+ | &DataType::Int32+ | &DataType::Int16+ | &DataType::Int8+ | &DataType::UInt64+ | &DataType::UInt32+ | &DataType::UInt16+ | &DataType::UInt8+ | &DataType::Float64+ | &DataType::Float32+ )+}++/// Converts an [`Interval`] of time intervals to one of `Duration`s, if applicable. Otherwise, returns [`None`].+pub fn convert_interval_type_to_duration(interval: &Interval) -> Option<Interval> {+ if let (Some(lower), Some(upper)) = (+ convert_interval_bound_to_duration(&interval.lower),+ convert_interval_bound_to_duration(&interval.upper),+ ) {+ Some(Interval::new(lower, upper))+ } else {+ None+ }+}++/// Converts an [`IntervalBound`] containing a time interval to one containing a `Duration`, if applicable. Otherwise, returns [`None`].+fn convert_interval_bound_to_duration(+ interval_bound: &IntervalBound,+) -> Option<IntervalBound> {+ match interval_bound.value {+ ScalarValue::IntervalMonthDayNano(Some(mdn)) => {+ interval_mdn_to_duration_ns(&mdn).ok().map(|duration| {+ IntervalBound::new(+ ScalarValue::DurationNanosecond(Some(duration)),+ interval_bound.open,+ )+ })+ }+ ScalarValue::IntervalDayTime(Some(dt)) => {+ interval_dt_to_duration_ms(&dt).ok().map(|duration| {+ IntervalBound::new(+ ScalarValue::DurationMillisecond(Some(duration)),+ interval_bound.open,+ )+ })+ }+ _ => None,+ }+}++/// Converts an [`Interval`] of `Duration`s to one of time intervals, if applicable. Otherwise, returns [`None`].+pub fn convert_duration_type_to_interval(interval: &Interval) -> Option<Interval> {+ if let (Some(lower), Some(upper)) = (+ convert_duration_bound_to_interval(&interval.lower),+ convert_duration_bound_to_interval(&interval.upper),+ ) {+ Some(Interval::new(lower, upper))+ } else {+ None+ }+}++/// Converts an [`IntervalBound`] containing a `Duration` to one containing a time interval, if applicable. Otherwise, returns [`None`].+fn convert_duration_bound_to_interval(+ interval_bound: &IntervalBound,+) -> Option<IntervalBound> {+ match interval_bound.value {+ ScalarValue::DurationNanosecond(Some(duration)) => Some(IntervalBound::new(+ ScalarValue::new_interval_mdn(0, 0, duration),+ interval_bound.open,+ )),+ ScalarValue::DurationMillisecond(Some(duration)) => Some(IntervalBound::new(+ ScalarValue::new_interval_dt(0, duration as i32),+ interval_bound.open,+ )),+ _ => None,+ }+}++/// If both the month and day fields of [`ScalarValue::IntervalMonthDayNano`] are zero, this function returns the nanoseconds part.+/// Otherwise, it returns an error.+fn interval_mdn_to_duration_ns(mdn: &i128) -> Result<i64> {+ let months = mdn >> 96;+ let days = (mdn & MDN_DAY_MASK) >> 64;+ let nanoseconds = mdn & MDN_NS_MASK;++ if months == 0 && days == 0 {+ nanoseconds.try_into().map_err(|_| {+ DataFusionError::Internal("Resulting duration exceeds i64::MAX".to_string())+ })+ } else {+ Err(DataFusionError::Internal(+ "The interval cannot have a non-zero month or day value for duration convertibility"+ .to_string(),+ ))+ }+}++/// If the day field of the [`ScalarValue::IntervalDayTime`] is zero, this function returns the milliseconds part.+/// Otherwise, it returns an error.+fn interval_dt_to_duration_ms(dt: &i64) -> Result<i64> {+ let days = dt >> 32;+ let milliseconds = dt & DT_MS_MASK;++ if days == 0 {+ Ok(milliseconds)+ } else {+ Err(DataFusionError::Internal(+ "The interval cannot have a non-zero day value for duration convertibility"+ .to_string(),+ ))+ }+}