vortex-functions 0.95.0

Vortex scalar functions beyond those the core array crate relies on
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright the Vortex contributors

//! Expression constructors for this crate's scalar functions.
//!
//! These complement the constructors in `vortex_expr`.

use std::sync::Arc;

use vortex_array::aggregate_fn::NumericalAggregateOpts;
use vortex_array::dtype::DType;
use vortex_array::dtype::FieldNames;
use vortex_array::dtype::Nullability;
use vortex_array::expr::BoundExpression;
use vortex_array::extension::datetime::TemporalRounding;
use vortex_array::extension::datetime::TimeUnit;
use vortex_array::scalar::Scalar;
use vortex_array::scalar::ScalarValue;
use vortex_array::scalar_fn::EmptyOptions;
use vortex_array::scalar_fn::builtin::operators::CompareOperator;
use vortex_error::VortexExpect;
use vortex_error::VortexResult;
use vortex_error::vortex_ensure;
use vortex_error::vortex_panic;
use vortex_expr::Expression;
use vortex_expr::Lambda;
use vortex_expr::ScalarFnExprExt;
use vortex_expr::lit;

use crate::between::Between;
use crate::between::BetweenOptions;
use crate::between::StrictComparison;
use crate::byte_length::ByteLength;
use crate::case_when::CaseWhen;
use crate::case_when::CaseWhenOptions;
use crate::change_time_unit::ChangeTimeUnit;
use crate::change_time_unit::ChangeTimeUnitOptions;
use crate::convert_time_zone::ConvertTimeZone;
use crate::convert_time_zone::ConvertTimeZoneOptions;
use crate::dynamic::DynamicComparison;
use crate::dynamic::DynamicComparisonExpr;
use crate::dynamic::Rhs;
use crate::dynamic_expression::DynamicExpression;
use crate::dynamic_expression::DynamicExpressionOptions;
use crate::dynamic_expression::DynamicExpressionSource;
use crate::ext_storage::ExtStorage;
use crate::is_nan::IsNan;
use crate::is_null::IsNull;
use crate::like::Like;
use crate::like::LikeOptions;
use crate::list_contains::ListContains;
use crate::list_contains::ListContainsOptions;
use crate::list_length::ListLength;
use crate::list_sum::ListSum;
use crate::list_transform::ListTransform;
use crate::list_transform::ListTransformOptions;
use crate::lower::Lower;
use crate::merge::DuplicateHandling;
use crate::merge::Merge;
use crate::replace_time_zone::ReplaceTimeZone;
use crate::replace_time_zone::ReplaceTimeZoneOptions;
use crate::select::FieldSelection;
use crate::select::Select;
use crate::strpos::Strpos;
use crate::timestamp_to_date::TimestampToDate;
use crate::timestamp_to_time::TimestampToTime;
use crate::variant_get::VariantGet;
use crate::variant_get::VariantGetOptions;
use crate::variant_get::VariantPath;
use crate::zip::Zip;

/// Convert a [`Date`], [`Time`], or [`Timestamp`] to a coarser `unit` with an explicit
/// [`TemporalRounding`].
///
/// `unit` **must** be coarser than the input unit and valid for the input type (a [`Date`]
/// supports only days and milliseconds), or binding fails. At execution,
/// [`TemporalRounding::Exact`] fails on a count with a remainder, and a [`Time`] fails when it
/// rounds up to midnight, because the result must stay within the same day. A [`Timestamp`] keeps
/// its time zone, and nulls stay null.
///
/// [`Date`]: vortex_array::extension::datetime::Date
/// [`Time`]: vortex_array::extension::datetime::Time
/// [`Timestamp`]: vortex_array::extension::datetime::Timestamp
pub fn change_time_unit(
    input: Expression,
    unit: TimeUnit,
    rounding: TemporalRounding,
) -> Expression {
    ChangeTimeUnit.new_expr(ChangeTimeUnitOptions { unit, rounding }, [input])
}

/// Change the time zone of a [`Timestamp`] and keep its instant, so the stored count does not
/// change.
///
/// The input **must** be a [`Timestamp`] with a time zone, or binding fails. Use
/// [`replace_time_zone`] to keep the local clock time in another zone instead.
///
/// [`Timestamp`]: vortex_array::extension::datetime::Timestamp
pub fn convert_time_zone(input: Expression, time_zone: impl Into<Arc<str>>) -> Expression {
    ConvertTimeZone.new_expr(
        ConvertTimeZoneOptions {
            time_zone: time_zone.into(),
        },
        [input],
    )
}

