1use std::collections::BTreeMap;
11use std::fmt::Debug;
12
13use mz_repr::{Datum, ReprColumnType, ReprRelationType, ReprScalarType, Row, RowArena};
14
15use crate::scalar::func::variadic::And;
16use crate::scalar::optimizable::OptimizableExpr;
17use crate::{
18 BinaryFunc, Eval, EvalError, MapFilterProject, MfpPlan, MirScalarExpr, UnaryFunc,
19 UnmaterializableFunc, VariadicFunc, func,
20};
21fn datum_is_nan(datum: Datum) -> bool {
30 match datum {
31 Datum::Float32(f) => f.is_nan(),
32 Datum::Float64(f) => f.is_nan(),
33 Datum::Numeric(n) => n.0.is_nan(),
34 _ => false,
35 }
36}
37
38fn datum_is_infinite(datum: Datum) -> bool {
40 match datum {
41 Datum::Float32(f) => f.is_infinite(),
42 Datum::Float64(f) => f.is_infinite(),
43 Datum::Numeric(n) => n.0.is_infinite(),
44 _ => false,
45 }
46}
47
48#[derive(Clone, Eq, PartialEq, Debug)]
50enum Values<'a> {
51 Empty,
53 Within(Datum<'a>, Datum<'a>),
56 Nested(BTreeMap<Datum<'a>, ResultSpec<'a>>),
60 All,
63}
64
65impl<'a> Values<'a> {
66 fn just(a: Datum<'a>) -> Values<'a> {
67 match a {
68 Datum::Map(datum_map) => Values::Nested(
69 datum_map
70 .iter()
71 .map(|(key, val)| (key.into(), ResultSpec::value(val)))
72 .collect(),
73 ),
74 other => Self::Within(other, other),
75 }
76 }
77
78 fn union(self, other: Values<'a>) -> Values<'a> {
79 match (self, other) {
80 (Values::Empty, r) => r,
81 (r, Values::Empty) => r,
82 (Values::Within(a0, a1), Values::Within(b0, b1)) => {
83 Values::Within(a0.min(b0), a1.max(b1))
84 }
85 (Values::Nested(a), Values::Nested(mut b)) => {
86 let mut merged = BTreeMap::new();
91 for (key, a_spec) in a {
92 if let Some(b_spec) = b.remove(&key) {
93 let unioned = a_spec.union(b_spec);
94 if unioned != ResultSpec::anything() {
95 merged.insert(key, unioned);
96 }
97 }
98 }
99 if merged.is_empty() {
100 Values::All
101 } else {
102 Values::Nested(merged)
103 }
104 }
105 _ => Values::All,
106 }
107 }
108
109 fn intersect(self, other: Values<'a>) -> Values<'a> {
110 match (self, other) {
111 (Values::Empty, _) => Values::Empty,
112 (_, Values::Empty) => Values::Empty,
113 (Values::Within(a0, a1), Values::Within(b0, b1)) => {
114 let min = a0.max(b0);
115 let max = a1.min(b1);
116 if min <= max {
117 Values::Within(min, max)
118 } else {
119 Values::Empty
120 }
121 }
122 (Values::Nested(mut a), Values::Nested(b)) => {
123 for (datum, other_spec) in b {
124 let spec = a.entry(datum).or_insert_with(ResultSpec::anything);
125 *spec = spec.clone().intersect(other_spec);
126 }
127 Values::Nested(a)
128 }
129 (Values::All, v) => v,
130 (v, Values::All) => v,
131 (nested @ Values::Nested(_), Values::Within(_, _))
138 | (Values::Within(_, _), nested @ Values::Nested(_)) => nested,
139 }
140 }
141
142 fn may_contain(&self, value: Datum<'a>) -> bool {
143 match self {
144 Values::Empty => false,
145 Values::Within(min, max) => *min <= value && value <= *max,
146 Values::All => true,
147 Values::Nested(field_map) => match value {
148 Datum::Map(datum_map) => {
149 datum_map
150 .iter()
151 .all(|(key, val)| match field_map.get(&key.into()) {
152 None => true,
153 Some(nested) => nested.may_contain(val),
154 })
155 }
156 _ => false,
157 },
158 }
159 }
160
161 fn as_single(&self) -> Option<Datum<'a>> {
170 match self {
171 Values::Within(a, b) if a == b => Some(*a),
172 _ => None,
173 }
174 }
175}
176
177#[derive(Debug, Clone, Eq, PartialEq)]
182pub struct ResultSpec<'a> {
183 nullable: bool,
185 fallible: bool,
187 values: Values<'a>,
189}
190
191impl<'a> ResultSpec<'a> {
192 pub fn nothing() -> Self {
194 ResultSpec {
195 nullable: false,
196 fallible: false,
197 values: Values::Empty,
198 }
199 }
200
201 pub fn anything() -> Self {
203 ResultSpec {
204 nullable: true,
205 fallible: true,
206 values: Values::All,
207 }
208 }
209
210 pub fn any_infallible() -> Self {
212 ResultSpec {
213 nullable: true,
214 fallible: false,
215 values: Values::All,
216 }
217 }
218
219 pub fn null() -> Self {
221 ResultSpec {
222 nullable: true,
223 ..Self::nothing()
224 }
225 }
226
227 pub fn fails() -> Self {
229 ResultSpec {
230 fallible: true,
231 ..Self::nothing()
232 }
233 }
234
235 pub fn has_type(col: &ReprColumnType, fallible: bool) -> ResultSpec<'a> {
237 let values = match &col.scalar_type {
238 ReprScalarType::Bool => Values::Within(Datum::False, Datum::True),
239 _ => Values::All,
241 };
242 ResultSpec {
243 nullable: col.nullable,
244 fallible,
245 values,
246 }
247 }
248
249 pub fn value(value: Datum<'a>) -> ResultSpec<'a> {
251 match value {
252 Datum::Null => Self::null(),
253 nonnull => ResultSpec {
254 values: Values::just(nonnull),
255 ..Self::nothing()
256 },
257 }
258 }
259
260 pub fn value_between(min: Datum<'a>, max: Datum<'a>) -> ResultSpec<'a> {
269 assert!(!min.is_null());
270 assert!(!max.is_null());
271 if min <= max {
272 ResultSpec {
273 values: Values::Within(min, max),
274 ..ResultSpec::nothing()
275 }
276 } else {
277 ResultSpec::value_all()
278 }
279 }
280
281 pub fn value_all() -> ResultSpec<'a> {
283 ResultSpec {
284 values: Values::All,
285 ..ResultSpec::nothing()
286 }
287 }
288
289 pub fn map_spec(map: BTreeMap<Datum<'a>, ResultSpec<'a>>) -> ResultSpec<'a> {
291 ResultSpec {
292 values: Values::Nested(map),
293 ..ResultSpec::nothing()
294 }
295 }
296
297 pub fn union(self, other: ResultSpec<'a>) -> ResultSpec<'a> {
299 ResultSpec {
300 nullable: self.nullable || other.nullable,
301 fallible: self.fallible || other.fallible,
302 values: self.values.union(other.values),
303 }
304 }
305
306 pub fn intersect(self, other: ResultSpec<'a>) -> ResultSpec<'a> {
308 ResultSpec {
309 nullable: self.nullable && other.nullable,
310 fallible: self.fallible && other.fallible,
311 values: self.values.intersect(other.values),
312 }
313 }
314
315 pub fn may_contain(&self, value: Datum<'a>) -> bool {
317 if value == Datum::Null {
318 return self.nullable;
319 }
320
321 self.values.may_contain(value)
322 }
323
324 pub fn may_fail(&self) -> bool {
326 self.fallible
327 }
328
329 fn is_single_value(&self) -> bool {
337 self.values.as_single().is_some()
338 }
339
340 fn may_be_infinite(&self) -> bool {
344 match &self.values {
345 Values::Within(min, max) => datum_is_infinite(*min) || datum_is_infinite(*max),
346 Values::All => true,
347 Values::Empty | Values::Nested(_) => false,
348 }
349 }
350
351 fn flat_map(
362 &self,
363 is_monotone: bool,
364 mut result_map: impl FnMut(Result<Datum<'a>, EvalError>) -> ResultSpec<'a>,
365 ) -> ResultSpec<'a> {
366 let null_spec = if self.nullable {
367 result_map(Ok(Datum::Null))
368 } else {
369 ResultSpec::nothing()
370 };
371
372 let error_spec = if self.fallible {
373 let map_err = result_map(Err(EvalError::Internal("".into())));
377 let raise_err = ResultSpec::fails();
378 raise_err.union(map_err)
383 } else {
384 ResultSpec::nothing()
385 };
386
387 let values_spec = match self.values {
388 Values::Empty => ResultSpec::nothing(),
389 Values::Within(min, max) if min == max => result_map(Ok(min)),
391 Values::Within(Datum::False, Datum::True) => {
393 result_map(Ok(Datum::False)).union(result_map(Ok(Datum::True)))
394 }
395 Values::Within(min, max) if is_monotone && !datum_is_nan(min) && !datum_is_nan(max) => {
402 let min_result = result_map(Ok(min));
403 let max_result = result_map(Ok(max));
404 match (min_result, max_result) {
413 (
416 ResultSpec {
417 nullable: n1,
418 fallible: f1,
419 values: a_values @ Values::Within(..),
420 },
421 ResultSpec {
422 nullable: n2,
423 fallible: f2,
424 values: b_values @ Values::Within(..),
425 },
426 ) => ResultSpec {
427 nullable: n1 || n2,
428 fallible: f1 || f2,
429 values: a_values.union(b_values),
430 },
431 (
437 ResultSpec {
438 nullable: true,
439 fallible: false,
440 values: Values::Empty,
441 },
442 ResultSpec {
443 nullable: true,
444 fallible: false,
445 values: Values::Empty,
446 },
447 ) => ResultSpec::null(),
448 _ => ResultSpec::anything(),
450 }
451 }
452 Values::Within(_, _) | Values::Nested(_) | Values::All => ResultSpec::anything(),
454 };
455
456 null_spec.union(error_spec).union(values_spec)
457 }
458}
459
460pub trait Interpreter {
469 type Summary: Clone + Debug + Sized;
470
471 fn column(&self, id: usize) -> Self::Summary;
473
474 fn literal(&self, result: &Result<Row, EvalError>, col_type: &ReprColumnType) -> Self::Summary;
477 fn unmaterializable(&self, func: &UnmaterializableFunc) -> Self::Summary;
482
483 fn unary(&self, func: &UnaryFunc, expr: Self::Summary) -> Self::Summary;
485
486 fn binary(&self, func: &BinaryFunc, left: Self::Summary, right: Self::Summary)
488 -> Self::Summary;
489
490 fn variadic(&self, func: &VariadicFunc, exprs: Vec<Self::Summary>) -> Self::Summary;
492
493 fn cond(&self, cond: Self::Summary, then: Self::Summary, els: Self::Summary) -> Self::Summary;
495
496 fn expr<X: Interpretable>(&self, expr: &X) -> Self::Summary {
498 expr.interpret(self)
499 }
500
501 fn mfp_filter<X: Interpretable + OptimizableExpr>(
504 &self,
505 mfp: &MapFilterProject<X>,
506 ) -> Self::Summary {
507 let mfp_eval = MfpEval::new(self, mfp.input_arity, &mfp.expressions);
508 let predicates = mfp
510 .predicates
511 .iter()
512 .map(|(_, e)| mfp_eval.expr(e))
513 .collect();
514 mfp_eval.variadic(&And.into(), predicates)
515 }
516
517 fn mfp_plan_filter<X: Interpretable + OptimizableExpr>(
520 &self,
521 plan: &MfpPlan<X>,
522 ) -> Self::Summary {
523 let mfp_eval = MfpEval::new(self, plan.mfp.input_arity, &plan.mfp.expressions);
524 let mut results: Vec<_> = plan
526 .mfp
527 .predicates
528 .iter()
529 .map(|(_, e)| mfp_eval.expr(e))
530 .collect();
531 let mz_now = mfp_eval.unmaterializable(&UnmaterializableFunc::MzNow);
532 for bound in &plan.lower_bounds {
533 let bound_range = mfp_eval.expr(bound);
534 let result = mfp_eval.binary(&BinaryFunc::Lte(func::Lte), bound_range, mz_now.clone());
535 results.push(result);
536 }
537 for bound in &plan.upper_bounds {
538 let bound_range = mfp_eval.expr(bound);
539 let result = mfp_eval.binary(&BinaryFunc::Gte(func::Gte), bound_range, mz_now.clone());
540 results.push(result);
541 }
542 self.variadic(&And.into(), results)
543 }
544}
545
546pub trait Interpretable {
551 fn interpret<I: Interpreter + ?Sized>(&self, interpreter: &I) -> I::Summary;
553}
554
555impl Interpretable for MirScalarExpr {
556 fn interpret<I: Interpreter + ?Sized>(&self, interpreter: &I) -> I::Summary {
557 match self {
558 MirScalarExpr::Column(id, _name) => interpreter.column(*id),
559 MirScalarExpr::Literal(value, col_type) => interpreter.literal(value, col_type),
560 MirScalarExpr::CallUnmaterializable(func) => interpreter.unmaterializable(func),
561 MirScalarExpr::CallUnary { func, expr } => {
562 let expr_range = expr.interpret(interpreter);
563 interpreter.unary(func, expr_range)
564 }
565 MirScalarExpr::CallBinary { func, expr1, expr2 } => {
566 let expr1_range = expr1.interpret(interpreter);
567 let expr2_range = expr2.interpret(interpreter);
568 interpreter.binary(func, expr1_range, expr2_range)
569 }
570 MirScalarExpr::CallVariadic { func, exprs } => {
571 let exprs: Vec<_> = exprs.iter().map(|e| e.interpret(interpreter)).collect();
572 interpreter.variadic(func, exprs)
573 }
574 MirScalarExpr::If { cond, then, els } => {
575 let cond_range = cond.interpret(interpreter);
576 let then_range = then.interpret(interpreter);
577 let els_range = els.interpret(interpreter);
578 interpreter.cond(cond_range, then_range, els_range)
579 }
580 }
581 }
582}
583
584pub(crate) struct MfpEval<'a, E: Interpreter + ?Sized> {
587 evaluator: &'a E,
588 input_arity: usize,
589 expressions: Vec<E::Summary>,
590}
591
592impl<'a, E: Interpreter + ?Sized> MfpEval<'a, E> {
593 pub(crate) fn new<X: Interpretable>(
594 evaluator: &'a E,
595 input_arity: usize,
596 expressions: &[X],
597 ) -> Self {
598 let mut mfp_eval = MfpEval {
599 evaluator,
600 input_arity,
601 expressions: vec![],
602 };
603 for expr in expressions {
604 let result = mfp_eval.expr(expr);
605 mfp_eval.expressions.push(result);
606 }
607 mfp_eval
608 }
609}
610
611impl<'a, E: Interpreter + ?Sized> Interpreter for MfpEval<'a, E> {
612 type Summary = E::Summary;
613
614 fn column(&self, id: usize) -> Self::Summary {
615 if id < self.input_arity {
616 self.evaluator.column(id)
617 } else {
618 self.expressions[id - self.input_arity].clone()
619 }
620 }
621
622 fn literal(&self, result: &Result<Row, EvalError>, col_type: &ReprColumnType) -> Self::Summary {
623 self.evaluator.literal(result, col_type)
624 }
625
626 fn unmaterializable(&self, func: &UnmaterializableFunc) -> Self::Summary {
627 self.evaluator.unmaterializable(func)
628 }
629
630 fn unary(&self, func: &UnaryFunc, expr: Self::Summary) -> Self::Summary {
631 self.evaluator.unary(func, expr)
632 }
633
634 fn binary(
635 &self,
636 func: &BinaryFunc,
637 left: Self::Summary,
638 right: Self::Summary,
639 ) -> Self::Summary {
640 self.evaluator.binary(func, left, right)
641 }
642
643 fn variadic(&self, func: &VariadicFunc, exprs: Vec<Self::Summary>) -> Self::Summary {
644 self.evaluator.variadic(func, exprs)
645 }
646
647 fn cond(&self, cond: Self::Summary, then: Self::Summary, els: Self::Summary) -> Self::Summary {
648 self.evaluator.cond(cond, then, els)
649 }
650}
651
652struct SpecialUnary {
657 map_fn: for<'a, 'b> fn(&'b ColumnSpecs<'a>, ResultSpec<'a>) -> ResultSpec<'a>,
658 pushdownable: bool,
659}
660
661impl SpecialUnary {
662 fn for_func(func: &UnaryFunc) -> Option<SpecialUnary> {
664 fn eagerly<'b>(
668 spec: ResultSpec<'b>,
669 value_fn: impl FnOnce(Values<'b>) -> ResultSpec<'b>,
670 ) -> ResultSpec<'b> {
671 let result = match spec.values {
672 Values::Empty => ResultSpec::nothing(),
673 other => value_fn(other),
674 };
675 ResultSpec {
676 fallible: spec.fallible || result.fallible,
677 nullable: spec.nullable || result.nullable,
678 values: result.values,
679 }
680 }
681 match func {
682 UnaryFunc::TryParseMonotonicIso8601Timestamp(_) => Some(SpecialUnary {
683 map_fn: |specs, range| {
684 let expr = MirScalarExpr::CallUnary {
685 func: UnaryFunc::TryParseMonotonicIso8601Timestamp(
686 crate::func::TryParseMonotonicIso8601Timestamp,
687 ),
688 expr: Box::new(MirScalarExpr::column(0)),
689 };
690 let eval = |d| specs.eval_result(expr.eval(&[d], specs.arena));
691
692 eagerly(range, |values| {
693 match values {
694 Values::Within(a, b) if a == b => eval(a),
695 Values::Within(a, b) => {
696 let spec = eval(a).union(eval(b));
697 let values_spec = if spec.nullable {
698 ResultSpec::value_all()
704 } else {
705 spec
706 };
707 values_spec.union(ResultSpec::null())
711 }
712 _ => ResultSpec::any_infallible(),
715 }
716 })
717 },
718 pushdownable: true,
719 }),
720 _ => None,
721 }
722 }
723}
724
725struct AbstractFunc {
736 handler: AbstractFuncHandler,
737 pushdownable: (bool, bool),
743}
744
745enum AbstractFuncHandler {
747 Override(for<'a> fn(ResultSpec<'a>, ResultSpec<'a>) -> ResultSpec<'a>),
750 DynamicMonotone(fn(&ResultSpec<'_>, &ResultSpec<'_>) -> (bool, bool)),
757}
758
759impl AbstractFunc {
760 fn for_func(func: &BinaryFunc) -> Option<AbstractFunc> {
762 fn eagerly<'b>(
766 left: ResultSpec<'b>,
767 right: ResultSpec<'b>,
768 value_fn: impl FnOnce(Values<'b>, Values<'b>) -> ResultSpec<'b>,
769 ) -> ResultSpec<'b> {
770 let result = match (left.values, right.values) {
771 (Values::Empty, _) | (_, Values::Empty) => ResultSpec::nothing(),
772 (l, r) => value_fn(l, r),
773 };
774 ResultSpec {
775 fallible: left.fallible || right.fallible || result.fallible,
776 nullable: left.nullable || right.nullable || result.nullable,
777 values: result.values,
778 }
779 }
780
781 fn jsonb_get_string<'b>(
782 left: ResultSpec<'b>,
783 right: ResultSpec<'b>,
784 stringify: bool,
785 ) -> ResultSpec<'b> {
786 eagerly(left, right, |left, right| {
787 let nested_spec = match (left, right) {
788 (Values::Nested(mut map_spec), Values::Within(key, key2)) if key == key2 => {
789 map_spec.remove(&key)
790 }
791 _ => None,
792 };
793
794 if let Some(field_spec) = nested_spec {
795 if stringify {
796 let values = match field_spec.values {
799 Values::Empty => Values::Empty,
800 Values::Within(min @ Datum::String(_), max @ Datum::String(_)) => {
801 Values::Within(min, max)
802 }
803 Values::Within(_, _) | Values::Nested(_) | Values::All => Values::All,
804 };
805 ResultSpec {
806 values,
807 ..field_spec
808 }
809 } else {
810 field_spec
811 }
812 } else {
813 ResultSpec::any_infallible()
818 }
819 })
820 }
821
822 fn eq<'b>(left: ResultSpec<'b>, right: ResultSpec<'b>) -> ResultSpec<'b> {
823 eagerly(left, right, |left, right| {
824 let maybe_true = match left.clone().intersect(right.clone()) {
826 Values::Empty => ResultSpec::nothing(),
827 _ => ResultSpec::value(Datum::True),
828 };
829
830 let maybe_false = match left.union(right) {
833 Values::Within(a, b) if a == b => ResultSpec::nothing(),
834 _ => ResultSpec::value(Datum::False),
835 };
836
837 maybe_true.union(maybe_false)
838 })
839 }
840
841 fn timestamp_plus_interval_monotone(
850 _left: &ResultSpec<'_>,
851 right: &ResultSpec<'_>,
852 ) -> (bool, bool) {
853 let months_zero = matches!(
854 right.values.as_single(),
855 Some(Datum::Interval(i)) if i.months == 0,
856 );
857 (months_zero, months_zero)
858 }
859
860 match func {
861 BinaryFunc::JsonbGetString(_) => Some(AbstractFunc {
862 handler: AbstractFuncHandler::Override(|l, r| jsonb_get_string(l, r, false)),
863 pushdownable: (true, false),
864 }),
865 BinaryFunc::JsonbGetStringStringify(_) => Some(AbstractFunc {
866 handler: AbstractFuncHandler::Override(|l, r| jsonb_get_string(l, r, true)),
867 pushdownable: (true, false),
868 }),
869 BinaryFunc::Eq(_) => Some(AbstractFunc {
870 handler: AbstractFuncHandler::Override(eq),
871 pushdownable: (true, true),
872 }),
873 BinaryFunc::AddTimestampInterval(_)
874 | BinaryFunc::AddTimestampTzInterval(_)
875 | BinaryFunc::SubTimestampInterval(_)
876 | BinaryFunc::SubTimestampTzInterval(_) => Some(AbstractFunc {
877 handler: AbstractFuncHandler::DynamicMonotone(timestamp_plus_interval_monotone),
878 pushdownable: (true, false),
885 }),
886 _ => None,
887 }
888 }
889}
890
891#[derive(Clone, Debug)]
892pub struct ColumnSpec<'a> {
893 pub col_type: ReprColumnType,
894 pub range: ResultSpec<'a>,
895}
896
897#[derive(Clone, Debug)]
903pub struct ColumnSpecs<'a> {
904 pub relation: &'a ReprRelationType,
905 pub columns: Vec<ResultSpec<'a>>,
906 pub unmaterializables: BTreeMap<UnmaterializableFunc, ResultSpec<'a>>,
907 pub arena: &'a RowArena,
908}
909
910impl<'a> ColumnSpecs<'a> {
911 const MAX_EVAL_ARGS: usize = 6;
918
919 pub fn new(relation: &'a ReprRelationType, arena: &'a RowArena) -> Self {
922 let columns = relation
923 .column_types
924 .iter()
925 .map(|ct| ResultSpec::has_type(ct, false))
926 .collect();
927 ColumnSpecs {
928 relation,
929 columns,
930 unmaterializables: Default::default(),
931 arena,
932 }
933 }
934
935 pub fn push_column(&mut self, id: usize, update: ResultSpec<'a>) {
938 let range = self.columns.get_mut(id).expect("valid column id");
939 *range = range.clone().intersect(update);
940 }
941
942 pub fn push_unmaterializable(&mut self, func: UnmaterializableFunc, update: ResultSpec<'a>) {
945 let range = self
946 .unmaterializables
947 .entry(func.clone())
948 .or_insert_with(|| ResultSpec::has_type(&func.output_type(), true));
949 *range = range.clone().intersect(update);
950 }
951
952 fn eval_result<'b, E>(&self, result: Result<Datum<'b>, E>) -> ResultSpec<'a> {
953 match result {
954 Ok(Datum::Null) => ResultSpec {
955 nullable: true,
956 ..ResultSpec::nothing()
957 },
958 Ok(d) => ResultSpec {
959 values: Values::just(self.arena.make_datum(|packer| packer.push(d))),
960 ..ResultSpec::nothing()
961 },
962 Err(_) => ResultSpec {
963 fallible: true,
964 ..ResultSpec::nothing()
965 },
966 }
967 }
968
969 fn set_literal(expr: &mut MirScalarExpr, update: Result<Datum, EvalError>) {
970 match expr {
971 MirScalarExpr::Literal(literal, col_type) => match update {
972 Err(error) => *literal = Err(error),
973 Ok(datum) => {
974 assert!(
975 datum.is_instance_of(col_type),
976 "{datum:?} must be an instance of {col_type:?}"
977 );
978 match literal {
979 Ok(row) => row.packer().push(datum),
981 literal => *literal = Ok(Row::pack_slice(&[datum])),
982 }
983 }
984 },
985 _ => panic!("not a literal"),
986 }
987 }
988
989 fn set_argument(expr: &mut MirScalarExpr, arg: usize, value: Result<Datum, EvalError>) {
990 match (expr, arg) {
991 (MirScalarExpr::CallUnary { expr, .. }, 0) => Self::set_literal(expr, value),
992 (MirScalarExpr::CallBinary { expr1, .. }, 0) => Self::set_literal(expr1, value),
993 (MirScalarExpr::CallBinary { expr2, .. }, 1) => Self::set_literal(expr2, value),
994 (MirScalarExpr::CallVariadic { exprs, .. }, n) if n < exprs.len() => {
995 Self::set_literal(&mut exprs[n], value)
996 }
997 _ => panic!("illegal argument for expression"),
998 }
999 }
1000
1001 fn placeholder(col_type: ReprColumnType) -> MirScalarExpr {
1005 MirScalarExpr::Literal(Err(EvalError::Internal("".into())), col_type)
1006 }
1007}
1008
1009impl<'a> Interpreter for ColumnSpecs<'a> {
1010 type Summary = ColumnSpec<'a>;
1011
1012 fn column(&self, id: usize) -> Self::Summary {
1013 let col_type = self.relation.column_types[id].clone();
1014 let range = self.columns[id].clone();
1015 ColumnSpec { col_type, range }
1016 }
1017
1018 fn literal(&self, result: &Result<Row, EvalError>, col_type: &ReprColumnType) -> Self::Summary {
1019 let col_type = col_type.clone();
1020 let range = self.eval_result(result.as_ref().map(|row| {
1021 self.arena
1022 .make_datum(|packer| packer.push(row.unpack_first()))
1023 }));
1024 ColumnSpec { col_type, range }
1025 }
1026
1027 fn unmaterializable(&self, func: &UnmaterializableFunc) -> Self::Summary {
1028 let col_type = func.output_type();
1029 let range = self
1030 .unmaterializables
1031 .get(func)
1032 .cloned()
1033 .unwrap_or_else(|| ResultSpec::has_type(&func.output_type(), true));
1034 ColumnSpec { col_type, range }
1035 }
1036
1037 fn unary(&self, func: &UnaryFunc, summary: Self::Summary) -> Self::Summary {
1038 let fallible = func.could_error() || summary.range.fallible;
1039 let input_multivalued = !summary.range.is_single_value();
1047 let mapped_spec = if let Some(special) = SpecialUnary::for_func(func) {
1048 (special.map_fn)(self, summary.range)
1049 } else if func.is_unbounded() {
1050 ResultSpec::anything()
1054 } else {
1055 let is_monotone = func.is_monotone();
1056 let mut expr = MirScalarExpr::CallUnary {
1057 func: func.clone(),
1058 expr: Box::new(Self::placeholder(summary.col_type.clone())),
1059 };
1060 summary.range.flat_map(is_monotone, |datum| {
1061 Self::set_argument(&mut expr, 0, datum);
1062 self.eval_result(expr.eval(&[], self.arena))
1063 })
1064 };
1065
1066 let col_type = func.output_type(summary.col_type);
1067
1068 let mut range = mapped_spec.intersect(ResultSpec::has_type(&col_type, fallible));
1069 if fallible && input_multivalued {
1073 range.fallible = true;
1074 }
1075 ColumnSpec { col_type, range }
1076 }
1077
1078 fn binary(
1079 &self,
1080 func: &BinaryFunc,
1081 left: Self::Summary,
1082 right: Self::Summary,
1083 ) -> Self::Summary {
1084 let fallible = func.could_error() || left.range.fallible || right.range.fallible;
1085 let inputs_multivalued = !left.range.is_single_value() || !right.range.is_single_value();
1088 let operand_may_be_infinite = left.range.may_be_infinite() || right.range.may_be_infinite();
1089
1090 let special = AbstractFunc::for_func(func);
1091 let (left_monotonic, right_monotonic) = match &special {
1092 Some(AbstractFunc {
1093 handler: AbstractFuncHandler::DynamicMonotone(monotone_fn),
1094 ..
1095 }) => monotone_fn(&left.range, &right.range),
1096 _ => func.is_monotone(),
1097 };
1098
1099 let mapped_spec = match special {
1100 Some(AbstractFunc {
1101 handler: AbstractFuncHandler::Override(f),
1102 ..
1103 }) => f(left.range, right.range),
1104 _ => {
1105 let mut expr = MirScalarExpr::CallBinary {
1106 func: func.clone(),
1107 expr1: Box::new(Self::placeholder(left.col_type.clone())),
1108 expr2: Box::new(Self::placeholder(right.col_type.clone())),
1109 };
1110 left.range.flat_map(left_monotonic, |left_result| {
1111 Self::set_argument(&mut expr, 0, left_result);
1112 right.range.flat_map(right_monotonic, |right_result| {
1113 Self::set_argument(&mut expr, 1, right_result);
1114 self.eval_result(expr.eval(&[], self.arena))
1115 })
1116 })
1117 }
1118 };
1119
1120 let col_type = func.output_type(&[left.col_type, right.col_type]);
1121
1122 let mut range = mapped_spec.intersect(ResultSpec::has_type(&col_type, fallible));
1123 if fallible && inputs_multivalued {
1126 range.fallible = true;
1127 }
1128 if operand_may_be_infinite && !func.is_infinity_monotone() {
1136 range.values = Values::All;
1137 }
1138 ColumnSpec { col_type, range }
1139 }
1140
1141 fn variadic(&self, func: &VariadicFunc, args: Vec<Self::Summary>) -> Self::Summary {
1142 let fallible = func.could_error() || args.iter().any(|s| s.range.fallible);
1143 let inputs_multivalued = args.iter().any(|s| !s.range.is_single_value());
1144 if func.is_associative() && args.len() > 2 {
1145 return args
1148 .into_iter()
1149 .reduce(|a, b| self.variadic(func, vec![a, b]))
1150 .expect("reducing over a non-empty argument list");
1151 }
1152
1153 let mapped_spec = if args.len() >= Self::MAX_EVAL_ARGS {
1154 ResultSpec::anything()
1155 } else {
1156 fn eval_loop<'a>(
1157 is_monotonic: bool,
1158 expr: &mut MirScalarExpr,
1159 args: &[ColumnSpec<'a>],
1160 index: usize,
1161 datum_map: &mut impl FnMut(&MirScalarExpr) -> ResultSpec<'a>,
1162 ) -> ResultSpec<'a> {
1163 if index >= args.len() {
1164 datum_map(expr)
1165 } else {
1166 args[index].range.flat_map(is_monotonic, |datum| {
1167 ColumnSpecs::set_argument(expr, index, datum);
1168 eval_loop(is_monotonic, expr, args, index + 1, datum_map)
1169 })
1170 }
1171 }
1172
1173 let mut fn_expr = MirScalarExpr::CallVariadic {
1174 func: func.clone(),
1175 exprs: args
1176 .iter()
1177 .map(|spec| Self::placeholder(spec.col_type.clone()))
1178 .collect(),
1179 };
1180 eval_loop(func.is_monotone(), &mut fn_expr, &args, 0, &mut |expr| {
1181 self.eval_result(expr.eval(&[], self.arena))
1182 })
1183 };
1184
1185 let col_types = args.into_iter().map(|spec| spec.col_type).collect();
1186 let col_type = func.output_type(col_types);
1187
1188 let mut range = mapped_spec.intersect(ResultSpec::has_type(&col_type, fallible));
1189 if fallible && inputs_multivalued {
1192 range.fallible = true;
1193 }
1194
1195 ColumnSpec { col_type, range }
1196 }
1197
1198 fn cond(&self, cond: Self::Summary, then: Self::Summary, els: Self::Summary) -> Self::Summary {
1199 let col_type = then
1200 .col_type
1201 .union(&els.col_type)
1202 .expect("failed type union for cond during abstract interpretation");
1203
1204 let range = cond
1205 .range
1206 .flat_map(true, |datum| match datum {
1207 Ok(Datum::True) => then.range.clone(),
1208 Ok(Datum::False) | Ok(Datum::Null) => els.range.clone(),
1213 _ => ResultSpec::fails(),
1214 })
1215 .intersect(ResultSpec::has_type(&col_type, true));
1216
1217 ColumnSpec { col_type, range }
1218 }
1219
1220 fn mfp_filter<X: Interpretable + OptimizableExpr>(
1234 &self,
1235 mfp: &MapFilterProject<X>,
1236 ) -> Self::Summary {
1237 let mfp_eval = MfpEval::new(self, mfp.input_arity, &mfp.expressions);
1238 let predicates = mfp
1239 .predicates
1240 .iter()
1241 .map(|(_, e)| mfp_eval.expr(e))
1242 .collect();
1243 let mut result = self.variadic(&And.into(), predicates);
1244 if mfp_eval.expressions.iter().any(|s| s.range.fallible) {
1245 result.range.fallible = true;
1246 }
1247 result
1248 }
1249
1250 fn mfp_plan_filter<X: Interpretable + OptimizableExpr>(
1251 &self,
1252 plan: &MfpPlan<X>,
1253 ) -> Self::Summary {
1254 let mfp_eval = MfpEval::new(self, plan.mfp.input_arity, &plan.mfp.expressions);
1255 let mut results: Vec<_> = plan
1256 .mfp
1257 .predicates
1258 .iter()
1259 .map(|(_, e)| mfp_eval.expr(e))
1260 .collect();
1261 let mz_now = mfp_eval.unmaterializable(&UnmaterializableFunc::MzNow);
1262 for bound in &plan.lower_bounds {
1263 let bound_range = mfp_eval.expr(bound);
1264 let result = mfp_eval.binary(&BinaryFunc::Lte(func::Lte), bound_range, mz_now.clone());
1265 results.push(result);
1266 }
1267 for bound in &plan.upper_bounds {
1268 let bound_range = mfp_eval.expr(bound);
1269 let result = mfp_eval.binary(&BinaryFunc::Gte(func::Gte), bound_range, mz_now.clone());
1270 results.push(result);
1271 }
1272 let mut result = self.variadic(&And.into(), results);
1273 if mfp_eval.expressions.iter().any(|s| s.range.fallible) {
1274 result.range.fallible = true;
1275 }
1276 result
1277 }
1278}
1279
1280#[derive(Debug)]
1289pub struct Trace;
1290
1291#[derive(Copy, Clone, Debug, PartialOrd, PartialEq, Ord, Eq)]
1298pub enum TraceSummary {
1299 Constant,
1302 Dynamic,
1307 Unknown,
1310}
1311
1312impl TraceSummary {
1313 fn apply_fn(self, pushdownable: bool) -> Self {
1318 match self {
1319 TraceSummary::Constant => TraceSummary::Constant,
1320 TraceSummary::Dynamic => match pushdownable {
1321 true => TraceSummary::Dynamic,
1322 false => TraceSummary::Unknown,
1323 },
1324 TraceSummary::Unknown => TraceSummary::Unknown,
1325 }
1326 }
1327
1328 pub fn pushdownable(self) -> bool {
1330 match self {
1331 TraceSummary::Constant | TraceSummary::Dynamic => true,
1332 TraceSummary::Unknown => false,
1333 }
1334 }
1335}
1336
1337impl Interpreter for Trace {
1338 type Summary = TraceSummary;
1339
1340 fn column(&self, _id: usize) -> Self::Summary {
1341 TraceSummary::Dynamic
1342 }
1343
1344 fn literal(
1345 &self,
1346 _result: &Result<Row, EvalError>,
1347 _col_type: &ReprColumnType,
1348 ) -> Self::Summary {
1349 TraceSummary::Constant
1350 }
1351
1352 fn unmaterializable(&self, _func: &UnmaterializableFunc) -> Self::Summary {
1353 TraceSummary::Dynamic
1354 }
1355
1356 fn unary(&self, func: &UnaryFunc, expr: Self::Summary) -> Self::Summary {
1357 if func.is_unbounded() {
1359 return TraceSummary::Unknown;
1360 }
1361 let pushdownable = match SpecialUnary::for_func(func) {
1362 None => func.is_monotone(),
1363 Some(special) => special.pushdownable,
1364 };
1365 expr.apply_fn(pushdownable)
1366 }
1367
1368 fn binary(
1369 &self,
1370 func: &BinaryFunc,
1371 left: Self::Summary,
1372 right: Self::Summary,
1373 ) -> Self::Summary {
1374 let (left_pushdownable, right_pushdownable) = match AbstractFunc::for_func(func) {
1375 None => func.is_monotone(),
1376 Some(special) => special.pushdownable,
1377 };
1378 left.apply_fn(left_pushdownable)
1379 .max(right.apply_fn(right_pushdownable))
1380 }
1381
1382 fn variadic(&self, func: &VariadicFunc, exprs: Vec<Self::Summary>) -> Self::Summary {
1383 if !func.is_associative() && exprs.len() >= ColumnSpecs::MAX_EVAL_ARGS {
1384 return TraceSummary::Unknown;
1387 }
1388
1389 let pushdownable_fn = func.is_monotone();
1390 exprs
1391 .into_iter()
1392 .map(|pushdownable_arg| pushdownable_arg.apply_fn(pushdownable_fn))
1393 .max()
1394 .unwrap_or(TraceSummary::Constant)
1395 }
1396
1397 fn cond(&self, cond: Self::Summary, then: Self::Summary, els: Self::Summary) -> Self::Summary {
1398 let cond = cond.min(TraceSummary::Dynamic);
1401 cond.max(then).max(els)
1402 }
1403}
1404
1405#[cfg(test)]
1406mod tests {
1407 use itertools::Itertools;
1408 use mz_repr::adt::datetime::DateTimeUnits;
1409 use mz_repr::{Datum, PropDatum, RowArena, SqlScalarType};
1410 use proptest::prelude::*;
1411 use proptest::sample::{Index, select};
1412
1413 use crate::func::*;
1414 use crate::scalar::func::variadic::Concat;
1415 use crate::{BinaryFunc, MirScalarExpr, UnaryFunc};
1416
1417 use super::*;
1418
1419 #[derive(Debug)]
1420 struct ExpressionData {
1421 relation_type: ReprRelationType,
1422 specs: Vec<ResultSpec<'static>>,
1423 rows: Vec<Row>,
1424 expr: MirScalarExpr,
1425 }
1426
1427 const NUM_TYPE: ReprScalarType = ReprScalarType::Numeric;
1432 static SCALAR_TYPES: &[ReprScalarType] = &[
1433 ReprScalarType::Bool,
1434 ReprScalarType::Jsonb,
1435 NUM_TYPE,
1436 ReprScalarType::Int16,
1437 ReprScalarType::Int32,
1438 ReprScalarType::Int64,
1439 ReprScalarType::UInt16,
1440 ReprScalarType::UInt32,
1441 ReprScalarType::UInt64,
1442 ReprScalarType::Float32,
1443 ReprScalarType::Float64,
1444 ReprScalarType::Date,
1445 ReprScalarType::Time,
1446 ReprScalarType::Timestamp,
1447 ReprScalarType::TimestampTz,
1448 ReprScalarType::MzTimestamp,
1449 ReprScalarType::Interval,
1450 ReprScalarType::String,
1451 ];
1452
1453 const INTERESTING_UNARY_FUNCS: &[UnaryFunc] = {
1454 &[
1455 UnaryFunc::CastNumericToMzTimestamp(CastNumericToMzTimestamp),
1456 UnaryFunc::CastTimestampToMzTimestamp(CastTimestampToMzTimestamp),
1457 UnaryFunc::NegNumeric(NegNumeric),
1458 UnaryFunc::NegFloat64(NegFloat64),
1459 UnaryFunc::CastJsonbToNumeric(CastJsonbToNumeric(None)),
1460 UnaryFunc::CastJsonbToBool(CastJsonbToBool),
1461 UnaryFunc::CastJsonbToString(CastJsonbToString),
1462 UnaryFunc::DateTruncTimestamp(DateTruncTimestamp(DateTimeUnits::Epoch)),
1463 UnaryFunc::ExtractTimestamp(ExtractTimestamp(DateTimeUnits::Epoch)),
1464 UnaryFunc::ExtractDate(ExtractDate(DateTimeUnits::Epoch)),
1465 UnaryFunc::Not(Not),
1466 UnaryFunc::IsNull(IsNull),
1467 UnaryFunc::IsFalse(IsFalse),
1468 UnaryFunc::TryParseMonotonicIso8601Timestamp(TryParseMonotonicIso8601Timestamp),
1469 UnaryFunc::NegInt32(NegInt32),
1474 UnaryFunc::NegInt64(NegInt64),
1475 UnaryFunc::CastInt32ToUint32(CastInt32ToUint32),
1476 UnaryFunc::CastInt64ToInt32(CastInt64ToInt32),
1477 UnaryFunc::CastInt64ToNumeric(CastInt64ToNumeric(None)),
1478 UnaryFunc::CastFloat64ToInt64(CastFloat64ToInt64),
1479 UnaryFunc::CastFloat64ToFloat32(CastFloat64ToFloat32),
1480 UnaryFunc::CastFloat32ToFloat64(CastFloat32ToFloat64),
1481 UnaryFunc::CastNumericToInt64(CastNumericToInt64),
1482 UnaryFunc::CeilNumeric(CeilNumeric),
1483 UnaryFunc::FloorNumeric(FloorNumeric),
1484 UnaryFunc::CastDateToTimestamp(CastDateToTimestamp(None)),
1485 UnaryFunc::CastTimestampToTimestampTz(CastTimestampToTimestampTz {
1486 from: None,
1487 to: None,
1488 }),
1489 UnaryFunc::CastTimestampTzToTimestamp(CastTimestampTzToTimestamp {
1490 from: None,
1491 to: None,
1492 }),
1493 UnaryFunc::ExtractTimestamp(ExtractTimestamp(DateTimeUnits::Year)),
1496 UnaryFunc::ExtractTimestamp(ExtractTimestamp(DateTimeUnits::Month)),
1497 UnaryFunc::ExtractTimestampTz(ExtractTimestampTz(DateTimeUnits::Epoch)),
1498 UnaryFunc::ExtractTimestampTz(ExtractTimestampTz(DateTimeUnits::Year)),
1499 UnaryFunc::CastBoolToInt32(CastBoolToInt32),
1503 UnaryFunc::CastBoolToString(CastBoolToString),
1504 UnaryFunc::NegInt16(NegInt16),
1505 UnaryFunc::CastInt16ToInt32(CastInt16ToInt32),
1506 UnaryFunc::CastInt16ToInt64(CastInt16ToInt64),
1507 UnaryFunc::CastInt16ToFloat32(CastInt16ToFloat32),
1508 UnaryFunc::CastInt16ToFloat64(CastInt16ToFloat64),
1509 UnaryFunc::CastInt16ToUint16(CastInt16ToUint16),
1510 UnaryFunc::CastInt16ToNumeric(CastInt16ToNumeric(None)),
1511 UnaryFunc::CastInt32ToInt16(CastInt32ToInt16),
1512 UnaryFunc::CastInt32ToInt64(CastInt32ToInt64),
1513 UnaryFunc::CastInt32ToFloat32(CastInt32ToFloat32),
1514 UnaryFunc::CastInt32ToFloat64(CastInt32ToFloat64),
1515 UnaryFunc::CastInt32ToUint16(CastInt32ToUint16),
1516 UnaryFunc::CastInt32ToNumeric(CastInt32ToNumeric(None)),
1517 UnaryFunc::CastInt32ToMzTimestamp(CastInt32ToMzTimestamp),
1518 UnaryFunc::CastInt64ToInt16(CastInt64ToInt16),
1519 UnaryFunc::CastInt64ToFloat32(CastInt64ToFloat32),
1520 UnaryFunc::CastInt64ToFloat64(CastInt64ToFloat64),
1521 UnaryFunc::CastInt64ToUint64(CastInt64ToUint64),
1522 UnaryFunc::CastInt64ToMzTimestamp(CastInt64ToMzTimestamp),
1523 UnaryFunc::CastUint64ToUint32(CastUint64ToUint32),
1524 UnaryFunc::CastUint64ToInt32(CastUint64ToInt32),
1525 UnaryFunc::CastUint64ToNumeric(CastUint64ToNumeric(None)),
1526 UnaryFunc::CastUint64ToMzTimestamp(CastUint64ToMzTimestamp),
1527 UnaryFunc::NegFloat32(NegFloat32),
1528 UnaryFunc::FloorFloat32(FloorFloat32),
1529 UnaryFunc::CastFloat32ToInt32(CastFloat32ToInt32),
1530 UnaryFunc::CastFloat32ToNumeric(CastFloat32ToNumeric(None)),
1531 UnaryFunc::FloorFloat64(FloorFloat64),
1532 UnaryFunc::CastFloat64ToInt32(CastFloat64ToInt32),
1533 UnaryFunc::CastFloat64ToUint64(CastFloat64ToUint64),
1534 UnaryFunc::CastFloat64ToNumeric(CastFloat64ToNumeric(None)),
1535 UnaryFunc::RoundNumeric(RoundNumeric),
1536 UnaryFunc::TruncNumeric(TruncNumeric),
1537 UnaryFunc::Log10Numeric(Log10Numeric),
1538 UnaryFunc::CastNumericToFloat64(CastNumericToFloat64),
1539 UnaryFunc::CastNumericToInt32(CastNumericToInt32),
1540 UnaryFunc::CastTimestampToDate(CastTimestampToDate),
1541 UnaryFunc::CastDateToMzTimestamp(CastDateToMzTimestamp),
1542 UnaryFunc::StepMzTimestamp(StepMzTimestamp),
1543 UnaryFunc::CastBoolToStringNonstandard(CastBoolToStringNonstandard),
1547 UnaryFunc::CastBoolToInt64(CastBoolToInt64),
1548 UnaryFunc::CastInt16ToUint32(CastInt16ToUint32),
1549 UnaryFunc::CastInt16ToUint64(CastInt16ToUint64),
1550 UnaryFunc::CastInt32ToUint64(CastInt32ToUint64),
1551 UnaryFunc::CastInt64ToUint16(CastInt64ToUint16),
1552 UnaryFunc::CastInt64ToUint32(CastInt64ToUint32),
1553 UnaryFunc::CastUint16ToUint32(CastUint16ToUint32),
1554 UnaryFunc::CastUint16ToUint64(CastUint16ToUint64),
1555 UnaryFunc::CastUint16ToInt16(CastUint16ToInt16),
1556 UnaryFunc::CastUint16ToInt32(CastUint16ToInt32),
1557 UnaryFunc::CastUint16ToFloat32(CastUint16ToFloat32),
1558 UnaryFunc::CastUint16ToFloat64(CastUint16ToFloat64),
1559 UnaryFunc::CastUint16ToNumeric(CastUint16ToNumeric(None)),
1560 UnaryFunc::CastUint16ToInt64(CastUint16ToInt64),
1561 UnaryFunc::BitNotUint16(BitNotUint16),
1562 UnaryFunc::CastUint32ToUint16(CastUint32ToUint16),
1563 UnaryFunc::CastUint32ToUint64(CastUint32ToUint64),
1564 UnaryFunc::CastUint32ToInt32(CastUint32ToInt32),
1565 UnaryFunc::CastUint32ToInt64(CastUint32ToInt64),
1566 UnaryFunc::CastUint32ToFloat32(CastUint32ToFloat32),
1567 UnaryFunc::CastUint32ToFloat64(CastUint32ToFloat64),
1568 UnaryFunc::CastUint32ToNumeric(CastUint32ToNumeric(None)),
1569 UnaryFunc::CastUint32ToInt16(CastUint32ToInt16),
1570 UnaryFunc::CastUint32ToMzTimestamp(CastUint32ToMzTimestamp),
1571 UnaryFunc::BitNotUint32(BitNotUint32),
1572 UnaryFunc::CastUint64ToUint16(CastUint64ToUint16),
1573 UnaryFunc::CastUint64ToInt16(CastUint64ToInt16),
1574 UnaryFunc::CastUint64ToInt64(CastUint64ToInt64),
1575 UnaryFunc::CastUint64ToFloat32(CastUint64ToFloat32),
1576 UnaryFunc::CastUint64ToFloat64(CastUint64ToFloat64),
1577 UnaryFunc::BitNotUint64(BitNotUint64),
1578 UnaryFunc::CastFloat32ToInt16(CastFloat32ToInt16),
1579 UnaryFunc::CastFloat32ToInt64(CastFloat32ToInt64),
1580 UnaryFunc::CastFloat32ToUint16(CastFloat32ToUint16),
1581 UnaryFunc::CastFloat32ToUint32(CastFloat32ToUint32),
1582 UnaryFunc::CastFloat32ToUint64(CastFloat32ToUint64),
1583 UnaryFunc::CastFloat64ToInt16(CastFloat64ToInt16),
1584 UnaryFunc::CastFloat64ToUint16(CastFloat64ToUint16),
1585 UnaryFunc::CastFloat64ToUint32(CastFloat64ToUint32),
1586 UnaryFunc::CastJsonbToInt16(CastJsonbToInt16),
1587 UnaryFunc::CastJsonbToInt32(CastJsonbToInt32),
1588 UnaryFunc::CastJsonbToInt64(CastJsonbToInt64),
1589 UnaryFunc::CastJsonbToFloat32(CastJsonbToFloat32),
1590 UnaryFunc::CastJsonbToFloat64(CastJsonbToFloat64),
1591 UnaryFunc::CastNumericToInt16(CastNumericToInt16),
1592 UnaryFunc::CastNumericToFloat32(CastNumericToFloat32),
1593 UnaryFunc::CastNumericToUint16(CastNumericToUint16),
1594 UnaryFunc::CastNumericToUint32(CastNumericToUint32),
1595 UnaryFunc::CastNumericToUint64(CastNumericToUint64),
1596 UnaryFunc::CastTimestampTzToDate(CastTimestampTzToDate),
1597 UnaryFunc::CastTimestampTzToMzTimestamp(CastTimestampTzToMzTimestamp),
1598 UnaryFunc::DateTruncTimestampTz(DateTruncTimestampTz(DateTimeUnits::Epoch)),
1599 UnaryFunc::CastDateToTimestampTz(CastDateToTimestampTz(None)),
1600 UnaryFunc::ExtractDate(ExtractDate(DateTimeUnits::Year)),
1601 UnaryFunc::ExtractDate(ExtractDate(DateTimeUnits::Day)),
1602 ]
1603 };
1604
1605 fn unary_typecheck(func: &UnaryFunc, arg: &ReprColumnType) -> bool {
1606 use UnaryFunc::*;
1607 match func {
1608 CastNumericToMzTimestamp(_)
1609 | NegNumeric(_)
1610 | CastNumericToInt64(_)
1611 | CeilNumeric(_)
1612 | FloorNumeric(_)
1613 | RoundNumeric(_)
1614 | TruncNumeric(_)
1615 | Log10Numeric(_)
1616 | CastNumericToFloat64(_)
1617 | CastNumericToInt32(_)
1618 | CastNumericToInt16(_)
1619 | CastNumericToFloat32(_)
1620 | CastNumericToUint16(_)
1621 | CastNumericToUint32(_)
1622 | CastNumericToUint64(_) => arg.scalar_type == NUM_TYPE,
1623 NegFloat64(_)
1624 | CastFloat64ToInt64(_)
1625 | CastFloat64ToFloat32(_)
1626 | FloorFloat64(_)
1627 | CastFloat64ToInt32(_)
1628 | CastFloat64ToUint64(_)
1629 | CastFloat64ToNumeric(_)
1630 | CastFloat64ToInt16(_)
1631 | CastFloat64ToUint16(_)
1632 | CastFloat64ToUint32(_) => arg.scalar_type == ReprScalarType::Float64,
1633 CastFloat32ToFloat64(_)
1634 | NegFloat32(_)
1635 | FloorFloat32(_)
1636 | CastFloat32ToInt32(_)
1637 | CastFloat32ToNumeric(_)
1638 | CastFloat32ToInt16(_)
1639 | CastFloat32ToInt64(_)
1640 | CastFloat32ToUint16(_)
1641 | CastFloat32ToUint32(_)
1642 | CastFloat32ToUint64(_) => arg.scalar_type == ReprScalarType::Float32,
1643 NegInt16(_)
1644 | CastInt16ToInt32(_)
1645 | CastInt16ToInt64(_)
1646 | CastInt16ToFloat32(_)
1647 | CastInt16ToFloat64(_)
1648 | CastInt16ToUint16(_)
1649 | CastInt16ToNumeric(_)
1650 | CastInt16ToUint32(_)
1651 | CastInt16ToUint64(_) => arg.scalar_type == ReprScalarType::Int16,
1652 NegInt32(_)
1653 | CastInt32ToUint32(_)
1654 | CastInt32ToInt16(_)
1655 | CastInt32ToInt64(_)
1656 | CastInt32ToFloat32(_)
1657 | CastInt32ToFloat64(_)
1658 | CastInt32ToUint16(_)
1659 | CastInt32ToNumeric(_)
1660 | CastInt32ToMzTimestamp(_)
1661 | CastInt32ToUint64(_) => arg.scalar_type == ReprScalarType::Int32,
1662 NegInt64(_)
1663 | CastInt64ToInt32(_)
1664 | CastInt64ToNumeric(_)
1665 | CastInt64ToInt16(_)
1666 | CastInt64ToFloat32(_)
1667 | CastInt64ToFloat64(_)
1668 | CastInt64ToUint64(_)
1669 | CastInt64ToMzTimestamp(_)
1670 | CastInt64ToUint16(_)
1671 | CastInt64ToUint32(_) => arg.scalar_type == ReprScalarType::Int64,
1672 CastUint16ToUint32(_)
1673 | CastUint16ToUint64(_)
1674 | CastUint16ToInt16(_)
1675 | CastUint16ToInt32(_)
1676 | CastUint16ToFloat32(_)
1677 | CastUint16ToFloat64(_)
1678 | CastUint16ToNumeric(_)
1679 | CastUint16ToInt64(_)
1680 | BitNotUint16(_) => arg.scalar_type == ReprScalarType::UInt16,
1681 CastUint32ToUint16(_)
1682 | CastUint32ToUint64(_)
1683 | CastUint32ToInt32(_)
1684 | CastUint32ToInt64(_)
1685 | CastUint32ToFloat32(_)
1686 | CastUint32ToFloat64(_)
1687 | CastUint32ToNumeric(_)
1688 | CastUint32ToInt16(_)
1689 | CastUint32ToMzTimestamp(_)
1690 | BitNotUint32(_) => arg.scalar_type == ReprScalarType::UInt32,
1691 CastUint64ToUint32(_)
1692 | CastUint64ToInt32(_)
1693 | CastUint64ToNumeric(_)
1694 | CastUint64ToMzTimestamp(_)
1695 | CastUint64ToUint16(_)
1696 | CastUint64ToInt16(_)
1697 | CastUint64ToInt64(_)
1698 | CastUint64ToFloat32(_)
1699 | CastUint64ToFloat64(_)
1700 | BitNotUint64(_) => arg.scalar_type == ReprScalarType::UInt64,
1701 StepMzTimestamp(_) => arg.scalar_type == ReprScalarType::MzTimestamp,
1702 CastBoolToInt32(_)
1703 | CastBoolToString(_)
1704 | CastBoolToStringNonstandard(_)
1705 | CastBoolToInt64(_) => arg.scalar_type == ReprScalarType::Bool,
1706 CastTimestampToMzTimestamp(_)
1707 | CastTimestampToTimestampTz(_)
1708 | CastTimestampToDate(_) => arg.scalar_type == ReprScalarType::Timestamp,
1709 CastTimestampTzToTimestamp(_)
1710 | ExtractTimestampTz(_)
1711 | CastTimestampTzToDate(_)
1712 | CastTimestampTzToMzTimestamp(_)
1713 | DateTruncTimestampTz(_) => arg.scalar_type == ReprScalarType::TimestampTz,
1714 CastJsonbToNumeric(_)
1715 | CastJsonbToBool(_)
1716 | CastJsonbToString(_)
1717 | CastJsonbToInt16(_)
1718 | CastJsonbToInt32(_)
1719 | CastJsonbToInt64(_)
1720 | CastJsonbToFloat32(_)
1721 | CastJsonbToFloat64(_) => arg.scalar_type == ReprScalarType::Jsonb,
1722 ExtractTimestamp(_) | DateTruncTimestamp(_) => {
1723 arg.scalar_type == ReprScalarType::Timestamp
1724 }
1725 ExtractDate(_)
1726 | CastDateToTimestamp(_)
1727 | CastDateToMzTimestamp(_)
1728 | CastDateToTimestampTz(_) => arg.scalar_type == ReprScalarType::Date,
1729 Not(_) => arg.scalar_type == ReprScalarType::Bool,
1730 IsNull(_) => true,
1731 TryParseMonotonicIso8601Timestamp(_) => arg.scalar_type == ReprScalarType::String,
1732 TryCast(f) => unary_typecheck(f.inner(), arg),
1733 _ => false,
1734 }
1735 }
1736
1737 const TRY_CAST_INNER_FUNCS: &[UnaryFunc] = &[
1741 UnaryFunc::CastInt64ToInt32(CastInt64ToInt32),
1742 UnaryFunc::CastInt32ToInt16(CastInt32ToInt16),
1743 UnaryFunc::CastInt64ToUint64(CastInt64ToUint64),
1744 UnaryFunc::CastFloat64ToInt64(CastFloat64ToInt64),
1745 UnaryFunc::CastFloat64ToFloat32(CastFloat64ToFloat32),
1746 UnaryFunc::CastNumericToInt32(CastNumericToInt32),
1747 UnaryFunc::CastNumericToMzTimestamp(CastNumericToMzTimestamp),
1748 UnaryFunc::CastJsonbToNumeric(CastJsonbToNumeric(None)),
1749 UnaryFunc::CastJsonbToBool(CastJsonbToBool),
1750 UnaryFunc::CastTimestampToMzTimestamp(CastTimestampToMzTimestamp),
1751 ];
1752
1753 fn interesting_unary_funcs() -> Vec<UnaryFunc> {
1757 let mut funcs = INTERESTING_UNARY_FUNCS.to_vec();
1758 funcs.extend(TRY_CAST_INNER_FUNCS.iter().map(|cast| {
1759 assert!(
1760 cast.could_error(),
1761 "{cast} never errors, so wrapping it is pointless"
1762 );
1763 UnaryFunc::try_cast_if_fallible(cast.clone())
1764 }));
1765 funcs
1766 }
1767
1768 fn interesting_binary_funcs() -> Vec<BinaryFunc> {
1769 vec![
1770 AddTimestampInterval.into(),
1771 AddNumeric.into(),
1772 SubNumeric.into(),
1773 MulNumeric.into(),
1774 DivNumeric.into(),
1775 AddFloat64.into(),
1776 SubFloat64.into(),
1777 MulFloat64.into(),
1778 DivFloat64.into(),
1779 MulFloat32.into(),
1780 DivFloat32.into(),
1781 RoundNumericBinary.into(),
1782 Eq.into(),
1783 Lt.into(),
1784 Gt.into(),
1785 Lte.into(),
1786 Gte.into(),
1787 DateTruncUnitsTimestamp.into(),
1788 JsonbGetString.into(),
1789 JsonbGetStringStringify.into(),
1790 AddInt32.into(),
1794 SubInt32.into(),
1795 MulInt32.into(),
1796 DivInt32.into(),
1797 AddInt64.into(),
1798 MulInt64.into(),
1799 AddFloat32.into(),
1800 SubFloat32.into(),
1801 TextConcatBinary.into(),
1803 AddDateInterval.into(),
1805 AddTimeInterval.into(),
1806 SubInt64.into(),
1808 DivInt64.into(),
1809 SubTimestamp.into(),
1810 SubDate.into(),
1811 AddInterval.into(),
1812 SubInterval.into(),
1813 AddInt16.into(),
1816 SubInt16.into(),
1817 MulInt16.into(),
1818 DivInt16.into(),
1819 AddUint16.into(),
1820 SubUint16.into(),
1821 MulUint16.into(),
1822 DivUint16.into(),
1823 AddUint32.into(),
1824 SubUint32.into(),
1825 MulUint32.into(),
1826 DivUint32.into(),
1827 AddUint64.into(),
1828 SubUint64.into(),
1829 MulUint64.into(),
1830 DivUint64.into(),
1831 SubTime.into(),
1832 SubTimestampTz.into(),
1833 AddDateTime.into(),
1834 SubDateInterval.into(),
1835 DateBinTimestamp.into(),
1836 ]
1837 }
1838
1839 fn binary_typecheck(func: &BinaryFunc, arg0: &ReprColumnType, arg1: &ReprColumnType) -> bool {
1840 use BinaryFunc::*;
1841 match func {
1842 AddTimestampInterval(_) => {
1843 arg0.scalar_type == ReprScalarType::Timestamp
1844 && arg1.scalar_type == ReprScalarType::Interval
1845 }
1846 AddNumeric(_) | SubNumeric(_) | MulNumeric(_) | DivNumeric(_) => {
1847 arg0.scalar_type == NUM_TYPE && arg1.scalar_type == NUM_TYPE
1848 }
1849 AddFloat64(_) | SubFloat64(_) | MulFloat64(_) | DivFloat64(_) => {
1850 arg0.scalar_type == ReprScalarType::Float64
1851 && arg1.scalar_type == ReprScalarType::Float64
1852 }
1853 MulFloat32(_) | DivFloat32(_) => {
1854 arg0.scalar_type == ReprScalarType::Float32
1855 && arg1.scalar_type == ReprScalarType::Float32
1856 }
1857 RoundNumeric(_) => {
1858 arg0.scalar_type == NUM_TYPE && arg1.scalar_type == ReprScalarType::Int32
1859 }
1860 Eq(_) | Lt(_) | Gt(_) | Lte(_) | Gte(_) => arg0.scalar_type == arg1.scalar_type,
1861 DateTruncTimestamp(_) => {
1862 arg0.scalar_type == ReprScalarType::String
1863 && arg1.scalar_type == ReprScalarType::Timestamp
1864 }
1865 JsonbGetString(_) | JsonbGetStringStringify(_) => {
1866 arg0.scalar_type == ReprScalarType::Jsonb
1867 && arg1.scalar_type == ReprScalarType::String
1868 }
1869 AddInt32(_) | SubInt32(_) | MulInt32(_) | DivInt32(_) => {
1870 arg0.scalar_type == ReprScalarType::Int32
1871 && arg1.scalar_type == ReprScalarType::Int32
1872 }
1873 AddInt64(_) | MulInt64(_) | SubInt64(_) | DivInt64(_) => {
1874 arg0.scalar_type == ReprScalarType::Int64
1875 && arg1.scalar_type == ReprScalarType::Int64
1876 }
1877 SubTimestamp(_) => {
1878 arg0.scalar_type == ReprScalarType::Timestamp
1879 && arg1.scalar_type == ReprScalarType::Timestamp
1880 }
1881 SubDate(_) => {
1882 arg0.scalar_type == ReprScalarType::Date && arg1.scalar_type == ReprScalarType::Date
1883 }
1884 AddInterval(_) | SubInterval(_) => {
1885 arg0.scalar_type == ReprScalarType::Interval
1886 && arg1.scalar_type == ReprScalarType::Interval
1887 }
1888 AddInt16(_) | SubInt16(_) | MulInt16(_) | DivInt16(_) => {
1889 arg0.scalar_type == ReprScalarType::Int16
1890 && arg1.scalar_type == ReprScalarType::Int16
1891 }
1892 AddUint16(_) | SubUint16(_) | MulUint16(_) | DivUint16(_) => {
1893 arg0.scalar_type == ReprScalarType::UInt16
1894 && arg1.scalar_type == ReprScalarType::UInt16
1895 }
1896 AddUint32(_) | SubUint32(_) | MulUint32(_) | DivUint32(_) => {
1897 arg0.scalar_type == ReprScalarType::UInt32
1898 && arg1.scalar_type == ReprScalarType::UInt32
1899 }
1900 AddUint64(_) | SubUint64(_) | MulUint64(_) | DivUint64(_) => {
1901 arg0.scalar_type == ReprScalarType::UInt64
1902 && arg1.scalar_type == ReprScalarType::UInt64
1903 }
1904 SubTime(_) => {
1905 arg0.scalar_type == ReprScalarType::Time && arg1.scalar_type == ReprScalarType::Time
1906 }
1907 SubTimestampTz(_) => {
1908 arg0.scalar_type == ReprScalarType::TimestampTz
1909 && arg1.scalar_type == ReprScalarType::TimestampTz
1910 }
1911 AddDateTime(_) => {
1912 arg0.scalar_type == ReprScalarType::Date && arg1.scalar_type == ReprScalarType::Time
1913 }
1914 SubDateInterval(_) => {
1915 arg0.scalar_type == ReprScalarType::Date
1916 && arg1.scalar_type == ReprScalarType::Interval
1917 }
1918 DateBinTimestamp(_) => {
1919 arg0.scalar_type == ReprScalarType::Interval
1920 && arg1.scalar_type == ReprScalarType::Timestamp
1921 }
1922 AddFloat32(_) | SubFloat32(_) => {
1923 arg0.scalar_type == ReprScalarType::Float32
1924 && arg1.scalar_type == ReprScalarType::Float32
1925 }
1926 TextConcat(_) => {
1927 arg0.scalar_type == ReprScalarType::String
1928 && arg1.scalar_type == ReprScalarType::String
1929 }
1930 AddDateInterval(_) => {
1931 arg0.scalar_type == ReprScalarType::Date
1932 && arg1.scalar_type == ReprScalarType::Interval
1933 }
1934 AddTimeInterval(_) => {
1935 arg0.scalar_type == ReprScalarType::Time
1936 && arg1.scalar_type == ReprScalarType::Interval
1937 }
1938 _ => false,
1939 }
1940 }
1941
1942 const INTERESTING_VARIADIC_FUNCS: &[VariadicFunc] = {
1943 use crate::scalar::func::variadic as v;
1944 use VariadicFunc::*;
1945 &[
1946 Coalesce(v::Coalesce),
1947 Greatest(v::Greatest),
1948 Least(v::Least),
1949 And(v::And),
1950 Or(v::Or),
1951 Concat(v::Concat),
1952 ConcatWs(v::ConcatWs),
1953 ]
1954 };
1955
1956 fn variadic_typecheck(func: &VariadicFunc, args: &[ReprColumnType]) -> bool {
1957 use VariadicFunc::*;
1958 fn all_eq<'a>(
1959 iter: impl IntoIterator<Item = &'a ReprColumnType>,
1960 other: &ReprScalarType,
1961 ) -> bool {
1962 iter.into_iter().all(|t| t.scalar_type == *other)
1963 }
1964 match func {
1965 Coalesce(_) | Greatest(_) | Least(_) => match args {
1966 [] => true,
1967 [first, rest @ ..] => all_eq(rest, &first.scalar_type),
1968 },
1969 And(_) | Or(_) => all_eq(args, &ReprScalarType::Bool),
1970 Concat(_) => all_eq(args, &ReprScalarType::String),
1971 ConcatWs(_) => args.len() > 1 && all_eq(args, &ReprScalarType::String),
1972 _ => false,
1973 }
1974 }
1975
1976 fn gen_datums_for_type(typ: &ReprColumnType) -> BoxedStrategy<Datum<'static>> {
1977 let mut values: Vec<Datum<'static>> = SqlScalarType::from_repr(&typ.scalar_type)
1978 .interesting_datums()
1979 .collect();
1980 if typ.nullable {
1981 values.push(Datum::Null)
1982 }
1983 select(values).boxed()
1984 }
1985
1986 fn gen_column() -> impl Strategy<Value = (ReprColumnType, Datum<'static>, ResultSpec<'static>)>
1987 {
1988 let col_type = (select(SCALAR_TYPES), any::<bool>())
1989 .prop_map(|(t, b)| t.nullable(b))
1990 .prop_filter("need at least one value", |c| {
1991 SqlScalarType::from_repr(&c.scalar_type)
1992 .interesting_datums()
1993 .count()
1994 > 0
1995 });
1996
1997 let result_spec = select(vec![
1998 ResultSpec::nothing(),
1999 ResultSpec::null(),
2000 ResultSpec::anything(),
2001 ResultSpec::value_all(),
2002 ]);
2003
2004 (col_type, result_spec).prop_flat_map(|(col, result_spec)| {
2005 gen_datums_for_type(&col).prop_map(move |datum| {
2006 let result_spec = result_spec.clone().union(ResultSpec::value(datum));
2007 (col.clone(), datum, result_spec)
2008 })
2009 })
2010 }
2011
2012 fn gen_expr_for_relation(
2013 relation: &ReprRelationType,
2014 ) -> BoxedStrategy<(MirScalarExpr, ReprColumnType)> {
2015 let column_gen = {
2016 let column_types = relation.column_types.clone();
2017 any::<Index>()
2018 .prop_map(move |idx| {
2019 let id = idx.index(column_types.len());
2020 (MirScalarExpr::column(id), column_types[id].clone())
2021 })
2022 .boxed()
2023 };
2024
2025 let literal_gen = (select(SCALAR_TYPES), any::<bool>())
2026 .prop_map(|(s, b)| s.nullable(b))
2027 .prop_flat_map(|ct| {
2028 let error_gen = any::<EvalError>().prop_map(Err).boxed();
2029 let value_gen = gen_datums_for_type(&ct)
2030 .prop_map(move |datum| Ok(Row::pack_slice(&[datum])))
2031 .boxed();
2032 error_gen.prop_union(value_gen).prop_map(move |result| {
2033 (MirScalarExpr::Literal(result, ct.clone()), ct.clone())
2034 })
2035 })
2036 .boxed();
2037
2038 column_gen
2039 .prop_union(literal_gen)
2040 .prop_recursive(4, 64, 8, |self_gen| {
2041 let unary_gen = (select(interesting_unary_funcs()), self_gen.clone())
2042 .prop_filter_map("unary func", |(func, (expr_in, type_in))| {
2043 if !unary_typecheck(&func, &type_in) {
2044 return None;
2045 }
2046 let type_out = func.output_type(type_in);
2047 let expr_out = MirScalarExpr::CallUnary {
2048 func,
2049 expr: Box::new(expr_in),
2050 };
2051 Some((expr_out, type_out))
2052 })
2053 .boxed();
2054 let binary_gen = (
2055 select(interesting_binary_funcs()),
2056 self_gen.clone(),
2057 self_gen.clone(),
2058 )
2059 .prop_filter_map(
2060 "binary func",
2061 |(func, (expr_left, type_left), (expr_right, type_right))| {
2062 if !binary_typecheck(&func, &type_left, &type_right) {
2063 return None;
2064 }
2065 let type_out = func.output_type(&[type_left, type_right]);
2066 let expr_out = MirScalarExpr::CallBinary {
2067 func,
2068 expr1: Box::new(expr_left),
2069 expr2: Box::new(expr_right),
2070 };
2071 Some((expr_out, type_out))
2072 },
2073 )
2074 .boxed();
2075 let variadic_gen = (
2076 select(INTERESTING_VARIADIC_FUNCS),
2077 prop::collection::vec(self_gen.clone(), 1..4),
2078 )
2079 .prop_filter_map("variadic func", |(func, exprs)| {
2080 let (exprs_in, type_in): (_, Vec<_>) = exprs.into_iter().unzip();
2081 if !variadic_typecheck(&func, &type_in) {
2082 return None;
2083 }
2084 let type_out = func.output_type(type_in);
2085 let expr_out = MirScalarExpr::CallVariadic {
2086 func,
2087 exprs: exprs_in,
2088 };
2089 Some((expr_out, type_out))
2090 })
2091 .boxed();
2092 let if_gen = {
2099 let bool_type = ReprScalarType::Bool.nullable(true);
2100 let cond_gen = gen_datums_for_type(&bool_type).prop_map(move |datum| {
2101 MirScalarExpr::Literal(Ok(Row::pack_slice(&[datum])), bool_type.clone())
2102 });
2103 (cond_gen, self_gen.clone())
2104 .prop_flat_map(|(cond_expr, (then_expr, then_type))| {
2105 let out_type = then_type.clone();
2106 gen_datums_for_type(&then_type).prop_map(move |datum| {
2107 let els_expr = MirScalarExpr::Literal(
2108 Ok(Row::pack_slice(&[datum])),
2109 out_type.clone(),
2110 );
2111 let expr_out = MirScalarExpr::If {
2112 cond: Box::new(cond_expr.clone()),
2113 then: Box::new(then_expr.clone()),
2114 els: Box::new(els_expr),
2115 };
2116 (expr_out, out_type.clone())
2117 })
2118 })
2119 .boxed()
2120 };
2121
2122 unary_gen
2123 .prop_union(binary_gen)
2124 .boxed()
2125 .prop_union(variadic_gen)
2126 .boxed()
2127 .prop_union(if_gen)
2128 })
2129 .boxed()
2130 }
2131
2132 fn gen_expr_data() -> impl Strategy<Value = ExpressionData> {
2133 let columns = prop::collection::vec(gen_column(), 1..10);
2134 columns.prop_flat_map(|data| {
2135 let (columns, datums, specs): (Vec<_>, Vec<_>, Vec<_>) = data.into_iter().multiunzip();
2136 let relation = ReprRelationType::new(columns);
2137 let row = Row::pack_slice(&datums);
2138 gen_expr_for_relation(&relation).prop_map(move |(expr, _)| ExpressionData {
2139 relation_type: relation.clone(),
2140 specs: specs.clone(),
2141 rows: vec![row.clone()],
2142 expr,
2143 })
2144 })
2145 }
2146
2147 #[mz_ore::test]
2148 #[cfg_attr(miri, ignore)] fn test_trivial_spec_matches() {
2150 fn check(datum: PropDatum) -> Result<(), TestCaseError> {
2151 let datum: Datum = (&datum).into();
2152 let spec = if datum.is_null() {
2153 ResultSpec::null()
2154 } else {
2155 ResultSpec::value(datum)
2156 };
2157 assert!(spec.may_contain(datum));
2158 Ok(())
2159 }
2160
2161 proptest!(|(datum in mz_repr::arb_datum(true))| {
2162 check(datum)?;
2163 });
2164
2165 assert!(ResultSpec::fails().may_fail());
2166 }
2167
2168 #[mz_ore::test]
2169 #[cfg_attr(miri, ignore)] fn test_equivalence() {
2171 fn check(data: ExpressionData) -> Result<(), TestCaseError> {
2172 let ExpressionData {
2173 relation_type,
2174 specs,
2175 rows,
2176 expr,
2177 } = data;
2178
2179 let arena = RowArena::new();
2183 let mut interpreter = ColumnSpecs::new(&relation_type, &arena);
2184 for (id, spec) in specs.into_iter().enumerate() {
2185 interpreter.push_column(id, spec);
2186 }
2187
2188 let spec = interpreter.expr(&expr);
2189
2190 for row in &rows {
2191 let datums: Vec<_> = row.iter().collect();
2192 let eval_result = expr.eval(&datums, &arena);
2193 match eval_result {
2194 Ok(value) => {
2195 assert!(spec.range.may_contain(value))
2196 }
2197 Err(_) => {
2198 assert!(spec.range.may_fail());
2199 }
2200 }
2201 }
2202
2203 Ok(())
2204 }
2205
2206 proptest!(|(data in gen_expr_data())| {
2207 check(data)?;
2208 });
2209 }
2210
2211 fn gen_range_column()
2220 -> impl Strategy<Value = (ReprColumnType, Datum<'static>, ResultSpec<'static>)> {
2221 select(SCALAR_TYPES)
2222 .prop_map(|t| t.nullable(false))
2223 .prop_filter("need at least two distinct values for a range", |c| {
2224 let mut datums: Vec<Datum> = SqlScalarType::from_repr(&c.scalar_type)
2225 .interesting_datums()
2226 .filter(|d| !d.is_null())
2227 .collect();
2228 datums.sort();
2229 datums.dedup();
2230 datums.len() >= 2
2231 })
2232 .prop_flat_map(|col| {
2233 let mut datums: Vec<Datum<'static>> = SqlScalarType::from_repr(&col.scalar_type)
2234 .interesting_datums()
2235 .filter(|d| !d.is_null())
2236 .collect();
2237 datums.sort();
2238 datums.dedup();
2239 (
2240 Just(col),
2241 Just(datums),
2242 any::<Index>(),
2243 any::<Index>(),
2244 any::<Index>(),
2245 )
2246 .prop_map(|(col, datums, a, b, c)| {
2247 let n = datums.len();
2248 let mut idxs = [a.index(n), b.index(n), c.index(n)];
2249 idxs.sort();
2250 let lo = datums[idxs[0]];
2251 let mid = datums[idxs[1]];
2252 let hi = datums[idxs[2]];
2253 let spec = ResultSpec::value_between(lo, hi);
2254 (col, mid, spec)
2255 })
2256 })
2257 }
2258
2259 fn gen_range_expr_data() -> impl Strategy<Value = ExpressionData> {
2260 let columns = prop::collection::vec(gen_range_column(), 1..10);
2261 columns.prop_flat_map(|data| {
2262 let (columns, datums, specs): (Vec<_>, Vec<_>, Vec<_>) = data.into_iter().multiunzip();
2263 let relation = ReprRelationType::new(columns);
2264 let row = Row::pack_slice(&datums);
2265 gen_expr_for_relation(&relation).prop_map(move |(expr, _)| ExpressionData {
2266 relation_type: relation.clone(),
2267 specs: specs.clone(),
2268 rows: vec![row.clone()],
2269 expr,
2270 })
2271 })
2272 }
2273
2274 #[mz_ore::test]
2285 #[cfg_attr(miri, ignore)] fn test_equivalence_ranges() {
2287 fn check(data: ExpressionData) -> Result<(), TestCaseError> {
2288 let ExpressionData {
2289 relation_type,
2290 specs,
2291 rows,
2292 expr,
2293 } = data;
2294
2295 let arena = RowArena::new();
2296 let mut interpreter = ColumnSpecs::new(&relation_type, &arena);
2297 for (id, spec) in specs.into_iter().enumerate() {
2298 interpreter.push_column(id, spec);
2299 }
2300
2301 let spec = interpreter.expr(&expr);
2302
2303 for row in &rows {
2304 let datums: Vec<_> = row.iter().collect();
2305 let eval_result = expr.eval(&datums, &arena);
2306 match eval_result {
2307 Ok(value) => {
2308 prop_assert!(
2309 spec.range.may_contain(value),
2310 "interpreter ruled out a value the evaluator produced \
2311 for an interior input: expr={expr:?} row={row:?} \
2312 value={value:?} spec={:?}",
2313 spec.range,
2314 );
2315 }
2316 Err(_) => {
2317 prop_assert!(
2318 spec.range.may_fail(),
2319 "interpreter ruled out an error the evaluator produced \
2320 for an interior input: expr={expr:?} row={row:?}",
2321 );
2322 }
2323 }
2324 }
2325
2326 Ok(())
2327 }
2328
2329 let default = ProptestConfig::default();
2338 let cases = if std::env::var_os("PROPTEST_CASES").is_some() {
2339 default.cases
2340 } else {
2341 2048
2342 };
2343 let config = ProptestConfig {
2344 cases,
2345 max_local_rejects: cases.saturating_mul(512),
2346 ..default
2347 };
2348 proptest!(config, |(data in gen_range_expr_data())| {
2349 check(data)?;
2350 });
2351 }
2352
2353 #[mz_ore::test]
2362 #[cfg_attr(miri, ignore)] fn test_result_spec_lattice_laws() {
2364 #[derive(Debug, Clone)]
2367 enum Recipe {
2368 Nothing,
2369 Null,
2370 Fails,
2371 Anything,
2372 ValueAll,
2373 Value(PropDatum),
2374 Between(PropDatum, PropDatum),
2375 Map(Vec<(PropDatum, Recipe)>),
2376 Union(Box<Recipe>, Box<Recipe>),
2377 }
2378
2379 fn materialize(recipe: &Recipe) -> ResultSpec<'_> {
2380 match recipe {
2381 Recipe::Nothing => ResultSpec::nothing(),
2382 Recipe::Null => ResultSpec::null(),
2383 Recipe::Fails => ResultSpec::fails(),
2384 Recipe::Anything => ResultSpec::anything(),
2385 Recipe::ValueAll => ResultSpec::value_all(),
2386 Recipe::Value(pd) => ResultSpec::value(pd.into()),
2387 Recipe::Between(a, b) => {
2388 let (a, b): (Datum, Datum) = (a.into(), b.into());
2389 if a.is_null() || b.is_null() {
2390 ResultSpec::nothing()
2391 } else if a <= b {
2392 ResultSpec::value_between(a, b)
2393 } else {
2394 ResultSpec::value_between(b, a)
2395 }
2396 }
2397 Recipe::Map(entries) => {
2398 let mut map = BTreeMap::new();
2399 for (key, val) in entries {
2400 let key: Datum = key.into();
2401 if !key.is_null() {
2402 map.insert(key, materialize(val));
2403 }
2404 }
2405 ResultSpec::map_spec(map)
2406 }
2407 Recipe::Union(a, b) => materialize(a).union(materialize(b)),
2408 }
2409 }
2410
2411 fn recipe_strategy() -> impl Strategy<Value = Recipe> {
2412 let leaf = proptest::strategy::Union::new(vec![
2413 Just(Recipe::Nothing).boxed(),
2414 Just(Recipe::Null).boxed(),
2415 Just(Recipe::Fails).boxed(),
2416 Just(Recipe::Anything).boxed(),
2417 Just(Recipe::ValueAll).boxed(),
2418 mz_repr::arb_datum(false).prop_map(Recipe::Value).boxed(),
2419 (mz_repr::arb_datum(false), mz_repr::arb_datum(false))
2420 .prop_map(|(a, b)| Recipe::Between(a, b))
2421 .boxed(),
2422 ]);
2423 leaf.prop_recursive(3, 24, 4, |inner| {
2424 proptest::strategy::Union::new(vec![
2425 prop::collection::vec((mz_repr::arb_datum(false), inner.clone()), 0..3)
2426 .prop_map(Recipe::Map)
2427 .boxed(),
2428 (inner.clone(), inner.clone())
2429 .prop_map(|(a, b)| Recipe::Union(Box::new(a), Box::new(b)))
2430 .boxed(),
2431 ])
2432 })
2433 }
2434
2435 fn check(a: Recipe, b: Recipe, v: PropDatum) -> Result<(), TestCaseError> {
2436 let a_spec = materialize(&a);
2437 let b_spec = materialize(&b);
2438 let v: Datum = (&v).into();
2439
2440 let in_a = a_spec.may_contain(v);
2441 let in_b = b_spec.may_contain(v);
2442
2443 if in_a || in_b {
2444 prop_assert!(
2445 a_spec.clone().union(b_spec.clone()).may_contain(v),
2446 "union dropped a value: a={a:?} b={b:?} v={v:?}",
2447 );
2448 }
2449 if in_a && in_b {
2450 prop_assert!(
2451 a_spec.intersect(b_spec).may_contain(v),
2452 "intersect dropped a common value: a={a:?} b={b:?} v={v:?}",
2453 );
2454 }
2455 Ok(())
2456 }
2457
2458 proptest!(
2459 ProptestConfig::with_cases(4096),
2460 |(a in recipe_strategy(), b in recipe_strategy(), v in mz_repr::arb_datum(true))| {
2461 check(a, b, v)?;
2462 }
2463 );
2464 }
2465
2466 #[mz_ore::test]
2477 #[cfg_attr(miri, ignore)] fn test_neg_numeric_nan_range() {
2479 use mz_repr::adt::numeric::Numeric;
2480
2481 let neg = MirScalarExpr::CallUnary {
2482 func: UnaryFunc::NegNumeric(NegNumeric),
2483 expr: Box::new(MirScalarExpr::column(0)),
2484 };
2485
2486 let relation = ReprRelationType::new(vec![ReprScalarType::Numeric.nullable(false)]);
2487 let arena = RowArena::new();
2488 let mut interpreter = ColumnSpecs::new(&relation, &arena);
2489 interpreter.push_column(
2490 0,
2491 ResultSpec::value_between(
2492 Datum::from(Numeric::from(f64::NEG_INFINITY)),
2493 Datum::from(Numeric::from(f64::NAN)),
2494 ),
2495 );
2496
2497 let spec = interpreter.expr(&neg);
2498
2499 let actual = neg
2501 .eval(&[Datum::from(Numeric::from(-1.0f64))], &arena)
2502 .expect("eval succeeds");
2503 assert!(
2504 spec.range.may_contain(actual),
2505 "interpreter must not rule out {actual:?}, which the evaluator \
2506 produces for an interior input; got spec {:?}",
2507 spec.range,
2508 );
2509 }
2510
2511 #[mz_ore::test]
2522 #[cfg_attr(miri, ignore)] fn test_fallible_monotone_interior_error() {
2524 use mz_repr::adt::numeric::Numeric;
2525
2526 let cast = MirScalarExpr::CallUnary {
2527 func: UnaryFunc::CastNumericToMzTimestamp(CastNumericToMzTimestamp),
2528 expr: Box::new(MirScalarExpr::column(0)),
2529 };
2530
2531 let relation = ReprRelationType::new(vec![ReprScalarType::Numeric.nullable(false)]);
2532 let arena = RowArena::new();
2533 let mut interpreter = ColumnSpecs::new(&relation, &arena);
2534 interpreter.push_column(
2535 0,
2536 ResultSpec::value_between(
2537 Datum::from(Numeric::from(0.0f64)),
2538 Datum::from(Numeric::from(2.0f64)),
2539 ),
2540 );
2541
2542 let spec = interpreter.expr(&cast);
2543
2544 let interior = Datum::from(Numeric::from(1.5f64));
2547 assert!(
2548 cast.eval(&[interior], &arena).is_err(),
2549 "precondition: a fractional numeric fails to cast to mz_timestamp",
2550 );
2551 assert!(
2552 spec.range.may_fail(),
2553 "interpreter must surface that a monotone-but-fallible function may \
2554 error on an interior value it never sampled; got spec {:?}",
2555 spec.range,
2556 );
2557 }
2558
2559 #[mz_ore::test]
2567 #[cfg_attr(miri, ignore)]
2568 fn test_mfp_unreferenced_fallible_expression() {
2569 use crate::scalar::func::CastStringToUuid;
2570
2571 let mfp = MapFilterProject {
2577 expressions: vec![MirScalarExpr::CallUnary {
2578 func: UnaryFunc::CastStringToUuid(CastStringToUuid),
2579 expr: Box::new(MirScalarExpr::column(0)),
2580 }],
2581 predicates: vec![(
2582 1,
2583 MirScalarExpr::literal_ok(Datum::True, ReprScalarType::Bool),
2584 )],
2585 projection: vec![0, 1],
2586 input_arity: 1,
2587 };
2588
2589 let relation = ReprRelationType::new(vec![ReprScalarType::String.nullable(false)]);
2590 let arena = RowArena::new();
2591 let mut interpreter = ColumnSpecs::new(&relation, &arena);
2592 interpreter.push_column(
2594 0,
2595 ResultSpec::value_between(Datum::String("not-a-uuid"), Datum::String("not-a-uuid")),
2596 );
2597 let spec = interpreter.mfp_filter(&mfp);
2598 assert!(
2599 spec.range.may_fail(),
2600 "an MFP expression that errors on the stats range must propagate \
2601 fallibility, otherwise persist filter pushdown can wrongly discard \
2602 a part that produces error rows",
2603 );
2604 }
2605
2606 #[mz_ore::test]
2616 #[cfg_attr(miri, ignore)]
2617 fn test_mfp_filter_fallibility_equivalence() {
2618 fn check(data: ExpressionData) -> Result<(), TestCaseError> {
2619 let ExpressionData {
2620 relation_type,
2621 specs,
2622 rows,
2623 expr,
2624 } = data;
2625
2626 let input_arity = relation_type.column_types.len();
2627 let mfp = MapFilterProject {
2628 expressions: vec![expr.clone()],
2629 predicates: vec![],
2630 projection: (0..input_arity).collect(),
2631 input_arity,
2632 };
2633
2634 let arena = RowArena::new();
2635 let mut interpreter = ColumnSpecs::new(&relation_type, &arena);
2636 for (id, spec) in specs.into_iter().enumerate() {
2637 interpreter.push_column(id, spec);
2638 }
2639 let summary = interpreter.mfp_filter(&mfp);
2640
2641 for row in &rows {
2642 let datums: Vec<_> = row.iter().collect();
2643 if expr.eval(&datums, &arena).is_err() {
2644 prop_assert!(
2645 summary.range.may_fail(),
2646 "mfp_filter must surface the fallibility of an \
2647 unreferenced MFP expression: row {:?} errored at \
2648 runtime but the interpreter ruled out errors",
2649 row,
2650 );
2651 }
2652 }
2653 Ok(())
2654 }
2655
2656 proptest!(|(data in gen_expr_data())| {
2657 check(data)?;
2658 });
2659 }
2660
2661 #[mz_ore::test]
2662 fn test_mfp() {
2663 use MirScalarExpr::*;
2665
2666 let mfp = MapFilterProject {
2667 expressions: vec![],
2668 predicates: vec![
2669 (
2671 1,
2672 CallUnary {
2673 func: UnaryFunc::IsNull(IsNull),
2674 expr: Box::new(CallBinary {
2675 func: MulInt32.into(),
2676 expr1: Box::new(MirScalarExpr::column(0)),
2677 expr2: Box::new(MirScalarExpr::column(0)),
2678 }),
2679 },
2680 ),
2681 (
2683 1,
2684 CallBinary {
2685 func: Eq.into(),
2686 expr1: Box::new(MirScalarExpr::column(0)),
2687 expr2: Box::new(MirScalarExpr::literal_ok(
2688 Datum::Int32(1727694505),
2689 ReprScalarType::Int32,
2690 )),
2691 },
2692 ),
2693 ],
2694 projection: vec![],
2695 input_arity: 1,
2696 };
2697
2698 let relation = ReprRelationType::new(vec![ReprScalarType::Int32.nullable(true)]);
2699 let arena = RowArena::new();
2700 let mut interpreter = ColumnSpecs::new(&relation, &arena);
2701 interpreter.push_column(0, ResultSpec::value(Datum::Int32(-1294725158)));
2702 let spec = interpreter.mfp_filter(&mfp);
2703 assert!(spec.range.may_fail());
2704 }
2705
2706 #[mz_ore::test]
2707 fn test_concat() {
2708 let expr = MirScalarExpr::call_variadic(
2709 Concat,
2710 vec![
2711 MirScalarExpr::column(0),
2712 MirScalarExpr::literal_ok(Datum::String("a"), ReprScalarType::String),
2713 MirScalarExpr::literal_ok(Datum::String("b"), ReprScalarType::String),
2714 ],
2715 );
2716
2717 let relation = ReprRelationType::new(vec![ReprScalarType::String.nullable(false)]);
2718 let arena = RowArena::new();
2719 let interpreter = ColumnSpecs::new(&relation, &arena);
2720 let spec = interpreter.expr(&expr);
2721 assert!(spec.range.may_contain(Datum::String("blab")));
2722 }
2723
2724 #[mz_ore::test]
2725 fn test_eval_range() {
2726 let period_ms = MirScalarExpr::literal_ok(Datum::Int64(10), ReprScalarType::Int64);
2738 let expr = MirScalarExpr::CallBinary {
2739 func: Gte.into(),
2740 expr1: Box::new(MirScalarExpr::CallUnmaterializable(
2741 UnmaterializableFunc::MzNow,
2742 )),
2743 expr2: Box::new(MirScalarExpr::CallUnary {
2744 func: UnaryFunc::CastInt64ToMzTimestamp(CastInt64ToMzTimestamp),
2745 expr: Box::new(MirScalarExpr::CallBinary {
2746 func: MulInt64.into(),
2747 expr1: Box::new(period_ms.clone()),
2748 expr2: Box::new(MirScalarExpr::CallBinary {
2749 func: DivInt64.into(),
2750 expr1: Box::new(MirScalarExpr::column(0)),
2751 expr2: Box::new(period_ms),
2752 }),
2753 }),
2754 }),
2755 };
2756 let relation = ReprRelationType::new(vec![ReprScalarType::Int64.nullable(false)]);
2757
2758 {
2759 let arena = RowArena::new();
2761 let mut interpreter = ColumnSpecs::new(&relation, &arena);
2762 interpreter.push_unmaterializable(
2763 UnmaterializableFunc::MzNow,
2764 ResultSpec::value_between(
2765 Datum::MzTimestamp(10.into()),
2766 Datum::MzTimestamp(20.into()),
2767 ),
2768 );
2769 interpreter.push_column(0, ResultSpec::value_between(30i64.into(), 40i64.into()));
2770
2771 let range_out = interpreter.expr(&expr).range;
2772 assert!(range_out.may_contain(Datum::False));
2773 assert!(!range_out.may_contain(Datum::True));
2774 assert!(!range_out.may_contain(Datum::Null));
2775 assert!(range_out.may_fail());
2776 }
2777
2778 {
2779 let arena = RowArena::new();
2781 let mut interpreter = ColumnSpecs::new(&relation, &arena);
2782 interpreter.push_unmaterializable(
2783 UnmaterializableFunc::MzNow,
2784 ResultSpec::value_between(
2785 Datum::MzTimestamp(10.into()),
2786 Datum::MzTimestamp(35.into()),
2787 ),
2788 );
2789 interpreter.push_column(0, ResultSpec::value_between(30i64.into(), 40i64.into()));
2790
2791 let range_out = interpreter.expr(&expr).range;
2792 assert!(range_out.may_contain(Datum::False));
2793 assert!(range_out.may_contain(Datum::True));
2794 assert!(!range_out.may_contain(Datum::Null));
2795 assert!(range_out.may_fail());
2796 }
2797 }
2798
2799 #[mz_ore::test]
2800 #[cfg_attr(miri, ignore)] fn test_jsonb() {
2802 let arena = RowArena::new();
2803
2804 let expr = MirScalarExpr::column(0)
2805 .call_binary(
2806 MirScalarExpr::literal_ok(Datum::from("ts"), ReprScalarType::String),
2807 JsonbGetString,
2808 )
2809 .call_unary(CastJsonbToNumeric(None));
2810
2811 let relation = ReprRelationType::new(vec![ReprScalarType::Jsonb.nullable(true)]);
2812 let mut interpreter = ColumnSpecs::new(&relation, &arena);
2813 interpreter.push_column(
2814 0,
2815 ResultSpec::map_spec(
2816 [(
2817 "ts".into(),
2818 ResultSpec::value_between(
2819 Datum::Numeric(100.into()),
2820 Datum::Numeric(300.into()),
2821 ),
2822 )]
2823 .into_iter()
2824 .collect(),
2825 ),
2826 );
2827
2828 let range_out = interpreter.expr(&expr).range;
2829 assert!(!range_out.may_contain(Datum::Numeric(0.into())));
2830 assert!(range_out.may_contain(Datum::Numeric(200.into())));
2831 assert!(!range_out.may_contain(Datum::Numeric(400.into())));
2832 }
2833
2834 #[mz_ore::test]
2835 fn test_unbounded_call_is_opaque() {
2836 let arena = RowArena::new();
2837
2838 let expr = MirScalarExpr::literal_ok(Datum::Numeric(1.into()), ReprScalarType::Jsonb)
2840 .call_unary(Jq(JqProgram::new(". + 1").expect("valid program")));
2841
2842 let relation = ReprRelationType::new(vec![]);
2843 let interpreter = ColumnSpecs::new(&relation, &arena);
2844
2845 let range_out = interpreter.expr(&expr).range;
2846 assert!(range_out.may_contain(Datum::Numeric(3.into())));
2847 assert_eq!(super::Trace.expr(&expr), TraceSummary::Unknown);
2848 }
2849
2850 #[mz_ore::test]
2851 fn test_nested_union_partial_overlap() {
2852 let a = ResultSpec::map_spec(
2857 [
2858 ("x".into(), ResultSpec::value(Datum::String("a"))),
2859 ("y".into(), ResultSpec::value(Datum::String("b"))),
2860 ("c".into(), ResultSpec::value(Datum::String("c"))),
2861 ]
2862 .into_iter()
2863 .collect(),
2864 );
2865 let b = ResultSpec::map_spec(
2866 [
2867 ("x".into(), ResultSpec::value(Datum::String("a2"))),
2868 ("y".into(), ResultSpec::value(Datum::String("b2"))),
2869 ("z".into(), ResultSpec::value(Datum::String("z"))),
2870 ]
2871 .into_iter()
2872 .collect(),
2873 );
2874
2875 let unioned = a.union(b);
2876
2877 let arena = RowArena::new();
2881 let relation = ReprRelationType::new(vec![ReprScalarType::Jsonb.nullable(false)]);
2882
2883 {
2885 let mut interpreter = ColumnSpecs::new(&relation, &arena);
2886 interpreter.push_column(0, unioned.clone());
2887 let expr = MirScalarExpr::column(0).call_binary(
2888 MirScalarExpr::literal_ok(Datum::from("c"), ReprScalarType::String),
2889 JsonbGetStringStringify,
2890 );
2891 assert!(interpreter.expr(&expr).range.may_contain(Datum::Null));
2892 }
2893
2894 {
2896 let mut interpreter = ColumnSpecs::new(&relation, &arena);
2897 interpreter.push_column(0, unioned.clone());
2898 let expr = MirScalarExpr::column(0).call_binary(
2899 MirScalarExpr::literal_ok(Datum::from("z"), ReprScalarType::String),
2900 JsonbGetStringStringify,
2901 );
2902 assert!(interpreter.expr(&expr).range.may_contain(Datum::Null));
2903 }
2904
2905 {
2907 let mut interpreter = ColumnSpecs::new(&relation, &arena);
2908 interpreter.push_column(0, unioned);
2909 let expr = MirScalarExpr::column(0).call_binary(
2910 MirScalarExpr::literal_ok(Datum::from("x"), ReprScalarType::String),
2911 JsonbGetStringStringify,
2912 );
2913 let x_range = interpreter.expr(&expr).range;
2914 assert!(x_range.may_contain(Datum::String("a")));
2915 assert!(x_range.may_contain(Datum::String("a2")));
2916 }
2917 }
2918
2919 #[mz_ore::test]
2920 #[cfg_attr(miri, ignore)] fn test_case_over_jsonb_columns() {
2922 let arena = RowArena::new();
2926
2927 let expr = MirScalarExpr::If {
2929 cond: Box::new(MirScalarExpr::column(0)),
2930 then: Box::new(MirScalarExpr::column(1)),
2931 els: Box::new(MirScalarExpr::column(2)),
2932 }
2933 .call_binary(
2934 MirScalarExpr::literal_ok(Datum::from("y"), ReprScalarType::String),
2935 JsonbGetStringStringify,
2936 )
2937 .call_unary(UnaryFunc::IsNull(IsNull));
2938
2939 let relation = ReprRelationType::new(vec![
2940 ReprScalarType::Bool.nullable(false),
2941 ReprScalarType::Jsonb.nullable(false),
2942 ReprScalarType::Jsonb.nullable(false),
2943 ]);
2944 let mut interpreter = ColumnSpecs::new(&relation, &arena);
2945 interpreter.push_column(0, ResultSpec::value_between(Datum::False, Datum::True));
2946 interpreter.push_column(
2947 1,
2948 ResultSpec::map_spec(
2949 [("x".into(), ResultSpec::value(Datum::String("a")))]
2950 .into_iter()
2951 .collect(),
2952 ),
2953 );
2954 interpreter.push_column(
2955 2,
2956 ResultSpec::map_spec(
2957 [("y".into(), ResultSpec::value(Datum::String("b")))]
2958 .into_iter()
2959 .collect(),
2960 ),
2961 );
2962
2963 let range_out = interpreter.expr(&expr).range;
2964 assert!(range_out.may_contain(Datum::True));
2967 }
2968
2969 #[mz_ore::test]
2970 fn test_like() {
2971 let arena = RowArena::new();
2972
2973 let expr = MirScalarExpr::CallUnary {
2974 func: UnaryFunc::IsLikeMatch(IsLikeMatch(
2975 crate::like_pattern::compile("%whatever%", true).unwrap(),
2976 )),
2977 expr: Box::new(MirScalarExpr::column(0)),
2978 };
2979
2980 let relation = ReprRelationType::new(vec![ReprScalarType::String.nullable(true)]);
2981 let mut interpreter = ColumnSpecs::new(&relation, &arena);
2982 interpreter.push_column(
2983 0,
2984 ResultSpec::value_between(Datum::String("aardvark"), Datum::String("zebra")),
2985 );
2986
2987 let range_out = interpreter.expr(&expr).range;
2988 assert!(
2989 !range_out.fallible,
2990 "like function should not error on non-error input"
2991 );
2992 assert!(range_out.may_contain(Datum::True));
2993 assert!(range_out.may_contain(Datum::False));
2994 assert!(range_out.may_contain(Datum::Null));
2995 }
2996
2997 #[mz_ore::test]
2998 fn test_try_parse_monotonic_iso8601_timestamp() {
2999 use chrono::NaiveDateTime;
3000
3001 let arena = RowArena::new();
3002
3003 let expr = MirScalarExpr::CallUnary {
3004 func: UnaryFunc::TryParseMonotonicIso8601Timestamp(TryParseMonotonicIso8601Timestamp),
3005 expr: Box::new(MirScalarExpr::column(0)),
3006 };
3007
3008 let relation = ReprRelationType::new(vec![ReprScalarType::String.nullable(true)]);
3009 let mut interpreter = ColumnSpecs::new(&relation, &arena);
3011 interpreter.push_column(
3012 0,
3013 ResultSpec::value_between(
3014 Datum::String("2024-01-11T00:00:00.000Z"),
3015 Datum::String("2024-01-11T20:00:00.000Z"),
3016 ),
3017 );
3018
3019 let timestamp = |ts| {
3020 Datum::Timestamp(
3021 NaiveDateTime::parse_from_str(ts, "%Y-%m-%dT%H:%M:%S")
3022 .unwrap()
3023 .try_into()
3024 .unwrap(),
3025 )
3026 };
3027
3028 let range_out = interpreter.expr(&expr).range;
3029 assert!(!range_out.fallible);
3030 assert!(range_out.nullable);
3031 assert!(!range_out.may_contain(timestamp("2024-01-10T10:00:00")));
3032 assert!(range_out.may_contain(timestamp("2024-01-11T10:00:00")));
3033 assert!(!range_out.may_contain(timestamp("2024-01-12T10:00:00")));
3034
3035 let mut interpreter = ColumnSpecs::new(&relation, &arena);
3037 interpreter.push_column(
3038 0,
3039 ResultSpec::value_between(Datum::String("2024-01-1"), Datum::String("2024-01-2")),
3040 );
3041
3042 let range_out = interpreter.expr(&expr).range;
3043 assert!(!range_out.fallible);
3044 assert!(range_out.nullable);
3045 assert!(range_out.may_contain(timestamp("2024-01-10T10:00:00")));
3046 assert!(range_out.may_contain(timestamp("2024-01-11T10:00:00")));
3047 assert!(range_out.may_contain(timestamp("2024-01-12T10:00:00")));
3048
3049 let mut interpreter = ColumnSpecs::new(&relation, &arena);
3051 interpreter.push_column(
3052 0,
3053 ResultSpec::value_between(
3054 Datum::String("2024-01-1"),
3055 Datum::String("2024-01-12T10:00:00"),
3056 )
3057 .union(ResultSpec::null()),
3058 );
3059
3060 let range_out = interpreter.expr(&expr).range;
3061 assert!(!range_out.fallible);
3062 assert!(range_out.nullable);
3063 assert!(range_out.may_contain(timestamp("2024-01-10T10:00:00")));
3064 assert!(range_out.may_contain(timestamp("2024-01-11T10:00:00")));
3065 assert!(range_out.may_contain(timestamp("2024-01-12T10:00:00")));
3066
3067 let mut interpreter = ColumnSpecs::new(&relation, &arena);
3069 interpreter.push_column(
3070 0,
3071 ResultSpec::value_between(
3072 Datum::String("2024-01-11T10:00:00.000Z"),
3073 Datum::String("2024-01-11T10:00:00.000Z"),
3074 ),
3075 );
3076
3077 let range_out = interpreter.expr(&expr).range;
3078 assert!(!range_out.fallible);
3079 assert!(!range_out.nullable);
3080 assert!(!range_out.may_contain(timestamp("2024-01-10T10:00:00")));
3081 assert!(range_out.may_contain(timestamp("2024-01-11T10:00:00")));
3082 assert!(!range_out.may_contain(timestamp("2024-01-12T10:00:00")));
3083 }
3084
3085 #[mz_ore::test]
3086 fn test_inequality() {
3087 let arena = RowArena::new();
3088
3089 let expr = MirScalarExpr::column(0).call_binary(
3090 MirScalarExpr::CallUnmaterializable(UnmaterializableFunc::MzNow),
3091 Gte,
3092 );
3093
3094 let relation = ReprRelationType::new(vec![ReprScalarType::MzTimestamp.nullable(true)]);
3095 let mut interpreter = ColumnSpecs::new(&relation, &arena);
3096 interpreter.push_column(
3097 0,
3098 ResultSpec::value_between(
3099 Datum::MzTimestamp(1704736444949u64.into()),
3100 Datum::MzTimestamp(1704736444949u64.into()),
3101 )
3102 .union(ResultSpec::null()),
3103 );
3104 interpreter.push_unmaterializable(
3105 UnmaterializableFunc::MzNow,
3106 ResultSpec::value_between(
3107 Datum::MzTimestamp(1704738791000u64.into()),
3108 Datum::MzTimestamp(18446744073709551615u64.into()),
3109 ),
3110 );
3111
3112 let range_out = interpreter.expr(&expr).range;
3113 assert!(
3114 !range_out.fallible,
3115 "<= function should not error on non-error input"
3116 );
3117 assert!(!range_out.may_contain(Datum::True));
3118 assert!(range_out.may_contain(Datum::False));
3119 assert!(range_out.may_contain(Datum::Null));
3120 }
3121
3122 #[mz_ore::test]
3130 #[cfg_attr(miri, ignore)]
3131 fn test_add_timestamp_interval_non_monotone() {
3132 use chrono::NaiveDateTime;
3133 use mz_repr::adt::interval::Interval;
3134 use mz_repr::adt::timestamp::CheckedTimestamp;
3135 use mz_repr::{Datum, Row};
3136
3137 let arena = RowArena::new();
3138
3139 let ts_lit = |s: &str| {
3151 let mut row = Row::default();
3152 row.packer().push(Datum::Timestamp(
3153 CheckedTimestamp::from_timestamplike(
3154 NaiveDateTime::parse_from_str(s, "%Y-%m-%dT%H:%M:%S").unwrap(),
3155 )
3156 .unwrap(),
3157 ));
3158 MirScalarExpr::Literal(Ok(row), ReprScalarType::Timestamp.nullable(false))
3159 };
3160 let interval = |months: i32, days: i32, micros: i64| {
3161 Datum::Interval(Interval {
3162 months,
3163 days,
3164 micros,
3165 })
3166 };
3167
3168 let expr = ts_lit("2024-01-31T00:00:00")
3170 .call_binary(MirScalarExpr::column(0), AddTimestampInterval)
3171 .call_binary(ts_lit("2024-03-15T00:00:00"), Gte);
3172
3173 let relation = ReprRelationType::new(vec![ReprScalarType::Interval.nullable(false)]);
3174 let mut interpreter = ColumnSpecs::new(&relation, &arena);
3175 interpreter.push_column(
3176 0,
3177 ResultSpec::value_between(interval(0, 31, 0), interval(1, 0, 0)),
3178 );
3179
3180 let range_out = interpreter.expr(&expr).range;
3181 assert!(
3188 range_out.may_contain(Datum::True),
3189 "interpreter incorrectly ruled out matching rows; \
3190 add_timestamp_interval is not monotone in the interval argument",
3191 );
3192 }
3193
3194 #[mz_ore::test]
3201 #[cfg_attr(miri, ignore)]
3202 fn test_timestamp_plus_interval_dynamic_monotone() {
3203 use chrono::NaiveDateTime;
3204 use mz_repr::adt::interval::Interval;
3205 use mz_repr::adt::timestamp::CheckedTimestamp;
3206 use mz_repr::{Datum, Row};
3207
3208 let arena = RowArena::new();
3209
3210 let ts = |s: &str| {
3211 Datum::Timestamp(
3212 CheckedTimestamp::from_timestamplike(
3213 NaiveDateTime::parse_from_str(s, "%Y-%m-%dT%H:%M:%S").unwrap(),
3214 )
3215 .unwrap(),
3216 )
3217 };
3218 let interval_lit = |months: i32, days: i32, micros: i64| {
3219 let mut row = Row::default();
3220 row.packer().push(Datum::Interval(Interval {
3221 months,
3222 days,
3223 micros,
3224 }));
3225 MirScalarExpr::Literal(Ok(row), ReprScalarType::Interval.nullable(false))
3226 };
3227
3228 let relation = ReprRelationType::new(vec![ReprScalarType::Timestamp.nullable(false)]);
3229
3230 {
3236 let expr = MirScalarExpr::column(0)
3237 .call_binary(interval_lit(0, 1, 0), SubTimestampInterval)
3238 .call_binary(
3239 MirScalarExpr::Literal(
3240 Ok({
3241 let mut r = Row::default();
3242 r.packer().push(ts("2024-01-15T00:00:00"));
3243 r
3244 }),
3245 ReprScalarType::Timestamp.nullable(false),
3246 ),
3247 Lt,
3248 );
3249 let mut interpreter = ColumnSpecs::new(&relation, &arena);
3250 interpreter.push_column(
3251 0,
3252 ResultSpec::value_between(ts("2024-01-15T00:00:00"), ts("2024-01-20T00:00:00")),
3253 );
3254 let range_out = interpreter.expr(&expr).range;
3255 assert!(
3256 range_out.may_contain(Datum::True),
3257 "day-only interval should preserve tight bounds",
3258 );
3259 assert!(
3260 range_out.may_contain(Datum::False),
3261 "day-only interval should preserve tight bounds",
3262 );
3263 }
3264
3265 {
3270 let expr = MirScalarExpr::column(0)
3271 .call_binary(interval_lit(0, 1, 0), SubTimestampInterval)
3272 .call_binary(
3273 MirScalarExpr::Literal(
3274 Ok({
3275 let mut r = Row::default();
3276 r.packer().push(ts("2024-01-15T00:00:00"));
3277 r
3278 }),
3279 ReprScalarType::Timestamp.nullable(false),
3280 ),
3281 Lt,
3282 );
3283 let mut interpreter = ColumnSpecs::new(&relation, &arena);
3284 interpreter.push_column(
3285 0,
3286 ResultSpec::value_between(ts("2024-01-17T00:00:00"), ts("2024-01-20T00:00:00")),
3287 );
3288 let range_out = interpreter.expr(&expr).range;
3289 assert!(
3290 !range_out.may_contain(Datum::True),
3291 "day-only interval should narrow out impossible matches",
3292 );
3293 }
3294
3295 {
3300 let expr = MirScalarExpr::column(0)
3301 .call_binary(interval_lit(1, 0, 0), SubTimestampInterval)
3302 .call_binary(
3303 MirScalarExpr::Literal(
3304 Ok({
3305 let mut r = Row::default();
3306 r.packer().push(ts("2024-01-15T00:00:00"));
3307 r
3308 }),
3309 ReprScalarType::Timestamp.nullable(false),
3310 ),
3311 Lt,
3312 );
3313 let mut interpreter = ColumnSpecs::new(&relation, &arena);
3314 interpreter.push_column(
3315 0,
3316 ResultSpec::value_between(ts("2024-01-17T00:00:00"), ts("2024-01-20T00:00:00")),
3317 );
3318 let range_out = interpreter.expr(&expr).range;
3319 assert!(
3320 range_out.may_contain(Datum::True),
3321 "month-bearing interval must conservatively admit True",
3322 );
3323 assert!(
3324 range_out.may_contain(Datum::False),
3325 "month-bearing interval must conservatively admit False",
3326 );
3327 }
3328 }
3329
3330 #[mz_ore::test]
3339 #[cfg_attr(miri, ignore)]
3340 fn proptest_timestamp_plus_interval_monotone_when_months_zero() {
3341 use mz_repr::adt::interval::Interval;
3342 use mz_repr::{Datum, RowArena, SqlScalarType, arb_datum_for_scalar};
3343 use proptest::prelude::*;
3344
3345 let timestamp_strat = || arb_datum_for_scalar(SqlScalarType::Timestamp { precision: None });
3346 let zero_month_interval_strat =
3353 (any::<i32>(), any::<i64>()).prop_map(|(days, micros)| Interval {
3354 months: 0,
3355 days,
3356 micros,
3357 });
3358
3359 let expr = MirScalarExpr::CallBinary {
3360 func: AddTimestampInterval.into(),
3361 expr1: Box::new(MirScalarExpr::column(0)),
3362 expr2: Box::new(MirScalarExpr::column(1)),
3363 };
3364 let arena = RowArena::new();
3365
3366 proptest!(|(
3367 t1 in timestamp_strat(),
3368 t2 in timestamp_strat(),
3369 i in zero_month_interval_strat,
3370 )| {
3371 let t1 = match t1 { PropDatum::Timestamp(t) => t, _ => unreachable!() };
3372 let t2 = match t2 { PropDatum::Timestamp(t) => t, _ => unreachable!() };
3373 let i = Datum::Interval(i);
3374 let r1 = expr.eval(&[Datum::Timestamp(t1), i], &arena);
3375 let r2 = expr.eval(&[Datum::Timestamp(t2), i], &arena);
3376 if let (Ok(Datum::Timestamp(r1)), Ok(Datum::Timestamp(r2))) = (r1, r2) {
3379 prop_assert_eq!(t1.cmp(&t2), r1.cmp(&r2));
3380 }
3381 });
3382 }
3383
3384 #[mz_ore::test]
3389 #[cfg_attr(miri, ignore)]
3390 fn test_date_bin_timestamp_non_monotone() {
3391 use chrono::NaiveDateTime;
3392 use mz_repr::adt::interval::Interval;
3393 use mz_repr::adt::timestamp::CheckedTimestamp;
3394 use mz_repr::{Datum, Row};
3395
3396 let arena = RowArena::new();
3397
3398 let ts_lit = |s: &str| {
3399 let mut row = Row::default();
3400 row.packer().push(Datum::Timestamp(
3401 CheckedTimestamp::from_timestamplike(
3402 NaiveDateTime::parse_from_str(s, "%Y-%m-%dT%H:%M:%S").unwrap(),
3403 )
3404 .unwrap(),
3405 ));
3406 MirScalarExpr::Literal(Ok(row), ReprScalarType::Timestamp.nullable(false))
3407 };
3408 let interval = |months: i32, days: i32, micros: i64| {
3409 Datum::Interval(Interval {
3410 months,
3411 days,
3412 micros,
3413 })
3414 };
3415
3416 let expr = MirScalarExpr::column(0)
3433 .call_binary(ts_lit("2024-01-01T12:00:00"), DateBinTimestamp)
3434 .call_binary(ts_lit("2024-01-01T06:00:00"), Gt);
3435
3436 let relation = ReprRelationType::new(vec![ReprScalarType::Interval.nullable(false)]);
3437 let mut interpreter = ColumnSpecs::new(&relation, &arena);
3438 interpreter.push_column(
3439 0,
3440 ResultSpec::value_between(interval(0, 1, 0), interval(0, 2, 0)),
3441 );
3442
3443 let range_out = interpreter.expr(&expr).range;
3444 assert!(
3445 range_out.may_contain(Datum::True),
3446 "date_bin is not monotone in the stride argument; \
3447 interior strides can produce outputs outside the endpoint-bounded \
3448 box, so the interpreter must admit True for `>`-style predicates",
3449 );
3450 }
3451
3452 #[mz_ore::test]
3457 #[cfg_attr(miri, ignore)]
3458 fn test_round_numeric_representation_independent() {
3459 use mz_repr::adt::date::Date;
3460
3461 let arena = RowArena::new();
3462 let lit = |d: Datum, ty: ReprScalarType| {
3463 let mut row = Row::default();
3464 row.packer().push(d);
3465 MirScalarExpr::Literal(Ok(row), ty.nullable(false))
3466 };
3467
3468 let expr = lit(
3471 Datum::Date(Date::from_pg_epoch(0).unwrap()),
3472 ReprScalarType::Date,
3473 )
3474 .call_unary(UnaryFunc::ExtractDate(ExtractDate(DateTimeUnits::Epoch)))
3475 .call_binary(
3476 lit(Datum::Int32(i32::MAX), ReprScalarType::Int32),
3477 BinaryFunc::from(RoundNumericBinary),
3478 );
3479
3480 let relation = ReprRelationType::new(vec![]);
3481 let range = ColumnSpecs::new(&relation, &arena).expr(&expr).range;
3482 match expr.eval(&[], &arena) {
3483 Ok(value) => assert!(
3484 range.may_contain(value),
3485 "interpreter ruled out {value:?}, which the evaluator produced: {range:?}",
3486 ),
3487 Err(_) => assert!(
3488 range.may_fail(),
3489 "interpreter ruled out the error the evaluator produced: {range:?}",
3490 ),
3491 }
3492 }
3493
3494 #[mz_ore::test]
3495 fn test_trace() {
3496 use super::Trace;
3497
3498 let expr = MirScalarExpr::column(0).call_binary(
3499 MirScalarExpr::column(1)
3500 .call_binary(MirScalarExpr::column(3).call_unary(NegInt64), AddInt64),
3501 Gte,
3502 );
3503 let summary = Trace.expr(&expr);
3504 assert!(summary.pushdownable());
3505 }
3506}