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::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
64/// Creates a CASE WHEN expression with one WHEN/THEN pair and an ELSE value.
65pub 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
77/// Creates a bound CASE WHEN expression with one WHEN/THEN pair and an ELSE value.
78pub 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
92/// Creates a CASE WHEN expression with one WHEN/THEN pair and no ELSE value.
93pub 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
101/// Creates a bound CASE WHEN expression with one WHEN/THEN pair and no ELSE value.
102pub 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
115/// Creates an n-ary CASE WHEN expression from WHEN/THEN pairs and an optional ELSE value.
116pub 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
145/// Creates a bound n-ary CASE WHEN expression from WHEN/THEN pairs and an optional ELSE value.
146pub 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
177/// Creates an expression that merges struct expressions into a single struct.
178///
179/// Combines fields from all input expressions. If field names are duplicated,
180/// later expressions win. Fields are not recursively merged.
181///
182/// ```rust
183/// # use vortex_array::dtype::Nullability;
184/// # use vortex_functions::expr::merge;
185/// # use vortex_expr::{get_item, root};
186/// let expr = merge([get_item("a", root()), get_item("b", root())]);
187/// ```
188pub 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
194/// Creates a bound expression that merges struct expressions.
195pub fn bound_merge(elements: impl IntoIterator<Item = BoundExpression>) -> BoundExpression {
196    bound_merge_opts(elements, DuplicateHandling::default())
197}
198
199/// Creates a merge expression with explicit duplicate handling.
200pub 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
209/// Creates a bound merge expression with explicit duplicate handling.
210pub 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
219/// Creates an expression that computes the byte length of each element.
220/// This is akin to ANSI SQL OCTET_LENGTH(), or DuckDB's strlen().
221///
222/// ```rust
223/// # use vortex_functions::expr::byte_length;
224/// # use vortex_expr::root;
225/// let expr = byte_length(root());
226/// ```
227pub fn byte_length(input: Expression) -> Expression {
228    ByteLength.new_expr(EmptyOptions, [input])
229}
230
231/// Creates a bound expression that computes each element's byte length.
232pub 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
238/// Creates an expression that computes the Unicode lowercase of each string, like SQL `lower`.
239///
240/// ```rust
241/// # use vortex_functions::expr::lower;
242/// # use vortex_expr::root;
243/// let expr = lower(root());
244/// ```
245pub fn lower(input: Expression) -> Expression {
246    Lower.new_expr(EmptyOptions, [input])
247}
248
249/// Creates an expression that computes the one-based character position of `search` in
250/// `input`, or zero when absent, like SQL `strpos`.
251///
252/// ```rust
253/// # use vortex_functions::expr::strpos;
254/// # use vortex_expr::{lit, root};
255/// let expr = strpos(root(), lit("needle"));
256/// ```
257pub fn strpos(input: Expression, search: Expression) -> Expression {
258    Strpos.new_expr(EmptyOptions, [input, search])
259}
260
261/// Creates an expression that extracts the storage values from an extension array.
262///
263/// ```rust
264/// # use vortex_functions::expr::ext_storage;
265/// # use vortex_expr::root;
266/// let expr = ext_storage(root());
267/// ```
268pub fn ext_storage(input: Expression) -> Expression {
269    ExtStorage.new_expr(EmptyOptions, [input])
270}
271
272/// Creates a bound expression that extracts an extension array's storage values.
273pub 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
279/// Creates an expression that computes the number of elements in each list
280/// for `List` and `FixedSizeList` inputs. This is akin to ANSI SQL `CARDINALITY()`,
281/// or DuckDB's `len()`/`array_length()`.
282///
283/// ```rust
284/// # use vortex_functions::expr::list_length;
285/// # use vortex_expr::root;
286/// let expr = list_length(root());
287/// ```
288pub fn list_length(input: Expression) -> Expression {
289    ListLength.new_expr(EmptyOptions, [input])
290}
291
292/// Creates a bound expression that computes the number of elements in each list.
293pub 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
299/// Creates an expression that sums the elements of each list for `List` and
300/// `FixedSizeList` inputs, akin to DuckDB's `list_sum()`.
301///
302/// Follows SQL `SUM` semantics per list: null lists, empty lists, and lists whose elements are
303/// all null yield null; null elements are skipped; integer and decimal overflow yields a null
304/// value. The result dtype follows `sum`'s widening rules and is always nullable. NaN float
305/// elements are skipped by default; see [`list_sum_opts`] for the NaN-including variant.
306///
307/// ```rust
308/// # use vortex_functions::expr::list_sum;
309/// # use vortex_expr::root;
310/// let expr = list_sum(root());
311/// ```
312pub fn list_sum(input: Expression) -> Expression {
313    ListSum.new_expr(NumericalAggregateOpts::default(), [input])
314}
315
316/// Creates a bound expression that sums the elements of each list.
317pub 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
323/// Creates a [`list_sum`] expression with explicit [`NumericalAggregateOpts`], controlling
324/// whether NaN float elements are skipped (the default) or poison the list's sum to NaN.
325pub fn list_sum_opts(input: Expression, options: NumericalAggregateOpts) -> Expression {
326    ListSum.new_expr(options, [input])
327}
328
329/// Creates a bound list-sum expression with explicit aggregate options.
330pub 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
339/// Reinterpret timestamp wall times in `options.time_zone`, preserving the time unit.
340///
341/// `ambiguous` is a UTF-8 expression containing `raise`, `earliest`, `latest`, or `null`.
342/// Removing the timezone preserves wall time in a timezone-naive timestamp.
343pub fn replace_time_zone(
344    input: Expression,
345    ambiguous: Expression,
346    options: ReplaceTimeZoneOptions,
347) -> Expression {
348    ReplaceTimeZone.new_expr(options, [input, ambiguous])
349}
350
351/// Create a bound timezone replacement expression.
352pub 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
362/// Constructors for expressions whose children have already been bound and type-checked.
363///
364/// These mirror the constructors in [`vortex_expr`] and panic when the supplied children do not
365/// form a well-typed expression.
366/// Creates a dynamic comparison expression from its complete options.
367pub fn dynamic_with_options(options: DynamicComparisonExpr, lhs: Expression) -> Expression {
368    DynamicComparison.new_expr(options, [lhs])
369}
370
371/// Creates a bound dynamic comparison expression from its complete options.
372pub 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
381/// Creates a dynamic comparison expression.
382pub 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
402/// Creates a bound dynamic comparison expression.
403pub 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
423// ---- Between ----
424
425/// Creates an expression that checks if values are between two bounds.
426///
427/// Returns a boolean array indicating which values fall within the specified range.
428/// The comparison strictness is controlled by the options parameter.
429///
430/// ```rust
431/// # use vortex_functions::between::BetweenOptions;
432/// # use vortex_functions::between::StrictComparison;
433/// # use vortex_expr::{lit, root};
434/// # use vortex_functions::expr::between;
435/// let opts = BetweenOptions {
436///     lower_strict: StrictComparison::NonStrict,
437///     upper_strict: StrictComparison::NonStrict,
438/// };
439/// let expr = between(root(), lit(10), lit(20), opts);
440/// ```
441pub 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
452/// Creates a bound expression that checks if values are between two bounds.
453pub 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
464// ---- ListContains ----
465
466/// Creates an expression that checks whether a list contains a value.
467///
468/// A null element never matches anything: a needle that matches no element yields `false`. For
469/// SQL's three-valued `IN`, where a null element makes that `null`, use [`in_list`].
470///
471/// ```rust
472/// # use vortex_expr::{lit, root};
473/// # use vortex_functions::expr::list_contains;
474/// let expr = list_contains(root(), lit(42));
475/// ```
476pub fn list_contains(list: Expression, value: Expression) -> Expression {
477    list_contains_opts(list, value, ListContainsOptions::default())
478}
479
480/// Creates an expression that checks whether a list contains a value, with explicit
481/// [`ListContainsOptions`].
482pub fn list_contains_opts(
483    list: Expression,
484    value: Expression,
485    options: ListContainsOptions,
486) -> Expression {
487    ListContains.new_expr(options, [list, value])
488}
489
490/// Creates `needle IN (list)` with SQL null semantics: a null element is an unknown value, so a
491/// needle that matches no element yields `null` rather than `false` when the list holds one, and
492/// `not(in_list(..))` never admits such a row.
493///
494/// ```rust
495/// # use vortex_expr::{lit, root};
496/// # use vortex_functions::expr::in_list;
497/// let expr = in_list(root(), lit(vec![1, 2, 3]));
498/// ```
499pub 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
509/// Creates `needle IN (elements)` with SQL null semantics for a list of constant elements of
510/// `element_dtype`, ignoring nullability. An element can also be an untyped null.
511///
512/// The nullability of `element_dtype` is not used: the list elements are nullable only when a
513/// null element is present.
514///
515/// Non-null integers that hold every value between their smallest and largest become a range
516/// check, which is cheaper to evaluate and prunes with tighter bounds than a set lookup, as for
517/// the keys of a small dimension table that a join pushes down.
518///
519/// # Errors
520///
521/// Returns an error if an element is not a null and not of `element_dtype`.
522///
523/// ```rust
524/// # use vortex_array::dtype::{DType, Nullability, PType};
525/// # use vortex_expr::root;
526/// # use vortex_functions::expr::in_list_of;
527/// let dtype = DType::Primitive(PType::I32, Nullability::NonNullable);
528/// let expr = in_list_of(root(), dtype, vec![3i32.into(), 1i32.into(), 2i32.into()])?;
529/// assert_eq!(expr.to_string(), "(1i32 <= $ <= 3i32)");
530/// # Ok::<(), vortex_error::VortexError>(())
531/// ```
532pub 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    // Ordered elements make equal lists from the same set, so that equal filters deduplicate.
568    // An engine can build a list from the keys of a hash join, which repeat, and each repeat makes
569    // the lookup more costly, so equal elements are removed. One null keeps the SQL semantics.
570    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
581/// The smallest and largest of non-null integer `scalars` when they hold every integer between
582/// those two.
583fn contiguous_integer_bounds(scalars: &[Scalar]) -> Option<(&Scalar, &Scalar)> {
584    let mut values = scalars
585        .iter()
586        .map(|scalar| {
587            // Viewing a scalar of another type as a primitive builds an error, which is costly.
588            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
607/// Creates a bound expression that checks whether a list contains a value.
608pub 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
614/// Creates a bound `needle IN (list)` with SQL null semantics. See [`in_list`].
615pub 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
626// ---- VariantGet ----
627
628/// Creates an expression that extracts a path from a Variant expression.
629///
630/// Missing paths, traversal mismatches, and failed casts return null. When `dtype` is `None`,
631/// results are nullable Variant values; otherwise results are nullable values of `dtype`.
632pub 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
640/// Creates a bound expression that extracts a path from a Variant expression.
641pub 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
651// ---- Like ----
652
653/// Creates a SQL LIKE expression.
654pub 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
664/// Creates a bound SQL LIKE expression.
665pub fn bound_like(child: BoundExpression, pattern: BoundExpression) -> BoundExpression {
666    bound_like_with_options(child, pattern, false, false)
667}
668
669/// Creates a case-insensitive SQL ILIKE expression.
670pub 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
680/// Creates a bound case-insensitive SQL ILIKE expression.
681pub fn bound_ilike(child: BoundExpression, pattern: BoundExpression) -> BoundExpression {
682    bound_like_with_options(child, pattern, false, true)
683}
684
685/// Creates a negated SQL NOT LIKE expression.
686pub 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
696/// Creates a bound negated SQL NOT LIKE expression.
697pub fn bound_not_like(child: BoundExpression, pattern: BoundExpression) -> BoundExpression {
698    bound_like_with_options(child, pattern, true, false)
699}
700
701/// Creates a negated case-insensitive SQL NOT ILIKE expression.
702pub 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
712/// Creates a bound negated case-insensitive SQL NOT ILIKE expression.
713pub 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
733// ---- IsNan ----
734
735/// Creates an expression that checks for NaN values.
736///
737/// The expression is strict: null inputs produce null outputs, so the output nullability
738/// follows the input. Only primitive float inputs are supported.
739///
740/// ```rust
741/// # use vortex_expr::root;
742/// # use vortex_functions::expr::is_nan;
743/// let expr = is_nan(root());
744/// ```
745pub fn is_nan(child: Expression) -> Expression {
746    IsNan.new_expr(EmptyOptions, vec![child])
747}
748
749/// Creates a bound expression that checks for NaN values.
750pub 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
756// ---- Zip ----
757
758/// Creates a zip expression that conditionally selects between two arrays.
759///
760/// ```rust
761/// # use vortex_expr::{lit, root};
762/// # use vortex_functions::expr::zip_expr;
763/// let expr = zip_expr(lit(true), root(), lit(0i32));
764/// ```
765pub fn zip_expr(mask: Expression, if_true: Expression, if_false: Expression) -> Expression {
766    Zip.new_expr(EmptyOptions, [if_true, if_false, mask])
767}
768
769/// Creates a bound zip expression that conditionally selects between two arrays.
770pub 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
779// ---- DynamicExpression ----
780
781/// Creates a dynamic expression that evaluates the current predicate of `source`.
782///
783/// The `inputs` are the expressions that every predicate of the source can read. A predicate
784/// reads input `i` as the field named by
785/// [`input_field_name(i)`](crate::dynamic_expression::input_field_name) of its
786/// scope.
787pub 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
794/// Creates a bound dynamic expression that evaluates the current predicate of `source`.
795pub 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
804// ---- ListTransform ----
805
806/// Creates an expression that applies a lambda to every element of each list.
807///
808/// The lambda takes one parameter, the element.
809///
810/// ```rust
811/// # use vortex_expr::{Lambda, checked_add, col, lit, var};
812/// # use vortex_functions::expr::list_transform;
813/// let lambda = Lambda::new(["x"], checked_add(var("x"), lit(1_i32))).unwrap();
814/// let expr = list_transform(col("l"), lambda);
815/// assert_eq!(expr.to_string(), "vortex.list.transform($.l, (x) -> (@x + 1i32))");
816/// ```
817pub fn list_transform(list: Expression, lambda: Lambda) -> Expression {
818    ListTransform.new_expr(ListTransformOptions::Lambda(lambda), [list])
819}
820
821// ---- IsNull ----
822
823/// Creates an expression that checks for null values.
824///
825/// Returns a boolean array indicating which positions contain null values.
826///
827/// ```rust
828/// # use vortex_expr::root;
829/// # use vortex_functions::expr::is_null;
830/// let expr = is_null(root());
831/// ```
832pub fn is_null(child: Expression) -> Expression {
833    IsNull.new_expr(EmptyOptions, vec![child])
834}
835
836/// Creates a bound expression that checks for null values.
837pub 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
843// ---- Select ----
844
845/// Creates an expression that selects (includes) specific fields from an array.
846///
847/// Projects only the specified fields from the child expression, which must be of DType struct.
848/// ```rust
849/// # use vortex_functions::expr::select;
850/// # use vortex_expr::root;
851/// let expr = select(["name", "age"], root());
852/// ```
853pub 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
859/// Creates a bound expression that selects specific fields from a struct expression.
860pub 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
866/// Creates an expression that excludes specific fields from an array.
867///
868/// Projects all fields except the specified ones from the input struct expression.
869///
870/// ```rust
871/// # use vortex_functions::expr::select_exclude;
872/// # use vortex_expr::root;
873/// let expr = select_exclude(["internal_id", "metadata"], root());
874/// ```
875pub 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
881/// Creates a bound expression that excludes specific fields from a struct expression.
882pub 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}