-
Notifications
You must be signed in to change notification settings - Fork 200
Expand file tree
/
Copy pathexprs.rs
More file actions
1271 lines (1146 loc) · 43.5 KB
/
Copy pathexprs.rs
File metadata and controls
1271 lines (1146 loc) · 43.5 KB
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
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright the Vortex contributors
//! Factory functions for creating [`Expression`]s from scalar function vtables.
use std::sync::Arc;
use vortex_error::VortexExpect;
use vortex_error::VortexResult;
use vortex_error::vortex_panic;
use vortex_utils::iter::ReduceBalancedIterExt;
use crate::aggregate_fn::NumericalAggregateOpts;
use crate::dtype::DType;
use crate::dtype::FieldName;
use crate::dtype::FieldNames;
use crate::dtype::Nullability;
use crate::expr::BoundExpression;
use crate::expr::Expression;
use crate::scalar::Scalar;
use crate::scalar::ScalarValue;
use crate::scalar_fn::EmptyOptions;
use crate::scalar_fn::ScalarFnVTableExt;
use crate::scalar_fn::fns::between::Between;
use crate::scalar_fn::fns::between::BetweenOptions;
use crate::scalar_fn::fns::binary::Binary;
use crate::scalar_fn::fns::byte_length::ByteLength;
use crate::scalar_fn::fns::case_when::CaseWhen;
use crate::scalar_fn::fns::case_when::CaseWhenOptions;
use crate::scalar_fn::fns::cast::Cast;
use crate::scalar_fn::fns::dynamic::DynamicComparison;
use crate::scalar_fn::fns::dynamic::DynamicComparisonExpr;
use crate::scalar_fn::fns::dynamic::Rhs;
use crate::scalar_fn::fns::ext_storage::ExtStorage;
use crate::scalar_fn::fns::fill_null::FillNull;
use crate::scalar_fn::fns::get_item::GetItem;
use crate::scalar_fn::fns::is_not_null::IsNotNull;
use crate::scalar_fn::fns::is_null::IsNull;
use crate::scalar_fn::fns::like::Like;
use crate::scalar_fn::fns::like::LikeOptions;
use crate::scalar_fn::fns::list_contains::ListContains;
use crate::scalar_fn::fns::list_length::ListLength;
use crate::scalar_fn::fns::list_sum::ListSum;
use crate::scalar_fn::fns::literal::Literal;
use crate::scalar_fn::fns::mask::Mask;
use crate::scalar_fn::fns::merge::DuplicateHandling;
use crate::scalar_fn::fns::merge::Merge;
use crate::scalar_fn::fns::not::Not;
use crate::scalar_fn::fns::operators::CompareOperator;
use crate::scalar_fn::fns::operators::Operator;
use crate::scalar_fn::fns::pack::Pack;
use crate::scalar_fn::fns::pack::PackOptions;
use crate::scalar_fn::fns::select::FieldSelection;
use crate::scalar_fn::fns::select::Select;
use crate::scalar_fn::fns::variant_get::VariantGet;
use crate::scalar_fn::fns::variant_get::VariantGetOptions;
use crate::scalar_fn::fns::variant_get::VariantPath;
use crate::scalar_fn::fns::zip::Zip;
/// Creates an expression that references the root scope.
///
/// Returns the entire input array as passed to the expression evaluator.
/// This is commonly used as the starting point for field access and other operations.
pub fn root() -> Expression {
Expression::Root
}
/// Creates a bound expression that references a root scope with the given dtype.
pub fn bound_root(dtype: DType) -> BoundExpression {
BoundExpression::new_root(dtype)
}
/// Return whether the expression is a root expression.
pub fn is_root(expr: &Expression) -> bool {
expr.is_root()
}
// ---- Literal ----
/// Create a new `Literal` expression from a type that coerces to `Scalar`.
///
///
/// ## Example usage
///
/// ```
/// use vortex_array::arrays::PrimitiveArray;
/// use vortex_array::dtype::Nullability;
/// use vortex_array::expr::lit;
/// use vortex_array::scalar_fn::fns::literal::Literal;
/// use vortex_array::scalar::Scalar;
///
/// let number = lit(34i32);
///
/// let scalar = number.as_::<Literal>();
/// assert_eq!(scalar, &Scalar::primitive(34i32, Nullability::NonNullable));
/// ```
pub fn lit(value: impl Into<Scalar>) -> Expression {
Literal.new_expr(value.into(), [])
}
/// Creates a bound literal expression.
pub fn bound_lit(value: impl Into<Scalar>) -> BoundExpression {
Literal
.try_new_bound_expr(value.into(), [])
.vortex_expect("literal expressions are always well-typed")
}
// ---- GetItem / Col ----
/// Creates an expression that accesses a field from the root array.
///
/// Equivalent to `get_item(field, root())` - extracts a named field from the input array.
///
/// ```rust
/// # use vortex_array::expr::col;
/// let expr = col("name");
/// ```
pub fn col(field: impl Into<FieldName>) -> Expression {
GetItem.new_expr(field.into(), vec![root()])
}
/// Creates a bound expression that accesses a field from a root scope with the given dtype.
pub fn bound_col(field: impl Into<FieldName>, scope: DType) -> BoundExpression {
bound_get_item(field, bound_root(scope))
}
/// Creates an expression that extracts a named field from a struct expression.
///
/// Accesses the specified field from the result of the child expression.
///
/// ```rust
/// # use vortex_array::expr::{get_item, root};
/// let expr = get_item("user_id", root());
/// ```
pub fn get_item(field: impl Into<FieldName>, child: Expression) -> Expression {
GetItem.new_expr(field.into(), vec![child])
}
/// Creates a bound expression that extracts a named field from a struct expression.
pub fn bound_get_item(field: impl Into<FieldName>, child: BoundExpression) -> BoundExpression {
GetItem
.try_new_bound_expr(field.into(), [child])
.vortex_expect("get-item expressions must reference a field in the child dtype")
}
// ---- 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")
}
// ---- CaseWhen ----
/// 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")
}
// ---- Binary operators ----
/// Creates a binary expression with the given operator.
pub fn binary(operator: Operator, lhs: Expression, rhs: Expression) -> Expression {
Binary
.try_new_expr(operator, [lhs, rhs])
.vortex_expect("Failed to create binary expression")
}
/// Creates a bound binary expression with the given operator.
pub fn bound_binary(
operator: Operator,
lhs: BoundExpression,
rhs: BoundExpression,
) -> BoundExpression {
Binary
.try_new_bound_expr(operator, [lhs, rhs])
.vortex_expect("binary expressions must have compatible operand dtypes")
}
/// Create a new [`Binary`] using the [`Eq`](Operator::Eq) operator.
///
/// ## Example usage
///
/// ```
/// # use vortex_array::arrays::{BoolArray, PrimitiveArray};
/// # use vortex_array::arrays::bool::BoolArrayExt;
/// # use vortex_array::IntoArray;
/// # use vortex_array::{VortexSessionExecute, array_session};
/// # use vortex_array::validity::Validity;
/// # use vortex_buffer::buffer;
/// # use vortex_array::expr::{eq, root, lit};
/// let xs = PrimitiveArray::new(buffer![1i32, 2i32, 3i32], Validity::NonNullable);
/// let result = xs.into_array().apply(&eq(root(), lit(3))).unwrap();
/// let mut ctx = array_session().create_execution_ctx();
///
/// assert_eq!(
/// result.execute::<BoolArray>(&mut ctx).unwrap().to_bit_buffer(),
/// BoolArray::from_iter(vec![false, false, true]).to_bit_buffer(),
/// );
/// ```
pub fn eq(lhs: Expression, rhs: Expression) -> Expression {
Binary
.try_new_expr(Operator::Eq, [lhs, rhs])
.vortex_expect("Failed to create Eq binary expression")
}
/// Creates a bound equality expression.
pub fn bound_eq(lhs: BoundExpression, rhs: BoundExpression) -> BoundExpression {
bound_binary(Operator::Eq, lhs, rhs)
}
/// Create a new [`Binary`] using the [`NotEq`](Operator::NotEq) operator.
///
/// ## Example usage
///
/// ```
/// # use vortex_array::arrays::{BoolArray, PrimitiveArray};
/// # use vortex_array::arrays::bool::BoolArrayExt;
/// # use vortex_array::IntoArray;
/// # use vortex_array::{VortexSessionExecute, array_session};
/// # use vortex_array::validity::Validity;
/// # use vortex_buffer::buffer;
/// # use vortex_array::expr::{root, lit, not_eq};
/// let xs = PrimitiveArray::new(buffer![1i32, 2i32, 3i32], Validity::NonNullable);
/// let result = xs.into_array().apply(¬_eq(root(), lit(3))).unwrap();
/// let mut ctx = array_session().create_execution_ctx();
///
/// assert_eq!(
/// result.execute::<BoolArray>(&mut ctx).unwrap().to_bit_buffer(),
/// BoolArray::from_iter(vec![true, true, false]).to_bit_buffer(),
/// );
/// ```
pub fn not_eq(lhs: Expression, rhs: Expression) -> Expression {
Binary
.try_new_expr(Operator::NotEq, [lhs, rhs])
.vortex_expect("Failed to create NotEq binary expression")
}
/// Creates a bound inequality expression.
pub fn bound_not_eq(lhs: BoundExpression, rhs: BoundExpression) -> BoundExpression {
bound_binary(Operator::NotEq, lhs, rhs)
}
/// Create a new [`Binary`] using the [`Gte`](Operator::Gte) operator.
///
/// ## Example usage
///
/// ```
/// # use vortex_array::arrays::{BoolArray, PrimitiveArray };
/// # use vortex_array::arrays::bool::BoolArrayExt;
/// # use vortex_array::IntoArray;
/// # use vortex_array::{VortexSessionExecute, array_session};
/// # use vortex_array::validity::Validity;
/// # use vortex_buffer::buffer;
/// # use vortex_array::expr::{gt_eq, root, lit};
/// let xs = PrimitiveArray::new(buffer![1i32, 2i32, 3i32], Validity::NonNullable);
/// let result = xs.into_array().apply(>_eq(root(), lit(3))).unwrap();
/// let mut ctx = array_session().create_execution_ctx();
///
/// assert_eq!(
/// result.execute::<BoolArray>(&mut ctx).unwrap().to_bit_buffer(),
/// BoolArray::from_iter(vec![false, false, true]).to_bit_buffer(),
/// );
/// ```
pub fn gt_eq(lhs: Expression, rhs: Expression) -> Expression {
Binary
.try_new_expr(Operator::Gte, [lhs, rhs])
.vortex_expect("Failed to create Gte binary expression")
}
/// Creates a bound greater-than-or-equal expression.
pub fn bound_gt_eq(lhs: BoundExpression, rhs: BoundExpression) -> BoundExpression {
bound_binary(Operator::Gte, lhs, rhs)
}
/// Create a new [`Binary`] using the [`Gt`](Operator::Gt) operator.
///
/// ## Example usage
///
/// ```
/// # use vortex_array::arrays::{BoolArray, PrimitiveArray };
/// # use vortex_array::arrays::bool::BoolArrayExt;
/// # use vortex_array::IntoArray;
/// # use vortex_array::{VortexSessionExecute, array_session};
/// # use vortex_array::validity::Validity;
/// # use vortex_buffer::buffer;
/// # use vortex_array::expr::{gt, root, lit};
/// let xs = PrimitiveArray::new(buffer![1i32, 2i32, 3i32], Validity::NonNullable);
/// let result = xs.into_array().apply(>(root(), lit(2))).unwrap();
/// let mut ctx = array_session().create_execution_ctx();
///
/// assert_eq!(
/// result.execute::<BoolArray>(&mut ctx).unwrap().to_bit_buffer(),
/// BoolArray::from_iter(vec![false, false, true]).to_bit_buffer(),
/// );
/// ```
pub fn gt(lhs: Expression, rhs: Expression) -> Expression {
Binary
.try_new_expr(Operator::Gt, [lhs, rhs])
.vortex_expect("Failed to create Gt binary expression")
}
/// Creates a bound greater-than expression.
pub fn bound_gt(lhs: BoundExpression, rhs: BoundExpression) -> BoundExpression {
bound_binary(Operator::Gt, lhs, rhs)
}
/// Create a new [`Binary`] using the [`Lte`](Operator::Lte) operator.
///
/// ## Example usage
///
/// ```
/// # use vortex_array::arrays::{BoolArray, PrimitiveArray };
/// # use vortex_array::arrays::bool::BoolArrayExt;
/// # use vortex_array::IntoArray;
/// # use vortex_array::{VortexSessionExecute, array_session};
/// # use vortex_array::validity::Validity;
/// # use vortex_buffer::buffer;
/// # use vortex_array::expr::{root, lit, lt_eq};
/// let xs = PrimitiveArray::new(buffer![1i32, 2i32, 3i32], Validity::NonNullable);
/// let result = xs.into_array().apply(<_eq(root(), lit(2))).unwrap();
/// let mut ctx = array_session().create_execution_ctx();
///
/// assert_eq!(
/// result.execute::<BoolArray>(&mut ctx).unwrap().to_bit_buffer(),
/// BoolArray::from_iter(vec![true, true, false]).to_bit_buffer(),
/// );
/// ```
pub fn lt_eq(lhs: Expression, rhs: Expression) -> Expression {
Binary
.try_new_expr(Operator::Lte, [lhs, rhs])
.vortex_expect("Failed to create Lte binary expression")
}
/// Creates a bound less-than-or-equal expression.
pub fn bound_lt_eq(lhs: BoundExpression, rhs: BoundExpression) -> BoundExpression {
bound_binary(Operator::Lte, lhs, rhs)
}
/// Create a new [`Binary`] using the [`Lt`](Operator::Lt) operator.
///
/// ## Example usage
///
/// ```
/// # use vortex_array::arrays::{BoolArray, PrimitiveArray };
/// # use vortex_array::arrays::bool::BoolArrayExt;
/// # use vortex_array::IntoArray;
/// # use vortex_array::{VortexSessionExecute, array_session};
/// # use vortex_array::validity::Validity;
/// # use vortex_buffer::buffer;
/// # use vortex_array::expr::{root, lit, lt};
/// let xs = PrimitiveArray::new(buffer![1i32, 2i32, 3i32], Validity::NonNullable);
/// let result = xs.into_array().apply(<(root(), lit(3))).unwrap();
/// let mut ctx = array_session().create_execution_ctx();
///
/// assert_eq!(
/// result.execute::<BoolArray>(&mut ctx).unwrap().to_bit_buffer(),
/// BoolArray::from_iter(vec![true, true, false]).to_bit_buffer(),
/// );
/// ```
pub fn lt(lhs: Expression, rhs: Expression) -> Expression {
Binary
.try_new_expr(Operator::Lt, [lhs, rhs])
.vortex_expect("Failed to create Lt binary expression")
}
/// Creates a bound less-than expression.
pub fn bound_lt(lhs: BoundExpression, rhs: BoundExpression) -> BoundExpression {
bound_binary(Operator::Lt, lhs, rhs)
}
/// Create a new [`Binary`] using the [`Or`](Operator::Or) operator.
///
/// ## Example usage
///
/// ```
/// # use vortex_array::arrays::BoolArray;
/// # use vortex_array::arrays::bool::BoolArrayExt;
/// # use vortex_array::IntoArray;
/// # use vortex_array::{VortexSessionExecute, array_session};
/// # use vortex_array::expr::{root, lit, or};
/// let xs = BoolArray::from_iter(vec![true, false, true]);
/// let result = xs.into_array().apply(&or(root(), lit(false))).unwrap();
/// let mut ctx = array_session().create_execution_ctx();
///
/// assert_eq!(
/// result.execute::<BoolArray>(&mut ctx).unwrap().to_bit_buffer(),
/// BoolArray::from_iter(vec![true, false, true]).to_bit_buffer(),
/// );
/// ```
pub fn or(lhs: Expression, rhs: Expression) -> Expression {
Binary
.try_new_expr(Operator::Or, [lhs, rhs])
.vortex_expect("Failed to create Or binary expression")
}
/// Creates a bound boolean OR expression.
pub fn bound_or(lhs: BoundExpression, rhs: BoundExpression) -> BoundExpression {
bound_binary(Operator::Or, lhs, rhs)
}
/// Collects a list of `or`ed values into a single expression using a balanced tree.
///
/// This creates a balanced binary tree to avoid deep nesting that could cause
/// stack overflow during drop or evaluation.
///
/// [a, b, c, d] => or(or(a, b), or(c, d))
pub fn or_collect<I>(iter: I) -> Option<Expression>
where
I: IntoIterator<Item = Expression>,
{
iter.into_iter().reduce_balanced(or)
}
/// Collects bound expressions into a balanced tree of boolean OR expressions.
pub fn bound_or_collect<I>(iter: I) -> Option<BoundExpression>
where
I: IntoIterator<Item = BoundExpression>,
{
iter.into_iter().reduce_balanced(bound_or)
}
/// Create a new [`Binary`] using the [`And`](Operator::And) operator.
///
/// ## Example usage
///
/// ```
/// # use vortex_array::arrays::BoolArray;
/// # use vortex_array::arrays::bool::BoolArrayExt;
/// # use vortex_array::IntoArray;
/// # use vortex_array::{VortexSessionExecute, array_session};
/// # use vortex_array::expr::{and, root, lit};
/// let xs = BoolArray::from_iter(vec![true, false, true]).into_array();
/// let result = xs.apply(&and(root(), lit(true))).unwrap();
/// let mut ctx = array_session().create_execution_ctx();
///
/// assert_eq!(
/// result.execute::<BoolArray>(&mut ctx).unwrap().to_bit_buffer(),
/// BoolArray::from_iter(vec![true, false, true]).to_bit_buffer(),
/// );
/// ```
pub fn and(lhs: Expression, rhs: Expression) -> Expression {
Binary
.try_new_expr(Operator::And, [lhs, rhs])
.vortex_expect("Failed to create And binary expression")
}
/// Creates a bound boolean AND expression.
pub fn bound_and(lhs: BoundExpression, rhs: BoundExpression) -> BoundExpression {
bound_binary(Operator::And, lhs, rhs)
}
/// Collects a list of `and`ed values into a single expression using a balanced tree.
///
/// This creates a balanced binary tree to avoid deep nesting that could cause
/// stack overflow during drop or evaluation.
///
/// [a, b, c, d] => and(and(a, b), and(c, d))
pub fn and_collect<I>(iter: I) -> Option<Expression>
where
I: IntoIterator<Item = Expression>,
{
iter.into_iter().reduce_balanced(and)
}
/// Collects bound expressions into a balanced tree of boolean AND expressions.
pub fn bound_and_collect<I>(iter: I) -> Option<BoundExpression>
where
I: IntoIterator<Item = BoundExpression>,
{
iter.into_iter().reduce_balanced(bound_and)
}
/// The conjunction of an expression's child validities — i.e. the validity of a scalar function
/// whose result is null exactly when any operand is null.
///
/// This is the `ScalarFnVTable::validity` for kernels that propagate nulls and never produce a
/// null from non-null inputs (comparisons, arithmetic, most spatial and tensor operations). Returning it lets
/// the planner derive the output's null mask without executing the kernel. Yields `None` when the
/// expression has no children.
pub fn union_child_validities(expression: &Expression) -> VortexResult<Option<Expression>> {
let child_validities = expression
.children()
.iter()
.map(Expression::validity)
.collect::<VortexResult<Vec<_>>>()?;
Ok(and_collect(child_validities))
}
/// Create a new [`Binary`] using the [`Add`](Operator::Add) operator.
///
/// ## Example usage
///
/// ```
/// # use vortex_array::IntoArray;
/// # use vortex_array::arrays::PrimitiveArray;
/// # use vortex_array::builtins::ArrayBuiltins;
/// # use vortex_array::{VortexSessionExecute, array_session};
/// # use vortex_buffer::buffer;
/// # use vortex_array::expr::{checked_add, lit, root};
/// let xs = buffer![1, 2, 3].into_array();
/// let result = xs.apply(&checked_add(root(), lit(5))).unwrap();
///
/// let mut ctx = array_session().create_execution_ctx();
/// let result = result.execute::<PrimitiveArray>(&mut ctx).unwrap();
/// assert_eq!(result.as_slice::<i32>(), [6, 7, 8]);
/// ```
pub fn checked_add(lhs: Expression, rhs: Expression) -> Expression {
Binary
.try_new_expr(Operator::Add, [lhs, rhs])
.vortex_expect("Failed to create Add binary expression")
}
/// Creates a bound checked-add expression.
pub fn bound_checked_add(lhs: BoundExpression, rhs: BoundExpression) -> BoundExpression {
bound_binary(Operator::Add, lhs, rhs)
}
// ---- Not ----
/// Creates an expression that logically inverts boolean values.
///
/// Returns the logical negation of the input boolean expression.
///
/// ```rust
/// # use vortex_array::expr::{not, root};
/// let expr = not(root());
/// ```
pub fn not(operand: Expression) -> Expression {
Not.new_expr(EmptyOptions, vec![operand])
}
/// Creates a bound expression that logically inverts boolean values.
pub fn bound_not(operand: BoundExpression) -> BoundExpression {
Not.try_new_bound_expr(EmptyOptions, [operand])
.vortex_expect("not expressions require a boolean operand")
}
// ---- 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_array::scalar_fn::fns::between::BetweenOptions;
/// # use vortex_array::scalar_fn::fns::between::StrictComparison;
/// # use vortex_array::expr::{between, lit, root};
/// 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")
}
// ---- 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_array::expr::{select, 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_array::expr::{select_exclude, 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")
}
// ---- Pack ----
/// Creates an expression that packs values into a struct with named fields.
///
/// ```rust
/// # use vortex_array::dtype::Nullability;
/// # use vortex_array::expr::{pack, col, lit};
/// let expr = pack([("id", col("user_id")), ("constant", lit(42))], Nullability::NonNullable);
/// ```
pub fn pack(
elements: impl IntoIterator<Item = (impl Into<FieldName>, Expression)>,
nullability: Nullability,
) -> Expression {
let (names, values): (Vec<_>, Vec<_>) = elements
.into_iter()
.map(|(name, value)| (name.into(), value))
.unzip();
Pack.new_expr(
PackOptions {
names: names.into(),
nullability,
},
values,
)
}
/// Creates a bound expression that packs values into a struct with named fields.
pub fn bound_pack(
elements: impl IntoIterator<Item = (impl Into<FieldName>, BoundExpression)>,
nullability: Nullability,
) -> BoundExpression {
let (names, values): (Vec<_>, Vec<_>) = elements
.into_iter()
.map(|(name, value)| (name.into(), value))
.unzip();
Pack.try_new_bound_expr(
PackOptions {
names: names.into(),
nullability,
},
values,
)
.vortex_expect("pack expressions must have one name per child")
}
// ---- Cast ----
/// Creates an expression that casts values to a target data type.
///
/// Converts the input expression's values to the specified target type.
///
/// ```rust
/// # use vortex_array::dtype::{DType, Nullability, PType};
/// # use vortex_array::expr::{cast, root};
/// let expr = cast(root(), DType::Primitive(PType::I64, Nullability::NonNullable));
/// ```
pub fn cast(child: Expression, target: DType) -> Expression {
Cast.try_new_expr(target, [child])
.vortex_expect("Failed to create Cast expression")
}
/// Creates a bound expression that casts values to a target dtype.
pub fn bound_cast(child: BoundExpression, target: DType) -> BoundExpression {
Cast.try_new_bound_expr(target, [child])
.vortex_expect("cast expressions require a supported source and target dtype")
}
// ---- FillNull ----
/// Creates an expression that replaces null values with a fill value.
///
/// ```rust
/// # use vortex_array::expr::{fill_null, root, lit};
/// let expr = fill_null(root(), lit(0i32));
/// ```
pub fn fill_null(child: Expression, fill_value: Expression) -> Expression {
FillNull.new_expr(EmptyOptions, [child, fill_value])
}
/// Creates a bound expression that replaces null values with a fill value.
pub fn bound_fill_null(child: BoundExpression, fill_value: BoundExpression) -> BoundExpression {
FillNull
.try_new_bound_expr(EmptyOptions, [child, fill_value])
.vortex_expect("fill-null expressions require compatible child and fill dtypes")
}
// ---- IsNull ----
/// Creates an expression that checks for null values.
///
/// Returns a boolean array indicating which positions contain null values.
///
/// ```rust
/// # use vortex_array::expr::{is_null, root};
/// 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")
}
// ---- IsNotNull ----
/// Creates an expression that checks for non-null values.
///
/// Returns a boolean array indicating which positions contain non-null values.
///
/// ```rust
/// # use vortex_array::expr::{is_not_null, root};
/// let expr = is_not_null(root());
/// ```
pub fn is_not_null(child: Expression) -> Expression {
IsNotNull.new_expr(EmptyOptions, vec![child])
}
/// Creates a bound expression that checks for non-null values.
pub fn bound_is_not_null(child: BoundExpression) -> BoundExpression {
IsNotNull
.try_new_bound_expr(EmptyOptions, [child])
.vortex_expect("is-not-null expressions are always well-typed")
}
// ---- 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")
}
// ---- Mask ----
/// Creates a mask expression that applies the given boolean mask to the input array.
pub fn mask(array: Expression, mask: Expression) -> Expression {
Mask.new_expr(EmptyOptions, [array, mask])
}
/// Creates a bound mask expression.
pub fn bound_mask(array: BoundExpression, mask: BoundExpression) -> BoundExpression {
Mask.try_new_bound_expr(EmptyOptions, [array, mask])
.vortex_expect("mask expressions require a boolean mask")
}
// ---- Merge ----
/// 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_array::expr::{merge, 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,