/// Extract the local calendar date of a [`Timestamp`] as a [`Date`] in days.
///
/// A timestamp with a time zone uses the offset of that zone at its instant, and a timestamp
/// without a time zone already counts local time. The input **must** be a [`Timestamp`], or
/// binding fails. A date outside the `i32` range of days fails at execution.
///
/// [`Date`]: vortex_array::extension::datetime::Date
/// [`Timestamp`]: vortex_array::extension::datetime::Timestamp
pub fn timestamp_to_date(input: Expression) -> Expression {
    TimestampToDate.new_expr(EmptyOptions, [input])
}

/// Extract the local time of day of a [`Timestamp`] as a [`Time`] in the same unit.
///
/// The time zone applies as in [`timestamp_to_date`]. The input **must** be a [`Timestamp`], or
/// binding fails.
///
/// [`Time`]: vortex_array::extension::datetime::Time
/// [`Timestamp`]: vortex_array::extension::datetime::Timestamp
pub fn timestamp_to_time(input: Expression) -> Expression {
    TimestampToTime.new_expr(EmptyOptions, [input])
}

/// Creates a CASE WHEN expression with one WHEN/THEN pair and an ELSE value.
pub fn case_when(
    condition: Expression,
    then_value: Expression,
    else_value: Expression,
) -> Expression {
    let options = CaseWhenOptions {
        num_when_then_pairs: 1,
        has_else: true,
    };
    CaseWhen.new_expr(options, [condition, then_value, else_value])
}

/// Creates a bound CASE WHEN expression with one WHEN/THEN pair and an ELSE value.
pub fn bound_case_when(
    condition: BoundExpression,
    then_value: BoundExpression,
    else_value: BoundExpression,
) -> BoundExpression {
    let options = CaseWhenOptions {
        num_when_then_pairs: 1,
        has_else: true,
    };
    CaseWhen
        .try_new_bound_expr(options, [condition, then_value, else_value])
        .vortex_expect("case expressions must have boolean conditions and matching branch dtypes")
}

/// Creates a CASE WHEN expression with one WHEN/THEN pair and no ELSE value.
pub fn case_when_no_else(condition: Expression, then_value: Expression) -> Expression {
    let options = CaseWhenOptions {
        num_when_then_pairs: 1,
        has_else: false,
    };
    CaseWhen.new_expr(options, [condition, then_value])
}

/// Creates a bound CASE WHEN expression with one WHEN/THEN pair and no ELSE value.
pub fn bound_case_when_no_else(
    condition: BoundExpression,
    then_value: BoundExpression,
) -> BoundExpression {
    let options = CaseWhenOptions {
        num_when_then_pairs: 1,
        has_else: false,
    };
    CaseWhen
        .try_new_bound_expr(options, [condition, then_value])
        .vortex_expect("case expressions must have boolean conditions")
}

/// Creates an n-ary CASE WHEN expression from WHEN/THEN pairs and an optional ELSE value.
pub fn nested_case_when(
    when_then_pairs: Vec<(Expression, Expression)>,
    else_value: Option<Expression>,
) -> Expression {
    assert!(
        !when_then_pairs.is_empty(),
        "nested_case_when requires at least one when/then pair"
    );

    let has_else = else_value.is_some();
    let mut children = Vec::with_capacity(when_then_pairs.len() * 2 + usize::from(has_else));
    for (condition, then_value) in &when_then_pairs {
        children.push(condition.clone());
        children.push(then_value.clone());
    }
    if let Some(else_expr) = else_value {
        children.push(else_expr);
    }

    let Ok(num_when_then_pairs) = u32::try_from(when_then_pairs.len()) else {
        vortex_panic!("nested_case_when has too many when/then pairs");
    };
    let options = CaseWhenOptions {
        num_when_then_pairs,
        has_else,
    };
    CaseWhen.new_expr(options, children)
}

/// Creates a bound n-ary CASE WHEN expression from WHEN/THEN pairs and an optional ELSE value.
pub fn bound_nested_case_when(
    when_then_pairs: Vec<(BoundExpression, BoundExpression)>,
    else_value: Option<BoundExpression>,
) -> BoundExpression {
    assert!(
        !when_then_pairs.is_empty(),
        "nested_case_when requires at least one when/then pair"
    );

    let Ok(num_when_then_pairs) = u32::try_from(when_then_pairs.len()) else {
        vortex_panic!("nested_case_when has too many when/then pairs");
    };
    let has_else = else_value.is_some();
    let mut children = Vec::with_capacity(when_then_pairs.len() * 2 + usize::from(has_else));
    for (condition, then_value) in when_then_pairs {
        children.push(condition);
        children.push(then_value);
    }
    if let Some(else_expr) = else_value {
        children.push(else_expr);
    }

    let options = CaseWhenOptions {
        num_when_then_pairs,
        has_else,
    };
    CaseWhen
        .try_new_bound_expr(options, children)
        .vortex_expect("case expressions must have boolean conditions and matching branch dtypes")
}

