1mod constant;
5mod decimal;
6mod find;
7mod kernel;
8mod primitive;
9mod widen;
10
11use std::fmt::Display;
12use std::fmt::Formatter;
13
14pub use find::find_between;
15pub use kernel::*;
16use prost::Message;
17use vortex_array::AnyCanonical;
18use vortex_array::ArrayRef;
19use vortex_array::Canonical;
20use vortex_array::ExecutionCtx;
21use vortex_array::IntoArray;
22use vortex_array::arrays::Constant;
23use vortex_array::arrays::ConstantArray;
24use vortex_array::arrays::Decimal;
25use vortex_array::arrays::Primitive;
26use vortex_array::arrays::ScalarFnArray;
27use vortex_array::arrays::Widen;
28use vortex_array::builtins::ArrayBuiltins;
29use vortex_array::dtype::DType;
30use vortex_array::dtype::DType::Bool;
31use vortex_array::dtype::NativePType;
32use vortex_array::optimizer::kernels::ArrayKernelsExt;
33use vortex_array::proto::expr as pb;
34use vortex_array::require_input;
35use vortex_array::scalar::Scalar;
36use vortex_array::scalar_fn::Arity;
37use vortex_array::scalar_fn::ChildName;
38use vortex_array::scalar_fn::ExecutionArgs;
39use vortex_array::scalar_fn::ScalarFnExecutionResult;
40use vortex_array::scalar_fn::ScalarFnId;
41use vortex_array::scalar_fn::ScalarFnVTable;
42use vortex_array::scalar_fn::ScalarFnVTableExt;
43use vortex_array::scalar_fn::builtin::operators::BooleanOperator;
44use vortex_array::scalar_fn::builtin::operators::CompareOperator;
45use vortex_array::scalar_fn::display::ExprDisplay;
46use vortex_array::scalar_fn::session::ScalarFnSessionExt;
47use vortex_error::VortexResult;
48use vortex_error::vortex_bail;
49use vortex_session::VortexSession;
50use vortex_session::registry::CachedId;
51
52use crate::builtins::ArrayFunctions;
53
54pub(crate) fn initialize(session: &VortexSession) {
56 session.scalar_fns().register(Between);
57 let kernels = session.kernels();
58 kernels.register_execute_parent_kernel(
59 Between.id(),
60 Primitive,
61 BetweenExecuteAdaptor(Primitive),
62 );
63 kernels.register_execute_parent_kernel(Between.id(), Decimal, BetweenExecuteAdaptor(Decimal));
64 kernels.register_reduce_parent_rule(
65 Between,
66 Constant,
67 const { &BetweenReduceAdaptor(Constant) },
68 );
69 kernels.register_reduce_parent_rule(Between, Widen, const { &BetweenReduceAdaptor(Widen) });
70}
71
72#[derive(Debug, Clone, PartialEq, Eq, Hash)]
73pub struct BetweenOptions {
74 pub lower_strict: StrictComparison,
75 pub upper_strict: StrictComparison,
76}
77
78impl Display for BetweenOptions {
79 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
80 let lower_op = if self.lower_strict.is_strict() {
81 "<"
82 } else {
83 "<="
84 };
85 let upper_op = if self.upper_strict.is_strict() {
86 "<"
87 } else {
88 "<="
89 };
90 write!(f, "lower_strict: {}, upper_strict: {}", lower_op, upper_op)
91 }
92}
93
94#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
96pub enum StrictComparison {
97 Strict,
99 NonStrict,
101}
102
103impl StrictComparison {
104 pub const fn to_operator(&self) -> CompareOperator {
105 match self {
106 StrictComparison::Strict => CompareOperator::Lt,
107 StrictComparison::NonStrict => CompareOperator::Lte,
108 }
109 }
110
111 pub const fn is_strict(&self) -> bool {
112 matches!(self, StrictComparison::Strict)
113 }
114
115 pub fn to_predicate<T: NativePType>(self) -> fn(T, T) -> bool {
117 match self {
118 StrictComparison::Strict => T::is_lt,
119 StrictComparison::NonStrict => T::is_le,
120 }
121 }
122}
123
124pub(super) fn short_circuit(
135 arr: &ArrayRef,
136 lower: &ArrayRef,
137 upper: &ArrayRef,
138 options: &BetweenOptions,
139) -> VortexResult<Option<ArrayRef>> {
140 let return_dtype =
141 Bool(arr.dtype().nullability() | lower.dtype().nullability() | upper.dtype().nullability());
142
143 if arr.is_empty() {
145 return Ok(Some(Canonical::empty(&return_dtype).into_array()));
146 }
147
148 if arr.as_constant().is_some_and(|v| v.is_null()) {
151 return Ok(Some(
152 ConstantArray::new(Scalar::null(return_dtype), arr.len()).into_array(),
153 ));
154 }
155
156 let lower_is_null = lower.as_constant().is_some_and(|v| v.is_null());
157 let upper_is_null = upper.as_constant().is_some_and(|v| v.is_null());
158
159 if lower_is_null && upper_is_null {
162 return Ok(Some(
163 ConstantArray::new(Scalar::null(return_dtype), arr.len()).into_array(),
164 ));
165 }
166
167 if lower_is_null || upper_is_null {
170 return as_two_compares(arr, lower, upper, options).map(Some);
171 }
172
173 Ok(None)
174}
175
176pub(crate) fn as_two_compares(
180 arr: &ArrayRef,
181 lower: &ArrayRef,
182 upper: &ArrayRef,
183 options: &BetweenOptions,
184) -> VortexResult<ArrayRef> {
185 let lower_cmp = lower.compare(arr.clone(), options.lower_strict.to_operator())?;
186 let upper_cmp = arr.compare(upper.clone(), options.upper_strict.to_operator())?;
187 lower_cmp.boolean(upper_cmp, BooleanOperator::And)
188}
189
190fn between_canonical(
194 arr: &ArrayRef,
195 lower: &ArrayRef,
196 upper: &ArrayRef,
197 options: &BetweenOptions,
198 ctx: &mut ExecutionCtx,
199) -> VortexResult<ArrayRef> {
200 if let Some(result) = short_circuit(arr, lower, upper, options)? {
201 return result.execute::<ArrayRef>(ctx);
204 }
205
206 if let Some(prim) = arr.as_opt::<Primitive>()
208 && let Some(result) =
209 <Primitive as BetweenKernel>::between(prim, lower, upper, options, ctx)?
210 {
211 return Ok(result);
212 }
213 if let Some(dec) = arr.as_opt::<Decimal>()
214 && let Some(result) = <Decimal as BetweenKernel>::between(dec, lower, upper, options, ctx)?
215 {
216 return Ok(result);
217 }
218
219 as_two_compares(arr, lower, upper, options)?.execute::<ArrayRef>(ctx)
222}
223
224#[derive(Clone)]
236pub struct Between;
237
238impl Between {
239 pub fn try_new(
245 array: ArrayRef,
246 lower: ArrayRef,
247 upper: ArrayRef,
248 options: BetweenOptions,
249 ) -> VortexResult<ScalarFnArray> {
250 ScalarFnArray::try_new(Between.bind(options), [array, lower, upper])
251 }
252}
253
254impl ScalarFnVTable for Between {
255 type Options = BetweenOptions;
256
257 fn id(&self) -> ScalarFnId {
258 static ID: CachedId = CachedId::new("vortex.between");
259 *ID
260 }
261
262 fn serialize(&self, instance: &Self::Options) -> VortexResult<Option<Vec<u8>>> {
263 Ok(Some(
264 pb::BetweenOpts {
265 lower_strict: instance.lower_strict.is_strict(),
266 upper_strict: instance.upper_strict.is_strict(),
267 }
268 .encode_to_vec(),
269 ))
270 }
271
272 fn deserialize(
273 &self,
274 _metadata: &[u8],
275 _session: &VortexSession,
276 ) -> VortexResult<Self::Options> {
277 let opts = pb::BetweenOpts::decode(_metadata)?;
278 Ok(BetweenOptions {
279 lower_strict: if opts.lower_strict {
280 StrictComparison::Strict
281 } else {
282 StrictComparison::NonStrict
283 },
284 upper_strict: if opts.upper_strict {
285 StrictComparison::Strict
286 } else {
287 StrictComparison::NonStrict
288 },
289 })
290 }
291
292 fn arity(&self, _options: &Self::Options) -> Arity {
293 Arity::Exact(3)
294 }
295
296 fn child_name(&self, _instance: &Self::Options, child_idx: usize) -> ChildName {
297 match child_idx {
298 0 => ChildName::from("array"),
299 1 => ChildName::from("lower"),
300 2 => ChildName::from("upper"),
301 _ => unreachable!("Invalid child index {} for Between expression", child_idx),
302 }
303 }
304
305 fn fmt_sql(
306 &self,
307 options: &Self::Options,
308 expr: &dyn ExprDisplay,
309 f: &mut Formatter<'_>,
310 ) -> std::fmt::Result {
311 let lower_op = if options.lower_strict.is_strict() {
312 "<"
313 } else {
314 "<="
315 };
316 let upper_op = if options.upper_strict.is_strict() {
317 "<"
318 } else {
319 "<="
320 };
321 write!(
322 f,
323 "({} {} {} {} {})",
324 expr.display_child(1),
325 lower_op,
326 expr.display_child(0),
327 upper_op,
328 expr.display_child(2)
329 )
330 }
331
332 fn return_dtype(&self, _options: &Self::Options, arg_dtypes: &[DType]) -> VortexResult<DType> {
333 let arr_dt = &arg_dtypes[0];
334 let lower_dt = &arg_dtypes[1];
335 let upper_dt = &arg_dtypes[2];
336
337 if !arr_dt.eq_ignore_nullability(lower_dt) {
338 vortex_bail!(
339 "Array dtype {} does not match lower dtype {}",
340 arr_dt,
341 lower_dt
342 );
343 }
344 if !arr_dt.eq_ignore_nullability(upper_dt) {
345 vortex_bail!(
346 "Array dtype {} does not match upper dtype {}",
347 arr_dt,
348 upper_dt
349 );
350 }
351
352 Ok(Bool(
353 arr_dt.nullability() | lower_dt.nullability() | upper_dt.nullability(),
354 ))
355 }
356
357 fn execute(
358 &self,
359 options: &Self::Options,
360 args: &dyn ExecutionArgs,
361 ctx: &mut ExecutionCtx,
362 ) -> VortexResult<ArrayRef> {
363 let arr = args.get(0)?;
364 let lower = args.get(1)?;
365 let upper = args.get(2)?;
366
367 if !arr.is_canonical() {
369 return arr.execute::<Canonical>(ctx)?.into_array().between(
370 lower,
371 upper,
372 options.clone(),
373 );
374 }
375
376 between_canonical(&arr, &lower, &upper, options, ctx)
377 }
378
379 fn execute_step(
380 &self,
381 options: &Self::Options,
382 args: &dyn ExecutionArgs,
383 ctx: &mut ExecutionCtx,
384 ) -> VortexResult<ScalarFnExecutionResult> {
385 require_input!(args, 0 => AnyCanonical);
386 self.execute(options, args, ctx)
387 .map(ScalarFnExecutionResult::done)
388 }
389
390 fn is_strict(&self, _options: &Self::Options) -> bool {
391 false }
393
394 fn is_infallible(&self, _options: &Self::Options) -> bool {
395 true
396 }
397}
398
399#[cfg(test)]
400mod trace_tests;
401
402#[cfg(test)]
403mod tests {
404 use std::sync::LazyLock;
405
406 use rstest::rstest;
407 use vortex_array::IntoArray;
408 use vortex_array::VortexSessionExecute;
409 use vortex_array::arrays::BoolArray;
410 use vortex_array::arrays::DecimalArray;
411 use vortex_array::arrays::PrimitiveArray;
412 use vortex_array::arrays::StructArray;
413 use vortex_array::arrays::WidenArray;
414 use vortex_array::assert_arrays_eq;
415 use vortex_array::dtype::DType;
416 use vortex_array::dtype::DecimalDType;
417 use vortex_array::dtype::Nullability;
418 use vortex_array::dtype::PType;
419 use vortex_array::scalar::DecimalValue;
420 use vortex_array::scalar::Scalar;
421 use vortex_array::test_harness::to_int_indices;
422 use vortex_array::validity::Validity;
423 use vortex_buffer::buffer;
424 use vortex_expr::ArrayExprExt;
425 use vortex_expr::Expression;
426 use vortex_expr::col;
427 use vortex_expr::get_item;
428 use vortex_expr::lit;
429 use vortex_expr::proto::ExprSerializeProtoExt;
430 use vortex_expr::root;
431
432 use super::*;
433 use crate::expr::between;
434
435 static SESSION: LazyLock<VortexSession> = LazyLock::new(|| {
436 let session = VortexSession::empty();
437
438 vortex_array::initialize(&session);
439
440 crate::initialize(&session);
441
442 session
443 });
444
445 const NON_STRICT: BetweenOptions = BetweenOptions {
446 lower_strict: StrictComparison::NonStrict,
447 upper_strict: StrictComparison::NonStrict,
448 };
449
450 fn null_i32s(len: usize) -> ArrayRef {
452 let null = Scalar::null(DType::Primitive(PType::I32, Nullability::Nullable));
453 ConstantArray::new(null, len).into_array()
454 }
455
456 #[test]
457 fn lazy_validity() -> VortexResult<()> {
458 let ctx = &mut SESSION.create_execution_ctx();
459
460 let x = PrimitiveArray::from_option_iter([Some(10), Some(10), Some(1)]).into_array();
461 let lo = PrimitiveArray::from_option_iter([None, None, Some(0)]).into_array();
462 let hi = PrimitiveArray::from_option_iter([Some(5), Some(50), Some(5)]).into_array();
463
464 let data = StructArray::from_fields(&[("x", x), ("lo", lo), ("hi", hi)])?.into_array();
465 let lazy = data.apply(&between(col("x"), col("lo"), col("hi"), NON_STRICT))?;
466
467 let Validity::Array(validity) = lazy.validity()? else {
468 vortex_bail!("non-lazy validity");
469 };
470 assert_eq!(
471 validity.encoding_id().to_string(),
472 "vortex.scalar_fn_validity"
473 );
474 assert_arrays_eq!(validity, BoolArray::from_iter([true, false, true]), ctx);
475 Ok(())
476 }
477
478 #[test]
483 fn validity_agrees_with_execution() -> VortexResult<()> {
484 let ctx = &mut SESSION.create_execution_ctx();
485
486 let x = PrimitiveArray::from_option_iter([Some(10), Some(10), Some(1)]).into_array();
491 let lo = PrimitiveArray::from_option_iter([None, None, Some(0)]).into_array();
492 let hi = PrimitiveArray::from_option_iter([Some(5), Some(50), Some(5)]).into_array();
493 let data = StructArray::from_fields(&[("x", x), ("lo", lo), ("hi", hi)])?.into_array();
494
495 let expr = between(col("x"), col("lo"), col("hi"), NON_STRICT);
496
497 let executed = data
498 .clone()
499 .apply(&expr)?
500 .execute::<BoolArray>(ctx)?
501 .opt_bool_vec(ctx);
502
503 let validity_expr = expr.bind(data.dtype())?.validity()?;
504 let declared = data
505 .apply_bound(&validity_expr)?
506 .execute::<BoolArray>(ctx)?
507 .bool_vec(ctx);
508
509 assert_eq!(executed, [Some(false), None, Some(true)]);
510 assert_eq!(
511 executed.iter().map(Option::is_some).collect::<Vec<_>>(),
512 declared
513 );
514
515 Ok(())
516 }
517
518 #[test]
519 fn is_not_strict() {
520 let expr = between(
521 root(),
522 lit(0),
523 lit(100),
524 BetweenOptions {
525 lower_strict: StrictComparison::NonStrict,
526 upper_strict: StrictComparison::NonStrict,
527 },
528 );
529
530 assert!(!expr.as_scalar().is_some_and(|f| f.signature().is_strict()));
531 }
532
533 #[test]
534 fn test_display() {
535 let expr = between(
536 get_item("score", root()),
537 lit(10),
538 lit(50),
539 BetweenOptions {
540 lower_strict: StrictComparison::NonStrict,
541 upper_strict: StrictComparison::Strict,
542 },
543 );
544 assert_eq!(expr.to_string(), "(10i32 <= $.score < 50i32)");
545
546 let expr2 = between(
547 root(),
548 lit(0),
549 lit(100),
550 BetweenOptions {
551 lower_strict: StrictComparison::Strict,
552 upper_strict: StrictComparison::NonStrict,
553 },
554 );
555 assert_eq!(expr2.to_string(), "(0i32 < $ <= 100i32)");
556 }
557
558 #[rstest]
559 #[case(StrictComparison::NonStrict, StrictComparison::NonStrict, vec![0, 1, 2, 3])]
560 #[case(StrictComparison::NonStrict, StrictComparison::Strict, vec![0, 1])]
561 #[case(StrictComparison::Strict, StrictComparison::NonStrict, vec![0, 2])]
562 #[case(StrictComparison::Strict, StrictComparison::Strict, vec![0])]
563 fn test_bounds(
564 #[case] lower_strict: StrictComparison,
565 #[case] upper_strict: StrictComparison,
566 #[case] expected: Vec<u64>,
567 ) {
568 let lower = buffer![0, 0, 0, 0, 2].into_array();
569 let array = buffer![1, 0, 1, 0, 1].into_array();
570 let upper = buffer![2, 1, 1, 0, 0].into_array();
571 let ctx = &mut SESSION.create_execution_ctx();
572
573 let matches = between_canonical(
574 &array,
575 &lower,
576 &upper,
577 &BetweenOptions {
578 lower_strict,
579 upper_strict,
580 },
581 ctx,
582 )
583 .unwrap()
584 .execute::<BoolArray>(ctx)
585 .unwrap();
586
587 let indices = to_int_indices(matches, ctx).unwrap();
588 assert_eq!(indices, expected);
589 }
590
591 #[test]
592 fn test_constants() {
593 let lower = buffer![0, 0, 2, 0, 2].into_array();
594 let array = buffer![1, 0, 1, 0, 1].into_array();
595 let ctx = &mut SESSION.create_execution_ctx();
596
597 let upper = ConstantArray::new(
599 Scalar::null(DType::Primitive(PType::I32, Nullability::Nullable)),
600 5,
601 )
602 .into_array();
603
604 let matches = between_canonical(
605 &array,
606 &lower,
607 &upper,
608 &BetweenOptions {
609 lower_strict: StrictComparison::NonStrict,
610 upper_strict: StrictComparison::NonStrict,
611 },
612 ctx,
613 )
614 .unwrap()
615 .execute::<BoolArray>(ctx)
616 .unwrap();
617
618 assert_eq!(
620 matches.opt_bool_vec(ctx),
621 [None, None, Some(false), None, Some(false)]
622 );
623
624 let upper = ConstantArray::new(Scalar::from(2), 5).into_array();
626 let matches = between_canonical(
627 &array,
628 &lower,
629 &upper,
630 &BetweenOptions {
631 lower_strict: StrictComparison::NonStrict,
632 upper_strict: StrictComparison::NonStrict,
633 },
634 ctx,
635 )
636 .unwrap()
637 .execute::<BoolArray>(ctx)
638 .unwrap();
639 let indices = to_int_indices(matches, ctx).unwrap();
640 assert_eq!(indices, vec![0, 1, 3]);
641
642 let lower = ConstantArray::new(Scalar::from(0), 5).into_array();
644
645 let matches = between_canonical(
646 &array,
647 &lower,
648 &upper,
649 &BetweenOptions {
650 lower_strict: StrictComparison::NonStrict,
651 upper_strict: StrictComparison::NonStrict,
652 },
653 ctx,
654 )
655 .unwrap()
656 .execute::<BoolArray>(ctx)
657 .unwrap();
658 let indices = to_int_indices(matches, ctx).unwrap();
659 assert_eq!(indices, vec![0, 1, 2, 3, 4]);
660 }
661
662 #[rstest]
666 #[case::primitive_nulls(PrimitiveArray::from_option_iter([None::<i32>, None]).into_array())]
667 #[case::constant_null(null_i32s(2))]
668 fn null_lower_bound(#[case] lower: ArrayRef) -> VortexResult<()> {
669 let ctx = &mut SESSION.create_execution_ctx();
670 let array = buffer![10, 10].into_array();
671 let upper = buffer![5, 50].into_array();
672
673 let result = between_canonical(&array, &lower, &upper, &NON_STRICT, ctx)?
674 .execute::<BoolArray>(ctx)?;
675
676 assert_eq!(result.opt_bool_vec(ctx), [Some(false), None]);
678
679 Ok(())
680 }
681
682 #[test]
684 fn both_bounds_null() -> VortexResult<()> {
685 let ctx = &mut SESSION.create_execution_ctx();
686 let array = buffer![10, 10].into_array();
687 let bound = null_i32s(2);
688
689 let result = between_canonical(&array, &bound, &bound, &NON_STRICT, ctx)?
690 .execute::<BoolArray>(ctx)?;
691
692 assert_eq!(result.opt_bool_vec(ctx), [None, None]);
693
694 Ok(())
695 }
696
697 #[rstest]
700 #[case::f64(Scalar::null_native::<f64>(), Scalar::from(-0.0f64), Scalar::from(0.0f64))]
701 #[case::i32(Scalar::null_native::<i32>(), Scalar::from(0i32), Scalar::from(0i32))]
702 fn constant_null_array(
703 #[case] null: Scalar,
704 #[case] lower: Scalar,
705 #[case] upper: Scalar,
706 ) -> VortexResult<()> {
707 let ctx = &mut SESSION.create_execution_ctx();
708 let array = ConstantArray::new(null, 3).into_array();
709 let lower = ConstantArray::new(lower, 3).into_array();
710 let upper = ConstantArray::new(upper, 3).into_array();
711
712 let between = array.between(lower, upper, NON_STRICT)?;
713 let not_between = between.not()?;
714
715 assert_eq!(
716 between.execute::<BoolArray>(ctx)?.opt_bool_vec(ctx),
717 [None, None, None]
718 );
719 assert_eq!(
720 not_between.execute::<BoolArray>(ctx)?.opt_bool_vec(ctx),
721 [None, None, None]
722 );
723
724 Ok(())
725 }
726
727 fn decimal_bound(value: i16, precision: u8, scale: i8) -> ArrayRef {
728 let dtype = DecimalDType::new(precision, scale);
729 let scalar = Scalar::decimal(DecimalValue::I16(value), dtype, Nullability::NonNullable);
730 ConstantArray::new(scalar, 1).into_array()
731 }
732
733 #[rstest]
734 #[case::lower_outside_native_width(decimal_bound(500, 4, 0), decimal_bound(1, 2, 0))]
735 #[case::upper_at_another_scale(decimal_bound(0, 2, 0), decimal_bound(10, 2, 1))]
736 fn kernel_declines_mismatched_decimal_bound(
737 #[case] lower: ArrayRef,
738 #[case] upper: ArrayRef,
739 ) -> VortexResult<()> {
740 let array = DecimalArray::from_iter([1i8], DecimalDType::new(2, 0));
741 let result = <Decimal as BetweenKernel>::between(
742 array.as_view(),
743 &lower,
744 &upper,
745 &NON_STRICT,
746 &mut SESSION.create_execution_ctx(),
747 )?;
748 assert!(result.is_none());
749 Ok(())
750 }
751
752 #[rstest]
753 #[case::open(StrictComparison::Strict, StrictComparison::Strict, false, false)]
754 #[case::left_open(StrictComparison::Strict, StrictComparison::NonStrict, false, true)]
755 #[case::right_open(StrictComparison::NonStrict, StrictComparison::Strict, true, false)]
756 #[case::closed(StrictComparison::NonStrict, StrictComparison::NonStrict, true, true)]
757 fn test_between_decimal(
758 #[case] lower_strict: StrictComparison,
759 #[case] upper_strict: StrictComparison,
760 #[case] includes_lower: bool,
761 #[case] includes_upper: bool,
762 ) -> VortexResult<()> {
763 let ctx = &mut SESSION.create_execution_ctx();
764 let dtype = DecimalDType::new(3, 2);
765 let array =
766 DecimalArray::from_option_iter([Some(100i16), Some(200), None, Some(400)], dtype)
767 .into_array();
768 let lower = Scalar::decimal(DecimalValue::I128(100), dtype, Nullability::NonNullable);
769 let upper = Scalar::decimal(DecimalValue::I128(400), dtype, Nullability::NonNullable);
770 let options = BetweenOptions {
771 lower_strict,
772 upper_strict,
773 };
774
775 let result = between_canonical(
776 &array,
777 &ConstantArray::new(lower, array.len()).into_array(),
778 &ConstantArray::new(upper, array.len()).into_array(),
779 &options,
780 ctx,
781 )?;
782 assert_arrays_eq!(
783 result,
784 BoolArray::from_iter([Some(includes_lower), Some(true), None, Some(includes_upper)]),
785 ctx
786 );
787
788 Ok(())
789 }
790
791 #[rstest]
793 #[case::upper_above(1, 82_246, [true, true, true, true])]
794 #[case::lower_above(82_246, 4, [false; 4])]
795 #[case::upper_below(1, -82_246, [false; 4])]
796 #[case::lower_below(-82_246, 2, [true, true, false, false])]
797 fn test_between_decimal_narrow_child(
798 #[case] lower: i32,
799 #[case] upper: i32,
800 #[case] expected: [bool; 4],
801 ) -> VortexResult<()> {
802 let dtype = DecimalDType::new(5, -67);
803 let child = DecimalArray::from_iter([1i16, 2, 3, 4], DecimalDType::new(4, -67));
804 let array = WidenArray::try_new(
805 child.into_array(),
806 DType::Decimal(dtype, Nullability::NonNullable),
807 )?;
808 let bound = |value: i32| {
809 let scalar = Scalar::decimal(DecimalValue::I32(value), dtype, Nullability::NonNullable);
810 ConstantArray::new(scalar, array.len()).into_array()
811 };
812 let lower = bound(lower);
813 let upper = bound(upper);
814
815 let result = array.into_array().between(lower, upper, NON_STRICT)?;
816 assert_arrays_eq!(
817 result,
818 BoolArray::from_iter(expected),
819 &mut SESSION.create_execution_ctx()
820 );
821
822 Ok(())
823 }
824
825 #[test]
827 fn executes_non_canonical_input_iteratively() -> VortexResult<()> {
828 let mut ctx = SESSION.create_execution_ctx();
829 let chunks = vec![
830 PrimitiveArray::from_iter([1i32, 5]).into_array(),
831 PrimitiveArray::from_iter([9i32, 12]).into_array(),
832 ];
833 let dtype = chunks[0].dtype().clone();
834 let chunked = vortex_array::arrays::ChunkedArray::try_new(chunks, dtype)?.into_array();
835 let result = chunked.between(
836 ConstantArray::new(5i32, 4).into_array(),
837 ConstantArray::new(10i32, 4).into_array(),
838 BetweenOptions {
839 lower_strict: StrictComparison::NonStrict,
840 upper_strict: StrictComparison::Strict,
841 },
842 )?;
843
844 assert_arrays_eq!(
845 result,
846 BoolArray::from_iter([false, true, true, false]),
847 &mut ctx
848 );
849 Ok(())
850 }
851
852 #[test]
853 fn test_display_tree_between() {
854 use insta::assert_snapshot;
855 let between_expr = between(
856 get_item("score", root()),
857 lit(0),
858 lit(100),
859 BetweenOptions {
860 lower_strict: StrictComparison::NonStrict,
861 upper_strict: StrictComparison::NonStrict,
862 },
863 );
864 assert_snapshot!(between_expr.display_tree().to_string(), @r"
865 vortex.between(lower_strict: <=, upper_strict: <=)
866 ├── array: vortex.get_item(score)
867 │ └── input: vortex.root()
868 ├── lower: vortex.literal(0i32)
869 └── upper: vortex.literal(100i32)
870 ");
871 }
872
873 #[test]
874 fn between_serde() -> VortexResult<()> {
875 let expr = between(
876 lit(1),
877 root(),
878 get_item("a", root()),
879 BetweenOptions {
880 lower_strict: StrictComparison::Strict,
881 upper_strict: StrictComparison::Strict,
882 },
883 );
884 let proto = expr.serialize_proto()?;
885 assert_eq!(Expression::from_proto(&proto, &SESSION)?, expr);
886 Ok(())
887 }
888}