Skip to main content

vortex_array/scalar_fn/fns/binary/
compare.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4use std::cmp::Ordering;
5
6use arrow_array::BooleanArray;
7use arrow_buffer::NullBuffer;
8use arrow_ord::cmp;
9use arrow_ord::ord::make_comparator;
10use arrow_schema::SortOptions;
11use vortex_error::VortexResult;
12use vortex_error::vortex_err;
13
14use crate::ArrayRef;
15use crate::Canonical;
16use crate::ExecutionCtx;
17use crate::IntoArray;
18use crate::array::ArrayView;
19use crate::array::VTable;
20use crate::arrays::Constant;
21use crate::arrays::ConstantArray;
22use crate::arrays::ScalarFn;
23use crate::arrays::scalar_fn::ExactScalarFn;
24use crate::arrays::scalar_fn::ScalarFnArrayExt;
25use crate::arrays::scalar_fn::ScalarFnArrayView;
26use crate::arrow::ArrowSessionExt;
27use crate::arrow::Datum;
28use crate::arrow::from_arrow_array_with_len;
29use crate::dtype::DType;
30use crate::dtype::Nullability;
31use crate::kernel::ExecuteParentKernel;
32use crate::scalar::Scalar;
33use crate::scalar_fn::fns::binary::Binary;
34use crate::scalar_fn::fns::operators::CompareOperator;
35
36/// Trait for encoding-specific comparison kernels that operate in encoded space.
37///
38/// Implementations can compare an encoded array against another array (typically a constant)
39/// without first decompressing. The adaptor normalizes operand order so `array` is always
40/// the left-hand side, swapping the operator when necessary.
41pub trait CompareKernel: VTable {
42    fn compare(
43        lhs: ArrayView<'_, Self>,
44        rhs: &ArrayRef,
45        operator: CompareOperator,
46        ctx: &mut ExecutionCtx,
47    ) -> VortexResult<Option<ArrayRef>>;
48}
49
50/// Adaptor that bridges [`CompareKernel`] implementations to [`ExecuteParentKernel`].
51///
52/// When a `ScalarFnArray(Binary, cmp_op)` wraps a child that implements `CompareKernel`,
53/// this adaptor extracts the comparison operator and other operand, normalizes operand order
54/// (swapping the operator if the encoded array is on the RHS), and delegates to the kernel.
55#[derive(Default, Debug)]
56pub struct CompareExecuteAdaptor<V>(pub V);
57
58impl<V> ExecuteParentKernel<V> for CompareExecuteAdaptor<V>
59where
60    V: CompareKernel,
61{
62    type Parent = ExactScalarFn<Binary>;
63
64    fn execute_parent(
65        &self,
66        array: ArrayView<'_, V>,
67        parent: ScalarFnArrayView<'_, Binary>,
68        child_idx: usize,
69        ctx: &mut ExecutionCtx,
70    ) -> VortexResult<Option<ArrayRef>> {
71        // Only handle comparison operators
72        let Ok(cmp_op) = CompareOperator::try_from(*parent.options) else {
73            return Ok(None);
74        };
75
76        // Get the ScalarFnArray to access children
77        let Some(scalar_fn_array) = parent.as_opt::<ScalarFn>() else {
78            return Ok(None);
79        };
80        // Normalize so `array` is always LHS, swapping the operator if needed
81        // TODO(joe): should be go this here or in the Rule/Kernel
82        let (cmp_op, other) = match child_idx {
83            0 => (cmp_op, scalar_fn_array.get_child(1)),
84            1 => (cmp_op.swap(), scalar_fn_array.get_child(0)),
85            _ => return Ok(None),
86        };
87
88        let len = array.len();
89        let nullable = array.dtype().is_nullable() || other.dtype().is_nullable();
90
91        // Empty array → empty bool result
92        if len == 0 {
93            return Ok(Some(
94                Canonical::empty(&DType::Bool(nullable.into())).into_array(),
95            ));
96        }
97
98        // Null constant on either side → all-null bool result
99        if other.as_constant().is_some_and(|s| s.is_null()) {
100            return Ok(Some(
101                ConstantArray::new(Scalar::null(DType::Bool(nullable.into())), len).into_array(),
102            ));
103        }
104
105        V::compare(array, other, cmp_op, ctx)
106    }
107}
108
109/// Execute a compare operation between two arrays.
110///
111/// This is the entry point for compare operations from the binary expression.
112/// Handles empty, constant-null, and constant-constant directly, otherwise falls back to Arrow.
113pub(crate) fn execute_compare(
114    lhs: &ArrayRef,
115    rhs: &ArrayRef,
116    op: CompareOperator,
117    ctx: &mut ExecutionCtx,
118) -> VortexResult<ArrayRef> {
119    let nullable = lhs.dtype().is_nullable() || rhs.dtype().is_nullable();
120
121    if lhs.is_empty() {
122        return Ok(Canonical::empty(&DType::Bool(nullable.into())).into_array());
123    }
124
125    let left_constant_null = lhs.as_constant().map(|l| l.is_null()).unwrap_or(false);
126    let right_constant_null = rhs.as_constant().map(|r| r.is_null()).unwrap_or(false);
127    if left_constant_null || right_constant_null {
128        return Ok(
129            ConstantArray::new(Scalar::null(DType::Bool(nullable.into())), lhs.len()).into_array(),
130        );
131    }
132
133    // Constant-constant fast path
134    if let (Some(lhs_const), Some(rhs_const)) = (lhs.as_opt::<Constant>(), rhs.as_opt::<Constant>())
135    {
136        let result = scalar_cmp(lhs_const.scalar(), rhs_const.scalar(), op)?;
137        return Ok(ConstantArray::new(result, lhs.len()).into_array());
138    }
139
140    arrow_compare_arrays(lhs, rhs, op, ctx)
141}
142
143/// Fall back to Arrow for comparison.
144fn arrow_compare_arrays(
145    left: &ArrayRef,
146    right: &ArrayRef,
147    operator: CompareOperator,
148    ctx: &mut ExecutionCtx,
149) -> VortexResult<ArrayRef> {
150    assert_eq!(left.len(), right.len());
151
152    let nullable = left.dtype().is_nullable() || right.dtype().is_nullable();
153
154    // Arrow's vectorized comparison kernels don't support nested types.
155    // For nested types, fall back to `make_comparator` which does element-wise comparison.
156    let arrow_array: BooleanArray = if left.dtype().is_nested() || right.dtype().is_nested() {
157        let session = ctx.session().clone();
158        let rhs = session.arrow().execute_arrow(right.clone(), None, ctx)?;
159        let lhs = session.arrow().execute_arrow(left.clone(), None, ctx)?;
160
161        assert!(
162            lhs.data_type().equals_datatype(rhs.data_type()),
163            "lhs data_type: {}, rhs data_type: {}",
164            lhs.data_type(),
165            rhs.data_type()
166        );
167
168        compare_nested_arrow_arrays(lhs.as_ref(), rhs.as_ref(), operator)?
169    } else {
170        // Fast path: use vectorized kernels for primitive types.
171        let lhs = Datum::try_new(left, ctx)?;
172        let rhs = Datum::try_new_with_target_datatype(right, lhs.data_type(), ctx)?;
173
174        match operator {
175            CompareOperator::Eq => cmp::eq(&lhs, &rhs)?,
176            CompareOperator::NotEq => cmp::neq(&lhs, &rhs)?,
177            CompareOperator::Gt => cmp::gt(&lhs, &rhs)?,
178            CompareOperator::Gte => cmp::gt_eq(&lhs, &rhs)?,
179            CompareOperator::Lt => cmp::lt(&lhs, &rhs)?,
180            CompareOperator::Lte => cmp::lt_eq(&lhs, &rhs)?,
181        }
182    };
183
184    from_arrow_array_with_len(&arrow_array, left.len(), nullable)
185}
186
187pub fn scalar_cmp(lhs: &Scalar, rhs: &Scalar, operator: CompareOperator) -> VortexResult<Scalar> {
188    if lhs.is_null() | rhs.is_null() {
189        return Ok(Scalar::null(DType::Bool(Nullability::Nullable)));
190    }
191
192    let nullability = lhs.dtype().nullability() | rhs.dtype().nullability();
193
194    // We use `partial_cmp` to ensure we do not lose a type mismatch error.
195    let ordering = lhs.partial_cmp(rhs).ok_or_else(|| {
196        vortex_err!(
197            "Cannot compare scalars with incompatible types: {} and {}",
198            lhs.dtype(),
199            rhs.dtype()
200        )
201    })?;
202
203    let b = match operator {
204        CompareOperator::Eq => ordering.is_eq(),
205        CompareOperator::NotEq => ordering.is_ne(),
206        CompareOperator::Gt => ordering.is_gt(),
207        CompareOperator::Gte => ordering.is_ge(),
208        CompareOperator::Lt => ordering.is_lt(),
209        CompareOperator::Lte => ordering.is_le(),
210    };
211
212    Ok(Scalar::bool(b, nullability))
213}
214
215/// Compare two Arrow arrays element-wise using [`make_comparator`].
216///
217/// This function is required for nested types (Struct, List, FixedSizeList) because Arrow's
218/// vectorized comparison kernels ([`cmp::eq`], [`cmp::neq`], etc.) do not support them.
219///
220/// The vectorized kernels are faster but only work on primitive types, so for non-nested types,
221/// prefer using the vectorized kernels directly for better performance.
222pub fn compare_nested_arrow_arrays(
223    lhs: &dyn arrow_array::Array,
224    rhs: &dyn arrow_array::Array,
225    operator: CompareOperator,
226) -> VortexResult<BooleanArray> {
227    let compare_arrays_at = make_comparator(lhs, rhs, SortOptions::default())?;
228
229    let cmp_fn = match operator {
230        CompareOperator::Eq => Ordering::is_eq,
231        CompareOperator::NotEq => Ordering::is_ne,
232        CompareOperator::Gt => Ordering::is_gt,
233        CompareOperator::Gte => Ordering::is_ge,
234        CompareOperator::Lt => Ordering::is_lt,
235        CompareOperator::Lte => Ordering::is_le,
236    };
237
238    let values = (0..lhs.len())
239        .map(|i| cmp_fn(compare_arrays_at(i, i)))
240        .collect();
241    let nulls = NullBuffer::union(lhs.nulls(), rhs.nulls());
242
243    Ok(BooleanArray::new(values, nulls))
244}
245
246#[cfg(test)]
247mod tests {
248    use std::sync::Arc;
249
250    use rstest::rstest;
251    use vortex_buffer::buffer;
252
253    use crate::ArrayRef;
254    use crate::IntoArray;
255    use crate::LEGACY_SESSION;
256    #[expect(deprecated)]
257    use crate::ToCanonical as _;
258    use crate::VortexSessionExecute;
259    use crate::arrays::BoolArray;
260    use crate::arrays::ListArray;
261    use crate::arrays::ListViewArray;
262    use crate::arrays::PrimitiveArray;
263    use crate::arrays::StructArray;
264    use crate::arrays::VarBinArray;
265    use crate::arrays::VarBinViewArray;
266    use crate::assert_arrays_eq;
267    use crate::builtins::ArrayBuiltins;
268    use crate::dtype::DType;
269    use crate::dtype::FieldName;
270    use crate::dtype::FieldNames;
271    use crate::dtype::Nullability;
272    use crate::dtype::PType;
273    use crate::extension::datetime::TimeUnit;
274    use crate::extension::datetime::Timestamp;
275    use crate::extension::datetime::TimestampOptions;
276    use crate::scalar::Scalar;
277    use crate::scalar_fn::fns::binary::compare::ConstantArray;
278    use crate::scalar_fn::fns::binary::scalar_cmp;
279    use crate::scalar_fn::fns::operators::CompareOperator;
280    use crate::scalar_fn::fns::operators::Operator;
281    use crate::test_harness::to_int_indices;
282    use crate::validity::Validity;
283
284    #[test]
285    fn test_bool_basic_comparisons() {
286        use vortex_buffer::BitBuffer;
287
288        let arr = BoolArray::new(
289            BitBuffer::from_iter([true, true, false, true, false]),
290            Validity::from_iter([false, true, true, true, true]),
291        );
292
293        #[expect(deprecated)]
294        let matches = arr
295            .clone()
296            .into_array()
297            .binary(arr.clone().into_array(), Operator::Eq)
298            .unwrap()
299            .to_bool();
300        assert_eq!(to_int_indices(matches).unwrap(), [1u64, 2, 3, 4]);
301
302        #[expect(deprecated)]
303        let matches = arr
304            .clone()
305            .into_array()
306            .binary(arr.clone().into_array(), Operator::NotEq)
307            .unwrap()
308            .to_bool();
309        let empty: [u64; 0] = [];
310        assert_eq!(to_int_indices(matches).unwrap(), empty);
311
312        let other = BoolArray::new(
313            BitBuffer::from_iter([false, false, false, true, true]),
314            Validity::from_iter([false, true, true, true, true]),
315        );
316
317        #[expect(deprecated)]
318        let matches = arr
319            .clone()
320            .into_array()
321            .binary(other.clone().into_array(), Operator::Lte)
322            .unwrap()
323            .to_bool();
324        assert_eq!(to_int_indices(matches).unwrap(), [2u64, 3, 4]);
325
326        #[expect(deprecated)]
327        let matches = arr
328            .clone()
329            .into_array()
330            .binary(other.clone().into_array(), Operator::Lt)
331            .unwrap()
332            .to_bool();
333        assert_eq!(to_int_indices(matches).unwrap(), [4u64]);
334
335        #[expect(deprecated)]
336        let matches = other
337            .clone()
338            .into_array()
339            .binary(arr.clone().into_array(), Operator::Gte)
340            .unwrap()
341            .to_bool();
342        assert_eq!(to_int_indices(matches).unwrap(), [2u64, 3, 4]);
343
344        #[expect(deprecated)]
345        let matches = other
346            .into_array()
347            .binary(arr.into_array(), Operator::Gt)
348            .unwrap()
349            .to_bool();
350        assert_eq!(to_int_indices(matches).unwrap(), [4u64]);
351    }
352
353    #[test]
354    fn constant_compare() {
355        let left = ConstantArray::new(Scalar::from(2u32), 10);
356        let right = ConstantArray::new(Scalar::from(10u32), 10);
357
358        let result = left
359            .into_array()
360            .binary(right.into_array(), Operator::Gt)
361            .unwrap();
362        assert_eq!(result.len(), 10);
363        let scalar = result
364            .execute_scalar(0, &mut LEGACY_SESSION.create_execution_ctx())
365            .unwrap();
366        assert_eq!(scalar.as_bool().value(), Some(false));
367    }
368
369    #[rstest]
370    #[case(VarBinArray::from(vec!["a", "b"]).into_array(), VarBinViewArray::from_iter_str(["a", "b"]).into_array())]
371    #[case(VarBinViewArray::from_iter_str(["a", "b"]).into_array(), VarBinArray::from(vec!["a", "b"]).into_array())]
372    #[case(VarBinArray::from(vec!["a".as_bytes(), "b".as_bytes()]).into_array(), VarBinViewArray::from_iter_bin(["a".as_bytes(), "b".as_bytes()]).into_array())]
373    #[case(VarBinViewArray::from_iter_bin(["a".as_bytes(), "b".as_bytes()]).into_array(), VarBinArray::from(vec!["a".as_bytes(), "b".as_bytes()]).into_array())]
374    fn arrow_compare_different_encodings(#[case] left: ArrayRef, #[case] right: ArrayRef) {
375        let res = left.binary(right, Operator::Eq).unwrap();
376        let expected = BoolArray::from_iter([true, true]);
377        assert_arrays_eq!(res, expected);
378    }
379
380    #[test]
381    fn test_list_array_comparison() {
382        let values1 = PrimitiveArray::from_iter([1i32, 2, 3, 4, 5, 6]);
383        let offsets1 = PrimitiveArray::from_iter([0i32, 2, 4, 6]);
384        let list1 = ListArray::try_new(
385            values1.into_array(),
386            offsets1.into_array(),
387            Validity::NonNullable,
388        )
389        .unwrap();
390
391        let values2 = PrimitiveArray::from_iter([1i32, 2, 3, 4, 7, 8]);
392        let offsets2 = PrimitiveArray::from_iter([0i32, 2, 4, 6]);
393        let list2 = ListArray::try_new(
394            values2.into_array(),
395            offsets2.into_array(),
396            Validity::NonNullable,
397        )
398        .unwrap();
399
400        let result = list1
401            .clone()
402            .into_array()
403            .binary(list2.clone().into_array(), Operator::Eq)
404            .unwrap();
405        let expected = BoolArray::from_iter([true, true, false]);
406        assert_arrays_eq!(result, expected);
407
408        let result = list1
409            .clone()
410            .into_array()
411            .binary(list2.clone().into_array(), Operator::NotEq)
412            .unwrap();
413        let expected = BoolArray::from_iter([false, false, true]);
414        assert_arrays_eq!(result, expected);
415
416        let result = list1
417            .into_array()
418            .binary(list2.into_array(), Operator::Lt)
419            .unwrap();
420        let expected = BoolArray::from_iter([false, false, true]);
421        assert_arrays_eq!(result, expected);
422    }
423
424    #[test]
425    fn test_list_array_constant_comparison() {
426        let values = PrimitiveArray::from_iter([1i32, 2, 3, 4, 5, 6]);
427        let offsets = PrimitiveArray::from_iter([0i32, 2, 4, 6]);
428        let list = ListArray::try_new(
429            values.into_array(),
430            offsets.into_array(),
431            Validity::NonNullable,
432        )
433        .unwrap();
434
435        let list_scalar = Scalar::list(
436            Arc::new(DType::Primitive(PType::I32, Nullability::NonNullable)),
437            vec![3i32.into(), 4i32.into()],
438            Nullability::NonNullable,
439        );
440        let constant = ConstantArray::new(list_scalar, 3);
441
442        let result = list
443            .into_array()
444            .binary(constant.into_array(), Operator::Eq)
445            .unwrap();
446        let expected = BoolArray::from_iter([false, true, false]);
447        assert_arrays_eq!(result, expected);
448    }
449
450    #[test]
451    fn test_struct_array_comparison() {
452        let bool_field1 = BoolArray::from_iter([Some(true), Some(false), Some(true)]);
453        let int_field1 = PrimitiveArray::from_iter([1i32, 2, 3]);
454
455        let bool_field2 = BoolArray::from_iter([Some(true), Some(false), Some(false)]);
456        let int_field2 = PrimitiveArray::from_iter([1i32, 2, 4]);
457
458        let struct1 = StructArray::from_fields(&[
459            ("bool_col", bool_field1.into_array()),
460            ("int_col", int_field1.into_array()),
461        ])
462        .unwrap();
463
464        let struct2 = StructArray::from_fields(&[
465            ("bool_col", bool_field2.into_array()),
466            ("int_col", int_field2.into_array()),
467        ])
468        .unwrap();
469
470        let result = struct1
471            .clone()
472            .into_array()
473            .binary(struct2.clone().into_array(), Operator::Eq)
474            .unwrap();
475        let expected = BoolArray::from_iter([true, true, false]);
476        assert_arrays_eq!(result, expected);
477
478        let result = struct1
479            .into_array()
480            .binary(struct2.into_array(), Operator::Gt)
481            .unwrap();
482        let expected = BoolArray::from_iter([false, false, true]);
483        assert_arrays_eq!(result, expected);
484    }
485
486    #[test]
487    fn test_empty_struct_compare() {
488        let empty1 = StructArray::try_new(
489            FieldNames::from(Vec::<FieldName>::new()),
490            Vec::new(),
491            5,
492            Validity::NonNullable,
493        )
494        .unwrap();
495
496        let empty2 = StructArray::try_new(
497            FieldNames::from(Vec::<FieldName>::new()),
498            Vec::new(),
499            5,
500            Validity::NonNullable,
501        )
502        .unwrap();
503
504        let result = empty1
505            .into_array()
506            .binary(empty2.into_array(), Operator::Eq)
507            .unwrap();
508        let expected = BoolArray::from_iter([true, true, true, true, true]);
509        assert_arrays_eq!(result, expected);
510    }
511
512    /// Regression test: `scalar_cmp` must error when comparing scalars with incompatible
513    /// extension types (e.g., timestamps with different time units) rather than silently
514    /// returning a wrong result.
515    #[test]
516    fn scalar_cmp_incompatible_extension_types_errors() {
517        let ms_scalar = Scalar::extension::<Timestamp>(
518            TimestampOptions {
519                unit: TimeUnit::Milliseconds,
520                tz: None,
521            },
522            Scalar::from(1704067200000i64),
523        );
524        let s_scalar = Scalar::extension::<Timestamp>(
525            TimestampOptions {
526                unit: TimeUnit::Seconds,
527                tz: None,
528            },
529            Scalar::from(1704067200i64),
530        );
531
532        // Ordering comparisons must error on incompatible types.
533        assert!(scalar_cmp(&ms_scalar, &s_scalar, CompareOperator::Gt).is_err());
534        assert!(scalar_cmp(&ms_scalar, &s_scalar, CompareOperator::Lt).is_err());
535        assert!(scalar_cmp(&ms_scalar, &s_scalar, CompareOperator::Gte).is_err());
536        assert!(scalar_cmp(&ms_scalar, &s_scalar, CompareOperator::Lte).is_err());
537        assert!(scalar_cmp(&ms_scalar, &s_scalar, CompareOperator::Eq).is_err());
538        assert!(scalar_cmp(&ms_scalar, &s_scalar, CompareOperator::NotEq).is_err());
539    }
540
541    #[test]
542    fn test_empty_list() {
543        let list = ListViewArray::new(
544            BoolArray::from_iter(Vec::<bool>::new()).into_array(),
545            buffer![0i32, 0i32, 0i32].into_array(),
546            buffer![0i32, 0i32, 0i32].into_array(),
547            Validity::AllValid,
548        );
549
550        let result = list
551            .clone()
552            .into_array()
553            .binary(list.into_array(), Operator::Eq)
554            .unwrap();
555        assert!(
556            result
557                .execute_scalar(0, &mut LEGACY_SESSION.create_execution_ctx())
558                .unwrap()
559                .is_valid()
560        );
561        assert!(
562            result
563                .execute_scalar(1, &mut LEGACY_SESSION.create_execution_ctx())
564                .unwrap()
565                .is_valid()
566        );
567        assert!(
568            result
569                .execute_scalar(2, &mut LEGACY_SESSION.create_execution_ctx())
570                .unwrap()
571                .is_valid()
572        );
573    }
574}