/// Creates an expression that merges struct expressions into a single struct.
///
/// Combines fields from all input expressions. If field names are duplicated,
/// later expressions win. Fields are not recursively merged.
///
/// ```rust
/// # use vortex_array::dtype::Nullability;
/// # use vortex_functions::expr::merge;
/// # use vortex_expr::{get_item, root};
/// let expr = merge([get_item("a", root()), get_item("b", root())]);
/// ```
pub fn merge(elements: impl IntoIterator<Item = impl Into<Expression>>) -> Expression {
    use itertools::Itertools as _;
    let values = elements.into_iter().map(|value| value.into()).collect_vec();
    Merge.new_expr(DuplicateHandling::default(), values)
}

/// Creates a bound expression that merges struct expressions.
pub fn bound_merge(elements: impl IntoIterator<Item = BoundExpression>) -> BoundExpression {
    bound_merge_opts(elements, DuplicateHandling::default())
}

/// Creates a merge expression with explicit duplicate handling.
pub fn merge_opts(
    elements: impl IntoIterator<Item = impl Into<Expression>>,
    duplicate_handling: DuplicateHandling,
) -> Expression {
    use itertools::Itertools as _;
    let values = elements.into_iter().map(|value| value.into()).collect_vec();
    Merge.new_expr(duplicate_handling, values)
}

/// Creates a bound merge expression with explicit duplicate handling.
pub fn bound_merge_opts(
    elements: impl IntoIterator<Item = BoundExpression>,
    duplicate_handling: DuplicateHandling,
) -> BoundExpression {
    Merge
        .try_new_bound_expr(duplicate_handling, elements)
        .vortex_expect("merge expressions require non-nullable struct children")
}

/// Creates an expression that computes the byte length of each element.
/// This is akin to ANSI SQL OCTET_LENGTH(), or DuckDB's strlen().
///
/// ```rust
/// # use vortex_functions::expr::byte_length;
/// # use vortex_expr::root;
/// let expr = byte_length(root());
/// ```
pub fn byte_length(input: Expression) -> Expression {
    ByteLength.new_expr(EmptyOptions, [input])
}

/// Creates a bound expression that computes each element's byte length.
pub fn bound_byte_length(input: BoundExpression) -> BoundExpression {
    ByteLength
        .try_new_bound_expr(EmptyOptions, [input])
        .vortex_expect("byte-length expressions require a variable-length binary child")
}

/// Creates an expression that computes the Unicode lowercase of each string, like SQL `lower`.
///
/// ```rust
/// # use vortex_functions::expr::lower;
/// # use vortex_expr::root;
/// let expr = lower(root());
/// ```
pub fn lower(input: Expression) -> Expression {
    Lower.new_expr(EmptyOptions, [input])
}

/// Creates an expression that computes the one-based character position of `search` in
/// `input`, or zero when absent, like SQL `strpos`.
///
/// ```rust
/// # use vortex_functions::expr::strpos;
/// # use vortex_expr::{lit, root};
/// let expr = strpos(root(), lit("needle"));
/// ```
pub fn strpos(input: Expression, search: Expression) -> Expression {
    Strpos.new_expr(EmptyOptions, [input, search])
}

/// Creates an expression that extracts the storage values from an extension array.
///
/// ```rust
/// # use vortex_functions::expr::ext_storage;
/// # use vortex_expr::root;
/// let expr = ext_storage(root());
/// ```
pub fn ext_storage(input: Expression) -> Expression {
    ExtStorage.new_expr(EmptyOptions, [input])
}

/// Creates a bound expression that extracts an extension array's storage values.
pub fn bound_ext_storage(input: BoundExpression) -> BoundExpression {
    ExtStorage
        .try_new_bound_expr(EmptyOptions, [input])
        .vortex_expect("extension-storage expressions require an extension child")
}

/// Creates an expression that computes the number of elements in each list
/// for `List` and `FixedSizeList` inputs. This is akin to ANSI SQL `CARDINALITY()`,
/// or DuckDB's `len()`/`array_length()`.
///
/// ```rust
/// # use vortex_functions::expr::list_length;
/// # use vortex_expr::root;
/// let expr = list_length(root());
/// ```
pub fn list_length(input: Expression) -> Expression {
    ListLength.new_expr(EmptyOptions, [input])
}

