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::extension::datetime::TemporalRounding;
16use vortex_array::extension::datetime::TimeUnit;
17use vortex_array::scalar::Scalar;
18use vortex_array::scalar::ScalarValue;
19use vortex_array::scalar_fn::EmptyOptions;
20use vortex_array::scalar_fn::builtin::operators::CompareOperator;
21use vortex_error::VortexExpect;
22use vortex_error::VortexResult;
23use vortex_error::vortex_ensure;
24use vortex_error::vortex_panic;
25use vortex_expr::Expression;
26use vortex_expr::Lambda;
27use vortex_expr::ScalarFnExprExt;
28use vortex_expr::lit;
29
30use crate::between::Between;
31use crate::between::BetweenOptions;
32use crate::between::StrictComparison;
33use crate::byte_length::ByteLength;
34use crate::case_when::CaseWhen;
35use crate::case_when::CaseWhenOptions;
36use crate::change_time_unit::ChangeTimeUnit;
37use crate::change_time_unit::ChangeTimeUnitOptions;
38use crate::convert_time_zone::ConvertTimeZone;
39use crate::convert_time_zone::ConvertTimeZoneOptions;
40use crate::dynamic::DynamicComparison;
41use crate::dynamic::DynamicComparisonExpr;
42use crate::dynamic::Rhs;
43use crate::dynamic_expression::DynamicExpression;
44use crate::dynamic_expression::DynamicExpressionOptions;
45use crate::dynamic_expression::DynamicExpressionSource;
46use crate::ext_storage::ExtStorage;
47use crate::is_nan::IsNan;
48use crate::is_null::IsNull;
49use crate::like::Like;
50use crate::like::LikeOptions;
51use crate::list_contains::ListContains;
52use crate::list_contains::ListContainsOptions;
53use crate::list_length::ListLength;
54use crate::list_sum::ListSum;
55use crate::list_transform::ListTransform;
56use crate::list_transform::ListTransformOptions;
57use crate::lower::Lower;
58use crate::merge::DuplicateHandling;
59use crate::merge::Merge;
60use crate::replace_time_zone::ReplaceTimeZone;
61use crate::replace_time_zone::ReplaceTimeZoneOptions;
62use crate::select::FieldSelection;
63use crate::select::Select;
64use crate::strpos::Strpos;
65use crate::timestamp_to_date::TimestampToDate;
66use crate::timestamp_to_time::TimestampToTime;
67use crate::variant_get::VariantGet;
68use crate::variant_get::VariantGetOptions;
69use crate::variant_get::VariantPath;
70use crate::zip::Zip;
71
72pub fn change_time_unit(
85 input: Expression,
86 unit: TimeUnit,
87 rounding: TemporalRounding,
88) -> Expression {
89 ChangeTimeUnit.new_expr(ChangeTimeUnitOptions { unit, rounding }, [input])
90}
91
92pub fn convert_time_zone(input: Expression, time_zone: impl Into<Arc<str>>) -> Expression {
100 ConvertTimeZone.new_expr(
101 ConvertTimeZoneOptions {
102 time_zone: time_zone.into(),
103 },
104 [input],
105 )
106}
107
108pub fn timestamp_to_date(input: Expression) -> Expression {
117 TimestampToDate.new_expr(EmptyOptions, [input])
118}
119
120pub fn timestamp_to_time(input: Expression) -> Expression {
128 TimestampToTime.new_expr(EmptyOptions, [input])
129}
130
131pub fn case_when(
133 condition: Expression,
134 then_value: Expression,
135 else_value: Expression,
136) -> Expression {
137 let options = CaseWhenOptions {
138 num_when_then_pairs: 1,
139 has_else: true,
140 };
141 CaseWhen.new_expr(options, [condition, then_value, else_value])
142}
143
144pub fn bound_case_when(
146 condition: BoundExpression,
147 then_value: BoundExpression,
148 else_value: BoundExpression,
149) -> BoundExpression {
150 let options = CaseWhenOptions {
151 num_when_then_pairs: 1,
152 has_else: true,
153 };
154 CaseWhen
155 .try_new_bound_expr(options, [condition, then_value, else_value])
156 .vortex_expect("case expressions must have boolean conditions and matching branch dtypes")
157}
158
159pub fn case_when_no_else(condition: Expression, then_value: Expression) -> Expression {
161 let options = CaseWhenOptions {
162 num_when_then_pairs: 1,
163 has_else: false,
164 };
165 CaseWhen.new_expr(options, [condition, then_value])
166}
167
168pub fn bound_case_when_no_else(
170 condition: BoundExpression,
171 then_value: BoundExpression,
172) -> BoundExpression {
173 let options = CaseWhenOptions {
174 num_when_then_pairs: 1,
175 has_else: false,
176 };
177 CaseWhen
178 .try_new_bound_expr(options, [condition, then_value])
179 .vortex_expect("case expressions must have boolean conditions")
180}
181
182pub fn nested_case_when(
184 when_then_pairs: Vec<(Expression, Expression)>,
185 else_value: Option<Expression>,
186) -> Expression {
187 assert!(
188 !when_then_pairs.is_empty(),
189 "nested_case_when requires at least one when/then pair"
190 );
191
192 let has_else = else_value.is_some();
193 let mut children = Vec::with_capacity(when_then_pairs.len() * 2 + usize::from(has_else));
194 for (condition, then_value) in &when_then_pairs {
195 children.push(condition.clone());
196 children.push(then_value.clone());
197 }
198 if let Some(else_expr) = else_value {
199 children.push(else_expr);
200 }
201
202 let Ok(num_when_then_pairs) = u32::try_from(when_then_pairs.len()) else {
203 vortex_panic!("nested_case_when has too many when/then pairs");
204 };
205 let options = CaseWhenOptions {
206 num_when_then_pairs,
207 has_else,
208 };
209 CaseWhen.new_expr(options, children)
210}
211
212pub fn bound_nested_case_when(
214 when_then_pairs: Vec<(BoundExpression, BoundExpression)>,
215 else_value: Option<BoundExpression>,
216) -> BoundExpression {
217 assert!(
218 !when_then_pairs.is_empty(),
219 "nested_case_when requires at least one when/then pair"
220 );
221
222 let Ok(num_when_then_pairs) = u32::try_from(when_then_pairs.len()) else {
223 vortex_panic!("nested_case_when has too many when/then pairs");
224 };
225 let has_else = else_value.is_some();
226 let mut children = Vec::with_capacity(when_then_pairs.len() * 2 + usize::from(has_else));
227 for (condition, then_value) in when_then_pairs {
228 children.push(condition);
229 children.push(then_value);
230 }
231 if let Some(else_expr) = else_value {
232 children.push(else_expr);
233 }
234
235 let options = CaseWhenOptions {
236 num_when_then_pairs,
237 has_else,
238 };
239 CaseWhen
240 .try_new_bound_expr(options, children)
241 .vortex_expect("case expressions must have boolean conditions and matching branch dtypes")
242}
243
244pub fn merge(elements: impl IntoIterator<Item = impl Into<Expression>>) -> Expression {
256 use itertools::Itertools as _;
257 let values = elements.into_iter().map(|value| value.into()).collect_vec();
258 Merge.new_expr(DuplicateHandling::default(), values)
259}
260
261pub fn bound_merge(elements: impl IntoIterator<Item = BoundExpression>) -> BoundExpression {
263 bound_merge_opts(elements, DuplicateHandling::default())
264}
265
266pub fn merge_opts(
268 elements: impl IntoIterator<Item = impl Into<Expression>>,
269 duplicate_handling: DuplicateHandling,
270) -> Expression {
271 use itertools::Itertools as _;
272 let values = elements.into_iter().map(|value| value.into()).collect_vec();
273 Merge.new_expr(duplicate_handling, values)
274}
275
276pub fn bound_merge_opts(
278 elements: impl IntoIterator<Item = BoundExpression>,
279 duplicate_handling: DuplicateHandling,
280) -> BoundExpression {
281 Merge
282 .try_new_bound_expr(duplicate_handling, elements)
283 .vortex_expect("merge expressions require non-nullable struct children")
284}
285
286pub fn byte_length(input: Expression) -> Expression {
295 ByteLength.new_expr(EmptyOptions, [input])
296}
297
298pub fn bound_byte_length(input: BoundExpression) -> BoundExpression {
300 ByteLength
301 .try_new_bound_expr(EmptyOptions, [input])
302 .vortex_expect("byte-length expressions require a variable-length binary child")
303}
304
305pub fn lower(input: Expression) -> Expression {
313 Lower.new_expr(EmptyOptions, [input])
314}
315
316pub fn strpos(input: Expression, search: Expression) -> Expression {
325 Strpos.new_expr(EmptyOptions, [input, search])
326}
327
328pub fn ext_storage(input: Expression) -> Expression {
336 ExtStorage.new_expr(EmptyOptions, [input])
337}
338
339pub fn bound_ext_storage(input: BoundExpression) -> BoundExpression {
341 ExtStorage
342 .try_new_bound_expr(EmptyOptions, [input])
343 .vortex_expect("extension-storage expressions require an extension child")
344}
345
346pub fn list_length(input: Expression) -> Expression {
356 ListLength.new_expr(EmptyOptions, [input])
357}
358
359pub fn bound_list_length(input: BoundExpression) -> BoundExpression {
361 ListLength
362 .try_new_bound_expr(EmptyOptions, [input])
363 .vortex_expect("list-length expressions require a list child")
364}
365
366pub fn list_sum(input: Expression) -> Expression {
380 ListSum.new_expr(NumericalAggregateOpts::default(), [input])
381}
382
383pub fn bound_list_sum(input: BoundExpression) -> BoundExpression {
385 ListSum
386 .try_new_bound_expr(NumericalAggregateOpts::default(), [input])
387 .vortex_expect("list-sum expressions require a numeric list child")
388}
389
390pub fn list_sum_opts(input: Expression, options: NumericalAggregateOpts) -> Expression {
393 ListSum.new_expr(options, [input])
394}
395
396pub fn bound_list_sum_opts(
398 input: BoundExpression,
399 options: NumericalAggregateOpts,
400) -> BoundExpression {
401 ListSum
402 .try_new_bound_expr(options, [input])
403 .vortex_expect("list-sum expressions require a numeric list child")
404}
405
406pub fn replace_time_zone(
411 input: Expression,
412 ambiguous: Expression,
413 options: ReplaceTimeZoneOptions,
414) -> Expression {
415 ReplaceTimeZone.new_expr(options, [input, ambiguous])
416}
417
418pub fn bound_replace_time_zone(
420 input: BoundExpression,
421 ambiguous: BoundExpression,
422 options: ReplaceTimeZoneOptions,
423) -> BoundExpression {
424 ReplaceTimeZone
425 .try_new_bound_expr(options, [input, ambiguous])
426 .vortex_expect("timezone replacement requires a timestamp and a UTF-8 ambiguity policy")
427}
428
429pub fn dynamic_with_options(options: DynamicComparisonExpr, lhs: Expression) -> Expression {
435 DynamicComparison.new_expr(options, [lhs])
436}
437
438pub fn bound_dynamic_with_options(
440 options: DynamicComparisonExpr,
441 lhs: BoundExpression,
442) -> BoundExpression {
443 DynamicComparison
444 .try_new_bound_expr(options, [lhs])
445 .vortex_expect("dynamic comparisons require a compatible left-hand dtype")
446}
447
448pub fn dynamic(
450 operator: CompareOperator,
451 rhs_value: impl Fn() -> Option<ScalarValue> + Send + Sync + 'static,
452 rhs_dtype: DType,
453 default: bool,
454 lhs: Expression,
455) -> Expression {
456 dynamic_with_options(
457 DynamicComparisonExpr {
458 operator,
459 rhs: Arc::new(Rhs {
460 value: Arc::new(rhs_value),
461 dtype: rhs_dtype,
462 }),
463 default,
464 },
465 lhs,
466 )
467}
468
469pub fn bound_dynamic(
471 operator: CompareOperator,
472 rhs_value: impl Fn() -> Option<ScalarValue> + Send + Sync + 'static,
473 rhs_dtype: DType,
474 default: bool,
475 lhs: BoundExpression,
476) -> BoundExpression {
477 bound_dynamic_with_options(
478 DynamicComparisonExpr {
479 operator,
480 rhs: Arc::new(Rhs {
481 value: Arc::new(rhs_value),
482 dtype: rhs_dtype,
483 }),
484 default,
485 },
486 lhs,
487 )
488}
489
490pub fn between(
509 arr: Expression,
510 lower: Expression,
511 upper: Expression,
512 options: BetweenOptions,
513) -> Expression {
514 Between
515 .try_new_expr(options, [arr, lower, upper])
516 .vortex_expect("Failed to create Between expression")
517}
518
519pub fn bound_between(
521 arr: BoundExpression,
522 lower: BoundExpression,
523 upper: BoundExpression,
524 options: BetweenOptions,
525) -> BoundExpression {
526 Between
527 .try_new_bound_expr(options, [arr, lower, upper])
528 .vortex_expect("between expressions require compatible operand dtypes")
529}
530
531pub fn list_contains(list: Expression, value: Expression) -> Expression {
544 list_contains_opts(list, value, ListContainsOptions::default())
545}
546
547pub fn list_contains_opts(
550 list: Expression,
551 value: Expression,
552 options: ListContainsOptions,
553) -> Expression {
554 ListContains.new_expr(options, [list, value])
555}
556
557pub fn in_list(needle: Expression, list: Expression) -> Expression {
567 list_contains_opts(
568 list,
569 needle,
570 ListContainsOptions {
571 sql_null_semantics: true,
572 },
573 )
574}
575
576pub fn in_list_of(
600 needle: Expression,
601 element_dtype: DType,
602 elements: Vec<Scalar>,
603) -> VortexResult<Expression> {
604 let element_dtype = if elements.iter().any(Scalar::is_null) {
605 element_dtype.as_nullable()
606 } else {
607 element_dtype.as_nonnullable()
608 };
609 let mut elements = elements
610 .iter()
611 .map(|element| {
612 vortex_ensure!(
613 element.dtype() == &DType::Null
614 || element.dtype().eq_ignore_nullability(&element_dtype),
615 "IN list element {element} is not of type {element_dtype}"
616 );
617 element.cast(&element_dtype)
618 })
619 .collect::<VortexResult<Vec<_>>>()?;
620
621 if let Some((low, high)) = contiguous_integer_bounds(&elements) {
622 let options = BetweenOptions {
623 lower_strict: StrictComparison::NonStrict,
624 upper_strict: StrictComparison::NonStrict,
625 };
626 return Ok(between(
627 needle,
628 lit(low.clone()),
629 lit(high.clone()),
630 options,
631 ));
632 }
633
634 if elements
638 .windows(2)
639 .all(|pair| pair[0].partial_cmp(&pair[1]).is_some())
640 {
641 elements.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));
642 elements.dedup();
643 }
644 let list = Scalar::list(Arc::new(element_dtype), elements, Nullability::NonNullable);
645 Ok(in_list(needle, lit(list)))
646}
647
648fn contiguous_integer_bounds(scalars: &[Scalar]) -> Option<(&Scalar, &Scalar)> {
651 let mut values = scalars
652 .iter()
653 .map(|scalar| {
654 if !matches!(scalar.dtype(), DType::Primitive(ptype, _) if ptype.is_int()) {
656 return None;
657 }
658 let primitive = scalar.as_primitive_opt()?;
659 let value = if primitive.ptype().is_unsigned_int() {
660 primitive.as_opt::<u64>()??.into()
661 } else {
662 i128::from(primitive.as_opt::<i64>()??)
663 };
664 Some((value, scalar))
665 })
666 .collect::<Option<Vec<(i128, &Scalar)>>>()?;
667 values.sort_unstable_by_key(|(value, _)| *value);
668 values.dedup_by_key(|(value, _)| *value);
669 let (low, low_scalar) = values.first()?;
670 let (high, high_scalar) = values.last()?;
671 (high - low + 1 == i128::try_from(values.len()).ok()?).then_some((*low_scalar, *high_scalar))
672}
673
674pub fn bound_list_contains(list: BoundExpression, value: BoundExpression) -> BoundExpression {
676 ListContains
677 .try_new_bound_expr(ListContainsOptions::default(), [list, value])
678 .vortex_expect("list-contains expressions require a list child")
679}
680
681pub fn bound_in_list(needle: BoundExpression, list: BoundExpression) -> BoundExpression {
683 ListContains
684 .try_new_bound_expr(
685 ListContainsOptions {
686 sql_null_semantics: true,
687 },
688 [list, needle],
689 )
690 .vortex_expect("list-contains expressions require a list child")
691}
692
693pub fn variant_get(
700 child: Expression,
701 path: impl Into<VariantPath>,
702 dtype: Option<DType>,
703) -> Expression {
704 VariantGet.new_expr(VariantGetOptions::new(path.into(), dtype), vec![child])
705}
706
707pub fn bound_variant_get(
709 child: BoundExpression,
710 path: impl Into<VariantPath>,
711 dtype: Option<DType>,
712) -> BoundExpression {
713 VariantGet
714 .try_new_bound_expr(VariantGetOptions::new(path.into(), dtype), [child])
715 .vortex_expect("variant-get expressions require a Variant child")
716}
717
718pub fn like(child: Expression, pattern: Expression) -> Expression {
722 Like.new_expr(
723 LikeOptions {
724 negated: false,
725 case_insensitive: false,
726 },
727 [child, pattern],
728 )
729}
730
731pub fn bound_like(child: BoundExpression, pattern: BoundExpression) -> BoundExpression {
733 bound_like_with_options(child, pattern, false, false)
734}
735
736pub fn ilike(child: Expression, pattern: Expression) -> Expression {
738 Like.new_expr(
739 LikeOptions {
740 negated: false,
741 case_insensitive: true,
742 },
743 [child, pattern],
744 )
745}
746
747pub fn bound_ilike(child: BoundExpression, pattern: BoundExpression) -> BoundExpression {
749 bound_like_with_options(child, pattern, false, true)
750}
751
752pub fn not_like(child: Expression, pattern: Expression) -> Expression {
754 Like.new_expr(
755 LikeOptions {
756 negated: true,
757 case_insensitive: false,
758 },
759 [child, pattern],
760 )
761}
762
763pub fn bound_not_like(child: BoundExpression, pattern: BoundExpression) -> BoundExpression {
765 bound_like_with_options(child, pattern, true, false)
766}
767
768pub fn not_ilike(child: Expression, pattern: Expression) -> Expression {
770 Like.new_expr(
771 LikeOptions {
772 negated: true,
773 case_insensitive: true,
774 },
775 [child, pattern],
776 )
777}
778
779pub fn bound_not_ilike(child: BoundExpression, pattern: BoundExpression) -> BoundExpression {
781 bound_like_with_options(child, pattern, true, true)
782}
783
784fn bound_like_with_options(
785 child: BoundExpression,
786 pattern: BoundExpression,
787 negated: bool,
788 case_insensitive: bool,
789) -> BoundExpression {
790 Like.try_new_bound_expr(
791 LikeOptions {
792 negated,
793 case_insensitive,
794 },
795 [child, pattern],
796 )
797 .vortex_expect("like expressions require UTF-8 or binary operands")
798}
799
800pub fn is_nan(child: Expression) -> Expression {
813 IsNan.new_expr(EmptyOptions, vec![child])
814}
815
816pub fn bound_is_nan(child: BoundExpression) -> BoundExpression {
818 IsNan
819 .try_new_bound_expr(EmptyOptions, [child])
820 .vortex_expect("is-nan expressions are always well-typed")
821}
822
823pub fn zip_expr(mask: Expression, if_true: Expression, if_false: Expression) -> Expression {
833 Zip.new_expr(EmptyOptions, [if_true, if_false, mask])
834}
835
836pub fn bound_zip_expr(
838 mask: BoundExpression,
839 if_true: BoundExpression,
840 if_false: BoundExpression,
841) -> BoundExpression {
842 Zip.try_new_bound_expr(EmptyOptions, [if_true, if_false, mask])
843 .vortex_expect("zip expressions require a boolean mask and compatible value dtypes")
844}
845
846pub fn dynamic_expression(
855 source: Arc<dyn DynamicExpressionSource>,
856 inputs: impl IntoIterator<Item = Expression>,
857) -> Expression {
858 DynamicExpression.new_expr(DynamicExpressionOptions::new(source), inputs)
859}
860
861pub fn bound_dynamic_expression(
863 source: Arc<dyn DynamicExpressionSource>,
864 inputs: impl IntoIterator<Item = BoundExpression>,
865) -> BoundExpression {
866 DynamicExpression
867 .try_new_bound_expr(DynamicExpressionOptions::new(source), inputs)
868 .vortex_expect("dynamic expressions accept any inputs")
869}
870
871pub fn list_transform(list: Expression, lambda: Lambda) -> Expression {
885 ListTransform.new_expr(ListTransformOptions::Lambda(lambda), [list])
886}
887
888pub fn is_null(child: Expression) -> Expression {
900 IsNull.new_expr(EmptyOptions, vec![child])
901}
902
903pub fn bound_is_null(child: BoundExpression) -> BoundExpression {
905 IsNull
906 .try_new_bound_expr(EmptyOptions, [child])
907 .vortex_expect("is-null expressions are always well-typed")
908}
909
910pub fn select(field_names: impl Into<FieldNames>, child: Expression) -> Expression {
921 Select
922 .try_new_expr(FieldSelection::Include(field_names.into()), [child])
923 .vortex_expect("Failed to create Select expression")
924}
925
926pub fn bound_select(field_names: impl Into<FieldNames>, child: BoundExpression) -> BoundExpression {
928 Select
929 .try_new_bound_expr(FieldSelection::Include(field_names.into()), [child])
930 .vortex_expect("select expressions require fields from a struct child")
931}
932
933pub fn select_exclude(fields: impl Into<FieldNames>, child: Expression) -> Expression {
943 Select
944 .try_new_expr(FieldSelection::Exclude(fields.into()), [child])
945 .vortex_expect("Failed to create Select expression")
946}
947
948pub fn bound_select_exclude(
950 fields: impl Into<FieldNames>,
951 child: BoundExpression,
952) -> BoundExpression {
953 Select
954 .try_new_bound_expr(FieldSelection::Exclude(fields.into()), [child])
955 .vortex_expect("select expressions require fields from a struct child")
956}
957
958pub mod bound {
959 pub use super::bound_between as between;
960 pub use super::bound_byte_length as byte_length;
961 pub use super::bound_case_when as case_when;
962 pub use super::bound_case_when_no_else as case_when_no_else;
963 pub use super::bound_dynamic as dynamic;
964 pub use super::bound_dynamic_expression as dynamic_expression;
965 pub use super::bound_dynamic_with_options as dynamic_with_options;
966 pub use super::bound_ext_storage as ext_storage;
967 pub use super::bound_ilike as ilike;
968 pub use super::bound_in_list as in_list;
969 pub use super::bound_is_nan as is_nan;
970 pub use super::bound_is_null as is_null;
971 pub use super::bound_like as like;
972 pub use super::bound_list_contains as list_contains;
973 pub use super::bound_list_length as list_length;
974 pub use super::bound_list_sum as list_sum;
975 pub use super::bound_list_sum_opts as list_sum_opts;
976 pub use super::bound_merge as merge;
977 pub use super::bound_merge_opts as merge_opts;
978 pub use super::bound_nested_case_when as nested_case_when;
979 pub use super::bound_not_ilike as not_ilike;
980 pub use super::bound_not_like as not_like;
981 pub use super::bound_replace_time_zone as replace_time_zone;
982 pub use super::bound_select as select;
983 pub use super::bound_select_exclude as select_exclude;
984 pub use super::bound_variant_get as variant_get;
985 pub use super::bound_zip_expr as zip_expr;
986}