Skip to main content

vortex_functions/between/
widen.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4use vortex_array::ArrayRef;
5use vortex_array::ArrayView;
6use vortex_array::arrays::Constant;
7use vortex_array::arrays::Widen;
8use vortex_array::arrays::widen::WidenArraySlotsExt;
9use vortex_array::arrays::widen::compute::constant_fits_values;
10use vortex_array::arrays::widen::compute::constant_in_values_dtype;
11use vortex_error::VortexResult;
12
13use crate::between::BetweenOptions;
14use crate::between::BetweenReduce;
15use crate::between::as_two_compares;
16use crate::builtins::ArrayFunctions;
17
18impl BetweenReduce for Widen {
19    fn between(
20        array: ArrayView<'_, Self>,
21        lower: &ArrayRef,
22        upper: &ArrayRef,
23        options: &BetweenOptions,
24    ) -> VortexResult<Option<ArrayRef>> {
25        let values = array.values();
26
27        if let (Some(lower), Some(upper)) = (lower.as_constant(), upper.as_constant())
28            && constant_fits_values(lower, values.dtype()) == Some(true)
29            && constant_fits_values(upper, values.dtype()) == Some(true)
30        {
31            let lower = constant_in_values_dtype(lower, values, array.len())?;
32            let upper = constant_in_values_dtype(upper, values, array.len())?;
33            return values
34                .clone()
35                .between(lower, upper, options.clone())
36                .map(Some);
37        }
38
39        // Each compare of a `Widen` with a constant or another `Widen` runs the compare kernel of
40        // `Widen`. Any other bound declines, so that `Between` decodes the `Widen` once.
41        let is_operand = |bound: &ArrayRef| bound.is::<Constant>() || bound.is::<Widen>();
42        if !is_operand(lower) || !is_operand(upper) {
43            return Ok(None);
44        }
45
46        as_two_compares(array.array(), lower, upper, options).map(Some)
47    }
48}
49
50#[cfg(test)]
51mod tests {
52    use std::sync::LazyLock;
53
54    use rstest::rstest;
55    use vortex_array::ArrayRef;
56    use vortex_array::Canonical;
57    use vortex_array::ExecutionCtx;
58    use vortex_array::IntoArray;
59    use vortex_array::VortexSessionExecute;
60    use vortex_array::arrays::ConstantArray;
61    use vortex_array::arrays::DecimalArray;
62    use vortex_array::arrays::PrimitiveArray;
63    use vortex_array::arrays::WidenArray;
64    use vortex_array::assert_arrays_eq;
65    use vortex_array::dtype::DType;
66    use vortex_array::dtype::DecimalDType;
67    use vortex_array::dtype::Nullability;
68    use vortex_array::dtype::PType;
69    use vortex_array::scalar::DecimalValue;
70    use vortex_array::scalar::Scalar;
71    use vortex_buffer::buffer;
72    use vortex_error::VortexExpect;
73    use vortex_error::VortexResult;
74    use vortex_session::VortexSession;
75
76    use crate::between::BetweenOptions;
77    use crate::between::StrictComparison;
78    use crate::builtins::ArrayFunctions;
79
80    static SESSION: LazyLock<VortexSession> = LazyLock::new(|| {
81        let session = VortexSession::empty();
82        vortex_array::initialize(&session);
83        crate::initialize(&session);
84        session
85    });
86
87    /// Returns `array` executed to its canonical form.
88    fn canonical(array: &ArrayRef, ctx: &mut ExecutionCtx) -> VortexResult<ArrayRef> {
89        Ok(array.clone().execute::<Canonical>(ctx)?.into_array())
90    }
91
92    /// Returns a `Widen` of the `logical` type over `values`, with the nullability of `values`.
93    fn widen(values: impl IntoArray, logical: PType) -> WidenArray {
94        let values = values.into_array();
95        let dtype = DType::Primitive(logical, values.dtype().nullability());
96        WidenArray::try_new(values, dtype).vortex_expect("fixture values are narrower integers")
97    }
98
99    /// Returns a `Widen` of the `parent` decimal dtype over `values`, with their nullability.
100    fn widen_decimal(values: impl IntoArray, parent: DecimalDType) -> VortexResult<WidenArray> {
101        let values = values.into_array();
102        let dtype = DType::Decimal(parent, values.dtype().nullability());
103        WidenArray::try_new(values, dtype)
104    }
105
106    /// Returns partially valid decimal values at both ends of the child precision.
107    fn partially_valid_decimal(parent: DecimalDType) -> VortexResult<WidenArray> {
108        widen_decimal(
109            DecimalArray::from_option_iter(
110                [Some(-99_999i32), None, Some(0), Some(99_999)],
111                DecimalDType::new(5, 2),
112            ),
113            parent,
114        )
115    }
116
117    /// Returns `value` as a scalar of the `parent` dtype, or a null scalar.
118    fn decimal_scalar(
119        value: Option<i64>,
120        parent: DecimalDType,
121        nullability: Nullability,
122    ) -> Scalar {
123        match value {
124            Some(value) => Scalar::decimal(DecimalValue::I64(value), parent, nullability),
125            None => Scalar::null(DType::Decimal(parent, Nullability::Nullable)),
126        }
127    }
128
129    /// Constant bounds inside the range of the values run on the values, and the other bounds run as
130    /// two compares. The strict lower and non-strict upper bounds check an exclusive and an inclusive
131    /// edge.
132    #[rstest]
133    fn test_between_constant_bounds(
134        #[values(-129i64, -128, 0, 128)] lower: i64,
135        #[values(-128i64, 0, 127, 128)] upper: i64,
136    ) -> VortexResult<()> {
137        let mut ctx = SESSION.create_execution_ctx();
138        let values = PrimitiveArray::from_option_iter([Some(-128i8), None, Some(0), Some(127)]);
139        let array = widen(values, PType::I64).into_array();
140        let lower = ConstantArray::new(lower, array.len()).into_array();
141        let upper = ConstantArray::new(upper, array.len()).into_array();
142        let options = BetweenOptions {
143            lower_strict: StrictComparison::Strict,
144            upper_strict: StrictComparison::NonStrict,
145        };
146
147        let between = array
148            .clone()
149            .between(lower.clone(), upper.clone(), options.clone())?;
150
151        let expected = canonical(&array, &mut ctx)?.between(lower, upper, options)?;
152        assert_arrays_eq!(between, expected, &mut ctx);
153
154        Ok(())
155    }
156
157    /// Nullable bounds, in range or null, give a nullable result over non-nullable values.
158    #[rstest]
159    #[case::in_range(
160        Scalar::primitive(-1i64, Nullability::Nullable),
161        Scalar::primitive(0i64, Nullability::Nullable),
162    )]
163    #[case::null(
164        Scalar::null(DType::Primitive(PType::I64, Nullability::Nullable)),
165        Scalar::primitive(0i64, Nullability::Nullable)
166    )]
167    fn test_between_nullable_bounds(
168        #[case] lower: Scalar,
169        #[case] upper: Scalar,
170    ) -> VortexResult<()> {
171        let mut ctx = SESSION.create_execution_ctx();
172        let array = widen(buffer![-128i8, 0, 127], PType::I64).into_array();
173        let lower = ConstantArray::new(lower, array.len()).into_array();
174        let upper = ConstantArray::new(upper, array.len()).into_array();
175        let options = BetweenOptions {
176            lower_strict: StrictComparison::NonStrict,
177            upper_strict: StrictComparison::NonStrict,
178        };
179
180        let between = array
181            .clone()
182            .between(lower.clone(), upper.clone(), options.clone())?;
183
184        let expected = canonical(&array, &mut ctx)?.between(lower, upper, options)?;
185        assert_arrays_eq!(between, expected, &mut ctx);
186
187        Ok(())
188    }
189
190    /// A `Widen` bound runs as two compares, and any other array bound declines.
191    #[rstest]
192    #[case::widen(
193        widen(PrimitiveArray::from_option_iter([Some(-129i16), None, Some(128)]), PType::I64)
194            .into_array()
195    )]
196    #[case::primitive(PrimitiveArray::from_option_iter([Some(-129i64), None, Some(128)]).into_array())]
197    fn test_between_array_bound(#[case] lower: ArrayRef) -> VortexResult<()> {
198        let mut ctx = SESSION.create_execution_ctx();
199        let array = widen(buffer![-128i8, 0, 127], PType::I64).into_array();
200        let upper = ConstantArray::new(0i64, array.len()).into_array();
201        let options = BetweenOptions {
202            lower_strict: StrictComparison::NonStrict,
203            upper_strict: StrictComparison::NonStrict,
204        };
205
206        let between = array
207            .clone()
208            .between(lower.clone(), upper.clone(), options.clone())?;
209
210        let expected =
211            canonical(&array, &mut ctx)?.between(canonical(&lower, &mut ctx)?, upper, options)?;
212        assert_arrays_eq!(between, expected, &mut ctx);
213
214        Ok(())
215    }
216
217    #[rstest]
218    #[case::inside(Some(-99_999), Some(99_999))]
219    #[case::outside(Some(-100_000), Some(100_000))]
220    #[case::below(Some(-100_001), Some(-100_000))]
221    #[case::above(Some(100_000), Some(100_001))]
222    #[case::reversed(Some(99_999), Some(-99_999))]
223    #[case::null_lower(None, Some(99_999))]
224    #[case::null_upper(Some(-99_999), None)]
225    fn test_decimal_between(
226        #[case] lower: Option<i64>,
227        #[case] upper: Option<i64>,
228    ) -> VortexResult<()> {
229        let mut ctx = SESSION.create_execution_ctx();
230        let parent = DecimalDType::new(18, 2);
231        let array = partially_valid_decimal(parent)?.into_array();
232        let lower = ConstantArray::new(
233            decimal_scalar(lower, parent, Nullability::Nullable),
234            array.len(),
235        )
236        .into_array();
237        let upper = ConstantArray::new(
238            decimal_scalar(upper, parent, Nullability::Nullable),
239            array.len(),
240        )
241        .into_array();
242        let options = BetweenOptions {
243            lower_strict: StrictComparison::Strict,
244            upper_strict: StrictComparison::NonStrict,
245        };
246
247        let result = array
248            .clone()
249            .between(lower.clone(), upper.clone(), options.clone())?;
250        let expected = canonical(&array, &mut ctx)?.between(lower, upper, options)?;
251        assert_arrays_eq!(result, expected, &mut ctx);
252
253        Ok(())
254    }
255}