/// Creates a bound expression that computes the number of elements in each list.
pub fn bound_list_length(input: BoundExpression) -> BoundExpression {
    ListLength
        .try_new_bound_expr(EmptyOptions, [input])
        .vortex_expect("list-length expressions require a list child")
}

/// Creates an expression that sums the elements of each list for `List` and
/// `FixedSizeList` inputs, akin to DuckDB's `list_sum()`.
///
/// Follows SQL `SUM` semantics per list: null lists, empty lists, and lists whose elements are
/// all null yield null; null elements are skipped; integer and decimal overflow yields a null
/// value. The result dtype follows `sum`'s widening rules and is always nullable. NaN float
/// elements are skipped by default; see [`list_sum_opts`] for the NaN-including variant.
///
/// ```rust
/// # use vortex_functions::expr::list_sum;
/// # use vortex_expr::root;
/// let expr = list_sum(root());
/// ```
pub fn list_sum(input: Expression) -> Expression {
    ListSum.new_expr(NumericalAggregateOpts::default(), [input])
}

/// Creates a bound expression that sums the elements of each list.
pub fn bound_list_sum(input: BoundExpression) -> BoundExpression {
    ListSum
        .try_new_bound_expr(NumericalAggregateOpts::default(), [input])
        .vortex_expect("list-sum expressions require a numeric list child")
}

/// Creates a [`list_sum`] expression with explicit [`NumericalAggregateOpts`], controlling
/// whether NaN float elements are skipped (the default) or poison the list's sum to NaN.
pub fn list_sum_opts(input: Expression, options: NumericalAggregateOpts) -> Expression {
    ListSum.new_expr(options, [input])
}

/// Creates a bound list-sum expression with explicit aggregate options.
pub fn bound_list_sum_opts(
    input: BoundExpression,
    options: NumericalAggregateOpts,
) -> BoundExpression {
    ListSum
        .try_new_bound_expr(options, [input])
        .vortex_expect("list-sum expressions require a numeric list child")
}

/// Reinterpret timestamp wall times in `options.time_zone`, preserving the time unit.
///
/// `ambiguous` is a UTF-8 expression containing `raise`, `earliest`, `latest`, or `null`.
/// Removing the timezone preserves wall time in a timezone-naive timestamp.
pub fn replace_time_zone(
    input: Expression,
    ambiguous: Expression,
    options: ReplaceTimeZoneOptions,
) -> Expression {
    ReplaceTimeZone.new_expr(options, [input, ambiguous])
}

/// Create a bound timezone replacement expression.
pub fn bound_replace_time_zone(
    input: BoundExpression,
    ambiguous: BoundExpression,
    options: ReplaceTimeZoneOptions,
) -> BoundExpression {
    ReplaceTimeZone
        .try_new_bound_expr(options, [input, ambiguous])
        .vortex_expect("timezone replacement requires a timestamp and a UTF-8 ambiguity policy")
}

/// Constructors for expressions whose children have already been bound and type-checked.
///
/// These mirror the constructors in [`vortex_expr`] and panic when the supplied children do not
/// form a well-typed expression.
/// Creates a dynamic comparison expression from its complete options.
pub fn dynamic_with_options(options: DynamicComparisonExpr, lhs: Expression) -> Expression {
    DynamicComparison.new_expr(options, [lhs])
}

/// Creates a bound dynamic comparison expression from its complete options.
pub fn bound_dynamic_with_options(
    options: DynamicComparisonExpr,
    lhs: BoundExpression,
) -> BoundExpression {
    DynamicComparison
        .try_new_bound_expr(options, [lhs])
        .vortex_expect("dynamic comparisons require a compatible left-hand dtype")
}

/// Creates a dynamic comparison expression.
pub fn dynamic(
    operator: CompareOperator,
    rhs_value: impl Fn() -> Option<ScalarValue> + Send + Sync + 'static,
    rhs_dtype: DType,
    default: bool,
    lhs: Expression,
) -> Expression {
    dynamic_with_options(
        DynamicComparisonExpr {
            operator,
            rhs: Arc::new(Rhs {
                value: Arc::new(rhs_value),
                dtype: rhs_dtype,
            }),
            default,
        },
        lhs,
    )
}

