Skip to main content

datafusion_physical_expr/intervals/
utils.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership
3// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements
4
5//! Utility functions for the interval arithmetic library
6
7use std::sync::Arc;
8
9use crate::{
10    PhysicalExpr,
11    expressions::{BinaryExpr, CastExpr, Column, Literal, NegativeExpr},
12};
13
14use arrow::array::types::{IntervalDayTime, IntervalMonthDayNano};
15use arrow::datatypes::{DataType, SchemaRef};
16use datafusion_common::{Result, ScalarValue, internal_err};
17use datafusion_expr::Operator;
18use datafusion_expr::interval_arithmetic::Interval;
19
20/// Indicates whether interval arithmetic is supported for the given expression.
21/// Currently, we do not support all [`PhysicalExpr`]s for interval calculations.
22/// We do not support every type of [`Operator`]s either. Over time, this check
23/// will relax as more types of `PhysicalExpr`s and `Operator`s are supported.
24/// Currently, [`CastExpr`], [`NegativeExpr`], [`BinaryExpr`], [`Column`] and [`Literal`] are supported.
25pub fn check_support(expr: &Arc<dyn PhysicalExpr>, schema: &SchemaRef) -> bool {
26    if let Some(binary_expr) = expr.downcast_ref::<BinaryExpr>() {
27        is_operator_supported(binary_expr.op())
28            && check_support(binary_expr.left(), schema)
29            && check_support(binary_expr.right(), schema)
30    } else if let Some(column) = expr.downcast_ref::<Column>() {
31        if let Ok(field) = schema.field_with_name(column.name()) {
32            is_datatype_supported(field.data_type())
33        } else {
34            false
35        }
36    } else if let Some(literal) = expr.downcast_ref::<Literal>() {
37        if let Ok(dt) = literal.data_type(schema) {
38            is_datatype_supported(&dt)
39        } else {
40            false
41        }
42    } else if let Some(cast) = expr.downcast_ref::<CastExpr>() {
43        // The cast target type must itself be one we can reason about. Casting
44        // interval endpoints to a type with a different ordering (e.g. integers
45        // to strings) does not preserve the interval, so such expressions are
46        // left unanalyzed rather than producing bogus bounds.
47        is_datatype_supported(cast.cast_type()) && check_support(cast.expr(), schema)
48    } else if let Some(negative) = expr.downcast_ref::<NegativeExpr>() {
49        check_support(negative.arg(), schema)
50    } else {
51        false
52    }
53}
54
55// This function returns the inverse operator of the given operator.
56pub fn get_inverse_op(op: Operator) -> Result<Operator> {
57    match op {
58        Operator::Plus => Ok(Operator::Minus),
59        Operator::Minus => Ok(Operator::Plus),
60        Operator::Multiply => Ok(Operator::Divide),
61        Operator::Divide => Ok(Operator::Multiply),
62        _ => internal_err!("Interval arithmetic does not support the operator {}", op),
63    }
64}
65
66/// Indicates whether interval arithmetic is supported for the given operator.
67pub fn is_operator_supported(op: &Operator) -> bool {
68    matches!(
69        op,
70        &Operator::Plus
71            | &Operator::Minus
72            | &Operator::And
73            | &Operator::Gt
74            | &Operator::GtEq
75            | &Operator::Lt
76            | &Operator::LtEq
77            | &Operator::Eq
78            | &Operator::Multiply
79            | &Operator::Divide
80    )
81}
82
83/// Indicates whether interval arithmetic is supported for the given data type.
84pub fn is_datatype_supported(data_type: &DataType) -> bool {
85    matches!(
86        data_type,
87        &DataType::Int64
88            | &DataType::Int32
89            | &DataType::Int16
90            | &DataType::Int8
91            | &DataType::UInt64
92            | &DataType::UInt32
93            | &DataType::UInt16
94            | &DataType::UInt8
95            | &DataType::Float64
96            | &DataType::Float32
97            | &DataType::Date32
98            | &DataType::Date64
99            | &DataType::Timestamp(_, _)
100    )
101}
102
103/// Converts an [`Interval`] of time intervals to one of `Duration`s, if applicable. Otherwise, returns [`None`].
104pub fn convert_interval_type_to_duration(interval: &Interval) -> Option<Interval> {
105    if let (Some(lower), Some(upper)) = (
106        convert_interval_bound_to_duration(interval.lower()),
107        convert_interval_bound_to_duration(interval.upper()),
108    ) {
109        Interval::try_new(lower, upper).ok()
110    } else {
111        None
112    }
113}
114
115/// Converts an [`ScalarValue`] containing a time interval to one containing a `Duration`, if applicable. Otherwise, returns [`None`].
116fn convert_interval_bound_to_duration(
117    interval_bound: &ScalarValue,
118) -> Option<ScalarValue> {
119    match interval_bound {
120        ScalarValue::IntervalMonthDayNano(Some(mdn)) => interval_mdn_to_duration_ns(mdn)
121            .ok()
122            .map(|duration| ScalarValue::DurationNanosecond(Some(duration))),
123        ScalarValue::IntervalDayTime(Some(dt)) => interval_dt_to_duration_ms(dt)
124            .ok()
125            .map(|duration| ScalarValue::DurationMillisecond(Some(duration))),
126        _ => None,
127    }
128}
129
130/// Converts an [`Interval`] of `Duration`s to one of time intervals, if applicable. Otherwise, returns [`None`].
131pub fn convert_duration_type_to_interval(interval: &Interval) -> Option<Interval> {
132    if let (Some(lower), Some(upper)) = (
133        convert_duration_bound_to_interval(interval.lower()),
134        convert_duration_bound_to_interval(interval.upper()),
135    ) {
136        Interval::try_new(lower, upper).ok()
137    } else {
138        None
139    }
140}
141
142/// Converts a [`ScalarValue`] containing a `Duration` to one containing a time interval, if applicable. Otherwise, returns [`None`].
143fn convert_duration_bound_to_interval(
144    interval_bound: &ScalarValue,
145) -> Option<ScalarValue> {
146    match interval_bound {
147        ScalarValue::DurationNanosecond(Some(duration)) => {
148            Some(ScalarValue::new_interval_mdn(0, 0, *duration))
149        }
150        ScalarValue::DurationMicrosecond(Some(duration)) => {
151            Some(ScalarValue::new_interval_mdn(0, 0, *duration * 1000))
152        }
153        ScalarValue::DurationMillisecond(Some(duration)) => {
154            Some(ScalarValue::new_interval_dt(0, *duration as i32))
155        }
156        ScalarValue::DurationSecond(Some(duration)) => {
157            Some(ScalarValue::new_interval_dt(0, *duration as i32 * 1000))
158        }
159        _ => None,
160    }
161}
162
163/// If both the month and day fields of [`ScalarValue::IntervalMonthDayNano`] are zero, this function returns the nanoseconds part.
164/// Otherwise, it returns an error.
165fn interval_mdn_to_duration_ns(mdn: &IntervalMonthDayNano) -> Result<i64> {
166    if mdn.months == 0 && mdn.days == 0 {
167        Ok(mdn.nanoseconds)
168    } else {
169        internal_err!(
170            "The interval cannot have a non-zero month or day value for duration convertibility"
171        )
172    }
173}
174
175/// If the day field of the [`ScalarValue::IntervalDayTime`] is zero, this function returns the milliseconds part.
176/// Otherwise, it returns an error.
177fn interval_dt_to_duration_ms(dt: &IntervalDayTime) -> Result<i64> {
178    if dt.days == 0 {
179        // Safe to cast i32 to i64
180        Ok(dt.milliseconds as i64)
181    } else {
182        internal_err!(
183            "The interval cannot have a non-zero day value for duration convertibility"
184        )
185    }
186}