Skip to main content

vortex_functions/
expr.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4//! Expression constructors for this crate's scalar functions.
5//!
6//! These complement the constructors in `vortex_expr`.
7
8use 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
72/// Convert a [`Date`], [`Time`], or [`Timestamp`] to a coarser `unit` with an explicit
73/// [`TemporalRounding`].
74///
75/// `unit` **must** be coarser than the input unit and valid for the input type (a [`Date`]
76/// supports only days and milliseconds), or binding fails. At execution,
77/// [`TemporalRounding::Exact`] fails on a count with a remainder, and a [`Time`] fails when it
78/// rounds up to midnight, because the result must stay within the same day. A [`Timestamp`] keeps
79/// its time zone, and nulls stay null.
80///
81/// [`Date`]: vortex_array::extension::datetime::Date
82/// [`Time`]: vortex_array::extension::datetime::Time
83/// [`Timestamp`]: vortex_array::extension::datetime::Timestamp
84pub 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
92/// Change the time zone of a [`Timestamp`] and keep its instant, so the stored count does not
93/// change.
94///
95/// The input **must** be a [`Timestamp`] with a time zone, or binding fails. Use
96/// [`replace_time_zone`] to keep the local clock time in another zone instead.
97///
98/// [`Timestamp`]: vortex_array::extension::datetime::Timestamp
99pub 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
108/// Extract the local calendar date of a [`Timestamp`] as a [`Date`] in days.
109///
110/// A timestamp with a time zone uses the offset of that zone at its instant, and a timestamp
111/// without a time zone already counts local time. The input **must** be a [`Timestamp`], or
112/// binding fails. A date outside the `i32` range of days fails at execution.
113///
114/// [`Date`]: vortex_array::extension::datetime::Date
115/// [`Timestamp`]: vortex_array::extension::datetime::Timestamp
116pub fn timestamp_to_date(input: Expression) -> Expression {
117    TimestampToDate.new_expr(EmptyOptions, [input])
118}
119
120/// Extract the local time of day of a [`Timestamp`] as a [`Time`] in the same unit.
121///
122/// The time zone applies as in [`timestamp_to_date`]. The input **must** be a [`Timestamp`], or
123/// binding fails.
124///
125/// [`Time`]: vortex_array::extension::datetime::Time
126/// [`Timestamp`]: vortex_array::extension::datetime::Timestamp
127pub fn timestamp_to_time(input: Expression) -> Expression {
128    TimestampToTime.new_expr(EmptyOptions, [input])
129}
130
131/// Creates a CASE WHEN expression with one WHEN/THEN pair and an ELSE value.
132pub 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
144/// Creates a bound CASE WHEN expression with one WHEN/THEN pair and an ELSE value.
145pub 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
159/// Creates a CASE WHEN expression with one WHEN/THEN pair and no ELSE value.
160pub 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
168/// Creates a bound CASE WHEN expression with one WHEN/THEN pair and no ELSE value.
169pub 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
182/// Creates an n-ary CASE WHEN expression from WHEN/THEN pairs and an optional ELSE value.
183pub 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
212/// Creates a bound n-ary CASE WHEN expression from WHEN/THEN pairs and an optional ELSE value.
213pub 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
244/// Creates an expression that merges struct expressions into a single struct.
245///
246/// Combines fields from all input expressions. If field names are duplicated,
247/// later expressions win. Fields are not recursively merged.
248///
249/// ```rust
250/// # use vortex_array::dtype::Nullability;
251/// # use vortex_functions::expr::merge;
252/// # use vortex_expr::{get_item, root};
253/// let expr = merge([get_item("a", root()), get_item("b", root())]);
254/// ```
255pub 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
261/// Creates a bound expression that merges struct expressions.
262pub fn bound_merge(elements: impl IntoIterator<Item = BoundExpression>) -> BoundExpression {
263    bound_merge_opts(elements, DuplicateHandling::default())
264}
265
266/// Creates a merge expression with explicit duplicate handling.
267pub 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
276/// Creates a bound merge expression with explicit duplicate handling.
277pub 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
286/// Creates an expression that computes the byte length of each element.
287/// This is akin to ANSI SQL OCTET_LENGTH(), or DuckDB's strlen().
288///
289/// ```rust
290/// # use vortex_functions::expr::byte_length;
291/// # use vortex_expr::root;
292/// let expr = byte_length(root());
293/// ```
294pub fn byte_length(input: Expression) -> Expression {
295    ByteLength.new_expr(EmptyOptions, [input])
296}
297
298/// Creates a bound expression that computes each element's byte length.
299pub 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
305/// Creates an expression that computes the Unicode lowercase of each string, like SQL `lower`.
306///
307/// ```rust
308/// # use vortex_functions::expr::lower;
309/// # use vortex_expr::root;
310/// let expr = lower(root());
311/// ```
312pub fn lower(input: Expression) -> Expression {
313    Lower.new_expr(EmptyOptions, [input])
314}
315
316/// Creates an expression that computes the one-based character position of `search` in
317/// `input`, or zero when absent, like SQL `strpos`.
318///
319/// ```rust
320/// # use vortex_functions::expr::strpos;
321/// # use vortex_expr::{lit, root};
322/// let expr = strpos(root(), lit("needle"));
323/// ```
324pub fn strpos(input: Expression, search: Expression) -> Expression {
325    Strpos.new_expr(EmptyOptions, [input, search])
326}
327
328/// Creates an expression that extracts the storage values from an extension array.
329///
330/// ```rust
331/// # use vortex_functions::expr::ext_storage;
332/// # use vortex_expr::root;
333/// let expr = ext_storage(root());
334/// ```
335pub fn ext_storage(input: Expression) -> Expression {
336    ExtStorage.new_expr(EmptyOptions, [input])
337}
338
339/// Creates a bound expression that extracts an extension array's storage values.
340pub 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
346/// Creates an expression that computes the number of elements in each list
347/// for `List` and `FixedSizeList` inputs. This is akin to ANSI SQL `CARDINALITY()`,
348/// or DuckDB's `len()`/`array_length()`.
349///
350/// ```rust
351/// # use vortex_functions::expr::list_length;
352/// # use vortex_expr::root;
353/// let expr = list_length(root());
354/// ```
355pub fn list_length(input: Expression) -> Expression {
356    ListLength.new_expr(EmptyOptions, [input])
357}
358
359/// Creates a bound expression that computes the number of elements in each list.
360pub 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
366/// Creates an expression that sums the elements of each list for `List` and
367/// `FixedSizeList` inputs, akin to DuckDB's `list_sum()`.
368///
369/// Follows SQL `SUM` semantics per list: null lists, empty lists, and lists whose elements are
370/// all null yield null; null elements are skipped; integer and decimal overflow yields a null
371/// value. The result dtype follows `sum`'s widening rules and is always nullable. NaN float
372/// elements are skipped by default; see [`list_sum_opts`] for the NaN-including variant.
373///
374/// ```rust
375/// # use vortex_functions::expr::list_sum;
376/// # use vortex_expr::root;
377/// let expr = list_sum(root());
378/// ```
379pub fn list_sum(input: Expression) -> Expression {
380    ListSum.new_expr(NumericalAggregateOpts::default(), [input])
381}
382
383/// Creates a bound expression that sums the elements of each list.
384pub 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
390/// Creates a [`list_sum`] expression with explicit [`NumericalAggregateOpts`], controlling
391/// whether NaN float elements are skipped (the default) or poison the list's sum to NaN.
392pub fn list_sum_opts(input: Expression, options: NumericalAggregateOpts) -> Expression {
393    ListSum.new_expr(options, [input])
394}
395
396/// Creates a bound list-sum expression with explicit aggregate options.
397pub 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
406/// Reinterpret timestamp wall times in `options.time_zone`, preserving the time unit.
407///
408/// `ambiguous` is a UTF-8 expression containing `raise`, `earliest`, `latest`, or `null`.
409/// Removing the timezone preserves wall time in a timezone-naive timestamp.
410pub fn replace_time_zone(
411    input: Expression,
412    ambiguous: Expression,
413    options: ReplaceTimeZoneOptions,
414) -> Expression {
415    ReplaceTimeZone.new_expr(options, [input, ambiguous])
416}
417
418/// Create a bound timezone replacement expression.
419pub 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
429/// Constructors for expressions whose children have already been bound and type-checked.
430///
431/// These mirror the constructors in [`vortex_expr`] and panic when the supplied children do not
432/// form a well-typed expression.
433/// Creates a dynamic comparison expression from its complete options.
434pub fn dynamic_with_options(options: DynamicComparisonExpr, lhs: Expression) -> Expression {
435    DynamicComparison.new_expr(options, [lhs])
436}
437
438/// Creates a bound dynamic comparison expression from its complete options.
439pub 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
448/// Creates a dynamic comparison expression.
449pub 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
469/// Creates a bound dynamic comparison expression.
470pub 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
490// ---- Between ----
491
492/// Creates an expression that checks if values are between two bounds.
493///
494/// Returns a boolean array indicating which values fall within the specified range.
495/// The comparison strictness is controlled by the options parameter.
496///
497/// ```rust
498/// # use vortex_functions::between::BetweenOptions;
499/// # use vortex_functions::between::StrictComparison;
500/// # use vortex_expr::{lit, root};
501/// # use vortex_functions::expr::between;
502/// let opts = BetweenOptions {
503///     lower_strict: StrictComparison::NonStrict,
504///     upper_strict: StrictComparison::NonStrict,
505/// };
506/// let expr = between(root(), lit(10), lit(20), opts);
507/// ```
508pub 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
519/// Creates a bound expression that checks if values are between two bounds.
520pub 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
531// ---- ListContains ----
532
533/// Creates an expression that checks whether a list contains a value.
534///
535/// A null element never matches anything: a needle that matches no element yields `false`. For
536/// SQL's three-valued `IN`, where a null element makes that `null`, use [`in_list`].
537///
538/// ```rust
539/// # use vortex_expr::{lit, root};
540/// # use vortex_functions::expr::list_contains;
541/// let expr = list_contains(root(), lit(42));
542/// ```
543pub fn list_contains(list: Expression, value: Expression) -> Expression {
544    list_contains_opts(list, value, ListContainsOptions::default())
545}
546
547/// Creates an expression that checks whether a list contains a value, with explicit
548/// [`ListContainsOptions`].
549pub fn list_contains_opts(
550    list: Expression,
551    value: Expression,
552    options: ListContainsOptions,
553) -> Expression {
554    ListContains.new_expr(options, [list, value])
555}
556
557/// Creates `needle IN (list)` with SQL null semantics: a null element is an unknown value, so a
558/// needle that matches no element yields `null` rather than `false` when the list holds one, and
559/// `not(in_list(..))` never admits such a row.
560///
561/// ```rust
562/// # use vortex_expr::{lit, root};
563/// # use vortex_functions::expr::in_list;
564/// let expr = in_list(root(), lit(vec![1, 2, 3]));
565/// ```
566pub 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
576/// Creates `needle IN (elements)` with SQL null semantics for a list of constant elements of
577/// `element_dtype`, ignoring nullability. An element can also be an untyped null.
578///
579/// The nullability of `element_dtype` is not used: the list elements are nullable only when a
580/// null element is present.
581///
582/// Non-null integers that hold every value between their smallest and largest become a range
583/// check, which is cheaper to evaluate and prunes with tighter bounds than a set lookup, as for
584/// the keys of a small dimension table that a join pushes down.
585///
586/// # Errors
587///
588/// Returns an error if an element is not a null and not of `element_dtype`.
589///
590/// ```rust
591/// # use vortex_array::dtype::{DType, Nullability, PType};
592/// # use vortex_expr::root;
593/// # use vortex_functions::expr::in_list_of;
594/// let dtype = DType::Primitive(PType::I32, Nullability::NonNullable);
595/// let expr = in_list_of(root(), dtype, vec![3i32.into(), 1i32.into(), 2i32.into()])?;
596/// assert_eq!(expr.to_string(), "(1i32 <= $ <= 3i32)");
597/// # Ok::<(), vortex_error::VortexError>(())
598/// ```
599pub 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    // Ordered elements make equal lists from the same set, so that equal filters deduplicate.
635    // An engine can build a list from the keys of a hash join, which repeat, and each repeat makes
636    // the lookup more costly, so equal elements are removed. One null keeps the SQL semantics.
637    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
648/// The smallest and largest of non-null integer `scalars` when they hold every integer between
649/// those two.
650fn contiguous_integer_bounds(scalars: &[Scalar]) -> Option<(&Scalar, &Scalar)> {
651    let mut values = scalars
652        .iter()
653        .map(|scalar| {
654            // Viewing a scalar of another type as a primitive builds an error, which is costly.
655            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
674/// Creates a bound expression that checks whether a list contains a value.
675pub 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
681/// Creates a bound `needle IN (list)` with SQL null semantics. See [`in_list`].
682pub 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
693// ---- VariantGet ----
694
695/// Creates an expression that extracts a path from a Variant expression.
696///
697/// Missing paths, traversal mismatches, and failed casts return null. When `dtype` is `None`,
698/// results are nullable Variant values; otherwise results are nullable values of `dtype`.
699pub 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
707/// Creates a bound expression that extracts a path from a Variant expression.
708pub 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
718// ---- Like ----
719
720/// Creates a SQL LIKE expression.
721pub 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
731/// Creates a bound SQL LIKE expression.
732pub fn bound_like(child: BoundExpression, pattern: BoundExpression) -> BoundExpression {
733    bound_like_with_options(child, pattern, false, false)
734}
735
736/// Creates a case-insensitive SQL ILIKE expression.
737pub 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
747/// Creates a bound case-insensitive SQL ILIKE expression.
748pub fn bound_ilike(child: BoundExpression, pattern: BoundExpression) -> BoundExpression {
749    bound_like_with_options(child, pattern, false, true)
750}
751
752/// Creates a negated SQL NOT LIKE expression.
753pub 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
763/// Creates a bound negated SQL NOT LIKE expression.
764pub fn bound_not_like(child: BoundExpression, pattern: BoundExpression) -> BoundExpression {
765    bound_like_with_options(child, pattern, true, false)
766}
767
768/// Creates a negated case-insensitive SQL NOT ILIKE expression.
769pub 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
779/// Creates a bound negated case-insensitive SQL NOT ILIKE expression.
780pub 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
800// ---- IsNan ----
801
802/// Creates an expression that checks for NaN values.
803///
804/// The expression is strict: null inputs produce null outputs, so the output nullability
805/// follows the input. Only primitive float inputs are supported.
806///
807/// ```rust
808/// # use vortex_expr::root;
809/// # use vortex_functions::expr::is_nan;
810/// let expr = is_nan(root());
811/// ```
812pub fn is_nan(child: Expression) -> Expression {
813    IsNan.new_expr(EmptyOptions, vec![child])
814}
815
816/// Creates a bound expression that checks for NaN values.
817pub 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
823// ---- Zip ----
824
825/// Creates a zip expression that conditionally selects between two arrays.
826///
827/// ```rust
828/// # use vortex_expr::{lit, root};
829/// # use vortex_functions::expr::zip_expr;
830/// let expr = zip_expr(lit(true), root(), lit(0i32));
831/// ```
832pub fn zip_expr(mask: Expression, if_true: Expression, if_false: Expression) -> Expression {
833    Zip.new_expr(EmptyOptions, [if_true, if_false, mask])
834}
835
836/// Creates a bound zip expression that conditionally selects between two arrays.
837pub 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
846// ---- DynamicExpression ----
847
848/// Creates a dynamic expression that evaluates the current predicate of `source`.
849///
850/// The `inputs` are the expressions that every predicate of the source can read. A predicate
851/// reads input `i` as the field named by
852/// [`input_field_name(i)`](crate::dynamic_expression::input_field_name) of its
853/// scope.
854pub 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
861/// Creates a bound dynamic expression that evaluates the current predicate of `source`.
862pub 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
871// ---- ListTransform ----
872
873/// Creates an expression that applies a lambda to every element of each list.
874///
875/// The lambda takes one parameter, the element.
876///
877/// ```rust
878/// # use vortex_expr::{Lambda, checked_add, col, lit, var};
879/// # use vortex_functions::expr::list_transform;
880/// let lambda = Lambda::new(["x"], checked_add(var("x"), lit(1_i32))).unwrap();
881/// let expr = list_transform(col("l"), lambda);
882/// assert_eq!(expr.to_string(), "vortex.list.transform($.l, (x) -> (@x + 1i32))");
883/// ```
884pub fn list_transform(list: Expression, lambda: Lambda) -> Expression {
885    ListTransform.new_expr(ListTransformOptions::Lambda(lambda), [list])
886}
887
888// ---- IsNull ----
889
890/// Creates an expression that checks for null values.
891///
892/// Returns a boolean array indicating which positions contain null values.
893///
894/// ```rust
895/// # use vortex_expr::root;
896/// # use vortex_functions::expr::is_null;
897/// let expr = is_null(root());
898/// ```
899pub fn is_null(child: Expression) -> Expression {
900    IsNull.new_expr(EmptyOptions, vec![child])
901}
902
903/// Creates a bound expression that checks for null values.
904pub 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
910// ---- Select ----
911
912/// Creates an expression that selects (includes) specific fields from an array.
913///
914/// Projects only the specified fields from the child expression, which must be of DType struct.
915/// ```rust
916/// # use vortex_functions::expr::select;
917/// # use vortex_expr::root;
918/// let expr = select(["name", "age"], root());
919/// ```
920pub 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
926/// Creates a bound expression that selects specific fields from a struct expression.
927pub 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
933/// Creates an expression that excludes specific fields from an array.
934///
935/// Projects all fields except the specified ones from the input struct expression.
936///
937/// ```rust
938/// # use vortex_functions::expr::select_exclude;
939/// # use vortex_expr::root;
940/// let expr = select_exclude(["internal_id", "metadata"], root());
941/// ```
942pub 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
948/// Creates a bound expression that excludes specific fields from a struct expression.
949pub 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}