/// Creates a bound dynamic comparison expression.
pub fn bound_dynamic(
    operator: CompareOperator,
    rhs_value: impl Fn() -> Option<ScalarValue> + Send + Sync + 'static,
    rhs_dtype: DType,
    default: bool,
    lhs: BoundExpression,
) -> BoundExpression {
    bound_dynamic_with_options(
        DynamicComparisonExpr {
            operator,
            rhs: Arc::new(Rhs {
                value: Arc::new(rhs_value),
                dtype: rhs_dtype,
            }),
            default,
        },
        lhs,
    )
}

// ---- Between ----

/// Creates an expression that checks if values are between two bounds.
///
/// Returns a boolean array indicating which values fall within the specified range.
/// The comparison strictness is controlled by the options parameter.
///
/// ```rust
/// # use vortex_functions::between::BetweenOptions;
/// # use vortex_functions::between::StrictComparison;
/// # use vortex_expr::{lit, root};
/// # use vortex_functions::expr::between;
/// let opts = BetweenOptions {
///     lower_strict: StrictComparison::NonStrict,
///     upper_strict: StrictComparison::NonStrict,
/// };
/// let expr = between(root(), lit(10), lit(20), opts);
/// ```
pub fn between(
    arr: Expression,
    lower: Expression,
    upper: Expression,
    options: BetweenOptions,
) -> Expression {
    Between
        .try_new_expr(options, [arr, lower, upper])
        .vortex_expect("Failed to create Between expression")
}

/// Creates a bound expression that checks if values are between two bounds.
pub fn bound_between(
    arr: BoundExpression,
    lower: BoundExpression,
    upper: BoundExpression,
    options: BetweenOptions,
) -> BoundExpression {
    Between
        .try_new_bound_expr(options, [arr, lower, upper])
        .vortex_expect("between expressions require compatible operand dtypes")
}

// ---- ListContains ----

/// Creates an expression that checks whether a list contains a value.
///
/// A null element never matches anything: a needle that matches no element yields `false`. For
/// SQL's three-valued `IN`, where a null element makes that `null`, use [`in_list`].
///
/// ```rust
/// # use vortex_expr::{lit, root};
/// # use vortex_functions::expr::list_contains;
/// let expr = list_contains(root(), lit(42));
/// ```
pub fn list_contains(list: Expression, value: Expression) -> Expression {
    list_contains_opts(list, value, ListContainsOptions::default())
}

/// Creates an expression that checks whether a list contains a value, with explicit
/// [`ListContainsOptions`].
pub fn list_contains_opts(
    list: Expression,
    value: Expression,
    options: ListContainsOptions,
) -> Expression {
    ListContains.new_expr(options, [list, value])
}

/// Creates `needle IN (list)` with SQL null semantics: a null element is an unknown value, so a
/// needle that matches no element yields `null` rather than `false` when the list holds one, and
/// `not(in_list(..))` never admits such a row.
///
/// ```rust
/// # use vortex_expr::{lit, root};
/// # use vortex_functions::expr::in_list;
/// let expr = in_list(root(), lit(vec![1, 2, 3]));
/// ```
pub fn in_list(needle: Expression, list: Expression) -> Expression {
    list_contains_opts(
        list,
        needle,
        ListContainsOptions {
            sql_null_semantics: true,
        },
    )
}

/// Creates `needle IN (elements)` with SQL null semantics for a list of constant elements of
/// `element_dtype`, ignoring nullability. An element can also be an untyped null.
///
/// The nullability of `element_dtype` is not used: the list elements are nullable only when a
/// null element is present.
///
/// Non-null integers that hold every value between their smallest and largest become a range
/// check, which is cheaper to evaluate and prunes with tighter bounds than a set lookup, as for
/// the keys of a small dimension table that a join pushes down.
///
/// # Errors
///
/// Returns an error if an element is not a null and not of `element_dtype`.
///
/// ```rust
/// # use vortex_array::dtype::{DType, Nullability, PType};
/// # use vortex_expr::root;
/// # use vortex_functions::expr::in_list_of;
/// let dtype = DType::Primitive(PType::I32, Nullability::NonNullable);
/// let expr = in_list_of(root(), dtype, vec![3i32.into(), 1i32.into(), 2i32.into()])?;
/// assert_eq!(expr.to_string(), "(1i32 <= $ <= 3i32)");
/// # Ok::<(), vortex_error::VortexError>(())
/// ```
pub fn in_list_of(
    needle: Expression,
    element_dtype: DType,
    elements: Vec<Scalar>,
) -> VortexResult<Expression> {
    let element_dtype = if elements.iter().any(Scalar::is_null) {
        element_dtype.as_nullable()
    } else {
        element_dtype.as_nonnullable()
    };
    let mut elements = elements
        .iter()
        .map(|element| {
            vortex_ensure!(
                element.dtype() == &DType::Null
                    || element.dtype().eq_ignore_nullability(&element_dtype),
                "IN list element {element} is not of type {element_dtype}"
            );
            element.cast(&element_dtype)
        })
        .collect::<VortexResult<Vec<_>>>()?;

    if let Some((low, high)) = contiguous_integer_bounds(&elements) {
        let options = BetweenOptions {
            lower_strict: StrictComparison::NonStrict,
            upper_strict: StrictComparison::NonStrict,
        };
        return Ok(between(
            needle,
            lit(low.clone()),
            lit(high.clone()),
            options,
        ));
    }

    // Ordered elements make equal lists from the same set, so that equal filters deduplicate.
    // An engine can build a list from the keys of a hash join, which repeat, and each repeat makes
    // the lookup more costly, so equal elements are removed. One null keeps the SQL semantics.
    if elements
        .windows(2)
        .all(|pair| pair[0].partial_cmp(&pair[1]).is_some())
    {
        elements.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));
        elements.dedup();
    }
    let list = Scalar::list(Arc::new(element_dtype), elements, Nullability::NonNullable);
    Ok(in_list(needle, lit(list)))
}

