-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathmod.rs
1475 lines (1355 loc) · 49.8 KB
/
mod.rs
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
use crate::env::Bindings;
use crate::error::EvaluationError;
use crate::eval::evaluable::SetQuantifier;
use crate::eval::expr::pattern_match::like_to_re_pattern;
use crate::eval::EvalContext;
use itertools::Itertools;
use partiql_catalog::BaseTableExpr;
use partiql_logical::Type;
use partiql_value::Value::{Boolean, Missing, Null};
use partiql_value::{
Bag, BinaryAnd, BinaryOr, BindingsName, DateTime, List, NullableEq, NullableOrd, Tuple,
UnaryPlus, Value,
};
use regex::{Regex, RegexBuilder};
use rust_decimal::prelude::FromPrimitive;
use rust_decimal::Decimal;
use std::borrow::{Borrow, Cow};
use std::fmt::Debug;
pub(crate) mod pattern_match;
/// A trait for expressions that require evaluation, e.g. `a + b` or `c > 2`.
pub trait EvalExpr: Debug {
fn evaluate<'a>(&'a self, bindings: &'a Tuple, ctx: &'a dyn EvalContext) -> Cow<'a, Value>;
}
/// Represents an evaluation operator for Tuple expressions such as `{t1.a: t1.b * 2}` in
/// `SELECT VALUE {t1.a: t1.b * 2} FROM table1 AS t1`.
#[derive(Debug)]
pub(crate) struct EvalTupleExpr {
pub(crate) attrs: Vec<Box<dyn EvalExpr>>,
pub(crate) vals: Vec<Box<dyn EvalExpr>>,
}
impl EvalExpr for EvalTupleExpr {
fn evaluate<'a>(&'a self, bindings: &'a Tuple, ctx: &'a dyn EvalContext) -> Cow<'a, Value> {
let tuple = self
.attrs
.iter()
.zip(self.vals.iter())
.filter_map(|(attr, val)| {
let key = attr.evaluate(bindings, ctx);
match key.as_ref() {
Value::String(key) => {
let val = val.evaluate(bindings, ctx);
match val.as_ref() {
Missing => None,
_ => Some((key.to_string(), val.into_owned())),
}
}
_ => None,
}
})
.collect::<Tuple>();
Cow::Owned(Value::from(tuple))
}
}
/// Represents an evaluation operator for List (ordered array) expressions such as
/// `[t1.a, t1.b * 2]` in `SELECT VALUE [t1.a, t1.b * 2] FROM table1 AS t1`.
#[derive(Debug)]
pub(crate) struct EvalListExpr {
pub(crate) elements: Vec<Box<dyn EvalExpr>>,
}
impl EvalExpr for EvalListExpr {
fn evaluate<'a>(&'a self, bindings: &'a Tuple, ctx: &'a dyn EvalContext) -> Cow<'a, Value> {
let values = self
.elements
.iter()
.map(|val| val.evaluate(bindings, ctx).into_owned());
Cow::Owned(Value::from(values.collect::<List>()))
}
}
/// Represents an evaluation operator for Bag (unordered array) expressions such as
/// `<<t1.a, t1.b * 2>>` in `SELECT VALUE <<t1.a, t1.b * 2>> FROM table1 AS t1`.
#[derive(Debug)]
pub(crate) struct EvalBagExpr {
pub(crate) elements: Vec<Box<dyn EvalExpr>>,
}
impl EvalExpr for EvalBagExpr {
fn evaluate<'a>(&'a self, bindings: &'a Tuple, ctx: &'a dyn EvalContext) -> Cow<'a, Value> {
let values = self
.elements
.iter()
.map(|val| val.evaluate(bindings, ctx).into_owned());
Cow::Owned(Value::from(values.collect::<Bag>()))
}
}
/// Represents an evaluation operator for path navigation expressions as outlined in Section `4` of
/// [PartiQL Specification — August 1, 2019](https://partiql.org/assets/PartiQL-Specification.pdf).
#[derive(Debug)]
pub(crate) struct EvalPath {
pub(crate) expr: Box<dyn EvalExpr>,
pub(crate) components: Vec<EvalPathComponent>,
}
#[derive(Debug)]
pub(crate) enum EvalPathComponent {
Key(BindingsName),
KeyExpr(Box<dyn EvalExpr>),
Index(i64),
IndexExpr(Box<dyn EvalExpr>),
}
impl EvalExpr for EvalPath {
fn evaluate<'a>(&'a self, bindings: &'a Tuple, ctx: &'a dyn EvalContext) -> Cow<'a, Value> {
#[inline]
fn path_into<'a>(
value: &'a Value,
path: &EvalPathComponent,
bindings: &'a Tuple,
ctx: &dyn EvalContext,
) -> Option<&'a Value> {
match path {
EvalPathComponent::Key(k) => match value {
Value::Tuple(tuple) => tuple.get(k),
_ => None,
},
EvalPathComponent::Index(idx) => match value {
Value::List(list) if (*idx as usize) < list.len() => list.get(*idx),
_ => None,
},
EvalPathComponent::KeyExpr(ke) => {
let key = ke.evaluate(bindings, ctx);
match (value, key.as_ref()) {
(Value::Tuple(tuple), Value::String(key)) => {
tuple.get(&BindingsName::CaseInsensitive(key.as_ref().clone()))
}
_ => None,
}
}
EvalPathComponent::IndexExpr(ie) => {
if let Value::Integer(idx) = ie.evaluate(bindings, ctx).as_ref() {
match value {
Value::List(list) if (*idx as usize) < list.len() => list.get(*idx),
_ => None,
}
} else {
None
}
}
}
}
let value = self.expr.evaluate(bindings, ctx);
self.components
.iter()
.fold(Some(value.as_ref()), |v, path| {
v.and_then(|v| path_into(v, path, bindings, ctx))
})
.map_or_else(|| Cow::Owned(Value::Missing), |v| Cow::Owned(v.clone()))
}
}
/// Represents an operator for dynamic variable name resolution of a (sub)query.
#[derive(Debug)]
pub(crate) struct EvalDynamicLookup {
pub(crate) lookups: Vec<Box<dyn EvalExpr>>,
}
impl EvalExpr for EvalDynamicLookup {
fn evaluate<'a>(&'a self, bindings: &'a Tuple, ctx: &'a dyn EvalContext) -> Cow<'a, Value> {
let mut lookups = self.lookups.iter().filter_map(|lookup| {
let val = lookup.evaluate(bindings, ctx);
match val.as_ref() {
Missing => None,
_ => Some(val),
}
});
lookups.next().unwrap_or_else(|| Cow::Owned(Value::Missing))
}
}
/// Represents a variable reference in a (sub)query, e.g. `a` in `SELECT b as a FROM`.
#[derive(Debug)]
pub(crate) struct EvalVarRef {
pub(crate) name: BindingsName,
}
impl EvalExpr for EvalVarRef {
fn evaluate<'a>(&'a self, bindings: &'a Tuple, ctx: &'a dyn EvalContext) -> Cow<'a, Value> {
let value = Bindings::get(bindings, &self.name).or_else(|| ctx.bindings().get(&self.name));
match value {
None => Cow::Owned(Missing),
Some(v) => Cow::Borrowed(v),
}
}
}
/// Represents a literal in (sub)query, e.g. `1` in `a + 1`.
#[derive(Debug)]
pub(crate) struct EvalLitExpr {
pub(crate) lit: Box<Value>,
}
impl EvalExpr for EvalLitExpr {
fn evaluate<'a>(&'a self, _bindings: &'a Tuple, _ctx: &'a dyn EvalContext) -> Cow<'a, Value> {
Cow::Borrowed(self.lit.as_ref())
}
}
/// Represents an evaluation unary operator, e.g. `NOT` in `NOT TRUE`.
#[derive(Debug)]
pub(crate) struct EvalUnaryOpExpr {
pub(crate) op: EvalUnaryOp,
pub(crate) operand: Box<dyn EvalExpr>,
}
// TODO we should replace this enum with some identifier that can be looked up in a symtab/funcregistry
#[derive(Debug)]
pub(crate) enum EvalUnaryOp {
Pos,
Neg,
Not,
}
impl EvalExpr for EvalUnaryOpExpr {
fn evaluate<'a>(&'a self, bindings: &'a Tuple, ctx: &'a dyn EvalContext) -> Cow<'a, Value> {
let operand = self.operand.evaluate(bindings, ctx);
let result = match self.op {
EvalUnaryOp::Pos => operand.into_owned().positive(),
EvalUnaryOp::Neg => -operand.as_ref(),
EvalUnaryOp::Not => !operand.as_ref(),
};
Cow::Owned(result)
}
}
/// Represents a PartiQL evaluation `IS` operator, e.g. `a IS INT`.
#[derive(Debug)]
pub(crate) struct EvalIsTypeExpr {
pub(crate) expr: Box<dyn EvalExpr>,
pub(crate) is_type: Type,
}
impl EvalExpr for EvalIsTypeExpr {
fn evaluate<'a>(&'a self, bindings: &'a Tuple, ctx: &'a dyn EvalContext) -> Cow<'a, Value> {
let expr = self.expr.evaluate(bindings, ctx);
let expr = expr.as_ref();
let result = match self.is_type {
Type::NullType => matches!(expr, Missing | Null),
Type::MissingType => matches!(expr, Missing),
_ => {
ctx.add_error(EvaluationError::NotYetImplemented(
"`IS` for other types".to_string(),
));
false
}
};
Cow::Owned(result.into())
}
}
/// Represents an evaluation binary operator, e.g.`a + b`.
#[derive(Debug)]
pub(crate) struct EvalBinOpExpr {
pub(crate) op: EvalBinOp,
pub(crate) lhs: Box<dyn EvalExpr>,
pub(crate) rhs: Box<dyn EvalExpr>,
}
// TODO we should replace this enum with some identifier that can be looked up in a symtab/funcregistry
#[derive(Debug)]
pub(crate) enum EvalBinOp {
And,
Or,
Concat,
Eq,
Neq,
Gt,
Gteq,
Lt,
Lteq,
// Arithmetic ops
Add,
Sub,
Mul,
Div,
Mod,
Exp,
// Boolean ops
In,
}
impl EvalExpr for EvalBinOpExpr {
fn evaluate<'a>(&'a self, bindings: &'a Tuple, ctx: &'a dyn EvalContext) -> Cow<'a, Value> {
#[inline]
fn short_circuit(op: &EvalBinOp, value: &Value) -> Option<Value> {
match (op, value) {
(EvalBinOp::And, Boolean(false)) => Some(false.into()),
(EvalBinOp::Or, Boolean(true)) => Some(true.into()),
(EvalBinOp::And, Missing) | (EvalBinOp::Or, Missing) | (EvalBinOp::In, Missing) => {
Some(Null)
}
(_, Missing) => Some(Missing),
_ => None,
}
}
let lhs = self.lhs.evaluate(bindings, ctx);
if let Some(propagate) = short_circuit(&self.op, &lhs) {
return Cow::Owned(propagate);
}
let rhs = self.rhs.evaluate(bindings, ctx);
let (lhs, rhs) = (lhs.as_ref(), rhs.as_ref());
let result = match self.op {
EvalBinOp::And => lhs.and(rhs),
EvalBinOp::Or => lhs.or(rhs),
EvalBinOp::Concat => {
// TODO non-naive concat (i.e., don't just use debug print for non-strings).
match (&lhs, &rhs) {
(Missing, _) => Missing,
(_, Missing) => Missing,
(Null, _) => Null,
(_, Null) => Null,
_ => {
let lhs = if let Value::String(s) = lhs {
s.as_ref().clone()
} else {
format!("{lhs:?}")
};
let rhs = if let Value::String(s) = rhs {
s.as_ref().clone()
} else {
format!("{rhs:?}")
};
Value::String(Box::new(format!("{lhs}{rhs}")))
}
}
}
EvalBinOp::Eq => NullableEq::eq(lhs, rhs),
EvalBinOp::Neq => lhs.neq(rhs),
EvalBinOp::Gt => NullableOrd::gt(lhs, rhs),
EvalBinOp::Gteq => NullableOrd::gteq(lhs, rhs),
EvalBinOp::Lt => NullableOrd::lt(lhs, rhs),
EvalBinOp::Lteq => NullableOrd::lteq(lhs, rhs),
EvalBinOp::Add => lhs + rhs,
EvalBinOp::Sub => lhs - rhs,
EvalBinOp::Mul => lhs * rhs,
EvalBinOp::Div => lhs / rhs,
EvalBinOp::Mod => lhs % rhs,
// TODO apply the changes once we clarify the rules of coercion for `IN` RHS.
// See also:
// - https://github.com/partiql/partiql-docs/pull/13
// - https://github.com/partiql/partiql-lang-kotlin/issues/524
// - https://github.com/partiql/partiql-lang-kotlin/pull/621#issuecomment-1147754213
// TODO change the Null propagation if required.
// Current implementation propagates `Null` as described in PartiQL spec section 8 [1]
// and differs from `partiql-lang-kotlin` impl [2].
// [1] https://github.com/partiql/partiql-lang-kotlin/issues/896
// [2] https://partiql.org/assets/PartiQL-Specification.pdf#section.8
EvalBinOp::In => match rhs.is_bag() || rhs.is_list() {
true => {
let mut has_missing = false;
let mut has_null = false;
for elem in rhs.iter() {
// b/c of short_circuiting as we've reached this branch, we know LHS is neither MISSING nor NULL.
if elem == lhs {
return Cow::Owned(Boolean(true));
} else if elem == &Missing {
has_missing = true;
} else if elem == &Null {
has_null = true;
}
}
match has_missing | has_null {
true => Null,
false => Boolean(false),
}
}
_ => Null,
},
EvalBinOp::Exp => {
ctx.add_error(EvaluationError::NotYetImplemented(
"Exponentiation".to_string(),
));
Missing
}
};
Cow::Owned(result)
}
}
/// Represents an evaluation PartiQL `BETWEEN` operator, e.g. `x BETWEEN 10 AND 20`.
#[derive(Debug)]
pub(crate) struct EvalBetweenExpr {
pub(crate) value: Box<dyn EvalExpr>,
pub(crate) from: Box<dyn EvalExpr>,
pub(crate) to: Box<dyn EvalExpr>,
}
impl EvalExpr for EvalBetweenExpr {
fn evaluate<'a>(&'a self, bindings: &'a Tuple, ctx: &'a dyn EvalContext) -> Cow<'a, Value> {
let value = self.value.evaluate(bindings, ctx);
let from = self.from.evaluate(bindings, ctx);
let to = self.to.evaluate(bindings, ctx);
let gteq = value.gteq(from.as_ref());
let lteq = value.lteq(to.as_ref());
Cow::Owned(gteq.and(<eq))
}
}
/// Represents an evaluation `LIKE` operator, e.g. in `s LIKE 'h%llo'`.
#[derive(Debug)]
pub(crate) struct EvalLikeMatch {
pub(crate) value: Box<dyn EvalExpr>,
pub(crate) pattern: Regex,
}
// TODO make configurable?
// Limit chosen somewhat arbitrarily, but to be smaller than the default of `10 * (1 << 20)`
pub(crate) const RE_SIZE_LIMIT: usize = 1 << 16;
impl EvalLikeMatch {
pub(crate) fn new(value: Box<dyn EvalExpr>, pattern: Regex) -> Self {
EvalLikeMatch { value, pattern }
}
}
impl EvalExpr for EvalLikeMatch {
fn evaluate<'a>(&'a self, bindings: &'a Tuple, ctx: &'a dyn EvalContext) -> Cow<'a, Value> {
let value = self.value.evaluate(bindings, ctx);
let result = match value.as_ref() {
Null => Null,
Missing => Missing,
Value::String(s) => Boolean(self.pattern.is_match(s.as_ref())),
_ => Missing,
};
Cow::Owned(result)
}
}
/// Represents an evaluation `LIKE` operator without string literals in the match and/or escape
/// pattern, e.g. in `s LIKE match_str ESCAPE escape_char`.
#[derive(Debug)]
pub(crate) struct EvalLikeNonStringNonLiteralMatch {
pub(crate) value: Box<dyn EvalExpr>,
pub(crate) pattern: Box<dyn EvalExpr>,
pub(crate) escape: Box<dyn EvalExpr>,
}
impl EvalLikeNonStringNonLiteralMatch {
pub(crate) fn new(
value: Box<dyn EvalExpr>,
pattern: Box<dyn EvalExpr>,
escape: Box<dyn EvalExpr>,
) -> Self {
EvalLikeNonStringNonLiteralMatch {
value,
pattern,
escape,
}
}
}
impl EvalExpr for EvalLikeNonStringNonLiteralMatch {
fn evaluate<'a>(&'a self, bindings: &'a Tuple, ctx: &'a dyn EvalContext) -> Cow<'a, Value> {
let value = self.value.evaluate(bindings, ctx);
let pattern = self.pattern.evaluate(bindings, ctx);
let escape = self.escape.evaluate(bindings, ctx);
let result = match (value.as_ref(), pattern.as_ref(), escape.as_ref()) {
(Missing, _, _) => Missing,
(_, Missing, _) => Missing,
(_, _, Missing) => Missing,
(Null, _, _) => Null,
(_, Null, _) => Null,
(_, _, Null) => Null,
(Value::String(v), Value::String(p), Value::String(e)) => {
if e.chars().count() > 1 {
ctx.add_error(EvaluationError::IllegalState(
"escape longer than 1 character".to_string(),
));
}
let escape = e.chars().next();
let regex_pattern = RegexBuilder::new(&like_to_re_pattern(p, escape))
.size_limit(RE_SIZE_LIMIT)
.build();
match regex_pattern {
Ok(pattern) => Boolean(pattern.is_match(v.as_ref())),
Err(err) => {
ctx.add_error(EvaluationError::IllegalState(err.to_string()));
Missing
}
}
}
_ => Missing,
};
Cow::Owned(result)
}
}
/// Represents a searched case operator, e.g. CASE [ WHEN <expr> THEN <expr> ]... [ ELSE <expr> ] END.
#[derive(Debug)]
pub(crate) struct EvalSearchedCaseExpr {
pub(crate) cases: Vec<(Box<dyn EvalExpr>, Box<dyn EvalExpr>)>,
pub(crate) default: Box<dyn EvalExpr>,
}
impl EvalExpr for EvalSearchedCaseExpr {
fn evaluate<'a>(&'a self, bindings: &'a Tuple, ctx: &'a dyn EvalContext) -> Cow<'a, Value> {
for (when_expr, then_expr) in &self.cases {
let when_expr_evaluated = when_expr.evaluate(bindings, ctx);
if when_expr_evaluated.as_ref() == &Value::Boolean(true) {
return then_expr.evaluate(bindings, ctx);
}
}
self.default.evaluate(bindings, ctx)
}
}
#[inline]
#[track_caller]
fn string_transform<FnTransform>(value: &Value, transform_fn: FnTransform) -> Value
where
FnTransform: Fn(&str) -> Value,
{
match value {
Null => Value::Null,
Value::String(s) => transform_fn(s.as_ref()),
_ => Value::Missing,
}
}
/// Represents a built-in `lower` string function, e.g. lower('AdBd').
#[derive(Debug)]
pub(crate) struct EvalFnLower {
pub(crate) value: Box<dyn EvalExpr>,
}
impl EvalExpr for EvalFnLower {
#[inline]
fn evaluate<'a>(&'a self, bindings: &'a Tuple, ctx: &'a dyn EvalContext) -> Cow<'a, Value> {
let transformed = string_transform(self.value.evaluate(bindings, ctx).as_ref(), |s| {
s.to_lowercase().into()
});
Cow::Owned(transformed)
}
}
/// Represents a built-in `upper` string function, e.g. upper('AdBd').
#[derive(Debug)]
pub(crate) struct EvalFnUpper {
pub(crate) value: Box<dyn EvalExpr>,
}
impl EvalExpr for EvalFnUpper {
#[inline]
fn evaluate<'a>(&'a self, bindings: &'a Tuple, ctx: &'a dyn EvalContext) -> Cow<'a, Value> {
let transformed = string_transform(self.value.evaluate(bindings, ctx).as_ref(), |s| {
s.to_uppercase().into()
});
Cow::Owned(transformed)
}
}
/// Represents a built-in character length string function, e.g. `char_length('123456789')`.
#[derive(Debug)]
pub(crate) struct EvalFnCharLength {
pub(crate) value: Box<dyn EvalExpr>,
}
impl EvalExpr for EvalFnCharLength {
#[inline]
fn evaluate<'a>(&'a self, bindings: &'a Tuple, ctx: &'a dyn EvalContext) -> Cow<'a, Value> {
let transformed = string_transform(self.value.evaluate(bindings, ctx).as_ref(), |s| {
s.chars().count().into()
});
Cow::Owned(transformed)
}
}
/// Represents a built-in octet length string function, e.g. `octet_length('123456789')`.
#[derive(Debug)]
pub(crate) struct EvalFnOctetLength {
pub(crate) value: Box<dyn EvalExpr>,
}
impl EvalExpr for EvalFnOctetLength {
#[inline]
fn evaluate<'a>(&'a self, bindings: &'a Tuple, ctx: &'a dyn EvalContext) -> Cow<'a, Value> {
let transformed = string_transform(self.value.evaluate(bindings, ctx).as_ref(), |s| {
s.len().into()
});
Cow::Owned(transformed)
}
}
/// Represents a built-in bit length string function, e.g. `bit_length('123456789')`.
#[derive(Debug)]
pub(crate) struct EvalFnBitLength {
pub(crate) value: Box<dyn EvalExpr>,
}
impl EvalExpr for EvalFnBitLength {
#[inline]
fn evaluate<'a>(&'a self, bindings: &'a Tuple, ctx: &'a dyn EvalContext) -> Cow<'a, Value> {
let transformed = string_transform(self.value.evaluate(bindings, ctx).as_ref(), |s| {
(s.len() * 8).into()
});
Cow::Owned(transformed)
}
}
/// Represents a built-in substring string function, e.g. `substring('123456789' FROM 2)`.
#[derive(Debug)]
pub(crate) struct EvalFnSubstring {
pub(crate) value: Box<dyn EvalExpr>,
pub(crate) offset: Box<dyn EvalExpr>,
pub(crate) length: Option<Box<dyn EvalExpr>>,
}
impl EvalExpr for EvalFnSubstring {
#[inline]
fn evaluate<'a>(&'a self, bindings: &'a Tuple, ctx: &'a dyn EvalContext) -> Cow<'a, Value> {
let value = self.value.evaluate(bindings, ctx);
let value = match value.as_ref() {
Null => None,
Value::String(s) => Some(s),
_ => return Cow::Owned(Value::Missing),
};
let offset = self.offset.evaluate(bindings, ctx);
let offset = match offset.as_ref() {
Null => None,
Value::Integer(i) => Some(i),
_ => return Cow::Owned(Value::Missing),
};
let result = if let Some(length) = &self.length {
let length = match length.evaluate(bindings, ctx).as_ref() {
Value::Integer(i) => *i as usize,
Value::Null => return Cow::Owned(Value::Null),
_ => return Cow::Owned(Value::Missing),
};
if let (Some(value), Some(&offset)) = (value, offset) {
let (offset, length) = if length < 1 {
(0, 0)
} else if offset < 1 {
let length = std::cmp::max(offset + (length - 1) as i64, 0) as usize;
let offset = std::cmp::max(offset, 0) as usize;
(offset, length)
} else {
((offset - 1) as usize, length)
};
value
.chars()
.skip(offset)
.take(length)
.collect::<String>()
.into()
} else {
// either value or offset was NULL; return NULL
Value::Null
}
} else if let (Some(value), Some(&offset)) = (value, offset) {
let offset = (std::cmp::max(offset, 1) - 1) as usize;
value.chars().skip(offset).collect::<String>().into()
} else {
// either value or offset was NULL; return NULL
Value::Null
};
Cow::Owned(result)
}
}
/// Represents a built-in position string function, e.g. `position('3' IN '123456789')`.
#[derive(Debug)]
pub(crate) struct EvalFnPosition {
pub(crate) needle: Box<dyn EvalExpr>,
pub(crate) haystack: Box<dyn EvalExpr>,
}
impl EvalExpr for EvalFnPosition {
#[inline]
fn evaluate<'a>(&'a self, bindings: &'a Tuple, ctx: &'a dyn EvalContext) -> Cow<'a, Value> {
let needle = self.needle.evaluate(bindings, ctx);
let needle = match needle.as_ref() {
Null => None,
Value::String(s) => Some(s),
_ => return Cow::Owned(Value::Missing),
};
let haystack = self.haystack.evaluate(bindings, ctx);
let haystack = match haystack.as_ref() {
Value::Null => return Cow::Owned(Value::Null),
Value::String(s) => s,
_ => return Cow::Owned(Value::Missing),
};
let result = if let Some(needle) = needle {
haystack
.find(needle.as_ref())
.map(|l| l + 1)
.unwrap_or(0)
.into()
} else {
Value::Null
};
Cow::Owned(result)
}
}
/// Represents a built-in overlay string function, e.g. `OVERLAY('hello' PLACING 'XX' FROM 2 FOR 3)`.
#[derive(Debug)]
pub(crate) struct EvalFnOverlay {
pub(crate) value: Box<dyn EvalExpr>,
pub(crate) replacement: Box<dyn EvalExpr>,
pub(crate) offset: Box<dyn EvalExpr>,
pub(crate) length: Option<Box<dyn EvalExpr>>,
}
impl EvalExpr for EvalFnOverlay {
#[inline]
fn evaluate<'a>(&'a self, bindings: &'a Tuple, ctx: &'a dyn EvalContext) -> Cow<'a, Value> {
let value = self.value.evaluate(bindings, ctx);
let value = match value.as_ref() {
Null => None,
Value::String(s) => Some(s),
_ => return Cow::Owned(Value::Missing),
};
let replacement = self.replacement.evaluate(bindings, ctx);
let replacement = match replacement.as_ref() {
Null => None,
Value::String(s) => Some(s),
_ => return Cow::Owned(Value::Missing),
};
let offset = self.offset.evaluate(bindings, ctx);
let offset = match offset.as_ref() {
Null => None,
Value::Integer(i) => Some(i),
_ => return Cow::Owned(Value::Missing),
};
let length = if let Some(length) = &self.length {
match length.evaluate(bindings, ctx).as_ref() {
Value::Integer(i) => *i as usize,
Value::Null => return Cow::Owned(Value::Null),
_ => return Cow::Owned(Value::Missing),
}
} else if let Some(replacement) = &replacement {
replacement.len()
} else {
// either replacement or length was NULL; return NULL
return Cow::Owned(Value::Null);
};
let result =
if let (Some(value), Some(replacement), Some(&offset)) = (value, replacement, offset) {
let mut value = *value.clone();
let start = std::cmp::max(offset - 1, 0) as usize;
if start > value.len() {
value += replacement;
} else {
let end = std::cmp::min(start + length, value.len());
value.replace_range(start..end, replacement);
}
Value::from(value)
} else {
// either value, replacement, or offset was NULL; return NULL
Value::Null
};
Cow::Owned(result)
}
}
#[inline]
#[track_caller]
fn trim<'a, FnTrim>(value: &'a Value, to_trim: &'a Value, trim_fn: FnTrim) -> Value
where
FnTrim: Fn(&'a str, &'a str) -> &'a str,
{
let value = match value {
Value::String(s) => Some(s),
Null => None,
_ => return Value::Missing,
};
let to_trim = match to_trim {
Value::String(s) => s,
Null => return Value::Null,
_ => return Value::Missing,
};
if let Some(s) = value {
let trimmed = trim_fn(s, to_trim);
Value::from(trimmed)
} else {
Value::Null
}
}
/// Represents a built-in both trim string function, e.g. `trim(both from ' foobar ')`.
#[derive(Debug)]
pub(crate) struct EvalFnBtrim {
pub(crate) value: Box<dyn EvalExpr>,
pub(crate) to_trim: Box<dyn EvalExpr>,
}
impl EvalExpr for EvalFnBtrim {
#[inline]
fn evaluate<'a>(&'a self, bindings: &'a Tuple, ctx: &'a dyn EvalContext) -> Cow<'a, Value> {
let value = self.value.evaluate(bindings, ctx);
let to_trim = self.to_trim.evaluate(bindings, ctx);
let trimmed = trim(value.as_ref(), to_trim.as_ref(), |s, to_trim| {
let to_trim = to_trim.chars().collect_vec();
s.trim_matches(&to_trim[..])
});
Cow::Owned(trimmed)
}
}
/// Represents a built-in right trim string function.
#[derive(Debug)]
pub(crate) struct EvalFnRtrim {
pub(crate) value: Box<dyn EvalExpr>,
pub(crate) to_trim: Box<dyn EvalExpr>,
}
impl EvalExpr for EvalFnRtrim {
#[inline]
fn evaluate<'a>(&'a self, bindings: &'a Tuple, ctx: &'a dyn EvalContext) -> Cow<'a, Value> {
let value = self.value.evaluate(bindings, ctx);
let to_trim = self.to_trim.evaluate(bindings, ctx);
let trimmed = trim(value.as_ref(), to_trim.as_ref(), |s, to_trim| {
let to_trim = to_trim.chars().collect_vec();
s.trim_end_matches(&to_trim[..])
});
Cow::Owned(trimmed)
}
}
/// Represents a built-in left trim string function.
#[derive(Debug)]
pub(crate) struct EvalFnLtrim {
pub(crate) value: Box<dyn EvalExpr>,
pub(crate) to_trim: Box<dyn EvalExpr>,
}
impl EvalExpr for EvalFnLtrim {
#[inline]
fn evaluate<'a>(&'a self, bindings: &'a Tuple, ctx: &'a dyn EvalContext) -> Cow<'a, Value> {
let value = self.value.evaluate(bindings, ctx);
let to_trim = self.to_trim.evaluate(bindings, ctx);
let trimmed = trim(value.as_ref(), to_trim.as_ref(), |s, to_trim| {
let to_trim = to_trim.chars().collect_vec();
s.trim_start_matches(&to_trim[..])
});
Cow::Owned(trimmed)
}
}
/// Represents an `EXISTS` function, e.g. `exists(`(1)`)`.
#[derive(Debug)]
pub(crate) struct EvalFnExists {
pub(crate) value: Box<dyn EvalExpr>,
}
impl EvalExpr for EvalFnExists {
#[inline]
fn evaluate<'a>(&'a self, bindings: &'a Tuple, ctx: &'a dyn EvalContext) -> Cow<'a, Value> {
let value = self.value.evaluate(bindings, ctx);
let exists = match value.borrow() {
Value::Bag(b) => !b.is_empty(),
Value::List(l) => !l.is_empty(),
Value::Tuple(t) => !t.is_empty(),
_ => false,
};
Cow::Owned(Value::Boolean(exists))
}
}
/// Represents an `ABS` function, e.g. `abs(-1)`.
#[derive(Debug)]
pub(crate) struct EvalFnAbs {
pub(crate) value: Box<dyn EvalExpr>,
}
impl EvalExpr for EvalFnAbs {
#[inline]
fn evaluate<'a>(&'a self, bindings: &'a Tuple, ctx: &'a dyn EvalContext) -> Cow<'a, Value> {
let value = self.value.evaluate(bindings, ctx);
let lhs: &Value = value.borrow();
let rhs = 0.into();
match NullableOrd::lt(lhs, &rhs) {
Null => Cow::Owned(Null),
Missing => Cow::Owned(Missing),
Value::Boolean(true) => Cow::Owned(-value.into_owned()),
_ => Cow::Owned(value.into_owned()),
}
}
}
/// Represents an `MOD` function, e.g. `MOD(10, 1)`.
#[derive(Debug)]
pub(crate) struct EvalFnModulus {
pub(crate) lhs: Box<dyn EvalExpr>,
pub(crate) rhs: Box<dyn EvalExpr>,
}
impl EvalExpr for EvalFnModulus {
#[inline]
fn evaluate<'a>(&'a self, bindings: &'a Tuple, ctx: &'a dyn EvalContext) -> Cow<'a, Value> {
let lhs = self.lhs.evaluate(bindings, ctx);
let lhs = match lhs.as_ref() {
Null => None,
Missing => return Cow::Owned(Value::Missing),
_ => Some(lhs),
};
let rhs = self.rhs.evaluate(bindings, ctx);
let rhs = match rhs.as_ref() {
Value::Null => return Cow::Owned(Value::Null),
Missing => return Cow::Owned(Value::Missing),
_ => rhs,
};
if let Some(lhs) = lhs {
let lhs: &Value = lhs.borrow();
let rhs: &Value = rhs.borrow();
Cow::Owned(lhs % rhs)
} else {
Cow::Owned(Value::Null)
}
}
}
/// Represents an `CARDINALITY` function, e.g. `cardinality([1,2,3])`.
#[derive(Debug)]
pub(crate) struct EvalFnCardinality {
pub(crate) value: Box<dyn EvalExpr>,
}
impl EvalExpr for EvalFnCardinality {
#[inline]
fn evaluate<'a>(&'a self, bindings: &'a Tuple, ctx: &'a dyn EvalContext) -> Cow<'a, Value> {
let value = self.value.evaluate(bindings, ctx);
let result = match value.borrow() {
Null => Null,
Missing => Missing,
Value::List(l) => Value::from(l.len()),
Value::Bag(b) => Value::from(b.len()),
Value::Tuple(t) => Value::from(t.len()),
_ => Missing,
};
Cow::Owned(result)
}
}
/// Represents a year `EXTRACT` function, e.g. `extract(YEAR FROM t)`.
#[derive(Debug)]
pub(crate) struct EvalFnExtractYear {
pub(crate) value: Box<dyn EvalExpr>,
}
impl EvalExpr for EvalFnExtractYear {
#[inline]
fn evaluate<'a>(&'a self, bindings: &'a Tuple, ctx: &'a dyn EvalContext) -> Cow<'a, Value> {
let value = self.value.evaluate(bindings, ctx);
let result = match value.borrow() {
Null => Null,
Value::DateTime(dt) => match dt.as_ref() {
DateTime::Date(d) => Value::from(d.year()),
DateTime::Timestamp(tstamp) => Value::from(tstamp.year()),
DateTime::TimestampWithTz(tstamp) => Value::from(tstamp.year()),
DateTime::Time(_) => Missing,
DateTime::TimeWithTz(_, _) => Missing,
},
_ => Missing,
};
Cow::Owned(result)
}
}
/// Represents a month `EXTRACT` function, e.g. `extract(MONTH FROM t)`.
#[derive(Debug)]
pub(crate) struct EvalFnExtractMonth {
pub(crate) value: Box<dyn EvalExpr>,
}
impl EvalExpr for EvalFnExtractMonth {
#[inline]
fn evaluate<'a>(&'a self, bindings: &'a Tuple, ctx: &'a dyn EvalContext) -> Cow<'a, Value> {
let value = self.value.evaluate(bindings, ctx);
let result = match value.borrow() {
Null => Null,
Value::DateTime(dt) => match dt.as_ref() {
DateTime::Date(d) => Value::from(d.month() as u8),
DateTime::Timestamp(tstamp) => Value::from(tstamp.month() as u8),
DateTime::TimestampWithTz(tstamp) => Value::from(tstamp.month() as u8),