Skip to content

Apache DataFusion SQL Query Engine

Open/Closed bounds for interval arithmetic (#6007)

Berkay Şahin64941fa99e13
diff --git a/datafusion/core/src/physical_plan/joins/symmetric_hash_join.rs b/datafusion/core/src/physical_plan/joins/symmetric_hash_join.rs
index c249219033..78c9aca515 100644
--- a/datafusion/core/src/physical_plan/joins/symmetric_hash_join.rs
+++ b/datafusion/core/src/physical_plan/joins/symmetric_hash_join.rs
@@ -48,7 +48,7 @@ use parking_lot::Mutex;
use datafusion_common::{utils::bisect, ScalarValue};
use datafusion_execution::memory_pool::MemoryConsumer;
-use datafusion_physical_expr::intervals::{ExprIntervalGraph, Interval};
+use datafusion_physical_expr::intervals::{ExprIntervalGraph, Interval, IntervalBound};
use crate::error::{DataFusionError, Result};
use crate::execution::context::TaskContext;
@@ -813,18 +813,12 @@ fn update_filter_expr_interval(
// Convert the array to a ScalarValue:
let value = ScalarValue::try_from_array(&array, 0)?;
// Create a ScalarValue representing positive or negative infinity for the same data type:
- let infinite = ScalarValue::try_from(value.get_datatype())?;
+ let unbounded = IntervalBound::make_unbounded(value.get_datatype())?;
// Update the interval with lower and upper bounds based on the sort option:
let interval = if sorted_expr.origin_sorted_expr().options.descending {
- Interval {
- lower: infinite,
- upper: value,
- }
+ Interval::new(unbounded, IntervalBound::new(value, false))
} else {
- Interval {
- lower: value,
- upper: infinite,
- }
+ Interval::new(IntervalBound::new(value, false), unbounded)
};
// Set the calculated interval for the sorted filter expression:
sorted_expr.set_interval(interval);
@@ -861,9 +855,9 @@ fn determine_prune_length(
// Get the lower or upper interval based on the sort direction
let target = if origin_sorted_expr.options.descending {
- interval.upper.clone()
+ interval.upper.value.clone()
} else {
- interval.lower.clone()
+ interval.lower.value.clone()
};
// Perform binary search on the array to determine the length of the record batch to be pruned
@@ -1735,6 +1729,7 @@ mod tests {
5,
3,
10,
+ (Operator::Gt, Operator::Lt),
),
// left_col - 1 > right_col + 5 AND left_col + 3 < right_col + 10
1 => gen_conjunctive_numeric_expr(
@@ -1748,6 +1743,7 @@ mod tests {
5,
3,
10,
+ (Operator::Gt, Operator::Lt),
),
// left_col - 1 > right_col + 5 AND left_col - 3 < right_col + 10
2 => gen_conjunctive_numeric_expr(
@@ -1761,6 +1757,7 @@ mod tests {
5,
3,
10,
+ (Operator::Gt, Operator::Lt),
),
// left_col - 10 > right_col - 5 AND left_col - 3 < right_col + 10
3 => gen_conjunctive_numeric_expr(
@@ -1774,6 +1771,7 @@ mod tests {
5,
3,
10,
+ (Operator::Gt, Operator::Lt),
),
// left_col - 10 > right_col - 5 AND left_col - 30 < right_col - 3
4 => gen_conjunctive_numeric_expr(
@@ -1787,6 +1785,49 @@ mod tests {
5,
30,
3,
+ (Operator::Gt, Operator::Lt),
+ ),
+ // left_col - 2 >= right_col - 5 AND left_col - 7 <= right_col - 3
+ 5 => gen_conjunctive_numeric_expr(
+ left_col,
+ right_col,
+ Operator::Minus,
+ Operator::Plus,
+ Operator::Plus,
+ Operator::Minus,
+ 2,
+ 5,
+ 7,
+ 3,
+ (Operator::GtEq, Operator::LtEq),
+ ),
+ // left_col - 28 >= right_col - 11 AND left_col - 21 <= right_col - 39
+ 6 => gen_conjunctive_numeric_expr(
+ left_col,
+ right_col,
+ Operator::Plus,
+ Operator::Minus,
+ Operator::Plus,
+ Operator::Plus,
+ 28,
+ 11,
+ 21,
+ 39,
+ (Operator::Gt, Operator::LtEq),
+ ),
+ // left_col - 28 >= right_col - 11 AND left_col - 21 <= right_col - 39
+ 7 => gen_conjunctive_numeric_expr(
+ left_col,
+ right_col,
+ Operator::Plus,
+ Operator::Minus,
+ Operator::Minus,
+ Operator::Plus,
+ 28,
+ 11,
+ 21,
+ 39,
+ (Operator::GtEq, Operator::Lt),
),
_ => unreachable!(),
}
@@ -2066,7 +2107,7 @@ mod tests {
(99, 12),
)]
cardinality: (i32, i32),
- #[values(0, 1, 2, 3, 4)] case_expr: usize,
+ #[values(0, 1, 2, 3, 4, 5, 6, 7)] case_expr: usize,
) -> Result<()> {
let session_ctx = SessionContext::new();
let task_ctx = session_ctx.task_ctx();
@@ -2141,7 +2182,7 @@ mod tests {
(99, 12),
)]
cardinality: (i32, i32),
- #[values(0, 1, 2, 3, 4)] case_expr: usize,
+ #[values(0, 1, 2, 3, 4, 5, 6)] case_expr: usize,
) -> Result<()> {
let session_ctx = SessionContext::new();
let task_ctx = session_ctx.task_ctx();
@@ -2232,7 +2273,7 @@ mod tests {
(99, 12),
)]
cardinality: (i32, i32),
- #[values(0, 1, 2, 3, 4)] case_expr: usize,
+ #[values(0, 1, 2, 3, 4, 5, 6)] case_expr: usize,
) -> Result<()> {
let session_ctx = SessionContext::new();
let task_ctx = session_ctx.task_ctx();
@@ -2772,6 +2813,7 @@ mod tests {
3,
0,
3,
+ (Operator::Gt, Operator::Lt),
);
let column_indices = vec![
ColumnIndex {
diff --git a/datafusion/physical-expr/src/expressions/binary.rs b/datafusion/physical-expr/src/expressions/binary.rs
index 070c12eb6f..5ef4342435 100644
--- a/datafusion/physical-expr/src/expressions/binary.rs
+++ b/datafusion/physical-expr/src/expressions/binary.rs
@@ -800,11 +800,7 @@ impl PhysicalExpr for BinaryExpr {
// changes accordingly.
return Ok(vec![]);
} else if self.op.is_comparison_operator() {
- if let Interval {
- lower: ScalarValue::Boolean(Some(false)),
- upper: ScalarValue::Boolean(Some(false)),
- } = interval
- {
+ if interval == &Interval::CERTAINLY_FALSE {
// TODO: We will handle strictly false clauses by negating
// the comparison operator (e.g. GT to LE, LT to GE)
// once open/closed intervals are supported.
diff --git a/datafusion/physical-expr/src/expressions/cast.rs b/datafusion/physical-expr/src/expressions/cast.rs
index f0e9a351c5..ff659edf0d 100644
--- a/datafusion/physical-expr/src/expressions/cast.rs
+++ b/datafusion/physical-expr/src/expressions/cast.rs
@@ -129,7 +129,7 @@ impl PhysicalExpr for CastExpr {
) -> Result<Vec<Option<Interval>>> {
let child_interval = children[0];
// Get child's datatype:
- let cast_type = child_interval.get_datatype();
+ let cast_type = child_interval.get_datatype()?;
Ok(vec![Some(
interval.cast_to(&cast_type, &self.cast_options)?,
)])
diff --git a/datafusion/physical-expr/src/expressions/datetime.rs b/datafusion/physical-expr/src/expressions/datetime.rs
index c2a54beceb..a1f7d82b38 100644
--- a/datafusion/physical-expr/src/expressions/datetime.rs
+++ b/datafusion/physical-expr/src/expressions/datetime.rs
@@ -182,11 +182,7 @@ impl PhysicalExpr for DateTimeIntervalExpr {
let left_interval = children[0];
let right_interval = children[1];
let (left, right) = if self.op.is_comparison_operator() {
- if let Interval {
- lower: ScalarValue::Boolean(Some(false)),
- upper: ScalarValue::Boolean(Some(false)),
- } = interval
- {
+ if interval == &Interval::CERTAINLY_FALSE {
// TODO: We will handle strictly false clauses by negating
// the comparison operator (e.g. GT to LE, LT to GE)
// once open/closed intervals are supported.
diff --git a/datafusion/physical-expr/src/intervals/cp_solver.rs b/datafusion/physical-expr/src/intervals/cp_solver.rs
index 5412d77cb2..65c8850b39 100644
--- a/datafusion/physical-expr/src/intervals/cp_solver.rs
+++ b/datafusion/physical-expr/src/intervals/cp_solver.rs
@@ -37,6 +37,8 @@ use crate::intervals::interval_aritmetic::{
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
@@ -184,10 +186,10 @@ impl ExprIntervalGraphNode {
let expr = node.expression().clone();
if let Some(literal) = expr.as_any().downcast_ref::<Literal>() {
let value = literal.value();
- let interval = Interval {
- lower: value.clone(),
- upper: value.clone(),
- };
+ let interval = Interval::new(
+ IntervalBound::new(value.clone(), false),
+ IntervalBound::new(value.clone(), false),
+ );
ExprIntervalGraphNode::new_with_interval(expr, interval)
} else {
ExprIntervalGraphNode::new(expr)
@@ -259,17 +261,13 @@ fn comparison_operator_target(
right_datatype: &DataType,
) -> Result<Interval> {
let datatype = coerce_types(left_datatype, &Operator::Minus, right_datatype)?;
- let unbounded = ScalarValue::try_from(&datatype)?;
+ let unbounded = IntervalBound::make_unbounded(&datatype)?;
let zero = ScalarValue::new_zero(&datatype)?;
Ok(match *op {
- Operator::Gt => Interval {
- lower: zero,
- upper: unbounded,
- },
- Operator::Lt => Interval {
- lower: unbounded,
- upper: zero,
- },
+ Operator::GtEq => Interval::new(IntervalBound::new(zero, false), unbounded),
+ Operator::Gt => Interval::new(IntervalBound::new(zero, true), unbounded),
+ Operator::LtEq => Interval::new(unbounded, IntervalBound::new(zero, false)),
+ Operator::Lt => Interval::new(unbounded, IntervalBound::new(zero, true)),
_ => unreachable!(),
})
}
@@ -287,9 +285,9 @@ pub fn propagate_comparison(
right_child: &Interval,
) -> Result<(Option<Interval>, Option<Interval>)> {
let parent = comparison_operator_target(
- &left_child.get_datatype(),
+ &left_child.get_datatype()?,
op,
- &right_child.get_datatype(),
+ &right_child.get_datatype()?,
)?;
propagate_arithmetic(&Operator::Minus, &parent, left_child, right_child)
}
@@ -437,7 +435,7 @@ impl ExprIntervalGraph {
/// use datafusion_common::ScalarValue;
/// use datafusion_expr::Operator;
/// use datafusion_physical_expr::expressions::{BinaryExpr, Column, Literal};
- /// use datafusion_physical_expr::intervals::{Interval, ExprIntervalGraph};
+ /// use datafusion_physical_expr::intervals::{Interval, IntervalBound, ExprIntervalGraph};
/// use datafusion_physical_expr::PhysicalExpr;
/// let expr = Arc::new(BinaryExpr::new(
/// Arc::new(Column::new("gnz", 0)),
@@ -452,19 +450,13 @@ impl ExprIntervalGraph {
/// // Provide intervals for leaf variables (here, there is only one).
/// let intervals = vec![(
/// left_index,
- /// Interval {
- /// lower: ScalarValue::Int32(Some(10)),
- /// upper: ScalarValue::Int32(Some(20)),
- /// },
- /// )];
+ /// Interval::make(Some(10), Some(20), (true, true)),
+ /// )];
/// // Evaluate bounds for the composite expression:
/// graph.assign_intervals(&intervals);
/// assert_eq!(
/// graph.evaluate_bounds().unwrap(),
- /// &Interval {
- /// lower: ScalarValue::Int32(Some(20)),
- /// upper: ScalarValue::Int32(Some(30))
- /// }
+ /// &Interval::make(Some(20), Some(30), (true, true)),
/// )
///
/// ```
@@ -528,20 +520,15 @@ impl ExprIntervalGraph {
leaf_bounds: &mut [(usize, Interval)],
) -> Result<PropagationResult> {
self.assign_intervals(leaf_bounds);
- match self.evaluate_bounds()? {
- Interval {
- lower: ScalarValue::Boolean(Some(false)),
- upper: ScalarValue::Boolean(Some(false)),
- } => Ok(PropagationResult::Infeasible),
- Interval {
- lower: ScalarValue::Boolean(Some(false)),
- upper: ScalarValue::Boolean(Some(true)),
- } => {
- let result = self.propagate_constraints();
- self.update_intervals(leaf_bounds);
- result
- }
- _ => Ok(PropagationResult::CannotPropagate),
+ let bounds = self.evaluate_bounds()?;
+ if bounds == &Interval::CERTAINLY_FALSE {
+ Ok(PropagationResult::Infeasible)
+ } else if bounds == &Interval::UNCERTAIN {
+ let result = self.propagate_constraints();
+ self.update_intervals(leaf_bounds);
+ result
+ } else {
+ Ok(PropagationResult::CannotPropagate)
}
}
}
@@ -579,40 +566,28 @@ mod tests {
exprs_with_interval: (Arc<dyn PhysicalExpr>, Arc<dyn PhysicalExpr>),
left_interval: (Option<i32>, Option<i32>),
right_interval: (Option<i32>, Option<i32>),
- left_waited: (Option<i32>, Option<i32>),
- right_waited: (Option<i32>, Option<i32>),
+ left_expected: (Option<i32>, Option<i32>),
+ right_expected: (Option<i32>, Option<i32>),
result: PropagationResult,
) -> Result<()> {
let col_stats = vec![
(
exprs_with_interval.0.clone(),
- Interval {
- lower: ScalarValue::Int32(left_interval.0),
- upper: ScalarValue::Int32(left_interval.1),
- },
+ Interval::make(left_interval.0, left_interval.1, (false, false)),
),
(
exprs_with_interval.1.clone(),
- Interval {
- lower: ScalarValue::Int32(right_interval.0),
- upper: ScalarValue::Int32(right_interval.1),
- },
+ Interval::make(right_interval.0, right_interval.1, (false, false)),
),
];
let expected = vec![
(
exprs_with_interval.0.clone(),
- Interval {
- lower: ScalarValue::Int32(left_waited.0),
- upper: ScalarValue::Int32(left_waited.1),
- },
+ Interval::make(left_expected.0, left_expected.1, (false, false)),
),
(
exprs_with_interval.1.clone(),
- Interval {
- lower: ScalarValue::Int32(right_waited.0),
- upper: ScalarValue::Int32(right_waited.1),
- },
+ Interval::make(right_expected.0, right_expected.1, (false, false)),
),
];
let mut graph = ExprIntervalGraph::try_new(expr)?;
@@ -632,10 +607,14 @@ mod tests {
let exp_result = graph.update_ranges(&mut col_stat_nodes[..])?;
assert_eq!(exp_result, result);
- col_stat_nodes
- .iter()
- .zip(expected_nodes.iter())
- .for_each(|((_, res), (_, expected))| assert_eq!(res, expected));
+ col_stat_nodes.iter().zip(expected_nodes.iter()).for_each(
+ |((_, res), (_, expected))| {
+ // NOTE: These randomized tests only check the correnctness of
+ // endpoint values, not open/closedness.
+ assert_eq!(res.lower.value, expected.lower.value);
+ assert_eq!(res.upper.value, expected.upper.value);
+ },
+ );
Ok(())
}
@@ -741,6 +720,7 @@ mod tests {
11,
3,
33,
+ (Operator::Gt, Operator::Lt),
);
// l > r + 10 AND r > l - 30
let l_gt_r = 10;
@@ -780,6 +760,7 @@ mod tests {
5,
3,
10,
+ (Operator::Gt, Operator::Lt),
);
// l > r + 6 AND r > l - 7
let l_gt_r = 6;
@@ -820,6 +801,7 @@ mod tests {
5,
3,
10,
+ (Operator::Gt, Operator::Lt),
);
// l > r + 6 AND r > l - 13
let l_gt_r = 6;
@@ -859,6 +841,7 @@ mod tests {
5,
3,
10,
+ (Operator::Gt, Operator::Lt),
);
// l > r + 5 AND r > l - 13
let l_gt_r = 5;
@@ -876,6 +859,7 @@ mod tests {
let r_lt_l = -l_gt_r;
let l_lt_r = -r_gt_l;
generate_case::<false>(expr, left_col, right_col, seed, l_lt_r, r_lt_l)?;
+
Ok(())
}
@@ -899,6 +883,7 @@ mod tests {
5,
30,
3,
+ (Operator::Gt, Operator::Lt),
);
// l > r + 5 AND r > l - 27
let l_gt_r = 5;
@@ -916,6 +901,130 @@ mod tests {
let r_lt_l = -l_gt_r;
let l_lt_r = -r_gt_l;
generate_case::<false>(expr, left_col, right_col, seed, l_lt_r, r_lt_l)?;
+
+ Ok(())
+ }
+
+ #[rstest]
+ #[test]
+ fn case_6(
+ #[values(0, 1, 2, 123, 756, 63, 345, 6443, 12341, 142, 123, 8900)] seed: u64,
+ ) -> Result<()> {
+ let left_col = Arc::new(Column::new("left_watermark", 0));
+ let right_col = Arc::new(Column::new("right_watermark", 0));
+ // left_watermark - 1 >= right_watermark + 5 AND left_watermark - 10 <= right_watermark + 3
+
+ let expr = gen_conjunctive_numeric_expr(
+ left_col.clone(),
+ right_col.clone(),
+ Operator::Minus,
+ Operator::Plus,
+ Operator::Minus,
+ Operator::Plus,
+ 1,
+ 5,
+ 10,
+ 3,
+ (Operator::GtEq, Operator::LtEq),
+ );
+ // l >= r + 6 AND r >= l - 13
+ let l_gt_r = 6;
+ let r_gt_l = -13;
+
+ generate_case::<true>(
+ expr.clone(),
+ left_col.clone(),
+ right_col.clone(),
+ seed,
+ l_gt_r,
+ r_gt_l,
+ )?;
+ generate_case::<true>(expr, left_col, right_col, seed, l_gt_r, r_gt_l)?;
+
+ Ok(())
+ }
+
+ #[rstest]
+ #[test]
+ fn case_7(
+ #[values(0, 1, 2, 123, 77, 93, 104, 624, 115, 613, 8365, 9345)] seed: u64,
+ ) -> Result<()> {
+ let left_col = Arc::new(Column::new("left_watermark", 0));
+ let right_col = Arc::new(Column::new("right_watermark", 0));
+ // left_watermark + 4 >= right_watermark + 5 AND left_watermark - 20 < right_watermark - 5
+
+ let expr = gen_conjunctive_numeric_expr(
+ left_col.clone(),
+ right_col.clone(),
+ Operator::Plus,
+ Operator::Plus,
+ Operator::Minus,
+ Operator::Minus,
+ 4,
+ 5,
+ 20,
+ 5,
+ (Operator::GtEq, Operator::Lt),
+ );
+ // l >= r + 1 AND r > l - 15
+ let l_gt_r = 1;
+ let r_gt_l = -15;
+ generate_case::<true>(
+ expr.clone(),
+ left_col.clone(),
+ right_col.clone(),
+ seed,
+ l_gt_r,
+ r_gt_l,
+ )?;
+ // Descending tests
+ // r < l - 5 AND l < r + 27
+ let r_lt_l = -l_gt_r;
+ let l_lt_r = -r_gt_l;
+ generate_case::<false>(expr, left_col, right_col, seed, l_lt_r, r_lt_l)?;
+
+ Ok(())
+ }
+
+ #[rstest]
+ #[test]
+ fn case_8(
+ #[values(0, 1, 2, 24, 53, 412, 364, 345, 737, 1010, 52, 1554)] seed: u64,
+ ) -> Result<()> {
+ let left_col = Arc::new(Column::new("left_watermark", 0));
+ let right_col = Arc::new(Column::new("right_watermark", 0));
+ // left_watermark + 4 >= right_watermark + 5 AND left_watermark - 20 < right_watermark - 5
+
+ let expr = gen_conjunctive_numeric_expr(
+ left_col.clone(),
+ right_col.clone(),
+ Operator::Plus,
+ Operator::Plus,
+ Operator::Minus,
+ Operator::Minus,
+ 4,
+ 5,
+ 20,
+ 5,
+ (Operator::Gt, Operator::LtEq),
+ );
+ // l >= r + 1 AND r > l - 15
+ let l_gt_r = 1;
+ let r_gt_l = -15;
+ generate_case::<true>(
+ expr.clone(),
+ left_col.clone(),
+ right_col.clone(),
+ seed,
+ l_gt_r,
+ r_gt_l,
+ )?;
+ // Descending tests
+ // r < l - 5 AND l < r + 27
+ let r_lt_l = -l_gt_r;
+ let l_lt_r = -r_gt_l;
+ generate_case::<false>(expr, left_col, right_col, seed, l_lt_r, r_lt_l)?;
+
Ok(())
}
diff --git a/datafusion/physical-expr/src/intervals/interval_aritmetic.rs b/datafusion/physical-expr/src/intervals/interval_aritmetic.rs
index 94ac4e9a81..9a4b0bfe8d 100644
--- a/datafusion/physical-expr/src/intervals/interval_aritmetic.rs
+++ b/datafusion/physical-expr/src/intervals/interval_aritmetic.rs
@@ -29,23 +29,135 @@ use datafusion_expr::Operator;
use crate::aggregate::min_max::{max, min};
+/// This type represents a single endpoint of an [`Interval`]. An endpoint can
+/// be open or closed, denoting whether the interval includes or excludes the
+/// endpoint itself.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct IntervalBound {
+ pub value: ScalarValue,
+ pub open: bool,
+}
+
+impl IntervalBound {
+ /// Creates a new `IntervalBound` object using the given value.
+ pub const fn new(value: ScalarValue, open: bool) -> IntervalBound {
+ IntervalBound { value, open }
+ }
+
+ /// This convenience function creates an unbounded interval endpoint.
+ pub fn make_unbounded<T: Borrow<DataType>>(data_type: T) -> Result<Self> {
+ ScalarValue::try_from(data_type.borrow()).map(|v| IntervalBound::new(v, true))
+ }
+
+ /// This convenience function returns the data type associated with this
+ /// `IntervalBound`.
+ pub fn get_datatype(&self) -> DataType {
+ self.value.get_datatype()
+ }
+
+ /// This convenience function checks whether the `IntervalBound` represents
+ /// an unbounded interval endpoint.
+ pub fn is_unbounded(&self) -> bool {
+ self.value.is_null()
+ }
+
+ /// This function casts the `IntervalBound` to the given data type.
+ pub(crate) fn cast_to(
+ &self,
+ data_type: &DataType,
+ cast_options: &CastOptions,
+ ) -> Result<IntervalBound> {
+ cast_scalar_value(&self.value, data_type, cast_options)
+ .map(|value| IntervalBound::new(value, self.open))
+ }
+
+ /// This function adds the given `IntervalBound` to this `IntervalBound`.
+ /// The result is unbounded if either is; otherwise, their values are
+ /// added. The result is closed if both original bounds are closed, or open
+ /// otherwise.
+ pub fn add<T: Borrow<IntervalBound>>(&self, other: T) -> Result<IntervalBound> {
+ let rhs = other.borrow();
+ if self.is_unbounded() || rhs.is_unbounded() {
+ IntervalBound::make_unbounded(coerce_types(
+ &self.get_datatype(),
+ &Operator::Plus,
+ &rhs.get_datatype(),
+ )?)
+ } else {
+ self.value
+ .add(&rhs.value)
+ .map(|v| IntervalBound::new(v, self.open || rhs.open))
+ }
+ }
+
+ /// This function subtracts the given `IntervalBound` from `self`.
+ /// The result is unbounded if either is; otherwise, their values are
+ /// subtracted. The result is closed if both original bounds are closed,
+ /// or open otherwise.
+ pub fn sub<T: Borrow<IntervalBound>>(&self, other: T) -> Result<IntervalBound> {
+ let rhs = other.borrow();
+ if self.is_unbounded() || rhs.is_unbounded() {
+ IntervalBound::make_unbounded(coerce_types(
+ &self.get_datatype(),
+ &Operator::Minus,
+ &rhs.get_datatype(),
+ )?)
+ } else {
+ self.value
+ .sub(&rhs.value)
+ .map(|v| IntervalBound::new(v, self.open || rhs.open))
+ }
+ }
+
+ /// This function chooses one of the given `IntervalBound`s according to
+ /// the given function `decide`. The result is unbounded if both are. If
+ /// only one of the arguments is unbounded, the other one is chosen by
+ /// default. If neither is unbounded, the function `decide` is used.
+ pub fn choose(
+ first: &IntervalBound,
+ second: &IntervalBound,
+ decide: fn(&ScalarValue, &ScalarValue) -> Result<ScalarValue>,
+ ) -> Result<IntervalBound> {
+ Ok(if first.is_unbounded() {
+ second.clone()
+ } else if second.is_unbounded() {
+ first.clone()
+ } else if first.value != second.value {
+ let chosen = decide(&first.value, &second.value)?;
+ if chosen.eq(&first.value) {
+ first.clone()
+ } else {
+ second.clone()
+ }
+ } else {
+ IntervalBound::new(second.value.clone(), first.open || second.open)
+ })
+ }
+}
+
+impl Display for IntervalBound {
+ fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
+ write!(f, "IntervalBound [{}]", self.value)
+ }
+}
+
/// This type represents an interval, which is used to calculate reliable
/// bounds for expressions. Currently, we only support addition and
/// subtraction, but more capabilities will be added in the future.
/// Upper/lower bounds having NULL values indicate an unbounded side. For
-/// example; [10, 20], [10, ∞], [-∞, 100] and [-∞, ∞] are all valid intervals.
-#[derive(Debug, PartialEq, Clone, Eq, Hash)]
+/// example; [10, 20], [10, ∞), (-∞, 100] and (-∞, ∞) are all valid intervals.
+#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Interval {
- pub lower: ScalarValue,
- pub upper: ScalarValue,
+ pub lower: IntervalBound,
+ pub upper: IntervalBound,
}
impl Default for Interval {
fn default() -> Self {
- Interval {
- lower: ScalarValue::Null,
- upper: ScalarValue::Null,
- }
+ Interval::new(
+ IntervalBound::new(ScalarValue::Null, true),
+ IntervalBound::new(ScalarValue::Null, true),
+ )
}
}
@@ -56,144 +168,233 @@ impl Display for Interval {
}
impl Interval {
+ /// Creates a new interval object using the given bounds.
+ /// For boolean intervals, having an open false lower bound is equivalent
+ /// to having a true closed lower bound. Similarly, open true upper bound
+ /// is equivalent to having a false closed upper bound. Also for boolean
+ /// intervals, having an unbounded left endpoint is equivalent to having a
+ /// false closed lower bound, while having an unbounded right endpoint is
+ /// equivalent to having a true closed upper bound. Therefore; input
+ /// parameters to construct an Interval can have different types, but they
+ /// all result in [false, false], [false, true] or [true, true].
+ pub fn new(lower: IntervalBound, upper: IntervalBound) -> Interval {
+ // Boolean intervals need a special handling.
+ if let ScalarValue::Boolean(_) = lower.value {
+ let standardized_lower = match lower.value {
+ ScalarValue::Boolean(None) if lower.open => {
+ ScalarValue::Boolean(Some(false))
+ }
+ ScalarValue::Boolean(Some(false)) if lower.open => {
+ ScalarValue::Boolean(Some(true))
+ }
+ // The rest may include some invalid interval cases. The validation of
+ // interval construction parameters will be implemented later.
+ // For now, let's return them unchanged.
+ _ => lower.value,
+ };
+ let standardized_upper = match upper.value {
+ ScalarValue::Boolean(None) if upper.open => {
+ ScalarValue::Boolean(Some(true))
+ }
+ ScalarValue::Boolean(Some(true)) if upper.open => {
+ ScalarValue::Boolean(Some(false))
+ }
+ _ => upper.value,
+ };
+ Interval {
+ lower: IntervalBound::new(standardized_lower, false),
+ upper: IntervalBound::new(standardized_upper, false),
+ }
+ } else {
+ Interval { lower, upper }
+ }
+ }
+
+ pub fn make<T>(lower: Option<T>, upper: Option<T>, open: (bool, bool)) -> Interval
+ where
+ ScalarValue: From<Option<T>>,
+ {
+ Interval::new(
+ IntervalBound::new(ScalarValue::from(lower), open.0),
+ IntervalBound::new(ScalarValue::from(upper), open.1),
+ )
+ }
+
+ /// Casts this interval to `data_type` using `cast_options`.
pub(crate) fn cast_to(
&self,
data_type: &DataType,
cast_options: &CastOptions,
) -> Result<Interval> {
- Ok(Interval {
- lower: cast_scalar_value(&self.lower, data_type, cast_options)?,
- upper: cast_scalar_value(&self.upper, data_type, cast_options)?,
- })
+ let lower = self.lower.cast_to(data_type, cast_options)?;
+ let upper = self.upper.cast_to(data_type, cast_options)?;
+ Ok(Interval::new(lower, upper))
}
- pub(crate) fn get_datatype(&self) -> DataType {
- self.lower.get_datatype()
+ /// This function returns the data type of this interval. If both endpoints
+ /// do not have the same data type, returns an error.
+ pub(crate) fn get_datatype(&self) -> Result<DataType> {
+ let lower_type = self.lower.get_datatype();
+ let upper_type = self.upper.get_datatype();
+ if lower_type == upper_type {
+ Ok(lower_type)
+ } else {
+ Err(DataFusionError::Internal(format!(
+ "Interval bounds have different types: {} != {}",
+ lower_type, upper_type,
+ )))
+ }
}
/// Decide if this interval is certainly greater than, possibly greater than,
/// or can't be greater than `other` by returning [true, true],
/// [false, true] or [false, false] respectively.
- pub(crate) fn gt(&self, other: &Interval) -> Interval {
- let flags = if !self.upper.is_null()
- && !other.lower.is_null()
- && (self.upper <= other.lower)
+ pub(crate) fn gt<T: Borrow<Interval>>(&self, other: T) -> Interval {
+ let rhs = other.borrow();
+ let flags = if !self.upper.is_unbounded()
+ && !rhs.lower.is_unbounded()
+ && self.upper.value <= rhs.lower.value
{
+ // Values in this interval are certainly less than or equal to those
+ // in the given interval.
(false, false)
- } else if !self.lower.is_null()
- && !other.upper.is_null()
- && (self.lower > other.upper)
+ } else if !self.lower.is_unbounded()
+ && !rhs.upper.is_unbounded()
+ && self.lower.value >= rhs.upper.value
+ && (self.lower.value > rhs.upper.value || self.lower.open || rhs.upper.open)
{
+ // Values in this interval are certainly greater than those in the
+ // given interval.
(true, true)
} else {
+ // All outcomes are possible.
(false, true)
};
- Interval {
- lower: ScalarValue::Boolean(Some(flags.0)),
- upper: ScalarValue::Boolean(Some(flags.1)),
- }
+
+ Interval::make(Some(flags.0), Some(flags.1), (false, false))
+ }
+
+ /// Decide if this interval is certainly greater than or equal to, possibly greater than
+ /// or equal to, or can't be greater than or equal to `other` by returning [true, true],
+ /// [false, true] or [false, false] respectively.
+ pub(crate) fn gt_eq<T: Borrow<Interval>>(&self, other: T) -> Interval {
+ let rhs = other.borrow();
+ let flags = if !self.lower.is_unbounded()
+ && !rhs.upper.is_unbounded()
+ && self.lower.value >= rhs.upper.value
+ {
+ // Values in this interval are certainly greater than or equal to those
+ // in the given interval.
+ (true, true)
+ } else if !self.upper.is_unbounded()
+ && !rhs.lower.is_unbounded()
+ && self.upper.value <= rhs.lower.value
+ && (self.upper.value < rhs.lower.value || self.upper.open || rhs.lower.open)
+ {
+ // Values in this interval are certainly less than those in the
+ // given interval.
+ (false, false)
+ } else {
+ // All outcomes are possible.
+ (false, true)
+ };
+
+ Interval::make(Some(flags.0), Some(flags.1), (false, false))
}
/// Decide if this interval is certainly less than, possibly less than,
/// or can't be less than `other` by returning [true, true],
/// [false, true] or [false, false] respectively.
- pub(crate) fn lt(&self, other: &Interval) -> Interval {
- other.gt(self)
+ pub(crate) fn lt<T: Borrow<Interval>>(&self, other: T) -> Interval {
+ other.borrow().gt(self)
+ }
+
+ /// Decide if this interval is certainly less than or equal to, possibly
+ /// less than or equal to, or can't be less than or equal to `other` by returning
+ /// [true, true], [false, true] or [false, false] respectively.
+ pub(crate) fn lt_eq<T: Borrow<Interval>>(&self, other: T) -> Interval {
+ other.borrow().gt_eq(self)
}
/// Decide if this interval is certainly equal to, possibly equal to,
/// or can't be equal to `other` by returning [true, true],
/// [false, true] or [false, false] respectively.
- pub(crate) fn equal(&self, other: &Interval) -> Interval {
- let flags = if !self.lower.is_null()
- && (self.lower == self.upper)
- && (other.lower == other.upper)
- && (self.lower == other.lower)
+ pub(crate) fn equal<T: Borrow<Interval>>(&self, other: T) -> Interval {
+ let rhs = other.borrow();
+ let flags = if !self.lower.is_unbounded()
+ && (self.lower.value == self.upper.value)
+ && (rhs.lower.value == rhs.upper.value)
+ && (self.lower.value == rhs.lower.value)
{
(true, true)
- } else if (!self.lower.is_null()
- && !other.upper.is_null()
- && (self.lower > other.upper))
- || (!self.upper.is_null()
- && !other.lower.is_null()
- && (self.upper < other.lower))
+ } else if self.gt(rhs) == Interval::CERTAINLY_TRUE
+ || self.lt(rhs) == Interval::CERTAINLY_TRUE
{
(false, false)
} else {
(false, true)
};
- Interval {
- lower: ScalarValue::Boolean(Some(flags.0)),
- upper: ScalarValue::Boolean(Some(flags.1)),
- }
+
+ Interval::make(Some(flags.0), Some(flags.1), (false, false))
}
- /// Compute the logical conjunction of this (boolean) interval with the
- /// given boolean interval.
- pub(crate) fn and(&self, other: &Interval) -> Result<Interval> {
- let flags = match (self, other) {
+ /// Compute the logical conjunction of this (boolean) interval with the given boolean interval.
+ pub(crate) fn and<T: Borrow<Interval>>(&self, other: T) -> Result<Interval> {
+ let rhs = other.borrow();
+ match (
+ &self.lower.value,
+ &self.upper.value,
+ &rhs.lower.value,
+ &rhs.upper.value,
+ ) {
(
- Interval {
- lower: ScalarValue::Boolean(Some(lower)),
- upper: ScalarValue::Boolean(Some(upper)),
- },
- Interval {
- lower: ScalarValue::Boolean(Some(other_lower)),
- upper: ScalarValue::Boolean(Some(other_upper)),
- },
+ ScalarValue::Boolean(Some(self_lower)),
+ ScalarValue::Boolean(Some(self_upper)),
+ ScalarValue::Boolean(Some(other_lower)),
+ ScalarValue::Boolean(Some(other_upper)),
) => {
- if *lower && *other_lower {
- (true, true)
- } else if *upper && *other_upper {
- (false, true)
- } else {
- (false, false)
- }
- }
- _ => {
- return Err(DataFusionError::Internal(
- "Incompatible types for logical conjunction".to_string(),
- ))
+ let lower = *self_lower && *other_lower;
+ let upper = *self_upper && *other_upper;
+
+ Ok(Interval {
+ lower: IntervalBound::new(ScalarValue::Boolean(Some(lower)), false),
+ upper: IntervalBound::new(ScalarValue::Boolean(Some(upper)), false),
+ })
}
- };
- Ok(Interval {
- lower: ScalarValue::Boolean(Some(flags.0)),
- upper: ScalarValue::Boolean(Some(flags.1)),
- })
+ _ => Err(DataFusionError::Internal(
+ "Incompatible types for logical conjunction".to_string(),
+ )),
+ }
}
/// Compute the intersection of the interval with the given interval.
/// If the intersection is empty, return None.
- pub(crate) fn intersect(&self, other: &Interval) -> Result<Option<Interval>> {
- let lower = if self.lower.is_null() {
- other.lower.clone()
- } else if other.lower.is_null() {
- self.lower.clone()
- } else {
- max(&self.lower, &other.lower)?
- };
- let upper = if self.upper.is_null() {
- other.upper.clone()
- } else if other.upper.is_null() {
- self.upper.clone()
- } else {
- min(&self.upper, &other.upper)?
- };
- Ok(if !lower.is_null() && !upper.is_null() && lower > upper {
+ pub(crate) fn intersect<T: Borrow<Interval>>(
+ &self,
+ other: T,
+ ) -> Result<Option<Interval>> {
+ let rhs = other.borrow();
+ // If it is evident that the result is an empty interval,
+ // do not make any calculation and directly return None.
+ if (!self.lower.is_unbounded()
+ && !rhs.upper.is_unbounded()
+ && self.lower.value > rhs.upper.value)
+ || (!self.upper.is_unbounded()
+ && !rhs.lower.is_unbounded()
+ && self.upper.value < rhs.lower.value)
+ {
// This None value signals an empty interval.
- None
- } else {
- Some(Interval { lower, upper })
- })
- }
+ return Ok(None);
+ }
- // Compute the negation of the interval.
- #[allow(dead_code)]
- pub(crate) fn arithmetic_negate(&self) -> Result<Interval> {
- Ok(Interval {
- lower: self.upper.arithmetic_negate()?,
- upper: self.lower.arithmetic_negate()?,
- })
+ let lower = IntervalBound::choose(&self.lower, &rhs.lower, max)?;
+ let upper = IntervalBound::choose(&self.upper, &rhs.upper, min)?;
+
+ let non_empty = lower.is_unbounded()
+ || upper.is_unbounded()
+ || lower.value != upper.value
+ || (!lower.open && !upper.open);
+ Ok(non_empty.then_some(Interval::new(lower, upper)))
}
/// Add the given interval (`other`) to this interval. Say we have
@@ -202,25 +403,10 @@ impl Interval {
/// one can choose single values arbitrarily from each of the operands.
pub fn add<T: Borrow<Interval>>(&self, other: T) -> Result<Interval> {
let rhs = other.borrow();
- let lower = if self.lower.is_null() || rhs.lower.is_null() {
- ScalarValue::try_from(&coerce_types(
- &self.get_datatype(),
- &Operator::Plus,
- &rhs.get_datatype(),
- )?)
- } else {
- self.lower.add(&rhs.lower)
- }?;
- let upper = if self.upper.is_null() || rhs.upper.is_null() {
- ScalarValue::try_from(coerce_types(
- &self.get_datatype(),
- &Operator::Plus,
- &rhs.get_datatype(),
- )?)
- } else {
- self.upper.add(&rhs.upper)
- }?;
- Ok(Interval { lower, upper })
+ Ok(Interval::new(
+ self.lower.add(&rhs.lower)?,
+ self.upper.add(&rhs.upper)?,
+ ))
}
/// Subtract the given interval (`other`) from this interval. Say we have
@@ -229,26 +415,26 @@ impl Interval {
/// if one can choose single values arbitrarily from each of the operands.
pub fn sub<T: Borrow<Interval>>(&self, other: T) -> Result<Interval> {
let rhs = other.borrow();
- let lower = if self.lower.is_null() || rhs.upper.is_null() {
- ScalarValue::try_from(coerce_types(
- &self.get_datatype(),
- &Operator::Minus,
- &rhs.get_datatype(),
- )?)
- } else {
- self.lower.sub(&rhs.upper)
- }?;
- let upper = if self.upper.is_null() || rhs.lower.is_null() {
- ScalarValue::try_from(coerce_types(
- &self.get_datatype(),
- &Operator::Minus,
- &rhs.get_datatype(),
- )?)
- } else {
- self.upper.sub(&rhs.lower)
- }?;
- Ok(Interval { lower, upper })
+ Ok(Interval::new(
+ self.lower.sub(&rhs.upper)?,
+ self.upper.sub(&rhs.lower)?,
+ ))
}
+
+ pub const CERTAINLY_FALSE: Interval = Interval {
+ lower: IntervalBound::new(ScalarValue::Boolean(Some(false)), false),
+ upper: IntervalBound::new(ScalarValue::Boolean(Some(false)), false),
+ };
+
+ pub const UNCERTAIN: Interval = Interval {
+ lower: IntervalBound::new(ScalarValue::Boolean(Some(false)), false),
+ upper: IntervalBound::new(ScalarValue::Boolean(Some(true)), false),
+ };
+
+ pub const CERTAINLY_TRUE: Interval = Interval {
+ lower: IntervalBound::new(ScalarValue::Boolean(Some(true)), false),
+ upper: IntervalBound::new(ScalarValue::Boolean(Some(true)), false),
+ };
}
/// Indicates whether interval arithmetic is supported for the given operator.
@@ -259,7 +445,9 @@ pub fn is_operator_supported(op: &Operator) -> bool {
| &Operator::Minus
| &Operator::And
| &Operator::Gt
+ | &Operator::GtEq
| &Operator::Lt
+ | &Operator::LtEq
)
}
@@ -282,14 +470,13 @@ pub fn apply_operator(op: &Operator, lhs: &Interval, rhs: &Interval) -> Result<I
match *op {
Operator::Eq => Ok(lhs.equal(rhs)),
Operator::Gt => Ok(lhs.gt(rhs)),
+ Operator::GtEq => Ok(lhs.gt_eq(rhs)),
Operator::Lt => Ok(lhs.lt(rhs)),
+ Operator::LtEq => Ok(lhs.lt_eq(rhs)),
Operator::And => lhs.and(rhs),
Operator::Plus => lhs.add(rhs),
Operator::Minus => lhs.sub(rhs),
- _ => Ok(Interval {
- lower: ScalarValue::Null,
- upper: ScalarValue::Null,
- }),
+ _ => Ok(Interval::default()),
}
}
@@ -305,64 +492,81 @@ fn cast_scalar_value(
#[cfg(test)]
mod tests {
- use crate::intervals::Interval;
+ use crate::intervals::{Interval, IntervalBound};
use datafusion_common::{Result, ScalarValue};
+ use ScalarValue::Boolean;
+
+ fn open_open<T>(lower: Option<T>, upper: Option<T>) -> Interval
+ where
+ ScalarValue: From<Option<T>>,
+ {
+ Interval::make(lower, upper, (true, true))
+ }
+
+ fn open_closed<T>(lower: Option<T>, upper: Option<T>) -> Interval
+ where
+ ScalarValue: From<Option<T>>,
+ {
+ Interval::make(lower, upper, (true, false))
+ }
+
+ fn closed_open<T>(lower: Option<T>, upper: Option<T>) -> Interval
+ where
+ ScalarValue: From<Option<T>>,
+ {
+ Interval::make(lower, upper, (false, true))
+ }
+
+ fn closed_closed<T>(lower: Option<T>, upper: Option<T>) -> Interval
+ where
+ ScalarValue: From<Option<T>>,
+ {
+ Interval::make(lower, upper, (false, false))
+ }
#[test]
fn intersect_test() -> Result<()> {
let possible_cases = vec![
- (Some(1000), None, None, None, Some(1000), None),
- (None, Some(1000), None, None, None, Some(1000)),
- (None, None, Some(1000), None, Some(1000), None),
- (None, None, None, Some(1000), None, Some(1000)),
- (Some(1000), None, Some(1000), None, Some(1000), None),
+ (Some(1000_i64), None, None, None, Some(1000_i64), None),
+ (None, Some(1000_i64), None, None, None, Some(1000_i64)),
+ (None, None, Some(1000_i64), None, Some(1000_i64), None),
+ (None, None, None, Some(1000_i64), None, Some(1000_i64)),
+ (
+ Some(1000_i64),
+ None,
+ Some(1000_i64),
+ None,
+ Some(1000_i64),
+ None,
+ ),
(
None,
- Some(1000),
- Some(999),
- Some(1002),
- Some(999),
- Some(1000),
+ Some(1000_i64),
+ Some(999_i64),
+ Some(1002_i64),
+ Some(999_i64),
+ Some(1000_i64),
),
- (None, Some(1000), Some(1000), None, Some(1000), Some(1000)), // singleton
(None, None, None, None, None, None),
];
for case in possible_cases {
assert_eq!(
- Interval {
- lower: ScalarValue::Int64(case.0),
- upper: ScalarValue::Int64(case.1)
- }
- .intersect(&Interval {
- lower: ScalarValue::Int64(case.2),
- upper: ScalarValue::Int64(case.3)
- })?
- .unwrap(),
- Interval {
- lower: ScalarValue::Int64(case.4),
- upper: ScalarValue::Int64(case.5)
- }
+ open_open(case.0, case.1).intersect(open_open(case.2, case.3))?,
+ Some(open_open(case.4, case.5))
)
}
let empty_cases = vec![
- (None, Some(1000), Some(1001), None),
- (Some(1001), None, None, Some(1000)),
- (None, Some(1000), Some(1001), Some(1002)),
- (Some(1001), Some(1002), None, Some(1000)),
+ (None, Some(1000_i64), Some(1001_i64), None),
+ (Some(1001_i64), None, None, Some(1000_i64)),
+ (None, Some(1000_i64), Some(1001_i64), Some(1002_i64)),
+ (Some(1001_i64), Some(1002_i64), None, Some(1000_i64)),
];
for case in empty_cases {
assert_eq!(
- Interval {
- lower: ScalarValue::Int64(case.0),
- upper: ScalarValue::Int64(case.1)
- }
- .intersect(&Interval {
- lower: ScalarValue::Int64(case.2),
- upper: ScalarValue::Int64(case.3)
- })?,
+ open_open(case.0, case.1).intersect(open_open(case.2, case.3))?,
None
)
}
@@ -373,68 +577,90 @@ mod tests {
#[test]
fn gt_test() {
let cases = vec![
- (Some(1000), None, None, None, false, true),
- (None, Some(1000), None, None, false, true),
- (None, None, Some(1000), None, false, true),
- (None, None, None, Some(1000), false, true),
- (None, Some(1000), Some(1000), None, false, false),
- (None, Some(1000), Some(1001), None, false, false),
- (Some(1000), None, Some(1000), None, false, true),
- (None, Some(1000), Some(1001), Some(1002), false, false),
- (None, Some(1000), Some(999), Some(1002), false, true),
- (Some(1002), None, Some(999), Some(1002), false, true),
- (Some(1003), None, Some(999), Some(1002), true, true),
+ (Some(1000_i64), None, None, None, false, true),
+ (None, Some(1000_i64), None, None, false, true),
+ (None, None, Some(1000_i64), None, false, true),
+ (None, None, None, Some(1000_i64), false, true),
+ (None, Some(1000_i64), Some(1000_i64), None, false, false),
+ (None, Some(1000_i64), Some(1001_i64), None, false, false),
+ (Some(1000_i64), None, Some(1000_i64), None, false, true),
+ (
+ None,
+ Some(1000_i64),
+ Some(1001_i64),
+ Some(1002_i64),
+ false,
+ false,
+ ),
+ (
+ None,
+ Some(1000_i64),
+ Some(999_i64),
+ Some(1002_i64),
+ false,
+ true,
+ ),
+ (
+ Some(1002_i64),
+ None,
+ Some(999_i64),
+ Some(1002_i64),
+ true,
+ true,
+ ),
+ (
+ Some(1003_i64),
+ None,
+ Some(999_i64),
+ Some(1002_i64),
+ true,
+ true,
+ ),
(None, None, None, None, false, true),
];
for case in cases {
assert_eq!(
- Interval {
- lower: ScalarValue::Int64(case.0),
- upper: ScalarValue::Int64(case.1)
- }
- .gt(&Interval {
- lower: ScalarValue::Int64(case.2),
- upper: ScalarValue::Int64(case.3)
- }),
- Interval {
- lower: ScalarValue::Boolean(Some(case.4)),
- upper: ScalarValue::Boolean(Some(case.5))
- }
- )
+ open_open(case.0, case.1).gt(open_open(case.2, case.3)),
+ closed_closed(Some(case.4), Some(case.5))
+ );
}
}
#[test]
fn lt_test() {
let cases = vec![
- (Some(1000), None, None, None, false, true),
- (None, Some(1000), None, None, false, true),
- (None, None, Some(1000), None, false, true),
- (None, None, None, Some(1000), false, true),
- (None, Some(1000), Some(1000), None, false, true),
- (None, Some(1000), Some(1001), None, true, true),
- (Some(1000), None, Some(1000), None, false, true),
- (None, Some(1000), Some(1001), Some(1002), true, true),
- (None, Some(1000), Some(999), Some(1002), false, true),
+ (Some(1000_i64), None, None, None, false, true),
+ (None, Some(1000_i64), None, None, false, true),
+ (None, None, Some(1000_i64), None, false, true),
+ (None, None, None, Some(1000_i64), false, true),
+ (None, Some(1000_i64), Some(1000_i64), None, true, true),
+ (None, Some(1000_i64), Some(1001_i64), None, true, true),
+ (Some(1000_i64), None, Some(1000_i64), None, false, true),
+ (
+ None,
+ Some(1000_i64),
+ Some(1001_i64),
+ Some(1002_i64),
+ true,
+ true,
+ ),
+ (
+ None,
+ Some(1000_i64),
+ Some(999_i64),
+ Some(1002_i64),
+ false,
+ true,
+ ),
(None, None, None, None, false, true),
];
for case in cases {
assert_eq!(
- Interval {
- lower: ScalarValue::Int64(case.0),
- upper: ScalarValue::Int64(case.1)
- }
- .lt(&Interval {
- lower: ScalarValue::Int64(case.2),
- upper: ScalarValue::Int64(case.3)
- }),
- Interval {
- lower: ScalarValue::Boolean(Some(case.4)),
- upper: ScalarValue::Boolean(Some(case.5))
- }
- )
+ open_open(case.0, case.1).lt(open_open(case.2, case.3)),
+ closed_closed(Some(case.4), Some(case.5))
+ );
}
}
@@ -451,19 +677,10 @@ mod tests {
for case in cases {
assert_eq!(
- Interval {
- lower: ScalarValue::Boolean(Some(case.0)),
- upper: ScalarValue::Boolean(Some(case.1))
- }
- .and(&Interval {
- lower: ScalarValue::Boolean(Some(case.2)),
- upper: ScalarValue::Boolean(Some(case.3))
- })?,
- Interval {
- lower: ScalarValue::Boolean(Some(case.4)),
- upper: ScalarValue::Boolean(Some(case.5))
- }
- )
+ open_open(Some(case.0), Some(case.1))
+ .and(open_open(Some(case.2), Some(case.3)))?,
+ open_open(Some(case.4), Some(case.5))
+ );
}
Ok(())
}
@@ -471,39 +688,43 @@ mod tests {
#[test]
fn add_test() -> Result<()> {
let cases = vec![
- (Some(1000), None, None, None, None, None),
- (None, Some(1000), None, None, None, None),
- (None, None, Some(1000), None, None, None),
- (None, None, None, Some(1000), None, None),
- (Some(1000), None, Some(1000), None, Some(2000), None),
- (None, Some(1000), Some(999), Some(1002), None, Some(2002)),
- (None, Some(1000), Some(1000), None, None, None),
- (
- Some(2001),
- Some(1),
- Some(1005),
- Some(-999),
- Some(3006),
- Some(-998),
+ (Some(1000_i64), None, None, None, None, None),
+ (None, Some(1000_i64), None, None, None, None),
+ (None, None, Some(1000_i64), None, None, None),
+ (None, None, None, Some(1000_i64), None, None),
+ (
+ Some(1000_i64),
+ None,
+ Some(1000_i64),
+ None,
+ Some(2000_i64),
+ None,
+ ),
+ (
+ None,
+ Some(1000_i64),
+ Some(999_i64),
+ Some(1002_i64),
+ None,
+ Some(2002_i64),
+ ),
+ (None, Some(1000_i64), Some(1000_i64), None, None, None),
+ (
+ Some(2001_i64),
+ Some(1_i64),
+ Some(1005_i64),
+ Some(-999_i64),
+ Some(3006_i64),
+ Some(-998_i64),
),
(None, None, None, None, None, None),
];
for case in cases {
assert_eq!(
- Interval {
- lower: ScalarValue::Int64(case.0),
- upper: ScalarValue::Int64(case.1)
- }
- .add(&Interval {
- lower: ScalarValue::Int64(case.2),
- upper: ScalarValue::Int64(case.3)
- })?,
- Interval {
- lower: ScalarValue::Int64(case.4),
- upper: ScalarValue::Int64(case.5)
- }
- )
+ open_open(case.0, case.1).add(open_open(case.2, case.3))?,
+ open_open(case.4, case.5)
+ );
}
Ok(())
}
@@ -511,39 +732,351 @@ mod tests {
#[test]
fn sub_test() -> Result<()> {
let cases = vec![
- (Some(1000), None, None, None, None, None),
- (None, Some(1000), None, None, None, None),
- (None, None, Some(1000), None, None, None),
- (None, None, None, Some(1000), None, None),
- (Some(1000), None, Some(1000), None, None, None),
- (None, Some(1000), Some(999), Some(1002), None, Some(1)),
- (None, Some(1000), Some(1000), None, None, Some(0)),
- (
- Some(2001),
- Some(1000),
+ (Some(1000_i64), None, None, None, None, None),
+ (None, Some(1000_i64), None, None, None, None),
+ (None, None, Some(1000_i64), None, None, None),
+ (None, None, None, Some(1000_i64), None, None),
+ (Some(1000_i64), None, Some(1000_i64), None, None, None),
+ (
+ None,
+ Some(1000_i64),
+ Some(999_i64),
+ Some(1002_i64),
+ None,
+ Some(1_i64),
+ ),
+ (
+ None,
+ Some(1000_i64),
+ Some(1000_i64),
+ None,
+ None,
+ Some(0_i64),
+ ),
+ (
+ Some(2001_i64),
+ Some(1000_i64),
Some(1005),
- Some(999),
- Some(1002),
- Some(-5),
+ Some(999_i64),
+ Some(1002_i64),
+ Some(-5_i64),
),
(None, None, None, None, None, None),
];
for case in cases {
assert_eq!(
- Interval {
- lower: ScalarValue::Int64(case.0),
- upper: ScalarValue::Int64(case.1)
- }
- .sub(&Interval {
- lower: ScalarValue::Int64(case.2),
- upper: ScalarValue::Int64(case.3)
- })?,
- Interval {
- lower: ScalarValue::Int64(case.4),
- upper: ScalarValue::Int64(case.5)
- }
- )
+ open_open(case.0, case.1).sub(open_open(case.2, case.3))?,
+ open_open(case.4, case.5)
+ );
+ }
+ Ok(())
+ }
+
+ #[test]
+ fn sub_test_various_bounds() -> Result<()> {
+ let cases = vec![
+ (
+ closed_closed(Some(100_i64), Some(200_i64)),
+ closed_open(Some(200_i64), None),
+ open_closed(None, Some(0_i64)),
+ ),
+ (
+ closed_open(Some(100_i64), Some(200_i64)),
+ open_closed(Some(300_i64), Some(150_i64)),
+ closed_open(Some(-50_i64), Some(-100_i64)),
+ ),
+ (
+ closed_open(Some(100_i64), Some(200_i64)),
+ open_open(Some(200_i64), None),
+ open_open(None, Some(0_i64)),
+ ),
+ (
+ closed_closed(Some(1_i64), Some(1_i64)),
+ closed_closed(Some(11_i64), Some(11_i64)),
+ closed_closed(Some(-10_i64), Some(-10_i64)),
+ ),
+ ];
+ for case in cases {
+ assert_eq!(case.0.sub(case.1)?, case.2)
+ }
+ Ok(())
+ }
+
+ #[test]
+ fn add_test_various_bounds() -> Result<()> {
+ let cases = vec![
+ (
+ closed_closed(Some(100_i64), Some(200_i64)),
+ open_closed(None, Some(200_i64)),
+ open_closed(None, Some(400_i64)),
+ ),
+ (
+ closed_open(Some(100_i64), Some(200_i64)),
+ closed_open(Some(-300_i64), Some(150_i64)),
+ closed_open(Some(-200_i64), Some(350_i64)),
+ ),
+ (
+ closed_open(Some(100_i64), Some(200_i64)),
+ open_open(Some(200_i64), None),
+ open_open(Some(300_i64), None),
+ ),
+ (
+ closed_closed(Some(1_i64), Some(1_i64)),
+ closed_closed(Some(11_i64), Some(11_i64)),
+ closed_closed(Some(12_i64), Some(12_i64)),
+ ),
+ ];
+ for case in cases {
+ assert_eq!(case.0.add(case.1)?, case.2)
+ }
+ Ok(())
+ }
+
+ #[test]
+ fn lt_test_various_bounds() -> Result<()> {
+ let cases = vec![
+ (
+ closed_closed(Some(100_i64), Some(200_i64)),
+ open_closed(None, Some(100_i64)),
+ closed_closed(Some(false), Some(false)),
+ ),
+ (
+ closed_closed(Some(100_i64), Some(200_i64)),
+ open_open(None, Some(100_i64)),
+ closed_closed(Some(false), Some(false)),
+ ),
+ (
+ open_open(Some(100_i64), Some(200_i64)),
+ closed_closed(Some(0_i64), Some(100_i64)),
+ closed_closed(Some(false), Some(false)),
+ ),
+ (
+ closed_closed(Some(2_i64), Some(2_i64)),
+ closed_closed(Some(1_i64), Some(2_i64)),
+ closed_closed(Some(false), Some(false)),
+ ),
+ (
+ closed_closed(Some(2_i64), Some(2_i64)),
+ closed_open(Some(1_i64), Some(2_i64)),
+ closed_closed(Some(false), Some(false)),
+ ),
+ (
+ closed_closed(Some(1_i64), Some(1_i64)),
+ open_open(Some(1_i64), Some(2_i64)),
+ closed_closed(Some(true), Some(true)),
+ ),
+ ];
+ for case in cases {
+ assert_eq!(case.0.lt(case.1), case.2)
+ }
+ Ok(())
+ }
+
+ #[test]
+ fn gt_test_various_bounds() -> Result<()> {
+ let cases = vec![
+ (
+ closed_closed(Some(100_i64), Some(200_i64)),
+ open_closed(None, Some(100_i64)),
+ closed_closed(Some(false), Some(true)),
+ ),
+ (
+ closed_closed(Some(100_i64), Some(200_i64)),
+ open_open(None, Some(100_i64)),
+ closed_closed(Some(true), Some(true)),
+ ),
+ (
+ open_open(Some(100_i64), Some(200_i64)),
+ closed_closed(Some(0_i64), Some(100_i64)),
+ closed_closed(Some(true), Some(true)),
+ ),
+ (
+ closed_closed(Some(2_i64), Some(2_i64)),
+ closed_closed(Some(1_i64), Some(2_i64)),
+ closed_closed(Some(false), Some(true)),
+ ),
+ (
+ closed_closed(Some(2_i64), Some(2_i64)),
+ closed_open(Some(1_i64), Some(2_i64)),
+ closed_closed(Some(true), Some(true)),
+ ),
+ (
+ closed_closed(Some(1_i64), Some(1_i64)),
+ open_open(Some(1_i64), Some(2_i64)),
+ closed_closed(Some(false), Some(false)),
+ ),
+ ];
+ for case in cases {
+ assert_eq!(case.0.gt(case.1), case.2)
+ }
+ Ok(())
+ }
+
+ #[test]
+ fn lt_eq_test_various_bounds() -> Result<()> {
+ let cases = vec![
+ (
+ closed_closed(Some(100_i64), Some(200_i64)),
+ open_closed(None, Some(100_i64)),
+ closed_closed(Some(false), Some(true)),
+ ),
+ (
+ closed_closed(Some(100_i64), Some(200_i64)),
+ open_open(None, Some(100_i64)),
+ closed_closed(Some(false), Some(false)),
+ ),
+ (
+ closed_closed(Some(2_i64), Some(2_i64)),
+ closed_closed(Some(1_i64), Some(2_i64)),
+ closed_closed(Some(false), Some(true)),
+ ),
+ (
+ closed_closed(Some(2_i64), Some(2_i64)),
+ closed_open(Some(1_i64), Some(2_i64)),
+ closed_closed(Some(false), Some(false)),
+ ),
+ (
+ closed_closed(Some(1_i64), Some(1_i64)),
+ closed_open(Some(1_i64), Some(2_i64)),
+ closed_closed(Some(true), Some(true)),
+ ),
+ (
+ closed_closed(Some(1_i64), Some(1_i64)),
+ open_open(Some(1_i64), Some(2_i64)),
+ closed_closed(Some(true), Some(true)),
+ ),
+ ];
+ for case in cases {
+ assert_eq!(case.0.lt_eq(case.1), case.2)
+ }
+ Ok(())
+ }
+
+ #[test]
+ fn gt_eq_test_various_bounds() -> Result<()> {
+ let cases = vec![
+ (
+ closed_closed(Some(100_i64), Some(200_i64)),
+ open_closed(None, Some(100_i64)),
+ closed_closed(Some(true), Some(true)),
+ ),
+ (
+ closed_closed(Some(100_i64), Some(200_i64)),
+ open_open(None, Some(100_i64)),
+ closed_closed(Some(true), Some(true)),
+ ),
+ (
+ closed_closed(Some(2_i64), Some(2_i64)),
+ closed_closed(Some(1_i64), Some(2_i64)),
+ closed_closed(Some(true), Some(true)),
+ ),
+ (
+ closed_closed(Some(2_i64), Some(2_i64)),
+ closed_open(Some(1_i64), Some(2_i64)),
+ closed_closed(Some(true), Some(true)),
+ ),
+ (
+ closed_closed(Some(1_i64), Some(1_i64)),
+ closed_open(Some(1_i64), Some(2_i64)),
+ closed_closed(Some(false), Some(true)),
+ ),
+ (
+ closed_closed(Some(1_i64), Some(1_i64)),
+ open_open(Some(1_i64), Some(2_i64)),
+ closed_closed(Some(false), Some(false)),
+ ),
+ ];
+ for case in cases {
+ assert_eq!(case.0.gt_eq(case.1), case.2)
+ }
+ Ok(())
+ }
+
+ #[test]
+ fn intersect_test_various_bounds() -> Result<()> {
+ let cases = vec![
+ (
+ closed_closed(Some(100_i64), Some(200_i64)),
+ open_closed(None, Some(100_i64)),
+ Some(closed_closed(Some(100_i64), Some(100_i64))),
+ ),
+ (
+ closed_closed(Some(100_i64), Some(200_i64)),
+ open_open(None, Some(100_i64)),
+ None,
+ ),
+ (
+ open_open(Some(100_i64), Some(200_i64)),
+ closed_closed(Some(0_i64), Some(100_i64)),
+ None,
+ ),
+ (
+ closed_closed(Some(2_i64), Some(2_i64)),
+ closed_closed(Some(1_i64), Some(2_i64)),
+ Some(closed_closed(Some(2_i64), Some(2_i64))),
+ ),
+ (
+ closed_closed(Some(2_i64), Some(2_i64)),
+ closed_open(Some(1_i64), Some(2_i64)),
+ None,
+ ),
+ (
+ closed_closed(Some(1_i64), Some(1_i64)),
+ open_open(Some(1_i64), Some(2_i64)),
+ None,
+ ),
+ (
+ closed_closed(Some(1_i64), Some(3_i64)),
+ open_open(Some(1_i64), Some(2_i64)),
+ Some(open_open(Some(1_i64), Some(2_i64))),
+ ),
+ ];
+ for case in cases {
+ assert_eq!(case.0.intersect(case.1)?, case.2)
+ }
+ Ok(())
+ }
+
+ // This function tests if valid constructions produce standardized objects
+ // ([false, false], [false, true], [true, true]) for boolean intervals.
+ #[test]
+ fn non_standard_interval_constructs() -> Result<()> {
+ let cases = vec![
+ (
+ IntervalBound::new(Boolean(None), true),
+ IntervalBound::new(Boolean(Some(true)), false),
+ closed_closed(Some(false), Some(true)),
+ ),
+ (
+ IntervalBound::new(Boolean(None), true),
+ IntervalBound::new(Boolean(Some(true)), true),
+ closed_closed(Some(false), Some(false)),
+ ),
+ (
+ IntervalBound::new(Boolean(Some(false)), false),
+ IntervalBound::new(Boolean(None), true),
+ closed_closed(Some(false), Some(true)),
+ ),
+ (
+ IntervalBound::new(Boolean(Some(true)), false),
+ IntervalBound::new(Boolean(None), true),
+ closed_closed(Some(true), Some(true)),
+ ),
+ (
+ IntervalBound::new(Boolean(None), true),
+ IntervalBound::new(Boolean(None), true),
+ closed_closed(Some(false), Some(true)),
+ ),
+ (
+ IntervalBound::new(Boolean(Some(false)), true),
+ IntervalBound::new(Boolean(None), true),
+ closed_closed(Some(true), Some(true)),
+ ),
+ ];
+
+ for case in cases {
+ assert_eq!(Interval::new(case.0, case.1), case.2)
}
Ok(())
}
diff --git a/datafusion/physical-expr/src/intervals/test_utils.rs b/datafusion/physical-expr/src/intervals/test_utils.rs
index 3070cb0a8f..f233b246a7 100644
--- a/datafusion/physical-expr/src/intervals/test_utils.rs
+++ b/datafusion/physical-expr/src/intervals/test_utils.rs
@@ -28,7 +28,7 @@ use datafusion_expr::Operator;
#[allow(clippy::too_many_arguments)]
/// This test function generates a conjunctive statement with two numeric
/// terms with the following form:
-/// left_col (op_1) a > right_col (op_2) b AND left_col (op_3) c < right_col (op_4) d
+/// left_col (op_1) a >/>= right_col (op_2) b AND left_col (op_3) c </<= right_col (op_4) d
pub fn gen_conjunctive_numeric_expr(
left_col: Arc<dyn PhysicalExpr>,
right_col: Arc<dyn PhysicalExpr>,
@@ -40,6 +40,7 @@ pub fn gen_conjunctive_numeric_expr(
b: i32,
c: i32,
d: i32,
+ bounds: (Operator, Operator),
) -> Arc<dyn PhysicalExpr> {
let left_and_1 = Arc::new(BinaryExpr::new(
left_col.clone(),
@@ -62,8 +63,10 @@ pub fn gen_conjunctive_numeric_expr(
op_4,
Arc::new(Literal::new(ScalarValue::Int32(Some(d)))),
));
- let left_expr = Arc::new(BinaryExpr::new(left_and_1, Operator::Gt, left_and_2));
- let right_expr = Arc::new(BinaryExpr::new(right_and_1, Operator::Lt, right_and_2));
+ let (greater_op, less_op) = bounds;
+
+ let left_expr = Arc::new(BinaryExpr::new(left_and_1, greater_op, left_and_2));
+ let right_expr = Arc::new(BinaryExpr::new(right_and_1, less_op, right_and_2));
Arc::new(BinaryExpr::new(left_expr, Operator::And, right_expr))
}