/// The smallest and largest of non-null integer `scalars` when they hold every integer between
/// those two.
fn contiguous_integer_bounds(scalars: &[Scalar]) -> Option<(&Scalar, &Scalar)> {
    let mut values = scalars
        .iter()
        .map(|scalar| {
            // Viewing a scalar of another type as a primitive builds an error, which is costly.
            if !matches!(scalar.dtype(), DType::Primitive(ptype, _) if ptype.is_int()) {
                return None;
            }
            let primitive = scalar.as_primitive_opt()?;
            let value = if primitive.ptype().is_unsigned_int() {
                primitive.as_opt::<u64>()??.into()
            } else {
                i128::from(primitive.as_opt::<i64>()??)
            };
            Some((value, scalar))
        })
        .collect::<Option<Vec<(i128, &Scalar)>>>()?;
    values.sort_unstable_by_key(|(value, _)| *value);
    values.dedup_by_key(|(value, _)| *value);
    let (low, low_scalar) = values.first()?;
    let (high, high_scalar) = values.last()?;
    (high - low + 1 == i128::try_from(values.len()).ok()?).then_some((*low_scalar, *high_scalar))
}

/// Creates a bound expression that checks whether a list contains a value.
pub fn bound_list_contains(list: BoundExpression, value: BoundExpression) -> BoundExpression {
    ListContains
        .try_new_bound_expr(ListContainsOptions::default(), [list, value])
        .vortex_expect("list-contains expressions require a list child")
}

/// Creates a bound `needle IN (list)` with SQL null semantics. See [`in_list`].
pub fn bound_in_list(needle: BoundExpression, list: BoundExpression) -> BoundExpression {
    ListContains
        .try_new_bound_expr(
            ListContainsOptions {
                sql_null_semantics: true,
            },
            [list, needle],
        )
        .vortex_expect("list-contains expressions require a list child")
}

// ---- VariantGet ----

/// Creates an expression that extracts a path from a Variant expression.
///
/// Missing paths, traversal mismatches, and failed casts return null. When `dtype` is `None`,
/// results are nullable Variant values; otherwise results are nullable values of `dtype`.
pub fn variant_get(
    child: Expression,
    path: impl Into<VariantPath>,
    dtype: Option<DType>,
) -> Expression {
    VariantGet.new_expr(VariantGetOptions::new(path.into(), dtype), vec![child])
}

/// Creates a bound expression that extracts a path from a Variant expression.
pub fn bound_variant_get(
    child: BoundExpression,
    path: impl Into<VariantPath>,
    dtype: Option<DType>,
) -> BoundExpression {
    VariantGet
        .try_new_bound_expr(VariantGetOptions::new(path.into(), dtype), [child])
        .vortex_expect("variant-get expressions require a Variant child")
}

// ---- Like ----

/// Creates a SQL LIKE expression.
pub fn like(child: Expression, pattern: Expression) -> Expression {
    Like.new_expr(
        LikeOptions {
            negated: false,
            case_insensitive: false,
        },
        [child, pattern],
    )
}

/// Creates a bound SQL LIKE expression.
pub fn bound_like(child: BoundExpression, pattern: BoundExpression) -> BoundExpression {
    bound_like_with_options(child, pattern, false, false)
}

