1use std::sync::Arc;
9
10use vortex_array::aggregate_fn::NumericalAggregateOpts;
11use vortex_array::dtype::DType;
12use vortex_array::dtype::FieldNames;
13use vortex_array::dtype::Nullability;
14use vortex_array::expr::BoundExpression;
15use vortex_array::scalar::Scalar;
16use vortex_array::scalar::ScalarValue;
17use vortex_array::scalar_fn::EmptyOptions;
18use vortex_array::scalar_fn::builtin::operators::CompareOperator;
19use vortex_error::VortexExpect;
20use vortex_error::VortexResult;
21use vortex_error::vortex_ensure;
22use vortex_error::vortex_panic;
23use vortex_expr::Expression;
24use vortex_expr::Lambda;
25use vortex_expr::ScalarFnExprExt;
26use vortex_expr::lit;
27
28use crate::between::Between;
29use crate::between::BetweenOptions;
30use crate::between::StrictComparison;
31use crate::byte_length::ByteLength;
32use crate::case_when::CaseWhen;
33use crate::case_when::CaseWhenOptions;
34use crate::dynamic::DynamicComparison;
35use crate::dynamic::DynamicComparisonExpr;
36use crate::dynamic::Rhs;
37use crate::dynamic_expression::DynamicExpression;
38use crate::dynamic_expression::DynamicExpressionOptions;
39use crate::dynamic_expression::DynamicExpressionSource;
40use crate::ext_storage::ExtStorage;
41use crate::is_nan::IsNan;
42use crate::is_null::IsNull;
43use crate::like::Like;
44use crate::like::LikeOptions;
45use crate::list_contains::ListContains;
46use crate::list_contains::ListContainsOptions;
47use crate::list_length::ListLength;
48use crate::list_sum::ListSum;
49use crate::list_transform::ListTransform;
50use crate::list_transform::ListTransformOptions;
51use crate::lower::Lower;
52use crate::merge::DuplicateHandling;
53use crate::merge::Merge;
54use crate::replace_time_zone::ReplaceTimeZone;
55use crate::replace_time_zone::ReplaceTimeZoneOptions;
56use crate::select::FieldSelection;
57use crate::select::Select;
58use crate::strpos::Strpos;
59use crate::variant_get::VariantGet;
60use crate::variant_get::VariantGetOptions;
61use crate::variant_get::VariantPath;
62use crate::zip::Zip;
63
64pub fn case_when(
66 condition: Expression,
67 then_value: Expression,
68 else_value: Expression,
69) -> Expression {
70 let options = CaseWhenOptions {
71 num_when_then_pairs: 1,
72 has_else: true,
73 };
74 CaseWhen.new_expr(options, [condition, then_value, else_value])
75}
76
77pub fn bound_case_when(
79 condition: BoundExpression,
80 then_value: BoundExpression,
81 else_value: BoundExpression,
82) -> BoundExpression {
83 let options = CaseWhenOptions {
84 num_when_then_pairs: 1,
85 has_else: true,
86 };
87 CaseWhen
88 .try_new_bound_expr(options, [condition, then_value, else_value])
89 .vortex_expect("case expressions must have boolean conditions and matching branch dtypes")
90}
91
92pub fn case_when_no_else(condition: Expression, then_value: Expression) -> Expression {
94 let options = CaseWhenOptions {
95 num_when_then_pairs: 1,
96 has_else: false,
97 };
98 CaseWhen.new_expr(options, [condition, then_value])
99}
100
101pub fn bound_case_when_no_else(
103 condition: BoundExpression,
104 then_value: BoundExpression,
105) -> BoundExpression {
106 let options = CaseWhenOptions {
107 num_when_then_pairs: 1,
108 has_else: false,
109 };
110 CaseWhen
111 .try_new_bound_expr(options, [condition, then_value])
112 .vortex_expect("case expressions must have boolean conditions")
113}
114
115pub fn nested_case_when(
117 when_then_pairs: Vec<(Expression, Expression)>,
118 else_value: Option<Expression>,
119) -> Expression {
120 assert!(
121 !when_then_pairs.is_empty(),
122 "nested_case_when requires at least one when/then pair"
123 );
124
125 let has_else = else_value.is_some();
126 let mut children = Vec::with_capacity(when_then_pairs.len() * 2 + usize::from(has_else));
127 for (condition, then_value) in &when_then_pairs {
128 children.push(condition.clone());
129 children.push(then_value.clone());
130 }
131 if let Some(else_expr) = else_value {
132 children.push(else_expr);
133 }
134
135 let Ok(num_when_then_pairs) = u32::try_from(when_then_pairs.len()) else {
136 vortex_panic!("nested_case_when has too many when/then pairs");
137 };
138 let options = CaseWhenOptions {
139 num_when_then_pairs,
140 has_else,
141 };
142 CaseWhen.new_expr(options, children)
143}
144
145pub fn bound_nested_case_when(
147 when_then_pairs: Vec<(BoundExpression, BoundExpression)>,
148 else_value: Option<BoundExpression>,
149) -> BoundExpression {
150 assert!(
151 !when_then_pairs.is_empty(),
152 "nested_case_when requires at least one when/then pair"
153 );
154
155 let Ok(num_when_then_pairs) = u32::try_from(when_then_pairs.len()) else {
156 vortex_panic!("nested_case_when has too many when/then pairs");
157 };
158 let has_else = else_value.is_some();
159 let mut children = Vec::with_capacity(when_then_pairs.len() * 2 + usize::from(has_else));
160 for (condition, then_value) in when_then_pairs {
161 children.push(condition);
162 children.push(then_value);
163 }
164 if let Some(else_expr) = else_value {
165 children.push(else_expr);
166 }
167
168 let options = CaseWhenOptions {
169 num_when_then_pairs,
170 has_else,
171 };
172 CaseWhen
173 .try_new_bound_expr(options, children)
174 .vortex_expect("case expressions must have boolean conditions and matching branch dtypes")
175}
176
177pub fn merge(elements: impl IntoIterator<Item = impl Into<Expression>>) -> Expression {
189 use itertools::Itertools as _;
190 let values = elements.into_iter().map(|value| value.into()).collect_vec();
191 Merge.new_expr(DuplicateHandling::default(), values)
192}
193
194pub fn bound_merge(elements: impl IntoIterator<Item = BoundExpression>) -> BoundExpression {
196 bound_merge_opts(elements, DuplicateHandling::default())
197}
198
199pub fn merge_opts(
201 elements: impl IntoIterator<Item = impl Into<Expression>>,
202 duplicate_handling: DuplicateHandling,
203) -> Expression {
204 use itertools::Itertools as _;
205 let values = elements.into_iter().map(|value| value.into()).collect_vec();
206 Merge.new_expr(duplicate_handling, values)
207}
208
209pub fn bound_merge_opts(
211 elements: impl IntoIterator<Item = BoundExpression>,
212 duplicate_handling: DuplicateHandling,
213) -> BoundExpression {
214 Merge
215 .try_new_bound_expr(duplicate_handling, elements)
216 .vortex_expect("merge expressions require non-nullable struct children")
217}
218
219pub fn byte_length(input: Expression) -> Expression {
228 ByteLength.new_expr(EmptyOptions, [input])
229}
230
231pub fn bound_byte_length(input: BoundExpression) -> BoundExpression {
233 ByteLength
234 .try_new_bound_expr(EmptyOptions, [input])
235 .vortex_expect("byte-length expressions require a variable-length binary child")
236}
237
238pub fn lower(input: Expression) -> Expression {
246 Lower.new_expr(EmptyOptions, [input])
247}
248
249pub fn strpos(input: Expression, search: Expression) -> Expression {
258 Strpos.new_expr(EmptyOptions, [input, search])
259}
260
261pub fn ext_storage(input: Expression) -> Expression {
269 ExtStorage.new_expr(EmptyOptions, [input])
270}
271
272pub fn bound_ext_storage(input: BoundExpression) -> BoundExpression {
274 ExtStorage
275 .try_new_bound_expr(EmptyOptions, [input])
276 .vortex_expect("extension-storage expressions require an extension child")
277}
278
279pub fn list_length(input: Expression) -> Expression {
289 ListLength.new_expr(EmptyOptions, [input])
290}
291
292pub fn bound_list_length(input: BoundExpression) -> BoundExpression {
294 ListLength
295 .try_new_bound_expr(EmptyOptions, [input])
296 .vortex_expect("list-length expressions require a list child")
297}
298
299pub fn list_sum(input: Expression) -> Expression {
313 ListSum.new_expr(NumericalAggregateOpts::default(), [input])
314}
315
316pub fn bound_list_sum(input: BoundExpression) -> BoundExpression {
318 ListSum
319 .try_new_bound_expr(NumericalAggregateOpts::default(), [input])
320 .vortex_expect("list-sum expressions require a numeric list child")
321}
322
323pub fn list_sum_opts(input: Expression, options: NumericalAggregateOpts) -> Expression {
326 ListSum.new_expr(options, [input])
327}
328
329pub fn bound_list_sum_opts(
331 input: BoundExpression,
332 options: NumericalAggregateOpts,
333) -> BoundExpression {
334 ListSum
335 .try_new_bound_expr(options, [input])
336 .vortex_expect("list-sum expressions require a numeric list child")
337}
338
339pub fn replace_time_zone(
344 input: Expression,
345 ambiguous: Expression,
346 options: ReplaceTimeZoneOptions,
347) -> Expression {
348 ReplaceTimeZone.new_expr(options, [input, ambiguous])
349}
350
351pub fn bound_replace_time_zone(
353 input: BoundExpression,
354 ambiguous: BoundExpression,
355 options: ReplaceTimeZoneOptions,
356) -> BoundExpression {
357 ReplaceTimeZone
358 .try_new_bound_expr(options, [input, ambiguous])
359 .vortex_expect("timezone replacement requires a timestamp and a UTF-8 ambiguity policy")
360}
361
362pub fn dynamic_with_options(options: DynamicComparisonExpr, lhs: Expression) -> Expression {
368 DynamicComparison.new_expr(options, [lhs])
369}
370
371pub fn bound_dynamic_with_options(
373 options: DynamicComparisonExpr,
374 lhs: BoundExpression,
375) -> BoundExpression {
376 DynamicComparison
377 .try_new_bound_expr(options, [lhs])
378 .vortex_expect("dynamic comparisons require a compatible left-hand dtype")
379}
380
381pub fn dynamic(
383 operator: CompareOperator,
384 rhs_value: impl Fn() -> Option<ScalarValue> + Send + Sync + 'static,
385 rhs_dtype: DType,
386 default: bool,
387 lhs: Expression,
388) -> Expression {
389 dynamic_with_options(
390 DynamicComparisonExpr {
391 operator,
392 rhs: Arc::new(Rhs {
393 value: Arc::new(rhs_value),
394 dtype: rhs_dtype,
395 }),
396 default,
397 },
398 lhs,
399 )
400}
401
402pub fn bound_dynamic(
404 operator: CompareOperator,
405 rhs_value: impl Fn() -> Option<ScalarValue> + Send + Sync + 'static,
406 rhs_dtype: DType,
407 default: bool,
408 lhs: BoundExpression,
409) -> BoundExpression {
410 bound_dynamic_with_options(
411 DynamicComparisonExpr {
412 operator,
413 rhs: Arc::new(Rhs {
414 value: Arc::new(rhs_value),
415 dtype: rhs_dtype,
416 }),
417 default,
418 },
419 lhs,
420 )
421}
422
423pub fn between(
442 arr: Expression,
443 lower: Expression,
444 upper: Expression,
445 options: BetweenOptions,
446) -> Expression {
447 Between
448 .try_new_expr(options, [arr, lower, upper])
449 .vortex_expect("Failed to create Between expression")
450}
451
452pub fn bound_between(
454 arr: BoundExpression,
455 lower: BoundExpression,
456 upper: BoundExpression,
457 options: BetweenOptions,
458) -> BoundExpression {
459 Between
460 .try_new_bound_expr(options, [arr, lower, upper])
461 .vortex_expect("between expressions require compatible operand dtypes")
462}
463
464pub fn list_contains(list: Expression, value: Expression) -> Expression {
477 list_contains_opts(list, value, ListContainsOptions::default())
478}
479
480pub fn list_contains_opts(
483 list: Expression,
484 value: Expression,
485 options: ListContainsOptions,
486) -> Expression {
487 ListContains.new_expr(options, [list, value])
488}
489
490pub fn in_list(needle: Expression, list: Expression) -> Expression {
500 list_contains_opts(
501 list,
502 needle,
503 ListContainsOptions {
504 sql_null_semantics: true,
505 },
506 )
507}
508
509pub fn in_list_of(
533 needle: Expression,
534 element_dtype: DType,
535 elements: Vec<Scalar>,
536) -> VortexResult<Expression> {
537 let element_dtype = if elements.iter().any(Scalar::is_null) {
538 element_dtype.as_nullable()
539 } else {
540 element_dtype.as_nonnullable()
541 };
542 let mut elements = elements
543 .iter()
544 .map(|element| {
545 vortex_ensure!(
546 element.dtype() == &DType::Null
547 || element.dtype().eq_ignore_nullability(&element_dtype),
548 "IN list element {element} is not of type {element_dtype}"
549 );
550 element.cast(&element_dtype)
551 })
552 .collect::<VortexResult<Vec<_>>>()?;
553
554 if let Some((low, high)) = contiguous_integer_bounds(&elements) {
555 let options = BetweenOptions {
556 lower_strict: StrictComparison::NonStrict,
557 upper_strict: StrictComparison::NonStrict,
558 };
559 return Ok(between(
560 needle,
561 lit(low.clone()),
562 lit(high.clone()),
563 options,
564 ));
565 }
566
567 if elements
571 .windows(2)
572 .all(|pair| pair[0].partial_cmp(&pair[1]).is_some())
573 {
574 elements.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));
575 elements.dedup();
576 }
577 let list = Scalar::list(Arc::new(element_dtype), elements, Nullability::NonNullable);
578 Ok(in_list(needle, lit(list)))
579}
580
581fn contiguous_integer_bounds(scalars: &[Scalar]) -> Option<(&Scalar, &Scalar)> {
584 let mut values = scalars
585 .iter()
586 .map(|scalar| {
587 if !matches!(scalar.dtype(), DType::Primitive(ptype, _) if ptype.is_int()) {
589 return None;
590 }
591 let primitive = scalar.as_primitive_opt()?;
592 let value = if primitive.ptype().is_unsigned_int() {
593 primitive.as_opt::<u64>()??.into()
594 } else {
595 i128::from(primitive.as_opt::<i64>()??)
596 };
597 Some((value, scalar))
598 })
599 .collect::<Option<Vec<(i128, &Scalar)>>>()?;
600 values.sort_unstable_by_key(|(value, _)| *value);
601 values.dedup_by_key(|(value, _)| *value);
602 let (low, low_scalar) = values.first()?;
603 let (high, high_scalar) = values.last()?;
604 (high - low + 1 == i128::try_from(values.len()).ok()?).then_some((*low_scalar, *high_scalar))
605}
606
607pub fn bound_list_contains(list: BoundExpression, value: BoundExpression) -> BoundExpression {
609 ListContains
610 .try_new_bound_expr(ListContainsOptions::default(), [list, value])
611 .vortex_expect("list-contains expressions require a list child")
612}
613
614pub fn bound_in_list(needle: BoundExpression, list: BoundExpression) -> BoundExpression {
616 ListContains
617 .try_new_bound_expr(
618 ListContainsOptions {
619 sql_null_semantics: true,
620 },
621 [list, needle],
622 )
623 .vortex_expect("list-contains expressions require a list child")
624}
625
626pub fn variant_get(
633 child: Expression,
634 path: impl Into<VariantPath>,
635 dtype: Option<DType>,
636) -> Expression {
637 VariantGet.new_expr(VariantGetOptions::new(path.into(), dtype), vec![child])
638}
639
640pub fn bound_variant_get(
642 child: BoundExpression,
643 path: impl Into<VariantPath>,
644 dtype: Option<DType>,
645) -> BoundExpression {
646 VariantGet
647 .try_new_bound_expr(VariantGetOptions::new(path.into(), dtype), [child])
648 .vortex_expect("variant-get expressions require a Variant child")
649}
650
651pub fn like(child: Expression, pattern: Expression) -> Expression {
655 Like.new_expr(
656 LikeOptions {
657 negated: false,
658 case_insensitive: false,
659 },
660 [child, pattern],
661 )
662}
663
664pub fn bound_like(child: BoundExpression, pattern: BoundExpression) -> BoundExpression {
666 bound_like_with_options(child, pattern, false, false)
667}
668
669pub fn ilike(child: Expression, pattern: Expression) -> Expression {
671 Like.new_expr(
672 LikeOptions {
673 negated: false,
674 case_insensitive: true,
675 },
676 [child, pattern],
677 )
678}
679
680pub fn bound_ilike(child: BoundExpression, pattern: BoundExpression) -> BoundExpression {
682 bound_like_with_options(child, pattern, false, true)
683}
684
685pub fn not_like(child: Expression, pattern: Expression) -> Expression {
687 Like.new_expr(
688 LikeOptions {
689 negated: true,
690 case_insensitive: false,
691 },
692 [child, pattern],
693 )
694}
695
696pub fn bound_not_like(child: BoundExpression, pattern: BoundExpression) -> BoundExpression {
698 bound_like_with_options(child, pattern, true, false)
699}
700
701pub fn not_ilike(child: Expression, pattern: Expression) -> Expression {
703 Like.new_expr(
704 LikeOptions {
705 negated: true,
706 case_insensitive: true,
707 },
708 [child, pattern],
709 )
710}
711
712pub fn bound_not_ilike(child: BoundExpression, pattern: BoundExpression) -> BoundExpression {
714 bound_like_with_options(child, pattern, true, true)
715}
716
717fn bound_like_with_options(
718 child: BoundExpression,
719 pattern: BoundExpression,
720 negated: bool,
721 case_insensitive: bool,
722) -> BoundExpression {
723 Like.try_new_bound_expr(
724 LikeOptions {
725 negated,
726 case_insensitive,
727 },
728 [child, pattern],
729 )
730 .vortex_expect("like expressions require UTF-8 or binary operands")
731}
732
733pub fn is_nan(child: Expression) -> Expression {
746 IsNan.new_expr(EmptyOptions, vec![child])
747}
748
749pub fn bound_is_nan(child: BoundExpression) -> BoundExpression {
751 IsNan
752 .try_new_bound_expr(EmptyOptions, [child])
753 .vortex_expect("is-nan expressions are always well-typed")
754}
755
756pub fn zip_expr(mask: Expression, if_true: Expression, if_false: Expression) -> Expression {
766 Zip.new_expr(EmptyOptions, [if_true, if_false, mask])
767}
768
769pub fn bound_zip_expr(
771 mask: BoundExpression,
772 if_true: BoundExpression,
773 if_false: BoundExpression,
774) -> BoundExpression {
775 Zip.try_new_bound_expr(EmptyOptions, [if_true, if_false, mask])
776 .vortex_expect("zip expressions require a boolean mask and compatible value dtypes")
777}
778
779pub fn dynamic_expression(
788 source: Arc<dyn DynamicExpressionSource>,
789 inputs: impl IntoIterator<Item = Expression>,
790) -> Expression {
791 DynamicExpression.new_expr(DynamicExpressionOptions::new(source), inputs)
792}
793
794pub fn bound_dynamic_expression(
796 source: Arc<dyn DynamicExpressionSource>,
797 inputs: impl IntoIterator<Item = BoundExpression>,
798) -> BoundExpression {
799 DynamicExpression
800 .try_new_bound_expr(DynamicExpressionOptions::new(source), inputs)
801 .vortex_expect("dynamic expressions accept any inputs")
802}
803
804pub fn list_transform(list: Expression, lambda: Lambda) -> Expression {
818 ListTransform.new_expr(ListTransformOptions::Lambda(lambda), [list])
819}
820
821pub fn is_null(child: Expression) -> Expression {
833 IsNull.new_expr(EmptyOptions, vec![child])
834}
835
836pub fn bound_is_null(child: BoundExpression) -> BoundExpression {
838 IsNull
839 .try_new_bound_expr(EmptyOptions, [child])
840 .vortex_expect("is-null expressions are always well-typed")
841}
842
843pub fn select(field_names: impl Into<FieldNames>, child: Expression) -> Expression {
854 Select
855 .try_new_expr(FieldSelection::Include(field_names.into()), [child])
856 .vortex_expect("Failed to create Select expression")
857}
858
859pub fn bound_select(field_names: impl Into<FieldNames>, child: BoundExpression) -> BoundExpression {
861 Select
862 .try_new_bound_expr(FieldSelection::Include(field_names.into()), [child])
863 .vortex_expect("select expressions require fields from a struct child")
864}
865
866pub fn select_exclude(fields: impl Into<FieldNames>, child: Expression) -> Expression {
876 Select
877 .try_new_expr(FieldSelection::Exclude(fields.into()), [child])
878 .vortex_expect("Failed to create Select expression")
879}
880
881pub fn bound_select_exclude(
883 fields: impl Into<FieldNames>,
884 child: BoundExpression,
885) -> BoundExpression {
886 Select
887 .try_new_bound_expr(FieldSelection::Exclude(fields.into()), [child])
888 .vortex_expect("select expressions require fields from a struct child")
889}
890
891pub mod bound {
892 pub use super::bound_between as between;
893 pub use super::bound_byte_length as byte_length;
894 pub use super::bound_case_when as case_when;
895 pub use super::bound_case_when_no_else as case_when_no_else;
896 pub use super::bound_dynamic as dynamic;
897 pub use super::bound_dynamic_expression as dynamic_expression;
898 pub use super::bound_dynamic_with_options as dynamic_with_options;
899 pub use super::bound_ext_storage as ext_storage;
900 pub use super::bound_ilike as ilike;
901 pub use super::bound_in_list as in_list;
902 pub use super::bound_is_nan as is_nan;
903 pub use super::bound_is_null as is_null;
904 pub use super::bound_like as like;
905 pub use super::bound_list_contains as list_contains;
906 pub use super::bound_list_length as list_length;
907 pub use super::bound_list_sum as list_sum;
908 pub use super::bound_list_sum_opts as list_sum_opts;
909 pub use super::bound_merge as merge;
910 pub use super::bound_merge_opts as merge_opts;
911 pub use super::bound_nested_case_when as nested_case_when;
912 pub use super::bound_not_ilike as not_ilike;
913 pub use super::bound_not_like as not_like;
914 pub use super::bound_replace_time_zone as replace_time_zone;
915 pub use super::bound_select as select;
916 pub use super::bound_select_exclude as select_exclude;
917 pub use super::bound_variant_get as variant_get;
918 pub use super::bound_zip_expr as zip_expr;
919}