/// Creates a case-insensitive SQL ILIKE expression.
pub fn ilike(child: Expression, pattern: Expression) -> Expression {
    Like.new_expr(
        LikeOptions {
            negated: false,
            case_insensitive: true,
        },
        [child, pattern],
    )
}

/// Creates a bound case-insensitive SQL ILIKE expression.
pub fn bound_ilike(child: BoundExpression, pattern: BoundExpression) -> BoundExpression {
    bound_like_with_options(child, pattern, false, true)
}

/// Creates a negated SQL NOT LIKE expression.
pub fn not_like(child: Expression, pattern: Expression) -> Expression {
    Like.new_expr(
        LikeOptions {
            negated: true,
            case_insensitive: false,
        },
        [child, pattern],
    )
}

/// Creates a bound negated SQL NOT LIKE expression.
pub fn bound_not_like(child: BoundExpression, pattern: BoundExpression) -> BoundExpression {
    bound_like_with_options(child, pattern, true, false)
}

/// Creates a negated case-insensitive SQL NOT ILIKE expression.
pub fn not_ilike(child: Expression, pattern: Expression) -> Expression {
    Like.new_expr(
        LikeOptions {
            negated: true,
            case_insensitive: true,
        },
        [child, pattern],
    )
}

/// Creates a bound negated case-insensitive SQL NOT ILIKE expression.
pub fn bound_not_ilike(child: BoundExpression, pattern: BoundExpression) -> BoundExpression {
    bound_like_with_options(child, pattern, true, true)
}

fn bound_like_with_options(
    child: BoundExpression,
    pattern: BoundExpression,
    negated: bool,
    case_insensitive: bool,
) -> BoundExpression {
    Like.try_new_bound_expr(
        LikeOptions {
            negated,
            case_insensitive,
        },
        [child, pattern],
    )
    .vortex_expect("like expressions require UTF-8 or binary operands")
}

// ---- IsNan ----

/// Creates an expression that checks for NaN values.
///
/// The expression is strict: null inputs produce null outputs, so the output nullability
/// follows the input. Only primitive float inputs are supported.
///
/// ```rust
/// # use vortex_expr::root;
/// # use vortex_functions::expr::is_nan;
/// let expr = is_nan(root());
/// ```
pub fn is_nan(child: Expression) -> Expression {
    IsNan.new_expr(EmptyOptions, vec![child])
}

/// Creates a bound expression that checks for NaN values.
pub fn bound_is_nan(child: BoundExpression) -> BoundExpression {
    IsNan
        .try_new_bound_expr(EmptyOptions, [child])
        .vortex_expect("is-nan expressions are always well-typed")
}

// ---- Zip ----

/// Creates a zip expression that conditionally selects between two arrays.
///
/// ```rust
/// # use vortex_expr::{lit, root};
/// # use vortex_functions::expr::zip_expr;
/// let expr = zip_expr(lit(true), root(), lit(0i32));
/// ```
pub fn zip_expr(mask: Expression, if_true: Expression, if_false: Expression) -> Expression {
    Zip.new_expr(EmptyOptions, [if_true, if_false, mask])
}

/// Creates a bound zip expression that conditionally selects between two arrays.
pub fn bound_zip_expr(
    mask: BoundExpression,
    if_true: BoundExpression,
    if_false: BoundExpression,
) -> BoundExpression {
    Zip.try_new_bound_expr(EmptyOptions, [if_true, if_false, mask])
        .vortex_expect("zip expressions require a boolean mask and compatible value dtypes")
}

// ---- DynamicExpression ----

/// Creates a dynamic expression that evaluates the current predicate of `source`.
///
/// The `inputs` are the expressions that every predicate of the source can read. A predicate
/// reads input `i` as the field named by
/// [`input_field_name(i)`](crate::dynamic_expression::input_field_name) of its
/// scope.
pub fn dynamic_expression(
    source: Arc<dyn DynamicExpressionSource>,
    inputs: impl IntoIterator<Item = Expression>,
) -> Expression {
    DynamicExpression.new_expr(DynamicExpressionOptions::new(source), inputs)
}

/// Creates a bound dynamic expression that evaluates the current predicate of `source`.
pub fn bound_dynamic_expression(
    source: Arc<dyn DynamicExpressionSource>,
    inputs: impl IntoIterator<Item = BoundExpression>,
) -> BoundExpression {
    DynamicExpression
        .try_new_bound_expr(DynamicExpressionOptions::new(source), inputs)
        .vortex_expect("dynamic expressions accept any inputs")
}

// ---- ListTransform ----

/// Creates an expression that applies a lambda to every element of each list.
///
/// The lambda takes one parameter, the element.
///
/// ```rust
/// # use vortex_expr::{Lambda, checked_add, col, lit, var};
/// # use vortex_functions::expr::list_transform;
/// let lambda = Lambda::new(["x"], checked_add(var("x"), lit(1_i32))).unwrap();
/// let expr = list_transform(col("l"), lambda);
/// assert_eq!(expr.to_string(), "vortex.list.transform($.l, (x) -> (@x + 1i32))");
/// ```
pub fn list_transform(list: Expression, lambda: Lambda) -> Expression {
    ListTransform.new_expr(ListTransformOptions::Lambda(lambda), [list])
}

// ---- IsNull ----

/// Creates an expression that checks for null values.
///
/// Returns a boolean array indicating which positions contain null values.
///
/// ```rust
/// # use vortex_expr::root;
/// # use vortex_functions::expr::is_null;
/// let expr = is_null(root());
/// ```
pub fn is_null(child: Expression) -> Expression {
    IsNull.new_expr(EmptyOptions, vec![child])
}

/// Creates a bound expression that checks for null values.
pub fn bound_is_null(child: BoundExpression) -> BoundExpression {
    IsNull
        .try_new_bound_expr(EmptyOptions, [child])
        .vortex_expect("is-null expressions are always well-typed")
}

// ---- Select ----

/// Creates an expression that selects (includes) specific fields from an array.
///
/// Projects only the specified fields from the child expression, which must be of DType struct.
/// ```rust
/// # use vortex_functions::expr::select;
/// # use vortex_expr::root;
/// let expr = select(["name", "age"], root());
/// ```
pub fn select(field_names: impl Into<FieldNames>, child: Expression) -> Expression {
    Select
        .try_new_expr(FieldSelection::Include(field_names.into()), [child])
        .vortex_expect("Failed to create Select expression")
}

/// Creates a bound expression that selects specific fields from a struct expression.
pub fn bound_select(field_names: impl Into<FieldNames>, child: BoundExpression) -> BoundExpression {
    Select
        .try_new_bound_expr(FieldSelection::Include(field_names.into()), [child])
        .vortex_expect("select expressions require fields from a struct child")
}

/// Creates an expression that excludes specific fields from an array.
///
/// Projects all fields except the specified ones from the input struct expression.
///
/// ```rust
/// # use vortex_functions::expr::select_exclude;
/// # use vortex_expr::root;
/// let expr = select_exclude(["internal_id", "metadata"], root());
/// ```
pub fn select_exclude(fields: impl Into<FieldNames>, child: Expression) -> Expression {
    Select
        .try_new_expr(FieldSelection::Exclude(fields.into()), [child])
        .vortex_expect("Failed to create Select expression")
}

/// Creates a bound expression that excludes specific fields from a struct expression.
pub fn bound_select_exclude(
    fields: impl Into<FieldNames>,
    child: BoundExpression,
) -> BoundExpression {
    Select
        .try_new_bound_expr(FieldSelection::Exclude(fields.into()), [child])
        .vortex_expect("select expressions require fields from a struct child")
}

pub mod bound {
    pub use super::bound_between as between;
    pub use super::bound_byte_length as byte_length;
    pub use super::bound_case_when as case_when;
    pub use super::bound_case_when_no_else as case_when_no_else;
    pub use super::bound_dynamic as dynamic;
    pub use super::bound_dynamic_expression as dynamic_expression;
    pub use super::bound_dynamic_with_options as dynamic_with_options;
    pub use super::bound_ext_storage as ext_storage;
    pub use super::bound_ilike as ilike;
    pub use super::bound_in_list as in_list;
    pub use super::bound_is_nan as is_nan;
    pub use super::bound_is_null as is_null;
    pub use super::bound_like as like;
    pub use super::bound_list_contains as list_contains;
    pub use super::bound_list_length as list_length;
    pub use super::bound_list_sum as list_sum;
    pub use super::bound_list_sum_opts as list_sum_opts;
    pub use super::bound_merge as merge;
    pub use super::bound_merge_opts as merge_opts;
    pub use super::bound_nested_case_when as nested_case_when;
    pub use super::bound_not_ilike as not_ilike;
    pub use super::bound_not_like as not_like;
    pub use super::bound_replace_time_zone as replace_time_zone;
    pub use super::bound_select as select;
    pub use super::bound_select_exclude as select_exclude;
    pub use super::bound_variant_get as variant_get;
    pub use super::bound_zip_expr as zip_expr;
}