Skip to main content

mz_expr/
scalar.rs

1// Copyright Materialize, Inc. and contributors. All rights reserved.
2//
3// Use of this software is governed by the Business Source License
4// included in the LICENSE file.
5//
6// As of the Change Date specified in that file, in accordance with
7// the Business Source License, use of this software will be governed
8// by the Apache License, Version 2.0.
9
10use std::collections::{BTreeMap, BTreeSet};
11use std::ops::BitOrAssign;
12use std::sync::Arc;
13use std::{fmt, mem};
14
15use itertools::Itertools;
16use mz_lowertest::MzReflect;
17use mz_ore::cast::CastFrom;
18use mz_ore::collections::CollectionExt;
19use mz_ore::iter::IteratorExt;
20use mz_ore::stack::RecursionLimitError;
21use mz_ore::str::StrExt;
22use mz_ore::treat_as_equal::TreatAsEqual;
23use mz_ore::vec::swap_remove_multiple;
24use mz_pgrepr::TypeFromOidError;
25use mz_pgtz::timezone::TimezoneSpec;
26use mz_proto::{IntoRustIfSome, ProtoType, RustType, TryFromProtoError};
27use mz_repr::adt::array::InvalidArrayError;
28use mz_repr::adt::date::DateError;
29use mz_repr::adt::datetime::DateTimeUnits;
30use mz_repr::adt::range::InvalidRangeError;
31use mz_repr::adt::regex::{Regex, RegexCompilationError};
32use mz_repr::adt::timestamp::TimestampError;
33use mz_repr::strconv::{ParseError, ParseHexError};
34use mz_repr::{Datum, ReprColumnType, Row, RowArena, SqlColumnType, SqlScalarType};
35use proptest::prelude::*;
36use proptest_derive::Arbitrary;
37use serde::{Deserialize, Serialize};
38
39use crate::scalar::func::format::DateTimeFormat;
40use crate::scalar::func::{
41    BinaryFunc, UnaryFunc, UnmaterializableFunc, VariadicFunc, parse_timezone,
42    regexp_replace_parse_flags,
43};
44use crate::scalar::proto_eval_error::proto_incompatible_array_dimensions::ProtoDims;
45use crate::visit::{Visit, VisitChildren};
46
47pub mod func;
48pub mod like_pattern;
49
50include!(concat!(env!("OUT_DIR"), "/mz_expr.scalar.rs"));
51
52#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize, MzReflect)]
53pub enum MirScalarExpr {
54    /// A column of the input row
55    Column(usize, TreatAsEqual<Option<Arc<str>>>),
56    /// A literal value.
57    /// (Stored as a row, because we can't own a Datum)
58    Literal(Result<Row, EvalError>, SqlColumnType),
59    /// A call to an unmaterializable function.
60    ///
61    /// These functions cannot be evaluated by `MirScalarExpr::eval`. They must
62    /// be transformed away by a higher layer.
63    CallUnmaterializable(UnmaterializableFunc),
64    /// A function call that takes one expression as an argument.
65    CallUnary {
66        func: UnaryFunc,
67        expr: Box<MirScalarExpr>,
68    },
69    /// A function call that takes two expressions as arguments.
70    CallBinary {
71        func: BinaryFunc,
72        expr1: Box<MirScalarExpr>,
73        expr2: Box<MirScalarExpr>,
74    },
75    /// A function call that takes an arbitrary number of arguments.
76    CallVariadic {
77        func: VariadicFunc,
78        exprs: Vec<MirScalarExpr>,
79    },
80    /// Conditionally evaluated expressions.
81    ///
82    /// It is important that `then` and `els` only be evaluated if
83    /// `cond` is true or not, respectively. This is the only way
84    /// users can guard execution (other logical operator do not
85    /// short-circuit) and we need to preserve that.
86    If {
87        cond: Box<MirScalarExpr>,
88        then: Box<MirScalarExpr>,
89        els: Box<MirScalarExpr>,
90    },
91}
92
93// We need a custom Debug because we don't want to show `None` for name information.
94// Sadly, the `derivative` crate doesn't support this use case.
95impl std::fmt::Debug for MirScalarExpr {
96    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
97        match self {
98            MirScalarExpr::Column(i, TreatAsEqual(Some(name))) => {
99                write!(f, "Column({i}, {name:?})")
100            }
101            MirScalarExpr::Column(i, TreatAsEqual(None)) => write!(f, "Column({i})"),
102            MirScalarExpr::Literal(lit, typ) => write!(f, "Literal({lit:?}, {typ:?})"),
103            MirScalarExpr::CallUnmaterializable(func) => {
104                write!(f, "CallUnmaterializable({func:?})")
105            }
106            MirScalarExpr::CallUnary { func, expr } => {
107                write!(f, "CallUnary({func:?}, {expr:?})")
108            }
109            MirScalarExpr::CallBinary { func, expr1, expr2 } => {
110                write!(f, "CallBinary({func:?}, {expr1:?}, {expr2:?})")
111            }
112            MirScalarExpr::CallVariadic { func, exprs } => {
113                write!(f, "CallVariadic({func:?}, {exprs:?})")
114            }
115            MirScalarExpr::If { cond, then, els } => {
116                write!(f, "If({cond:?}, {then:?}, {els:?})")
117            }
118        }
119    }
120}
121
122impl MirScalarExpr {
123    pub fn columns(is: &[usize]) -> Vec<MirScalarExpr> {
124        is.iter().map(|i| MirScalarExpr::column(*i)).collect()
125    }
126
127    pub fn column(column: usize) -> Self {
128        MirScalarExpr::Column(column, TreatAsEqual(None))
129    }
130
131    pub fn named_column(column: usize, name: Arc<str>) -> Self {
132        MirScalarExpr::Column(column, TreatAsEqual(Some(name)))
133    }
134
135    pub fn literal(res: Result<Datum, EvalError>, typ: SqlScalarType) -> Self {
136        let typ = typ.nullable(matches!(res, Ok(Datum::Null)));
137        let row = res.map(|datum| Row::pack_slice(&[datum]));
138        MirScalarExpr::Literal(row, typ)
139    }
140
141    pub fn literal_ok(datum: Datum, typ: SqlScalarType) -> Self {
142        MirScalarExpr::literal(Ok(datum), typ)
143    }
144
145    pub fn literal_null(typ: SqlScalarType) -> Self {
146        MirScalarExpr::literal_ok(Datum::Null, typ)
147    }
148
149    pub fn literal_false() -> Self {
150        MirScalarExpr::literal_ok(Datum::False, SqlScalarType::Bool)
151    }
152
153    pub fn literal_true() -> Self {
154        MirScalarExpr::literal_ok(Datum::True, SqlScalarType::Bool)
155    }
156
157    pub fn call_unary<U: Into<UnaryFunc>>(self, func: U) -> Self {
158        MirScalarExpr::CallUnary {
159            func: func.into(),
160            expr: Box::new(self),
161        }
162    }
163
164    pub fn call_binary<B: Into<BinaryFunc>>(self, other: Self, func: B) -> Self {
165        MirScalarExpr::CallBinary {
166            func: func.into(),
167            expr1: Box::new(self),
168            expr2: Box::new(other),
169        }
170    }
171
172    pub fn if_then_else(self, t: Self, f: Self) -> Self {
173        MirScalarExpr::If {
174            cond: Box::new(self),
175            then: Box::new(t),
176            els: Box::new(f),
177        }
178    }
179
180    pub fn or(self, other: Self) -> Self {
181        MirScalarExpr::CallVariadic {
182            func: VariadicFunc::Or,
183            exprs: vec![self, other],
184        }
185    }
186
187    pub fn and(self, other: Self) -> Self {
188        MirScalarExpr::CallVariadic {
189            func: VariadicFunc::And,
190            exprs: vec![self, other],
191        }
192    }
193
194    pub fn not(self) -> Self {
195        self.call_unary(UnaryFunc::Not(func::Not))
196    }
197
198    pub fn call_is_null(self) -> Self {
199        self.call_unary(UnaryFunc::IsNull(func::IsNull))
200    }
201
202    /// Match AND or OR on self and get the args. If no match, then interpret self as if it were
203    /// wrapped in a 1-arg AND/OR.
204    pub fn and_or_args(&self, func_to_match: VariadicFunc) -> Vec<MirScalarExpr> {
205        assert!(func_to_match == VariadicFunc::Or || func_to_match == VariadicFunc::And);
206        match self {
207            MirScalarExpr::CallVariadic { func, exprs } if *func == func_to_match => exprs.clone(),
208            _ => vec![self.clone()],
209        }
210    }
211
212    /// Try to match a literal equality involving the given expression on one side.
213    /// Return the (non-null) literal and a bool that indicates whether an inversion was needed.
214    ///
215    /// More specifically:
216    /// If `self` is an equality with a `null` literal on any side, then the match fails!
217    /// Otherwise: for a given `expr`, if `self` is `<expr> = <literal>` or `<literal> = <expr>`
218    /// then return `Some((<literal>, false))`. In addition to just trying to match `<expr>` as it
219    /// is, we also try to remove an invertible function call (such as a cast). If the match
220    /// succeeds with the inversion, then return `Some((<inverted-literal>, true))`. For more
221    /// details on the inversion, see `invert_casts_on_expr_eq_literal_inner`.
222    pub fn expr_eq_literal(&self, expr: &MirScalarExpr) -> Option<(Row, bool)> {
223        if let MirScalarExpr::CallBinary {
224            func: BinaryFunc::Eq(_),
225            expr1,
226            expr2,
227        } = self
228        {
229            if expr1.is_literal_null() || expr2.is_literal_null() {
230                return None;
231            }
232            if let Some(Ok(lit)) = expr1.as_literal_owned() {
233                return Self::expr_eq_literal_inner(expr, lit, expr1, expr2);
234            }
235            if let Some(Ok(lit)) = expr2.as_literal_owned() {
236                return Self::expr_eq_literal_inner(expr, lit, expr2, expr1);
237            }
238        }
239        None
240    }
241
242    fn expr_eq_literal_inner(
243        expr_to_match: &MirScalarExpr,
244        literal: Row,
245        literal_expr: &MirScalarExpr,
246        other_side: &MirScalarExpr,
247    ) -> Option<(Row, bool)> {
248        if other_side == expr_to_match {
249            return Some((literal, false));
250        } else {
251            // expr didn't exactly match. See if we can match it by inverse-casting.
252            let (cast_removed, inv_cast_lit) =
253                Self::invert_casts_on_expr_eq_literal_inner(other_side, literal_expr);
254            if &cast_removed == expr_to_match {
255                if let Some(Ok(inv_cast_lit_row)) = inv_cast_lit.as_literal_owned() {
256                    return Some((inv_cast_lit_row, true));
257                }
258            }
259        }
260        None
261    }
262
263    /// If `self` is `<expr> = <literal>` or `<literal> = <expr>` then
264    /// return `<expr>`. It also tries to remove a cast (or other invertible function call) from
265    /// `<expr>` before returning it, see `invert_casts_on_expr_eq_literal_inner`.
266    pub fn any_expr_eq_literal(&self) -> Option<MirScalarExpr> {
267        if let MirScalarExpr::CallBinary {
268            func: BinaryFunc::Eq(_),
269            expr1,
270            expr2,
271        } = self
272        {
273            if expr1.is_literal() {
274                let (expr, _literal) = Self::invert_casts_on_expr_eq_literal_inner(expr2, expr1);
275                return Some(expr);
276            }
277            if expr2.is_literal() {
278                let (expr, _literal) = Self::invert_casts_on_expr_eq_literal_inner(expr1, expr2);
279                return Some(expr);
280            }
281        }
282        None
283    }
284
285    /// If the given `MirScalarExpr` is a literal equality where one side is an invertible function
286    /// call, then calls the inverse function on both sides of the equality and returns the modified
287    /// version of the given `MirScalarExpr`. Otherwise, it returns the original expression.
288    /// For more details, see `invert_casts_on_expr_eq_literal_inner`.
289    pub fn invert_casts_on_expr_eq_literal(&self) -> MirScalarExpr {
290        if let MirScalarExpr::CallBinary {
291            func: BinaryFunc::Eq(_),
292            expr1,
293            expr2,
294        } = self
295        {
296            if expr1.is_literal() {
297                let (expr, literal) = Self::invert_casts_on_expr_eq_literal_inner(expr2, expr1);
298                return literal.call_binary(expr, func::Eq);
299            }
300            if expr2.is_literal() {
301                let (expr, literal) = Self::invert_casts_on_expr_eq_literal_inner(expr1, expr2);
302                return literal.call_binary(expr, func::Eq);
303            }
304            // Note: The above return statements should be consistent in whether they put the
305            // literal in expr1 or expr2, for the deduplication in CanonicalizeMfp to work.
306        }
307        self.clone()
308    }
309
310    /// Given an `<expr>` and a `<literal>` that were taken out from `<expr> = <literal>` or
311    /// `<literal> = <expr>`, it tries to simplify the equality by applying the inverse function of
312    /// the outermost function call of `<expr>` (if exists):
313    ///
314    /// `<literal> = func(<inner_expr>)`, where `func` is invertible
315    ///  -->
316    /// `<func^-1(literal)> = <inner_expr>`
317    /// if `func^-1(literal)` doesn't error out, and both `func` and `func^-1` preserve uniqueness.
318    ///
319    /// The return value is the `<inner_expr>` and the literal value that we get by applying the
320    /// inverse function.
321    fn invert_casts_on_expr_eq_literal_inner(
322        expr: &MirScalarExpr,
323        literal: &MirScalarExpr,
324    ) -> (MirScalarExpr, MirScalarExpr) {
325        assert!(matches!(literal, MirScalarExpr::Literal(..)));
326
327        let temp_storage = &RowArena::new();
328        let eval = |e: &MirScalarExpr| {
329            MirScalarExpr::literal(e.eval(&[], temp_storage), e.typ(&[]).scalar_type)
330        };
331
332        if let MirScalarExpr::CallUnary {
333            func,
334            expr: inner_expr,
335        } = expr
336        {
337            if let Some(inverse_func) = func.inverse() {
338                // We don't want to remove a function call that doesn't preserve uniqueness, e.g.,
339                // if `f` is a float, we don't want to inverse-cast `f::INT = 0`, because the
340                // inserted int-to-float cast wouldn't be able to invert the rounding.
341                // Also, we don't want to insert a function call that doesn't preserve
342                // uniqueness. E.g., if `a` has an integer type, we don't want to do
343                // a surprise rounding for `WHERE a = 3.14`.
344                if func.preserves_uniqueness() && inverse_func.preserves_uniqueness() {
345                    let lit_inv = eval(&MirScalarExpr::CallUnary {
346                        func: inverse_func,
347                        expr: Box::new(literal.clone()),
348                    });
349                    // The evaluation can error out, e.g., when casting a too large int32 to int16.
350                    // This case is handled by `impossible_literal_equality_because_types`.
351                    if !lit_inv.is_literal_err() {
352                        return (*inner_expr.clone(), lit_inv);
353                    }
354                }
355            }
356        }
357        (expr.clone(), literal.clone())
358    }
359
360    /// Tries to remove a cast (or other invertible function) in the same way as
361    /// `invert_casts_on_expr_eq_literal`, but if calling the inverse function fails on the literal,
362    /// then it deems the equality to be impossible. For example if `a` is a smallint column, then
363    /// it catches `a::integer = 1000000` to be an always false predicate (where the `::integer`
364    /// could have been inserted implicitly).
365    pub fn impossible_literal_equality_because_types(&self) -> bool {
366        if let MirScalarExpr::CallBinary {
367            func: BinaryFunc::Eq(_),
368            expr1,
369            expr2,
370        } = self
371        {
372            if expr1.is_literal() {
373                return Self::impossible_literal_equality_because_types_inner(expr1, expr2);
374            }
375            if expr2.is_literal() {
376                return Self::impossible_literal_equality_because_types_inner(expr2, expr1);
377            }
378        }
379        false
380    }
381
382    fn impossible_literal_equality_because_types_inner(
383        literal: &MirScalarExpr,
384        other_side: &MirScalarExpr,
385    ) -> bool {
386        assert!(matches!(literal, MirScalarExpr::Literal(..)));
387
388        let temp_storage = &RowArena::new();
389        let eval = |e: &MirScalarExpr| {
390            MirScalarExpr::literal(e.eval(&[], temp_storage), e.typ(&[]).scalar_type)
391        };
392
393        if let MirScalarExpr::CallUnary { func, .. } = other_side {
394            if let Some(inverse_func) = func.inverse() {
395                if inverse_func.preserves_uniqueness()
396                    && eval(&MirScalarExpr::CallUnary {
397                        func: inverse_func,
398                        expr: Box::new(literal.clone()),
399                    })
400                    .is_literal_err()
401                {
402                    return true;
403                }
404            }
405        }
406
407        false
408    }
409
410    /// Determines if `self` is
411    /// `<expr> < <literal>` or
412    /// `<expr> > <literal>` or
413    /// `<literal> < <expr>` or
414    /// `<literal> > <expr>` or
415    /// `<expr> <= <literal>` or
416    /// `<expr> >= <literal>` or
417    /// `<literal> <= <expr>` or
418    /// `<literal> >= <expr>`.
419    pub fn any_expr_ineq_literal(&self) -> bool {
420        match self {
421            MirScalarExpr::CallBinary {
422                func:
423                    BinaryFunc::Lt(_) | BinaryFunc::Lte(_) | BinaryFunc::Gt(_) | BinaryFunc::Gte(_),
424                expr1,
425                expr2,
426            } => expr1.is_literal() || expr2.is_literal(),
427            _ => false,
428        }
429    }
430
431    /// Rewrites column indices with their value in `permutation`.
432    ///
433    /// This method is applicable even when `permutation` is not a
434    /// strict permutation, and it only needs to have entries for
435    /// each column referenced in `self`.
436    pub fn permute(&mut self, permutation: &[usize]) {
437        self.visit_columns(|c| *c = permutation[*c]);
438    }
439
440    /// Rewrites column indices with their value in `permutation`.
441    ///
442    /// This method is applicable even when `permutation` is not a
443    /// strict permutation, and it only needs to have entries for
444    /// each column referenced in `self`.
445    pub fn permute_map(&mut self, permutation: &BTreeMap<usize, usize>) {
446        self.visit_columns(|c| *c = permutation[c]);
447    }
448
449    /// Visits each column reference and applies `action` to the column.
450    ///
451    /// Useful for remapping columns, or for collecting expression support.
452    pub fn visit_columns<F>(&mut self, mut action: F)
453    where
454        F: FnMut(&mut usize),
455    {
456        self.visit_pre_mut(|e| {
457            if let MirScalarExpr::Column(col, _) = e {
458                action(col);
459            }
460        });
461    }
462
463    pub fn support(&self) -> BTreeSet<usize> {
464        let mut support = BTreeSet::new();
465        self.support_into(&mut support);
466        support
467    }
468
469    pub fn support_into(&self, support: &mut BTreeSet<usize>) {
470        self.visit_pre(|e| {
471            if let MirScalarExpr::Column(i, _) = e {
472                support.insert(*i);
473            }
474        });
475    }
476
477    pub fn take(&mut self) -> Self {
478        mem::replace(self, MirScalarExpr::literal_null(SqlScalarType::String))
479    }
480
481    /// If the expression is a literal, this returns the literal's Datum or the literal's EvalError.
482    /// Otherwise, it returns None.
483    pub fn as_literal(&self) -> Option<Result<Datum<'_>, &EvalError>> {
484        if let MirScalarExpr::Literal(lit, _column_type) = self {
485            Some(lit.as_ref().map(|row| row.unpack_first()))
486        } else {
487            None
488        }
489    }
490
491    /// Flattens the two failure modes of `as_literal` into one layer of Option: returns the
492    /// literal's Datum only if the expression is a literal, and it's not a literal error.
493    pub fn as_literal_non_error(&self) -> Option<Datum<'_>> {
494        self.as_literal().map(|eval_err| eval_err.ok()).flatten()
495    }
496
497    pub fn as_literal_owned(&self) -> Option<Result<Row, EvalError>> {
498        if let MirScalarExpr::Literal(lit, _column_type) = self {
499            Some(lit.clone())
500        } else {
501            None
502        }
503    }
504
505    pub fn as_literal_str(&self) -> Option<&str> {
506        match self.as_literal() {
507            Some(Ok(Datum::String(s))) => Some(s),
508            _ => None,
509        }
510    }
511
512    pub fn as_literal_int64(&self) -> Option<i64> {
513        match self.as_literal() {
514            Some(Ok(Datum::Int64(i))) => Some(i),
515            _ => None,
516        }
517    }
518
519    pub fn as_literal_err(&self) -> Option<&EvalError> {
520        self.as_literal().and_then(|lit| lit.err())
521    }
522
523    pub fn is_literal(&self) -> bool {
524        matches!(self, MirScalarExpr::Literal(_, _))
525    }
526
527    pub fn is_literal_true(&self) -> bool {
528        Some(Ok(Datum::True)) == self.as_literal()
529    }
530
531    pub fn is_literal_false(&self) -> bool {
532        Some(Ok(Datum::False)) == self.as_literal()
533    }
534
535    pub fn is_literal_null(&self) -> bool {
536        Some(Ok(Datum::Null)) == self.as_literal()
537    }
538
539    pub fn is_literal_ok(&self) -> bool {
540        matches!(self, MirScalarExpr::Literal(Ok(_), _typ))
541    }
542
543    pub fn is_literal_err(&self) -> bool {
544        matches!(self, MirScalarExpr::Literal(Err(_), _typ))
545    }
546
547    pub fn is_column(&self) -> bool {
548        matches!(self, MirScalarExpr::Column(_col, _name))
549    }
550
551    pub fn is_error_if_null(&self) -> bool {
552        matches!(
553            self,
554            Self::CallVariadic {
555                func: VariadicFunc::ErrorIfNull,
556                ..
557            }
558        )
559    }
560
561    /// If `self` expresses a temporal filter, normalize it to start with `mz_now()` and return
562    /// references.
563    ///
564    /// A temporal filter is an expression of the form `mz_now() <BINOP> <EXPR>`,
565    /// for a restricted set of `BINOP` and `EXPR` that do not themselves contain `mz_now()`.
566    /// Expressions may conform to this once their expressions are swapped.
567    ///
568    /// If the expression is not a temporal filter, it will be unchanged, and the reason for why
569    /// it's not a temporal filter is returned as a string.
570    pub fn as_mut_temporal_filter(&mut self) -> Result<(&BinaryFunc, &mut MirScalarExpr), String> {
571        if !self.contains_temporal() {
572            return Err("Does not involve mz_now()".to_string());
573        }
574        // Supported temporal predicates are exclusively binary operators.
575        if let MirScalarExpr::CallBinary { func, expr1, expr2 } = self {
576            // Attempt to put `LogicalTimestamp` in the first argument position.
577            if !expr1.contains_temporal()
578                && **expr2 == MirScalarExpr::CallUnmaterializable(UnmaterializableFunc::MzNow)
579            {
580                std::mem::swap(expr1, expr2);
581                *func = match func {
582                    BinaryFunc::Eq(_) => func::Eq.into(),
583                    BinaryFunc::Lt(_) => func::Gt.into(),
584                    BinaryFunc::Lte(_) => func::Gte.into(),
585                    BinaryFunc::Gt(_) => func::Lt.into(),
586                    BinaryFunc::Gte(_) => func::Lte.into(),
587                    x => {
588                        return Err(format!("Unsupported binary temporal operation: {:?}", x));
589                    }
590                };
591            }
592
593            // Error if MLT is referenced in an unsupported position.
594            if expr2.contains_temporal()
595                || **expr1 != MirScalarExpr::CallUnmaterializable(UnmaterializableFunc::MzNow)
596            {
597                return Err(format!(
598                    "Unsupported temporal predicate. Note: `mz_now()` must be directly compared to a mz_timestamp-castable expression. Expression found: {}",
599                    MirScalarExpr::CallBinary {
600                        func: func.clone(),
601                        expr1: expr1.clone(),
602                        expr2: expr2.clone()
603                    },
604                ));
605            }
606
607            Ok((&*func, expr2))
608        } else {
609            Err(format!(
610                "Unsupported temporal predicate. Note: `mz_now()` must be directly compared to a non-temporal expression of mz_timestamp-castable type. Expression found: {}",
611                self,
612            ))
613        }
614    }
615
616    #[deprecated = "Use `might_error` instead"]
617    pub fn contains_error_if_null(&self) -> bool {
618        let mut worklist = vec![self];
619        while let Some(expr) = worklist.pop() {
620            if expr.is_error_if_null() {
621                return true;
622            }
623            worklist.extend(expr.children());
624        }
625        false
626    }
627
628    pub fn contains_err(&self) -> bool {
629        let mut worklist = vec![self];
630        while let Some(expr) = worklist.pop() {
631            if expr.is_literal_err() {
632                return true;
633            }
634            worklist.extend(expr.children());
635        }
636        false
637    }
638
639    /// A very crude approximation for scalar expressions that might produce an
640    /// error.
641    ///
642    /// Currently, this is restricted only to expressions that either contain a
643    /// literal error or a [`VariadicFunc::ErrorIfNull`] call.
644    pub fn might_error(&self) -> bool {
645        let mut worklist = vec![self];
646        while let Some(expr) = worklist.pop() {
647            if expr.is_literal_err() || expr.is_error_if_null() {
648                return true;
649            }
650            worklist.extend(expr.children());
651        }
652        false
653    }
654
655    /// If self is a column, return the column index, otherwise `None`.
656    pub fn as_column(&self) -> Option<usize> {
657        if let MirScalarExpr::Column(c, _) = self {
658            Some(*c)
659        } else {
660            None
661        }
662    }
663
664    /// Reduces a complex expression where possible.
665    ///
666    /// This function uses nullability information present in `column_types`,
667    /// and the result may only continue to be a correct transformation as
668    /// long as this information continues to hold (nullability may not hold
669    /// as expressions migrate around).
670    ///
671    /// (If you'd like to not use nullability information here, then you can
672    /// tweak the nullabilities in `column_types` before passing it to this
673    /// function, see e.g. in `EquivalenceClasses::minimize`.)
674    ///
675    /// Also performs partial canonicalization on the expression.
676    ///
677    /// ```rust
678    /// use mz_expr::MirScalarExpr;
679    /// use mz_repr::{SqlColumnType, Datum, SqlScalarType};
680    ///
681    /// let expr_0 = MirScalarExpr::column(0);
682    /// let expr_t = MirScalarExpr::literal_true();
683    /// let expr_f = MirScalarExpr::literal_false();
684    ///
685    /// let mut test =
686    /// expr_t
687    ///     .clone()
688    ///     .and(expr_f.clone())
689    ///     .if_then_else(expr_0, expr_t.clone());
690    ///
691    /// let input_type = vec![SqlScalarType::Int32.nullable(false)];
692    /// test.reduce(&input_type);
693    /// assert_eq!(test, expr_t);
694    /// ```
695    pub fn reduce(&mut self, column_types: &[SqlColumnType]) {
696        let temp_storage = &RowArena::new();
697        let eval = |e: &MirScalarExpr| {
698            MirScalarExpr::literal(e.eval(&[], temp_storage), e.typ(column_types).scalar_type)
699        };
700
701        // Simplifications run in a loop until `self` no longer changes.
702        let mut old_self = MirScalarExpr::column(0);
703        while old_self != *self {
704            old_self = self.clone();
705            #[allow(deprecated)]
706            self.visit_mut_pre_post_nolimit(
707                &mut |e| {
708                    match e {
709                        MirScalarExpr::CallUnary { func, expr } => {
710                            if *func == UnaryFunc::IsNull(func::IsNull) {
711                                if !expr.typ(column_types).nullable {
712                                    *e = MirScalarExpr::literal_false();
713                                } else {
714                                    // Try to at least decompose IsNull into a disjunction
715                                    // of simpler IsNull subexpressions.
716                                    if let Some(expr) = expr.decompose_is_null() {
717                                        *e = expr
718                                    }
719                                }
720                            } else if *func == UnaryFunc::Not(func::Not) {
721                                // Push down not expressions
722                                match &mut **expr {
723                                    // Two negates cancel each other out.
724                                    MirScalarExpr::CallUnary {
725                                        expr: inner_expr,
726                                        func: UnaryFunc::Not(func::Not),
727                                    } => *e = inner_expr.take(),
728                                    // Transforms `NOT(a <op> b)` to `a negate(<op>) b`
729                                    // if a negation exists.
730                                    MirScalarExpr::CallBinary { expr1, expr2, func } => {
731                                        if let Some(negated_func) = func.negate() {
732                                            *e = MirScalarExpr::CallBinary {
733                                                expr1: Box::new(expr1.take()),
734                                                expr2: Box::new(expr2.take()),
735                                                func: negated_func,
736                                            }
737                                        }
738                                    }
739                                    MirScalarExpr::CallVariadic { .. } => {
740                                        e.demorgans();
741                                    }
742                                    _ => {}
743                                }
744                            }
745                        }
746                        _ => {}
747                    };
748                    None
749                },
750                &mut |e| match e {
751                    // Evaluate and pull up constants
752                    MirScalarExpr::Column(_, _)
753                    | MirScalarExpr::Literal(_, _)
754                    | MirScalarExpr::CallUnmaterializable(_) => (),
755                    MirScalarExpr::CallUnary { func, expr } => {
756                        if expr.is_literal() && *func != UnaryFunc::Panic(func::Panic) {
757                            *e = eval(e);
758                        } else if let UnaryFunc::RecordGet(func::RecordGet(i)) = *func {
759                            if let MirScalarExpr::CallVariadic {
760                                func: VariadicFunc::RecordCreate { .. },
761                                exprs,
762                            } = &mut **expr
763                            {
764                                *e = exprs.swap_remove(i);
765                            }
766                        }
767                    }
768                    MirScalarExpr::CallBinary { func, expr1, expr2 } => {
769                        if expr1.is_literal() && expr2.is_literal() {
770                            *e = eval(e);
771                        } else if (expr1.is_literal_null() || expr2.is_literal_null())
772                            && func.propagates_nulls()
773                        {
774                            *e = MirScalarExpr::literal_null(e.typ(column_types).scalar_type);
775                        } else if let Some(err) = expr1.as_literal_err() {
776                            *e = MirScalarExpr::literal(
777                                Err(err.clone()),
778                                e.typ(column_types).scalar_type,
779                            );
780                        } else if let Some(err) = expr2.as_literal_err() {
781                            *e = MirScalarExpr::literal(
782                                Err(err.clone()),
783                                e.typ(column_types).scalar_type,
784                            );
785                        } else if let BinaryFunc::IsLikeMatchCaseInsensitive(_) = func {
786                            if expr2.is_literal() {
787                                // We can at least precompile the regex.
788                                let pattern = expr2.as_literal_str().unwrap();
789                                *e = match like_pattern::compile(pattern, true) {
790                                    Ok(matcher) => expr1.take().call_unary(UnaryFunc::IsLikeMatch(
791                                        func::IsLikeMatch(matcher),
792                                    )),
793                                    Err(err) => MirScalarExpr::literal(
794                                        Err(err),
795                                        e.typ(column_types).scalar_type,
796                                    ),
797                                };
798                            }
799                        } else if let BinaryFunc::IsLikeMatchCaseSensitive(_) = func {
800                            if expr2.is_literal() {
801                                // We can at least precompile the regex.
802                                let pattern = expr2.as_literal_str().unwrap();
803                                *e = match like_pattern::compile(pattern, false) {
804                                    Ok(matcher) => expr1.take().call_unary(UnaryFunc::IsLikeMatch(
805                                        func::IsLikeMatch(matcher),
806                                    )),
807                                    Err(err) => MirScalarExpr::literal(
808                                        Err(err),
809                                        e.typ(column_types).scalar_type,
810                                    ),
811                                };
812                            }
813                        } else if let BinaryFunc::IsRegexpMatch { case_insensitive } = func {
814                            if let MirScalarExpr::Literal(Ok(row), _) = &**expr2 {
815                                *e = match Regex::new(
816                                    row.unpack_first().unwrap_str(),
817                                    *case_insensitive,
818                                ) {
819                                    Ok(regex) => expr1.take().call_unary(UnaryFunc::IsRegexpMatch(
820                                        func::IsRegexpMatch(regex),
821                                    )),
822                                    Err(err) => MirScalarExpr::literal(
823                                        Err(err.into()),
824                                        e.typ(column_types).scalar_type,
825                                    ),
826                                };
827                            }
828                        } else if let BinaryFunc::ExtractInterval(_) = *func
829                            && expr1.is_literal()
830                        {
831                            let units = expr1.as_literal_str().unwrap();
832                            *e = match units.parse::<DateTimeUnits>() {
833                                Ok(units) => MirScalarExpr::CallUnary {
834                                    func: UnaryFunc::ExtractInterval(func::ExtractInterval(units)),
835                                    expr: Box::new(expr2.take()),
836                                },
837                                Err(_) => MirScalarExpr::literal(
838                                    Err(EvalError::UnknownUnits(units.into())),
839                                    e.typ(column_types).scalar_type,
840                                ),
841                            }
842                        } else if let BinaryFunc::ExtractTime(_) = *func
843                            && expr1.is_literal()
844                        {
845                            let units = expr1.as_literal_str().unwrap();
846                            *e = match units.parse::<DateTimeUnits>() {
847                                Ok(units) => MirScalarExpr::CallUnary {
848                                    func: UnaryFunc::ExtractTime(func::ExtractTime(units)),
849                                    expr: Box::new(expr2.take()),
850                                },
851                                Err(_) => MirScalarExpr::literal(
852                                    Err(EvalError::UnknownUnits(units.into())),
853                                    e.typ(column_types).scalar_type,
854                                ),
855                            }
856                        } else if let BinaryFunc::ExtractTimestamp(_) = *func
857                            && expr1.is_literal()
858                        {
859                            let units = expr1.as_literal_str().unwrap();
860                            *e = match units.parse::<DateTimeUnits>() {
861                                Ok(units) => MirScalarExpr::CallUnary {
862                                    func: UnaryFunc::ExtractTimestamp(func::ExtractTimestamp(
863                                        units,
864                                    )),
865                                    expr: Box::new(expr2.take()),
866                                },
867                                Err(_) => MirScalarExpr::literal(
868                                    Err(EvalError::UnknownUnits(units.into())),
869                                    e.typ(column_types).scalar_type,
870                                ),
871                            }
872                        } else if let BinaryFunc::ExtractTimestampTz(_) = *func
873                            && expr1.is_literal()
874                        {
875                            let units = expr1.as_literal_str().unwrap();
876                            *e = match units.parse::<DateTimeUnits>() {
877                                Ok(units) => MirScalarExpr::CallUnary {
878                                    func: UnaryFunc::ExtractTimestampTz(func::ExtractTimestampTz(
879                                        units,
880                                    )),
881                                    expr: Box::new(expr2.take()),
882                                },
883                                Err(_) => MirScalarExpr::literal(
884                                    Err(EvalError::UnknownUnits(units.into())),
885                                    e.typ(column_types).scalar_type,
886                                ),
887                            }
888                        } else if let BinaryFunc::ExtractDate(_) = *func
889                            && expr1.is_literal()
890                        {
891                            let units = expr1.as_literal_str().unwrap();
892                            *e = match units.parse::<DateTimeUnits>() {
893                                Ok(units) => MirScalarExpr::CallUnary {
894                                    func: UnaryFunc::ExtractDate(func::ExtractDate(units)),
895                                    expr: Box::new(expr2.take()),
896                                },
897                                Err(_) => MirScalarExpr::literal(
898                                    Err(EvalError::UnknownUnits(units.into())),
899                                    e.typ(column_types).scalar_type,
900                                ),
901                            }
902                        } else if let BinaryFunc::DatePartInterval(_) = *func
903                            && expr1.is_literal()
904                        {
905                            let units = expr1.as_literal_str().unwrap();
906                            *e = match units.parse::<DateTimeUnits>() {
907                                Ok(units) => MirScalarExpr::CallUnary {
908                                    func: UnaryFunc::DatePartInterval(func::DatePartInterval(
909                                        units,
910                                    )),
911                                    expr: Box::new(expr2.take()),
912                                },
913                                Err(_) => MirScalarExpr::literal(
914                                    Err(EvalError::UnknownUnits(units.into())),
915                                    e.typ(column_types).scalar_type,
916                                ),
917                            }
918                        } else if let BinaryFunc::DatePartTime(_) = *func
919                            && expr1.is_literal()
920                        {
921                            let units = expr1.as_literal_str().unwrap();
922                            *e = match units.parse::<DateTimeUnits>() {
923                                Ok(units) => MirScalarExpr::CallUnary {
924                                    func: UnaryFunc::DatePartTime(func::DatePartTime(units)),
925                                    expr: Box::new(expr2.take()),
926                                },
927                                Err(_) => MirScalarExpr::literal(
928                                    Err(EvalError::UnknownUnits(units.into())),
929                                    e.typ(column_types).scalar_type,
930                                ),
931                            }
932                        } else if let BinaryFunc::DatePartTimestamp(_) = *func
933                            && expr1.is_literal()
934                        {
935                            let units = expr1.as_literal_str().unwrap();
936                            *e = match units.parse::<DateTimeUnits>() {
937                                Ok(units) => MirScalarExpr::CallUnary {
938                                    func: UnaryFunc::DatePartTimestamp(func::DatePartTimestamp(
939                                        units,
940                                    )),
941                                    expr: Box::new(expr2.take()),
942                                },
943                                Err(_) => MirScalarExpr::literal(
944                                    Err(EvalError::UnknownUnits(units.into())),
945                                    e.typ(column_types).scalar_type,
946                                ),
947                            }
948                        } else if let BinaryFunc::DatePartTimestampTz(_) = *func
949                            && expr1.is_literal()
950                        {
951                            let units = expr1.as_literal_str().unwrap();
952                            *e = match units.parse::<DateTimeUnits>() {
953                                Ok(units) => MirScalarExpr::CallUnary {
954                                    func: UnaryFunc::DatePartTimestampTz(
955                                        func::DatePartTimestampTz(units),
956                                    ),
957                                    expr: Box::new(expr2.take()),
958                                },
959                                Err(_) => MirScalarExpr::literal(
960                                    Err(EvalError::UnknownUnits(units.into())),
961                                    e.typ(column_types).scalar_type,
962                                ),
963                            }
964                        } else if let BinaryFunc::DateTruncTimestamp(_) = *func
965                            && expr1.is_literal()
966                        {
967                            let units = expr1.as_literal_str().unwrap();
968                            *e = match units.parse::<DateTimeUnits>() {
969                                Ok(units) => MirScalarExpr::CallUnary {
970                                    func: UnaryFunc::DateTruncTimestamp(func::DateTruncTimestamp(
971                                        units,
972                                    )),
973                                    expr: Box::new(expr2.take()),
974                                },
975                                Err(_) => MirScalarExpr::literal(
976                                    Err(EvalError::UnknownUnits(units.into())),
977                                    e.typ(column_types).scalar_type,
978                                ),
979                            }
980                        } else if let BinaryFunc::DateTruncTimestampTz(_) = *func
981                            && expr1.is_literal()
982                        {
983                            let units = expr1.as_literal_str().unwrap();
984                            *e = match units.parse::<DateTimeUnits>() {
985                                Ok(units) => MirScalarExpr::CallUnary {
986                                    func: UnaryFunc::DateTruncTimestampTz(
987                                        func::DateTruncTimestampTz(units),
988                                    ),
989                                    expr: Box::new(expr2.take()),
990                                },
991                                Err(_) => MirScalarExpr::literal(
992                                    Err(EvalError::UnknownUnits(units.into())),
993                                    e.typ(column_types).scalar_type,
994                                ),
995                            }
996                        } else if *func == BinaryFunc::TimezoneTimestamp && expr1.is_literal() {
997                            // If the timezone argument is a literal, and we're applying the function on many rows at the same
998                            // time we really don't want to parse it again and again, so we parse it once and embed it into the
999                            // UnaryFunc enum. The memory footprint of Timezone is small (8 bytes).
1000                            let tz = expr1.as_literal_str().unwrap();
1001                            *e = match parse_timezone(tz, TimezoneSpec::Posix) {
1002                                Ok(tz) => MirScalarExpr::CallUnary {
1003                                    func: UnaryFunc::TimezoneTimestamp(func::TimezoneTimestamp(tz)),
1004                                    expr: Box::new(expr2.take()),
1005                                },
1006                                Err(err) => MirScalarExpr::literal(
1007                                    Err(err),
1008                                    e.typ(column_types).scalar_type,
1009                                ),
1010                            }
1011                        } else if *func == BinaryFunc::TimezoneTimestampTz && expr1.is_literal() {
1012                            let tz = expr1.as_literal_str().unwrap();
1013                            *e = match parse_timezone(tz, TimezoneSpec::Posix) {
1014                                Ok(tz) => MirScalarExpr::CallUnary {
1015                                    func: UnaryFunc::TimezoneTimestampTz(
1016                                        func::TimezoneTimestampTz(tz),
1017                                    ),
1018                                    expr: Box::new(expr2.take()),
1019                                },
1020                                Err(err) => MirScalarExpr::literal(
1021                                    Err(err),
1022                                    e.typ(column_types).scalar_type,
1023                                ),
1024                            }
1025                        } else if let BinaryFunc::ToCharTimestamp(_) = *func
1026                            && expr2.is_literal()
1027                        {
1028                            let format_str = expr2.as_literal_str().unwrap();
1029                            *e = MirScalarExpr::CallUnary {
1030                                func: UnaryFunc::ToCharTimestamp(func::ToCharTimestamp {
1031                                    format_string: format_str.to_string(),
1032                                    format: DateTimeFormat::compile(format_str),
1033                                }),
1034                                expr: Box::new(expr1.take()),
1035                            };
1036                        } else if let BinaryFunc::ToCharTimestampTz(_) = *func
1037                            && expr2.is_literal()
1038                        {
1039                            let format_str = expr2.as_literal_str().unwrap();
1040                            *e = MirScalarExpr::CallUnary {
1041                                func: UnaryFunc::ToCharTimestampTz(func::ToCharTimestampTz {
1042                                    format_string: format_str.to_string(),
1043                                    format: DateTimeFormat::compile(format_str),
1044                                }),
1045                                expr: Box::new(expr1.take()),
1046                            };
1047                        } else if matches!(*func, BinaryFunc::Eq(_) | BinaryFunc::NotEq(_))
1048                            && expr2 < expr1
1049                        {
1050                            // Canonically order elements so that deduplication works better.
1051                            // Also, the below `Literal([c1, c2]) = record_create(e1, e2)` matching
1052                            // relies on this canonical ordering.
1053                            mem::swap(expr1, expr2);
1054                        } else if let (
1055                            BinaryFunc::Eq(_),
1056                            MirScalarExpr::Literal(
1057                                Ok(lit_row),
1058                                SqlColumnType {
1059                                    scalar_type:
1060                                        SqlScalarType::Record {
1061                                            fields: field_types,
1062                                            ..
1063                                        },
1064                                    ..
1065                                },
1066                            ),
1067                            MirScalarExpr::CallVariadic {
1068                                func: VariadicFunc::RecordCreate { .. },
1069                                exprs: rec_create_args,
1070                            },
1071                        ) = (&*func, &**expr1, &**expr2)
1072                        {
1073                            // Literal([c1, c2]) = record_create(e1, e2)
1074                            //  -->
1075                            // c1 = e1 AND c2 = e2
1076                            //
1077                            // (Records are represented as lists.)
1078                            //
1079                            // `MapFilterProject::literal_constraints` relies on this transform,
1080                            // because `(e1,e2) IN ((1,2))` is desugared using `record_create`.
1081                            match lit_row.unpack_first() {
1082                                Datum::List(datum_list) => {
1083                                    *e = MirScalarExpr::CallVariadic {
1084                                        func: VariadicFunc::And,
1085                                        exprs: datum_list
1086                                            .iter()
1087                                            .zip_eq(field_types)
1088                                            .zip_eq(rec_create_args)
1089                                            .map(|((d, (_, typ)), a)| {
1090                                                MirScalarExpr::literal_ok(
1091                                                    d,
1092                                                    typ.scalar_type.clone(),
1093                                                )
1094                                                .call_binary(a.clone(), func::Eq)
1095                                            })
1096                                            .collect(),
1097                                    };
1098                                }
1099                                _ => {}
1100                            }
1101                        } else if let (
1102                            BinaryFunc::Eq(_),
1103                            MirScalarExpr::CallVariadic {
1104                                func: VariadicFunc::RecordCreate { .. },
1105                                exprs: rec_create_args1,
1106                            },
1107                            MirScalarExpr::CallVariadic {
1108                                func: VariadicFunc::RecordCreate { .. },
1109                                exprs: rec_create_args2,
1110                            },
1111                        ) = (&*func, &**expr1, &**expr2)
1112                        {
1113                            // record_create(a1, a2, ...) = record_create(b1, b2, ...)
1114                            //  -->
1115                            // a1 = b1 AND a2 = b2 AND ...
1116                            //
1117                            // This is similar to the previous reduction, but this one kicks in also
1118                            // when only some (or none) of the record fields are literals. This
1119                            // enables the discovery of literal constraints for those fields.
1120                            //
1121                            // Note that there is a similar decomposition in
1122                            // `mz_sql::plan::transform_ast::Desugarer`, but that is earlier in the
1123                            // pipeline than the compilation of IN lists to `record_create`.
1124                            *e = MirScalarExpr::CallVariadic {
1125                                func: VariadicFunc::And,
1126                                exprs: rec_create_args1
1127                                    .into_iter()
1128                                    .zip_eq(rec_create_args2)
1129                                    .map(|(a, b)| a.clone().call_binary(b.clone(), func::Eq))
1130                                    .collect(),
1131                            }
1132                        }
1133                    }
1134                    MirScalarExpr::CallVariadic { .. } => {
1135                        e.flatten_associative();
1136                        let (func, exprs) = match e {
1137                            MirScalarExpr::CallVariadic { func, exprs } => (func, exprs),
1138                            _ => unreachable!("`flatten_associative` shouldn't change node type"),
1139                        };
1140                        if *func == VariadicFunc::Coalesce {
1141                            // If all inputs are null, output is null. This check must
1142                            // be done before `exprs.retain...` because `e.typ` requires
1143                            // > 0 `exprs` remain.
1144                            if exprs.iter().all(|expr| expr.is_literal_null()) {
1145                                *e = MirScalarExpr::literal_null(e.typ(column_types).scalar_type);
1146                                return;
1147                            }
1148
1149                            // Remove any null values if not all values are null.
1150                            exprs.retain(|e| !e.is_literal_null());
1151
1152                            // Find the first argument that is a literal or non-nullable
1153                            // column. All arguments after it get ignored, so throw them
1154                            // away. This intentionally throws away errors that can
1155                            // never happen.
1156                            if let Some(i) = exprs
1157                                .iter()
1158                                .position(|e| e.is_literal() || !e.typ(column_types).nullable)
1159                            {
1160                                exprs.truncate(i + 1);
1161                            }
1162
1163                            // Deduplicate arguments in cases like `coalesce(#0, #0)`.
1164                            let mut prior_exprs = BTreeSet::new();
1165                            exprs.retain(|e| prior_exprs.insert(e.clone()));
1166
1167                            if exprs.len() == 1 {
1168                                // Only one argument, so the coalesce is a no-op.
1169                                *e = exprs[0].take();
1170                            }
1171                        } else if exprs.iter().all(|e| e.is_literal()) {
1172                            *e = eval(e);
1173                        } else if func.propagates_nulls()
1174                            && exprs.iter().any(|e| e.is_literal_null())
1175                        {
1176                            *e = MirScalarExpr::literal_null(e.typ(column_types).scalar_type);
1177                        } else if let Some(err) = exprs.iter().find_map(|e| e.as_literal_err()) {
1178                            *e = MirScalarExpr::literal(
1179                                Err(err.clone()),
1180                                e.typ(column_types).scalar_type,
1181                            );
1182                        } else if *func == VariadicFunc::RegexpMatch
1183                            && exprs[1].is_literal()
1184                            && exprs.get(2).map_or(true, |e| e.is_literal())
1185                        {
1186                            let needle = exprs[1].as_literal_str().unwrap();
1187                            let flags = match exprs.len() {
1188                                3 => exprs[2].as_literal_str().unwrap(),
1189                                _ => "",
1190                            };
1191                            *e = match func::build_regex(needle, flags) {
1192                                Ok(regex) => mem::take(exprs)
1193                                    .into_first()
1194                                    .call_unary(UnaryFunc::RegexpMatch(func::RegexpMatch(regex))),
1195                                Err(err) => MirScalarExpr::literal(
1196                                    Err(err),
1197                                    e.typ(column_types).scalar_type,
1198                                ),
1199                            };
1200                        } else if *func == VariadicFunc::RegexpReplace
1201                            && exprs[1].is_literal()
1202                            && exprs.get(3).map_or(true, |e| e.is_literal())
1203                        {
1204                            let pattern = exprs[1].as_literal_str().unwrap();
1205                            let flags = exprs
1206                                .get(3)
1207                                .map_or("", |expr| expr.as_literal_str().unwrap());
1208                            let (limit, flags) = regexp_replace_parse_flags(flags);
1209
1210                            // The behavior of `regexp_replace` is that if the data is `NULL`, the
1211                            // function returns `NULL`, independently of whether the pattern or
1212                            // flags are correct. We need to check for this case and introduce an
1213                            // if-then-else on the error path to only surface the error if the first
1214                            // input is non-NULL.
1215                            *e = match func::build_regex(pattern, &flags) {
1216                                Ok(regex) => {
1217                                    let mut exprs = mem::take(exprs);
1218                                    let replacement = exprs.swap_remove(2);
1219                                    let source = exprs.swap_remove(0);
1220                                    source.call_binary(
1221                                        replacement,
1222                                        BinaryFunc::RegexpReplace { regex, limit },
1223                                    )
1224                                }
1225                                Err(err) => {
1226                                    let mut exprs = mem::take(exprs);
1227                                    let source = exprs.swap_remove(0);
1228                                    let scalar_type = e.typ(column_types).scalar_type;
1229                                    // We need to return `NULL` on `NULL` input, and error otherwise.
1230                                    source.call_is_null().if_then_else(
1231                                        MirScalarExpr::literal_null(scalar_type.clone()),
1232                                        MirScalarExpr::literal(Err(err), scalar_type),
1233                                    )
1234                                }
1235                            };
1236                        } else if *func == VariadicFunc::RegexpSplitToArray
1237                            && exprs[1].is_literal()
1238                            && exprs.get(2).map_or(true, |e| e.is_literal())
1239                        {
1240                            let needle = exprs[1].as_literal_str().unwrap();
1241                            let flags = match exprs.len() {
1242                                3 => exprs[2].as_literal_str().unwrap(),
1243                                _ => "",
1244                            };
1245                            *e = match func::build_regex(needle, flags) {
1246                                Ok(regex) => mem::take(exprs).into_first().call_unary(
1247                                    UnaryFunc::RegexpSplitToArray(func::RegexpSplitToArray(regex)),
1248                                ),
1249                                Err(err) => MirScalarExpr::literal(
1250                                    Err(err),
1251                                    e.typ(column_types).scalar_type,
1252                                ),
1253                            };
1254                        } else if *func == VariadicFunc::ListIndex && is_list_create_call(&exprs[0])
1255                        {
1256                            // We are looking for ListIndex(ListCreate, literal), and eliminate
1257                            // both the ListIndex and the ListCreate. E.g.: `LIST[f1,f2][2]` --> `f2`
1258                            let ind_exprs = exprs.split_off(1);
1259                            let top_list_create = exprs.swap_remove(0);
1260                            *e = reduce_list_create_list_index_literal(top_list_create, ind_exprs);
1261                        } else if *func == VariadicFunc::Or || *func == VariadicFunc::And {
1262                            // Note: It's important that we have called `flatten_associative` above.
1263                            e.undistribute_and_or();
1264                            e.reduce_and_canonicalize_and_or();
1265                        } else if let VariadicFunc::TimezoneTime = func {
1266                            if exprs[0].is_literal() && exprs[2].is_literal_ok() {
1267                                let tz = exprs[0].as_literal_str().unwrap();
1268                                *e = match parse_timezone(tz, TimezoneSpec::Posix) {
1269                                    Ok(tz) => MirScalarExpr::CallUnary {
1270                                        func: UnaryFunc::TimezoneTime(func::TimezoneTime {
1271                                            tz,
1272                                            wall_time: exprs[2]
1273                                                .as_literal()
1274                                                .unwrap()
1275                                                .unwrap()
1276                                                .unwrap_timestamptz()
1277                                                .naive_utc(),
1278                                        }),
1279                                        expr: Box::new(exprs[1].take()),
1280                                    },
1281                                    Err(err) => MirScalarExpr::literal(
1282                                        Err(err),
1283                                        e.typ(column_types).scalar_type,
1284                                    ),
1285                                }
1286                            }
1287                        }
1288                    }
1289                    MirScalarExpr::If { cond, then, els } => {
1290                        if let Some(literal) = cond.as_literal() {
1291                            match literal {
1292                                Ok(Datum::True) => *e = then.take(),
1293                                Ok(Datum::False) | Ok(Datum::Null) => *e = els.take(),
1294                                Err(err) => {
1295                                    *e = MirScalarExpr::Literal(
1296                                        Err(err.clone()),
1297                                        then.typ(column_types)
1298                                            .union(&els.typ(column_types))
1299                                            .unwrap(),
1300                                    )
1301                                }
1302                                _ => unreachable!(),
1303                            }
1304                        } else if then == els {
1305                            *e = then.take();
1306                        } else if then.is_literal_ok()
1307                            && els.is_literal_ok()
1308                            && then.typ(column_types).scalar_type == SqlScalarType::Bool
1309                            && els.typ(column_types).scalar_type == SqlScalarType::Bool
1310                        {
1311                            match (then.as_literal(), els.as_literal()) {
1312                                // Note: NULLs from the condition should not be propagated to the result
1313                                // of the expression.
1314                                (Some(Ok(Datum::True)), _) => {
1315                                    // Rewritten as ((<cond> IS NOT NULL) AND (<cond>)) OR (<els>)
1316                                    // NULL <cond> results in: (FALSE AND NULL) OR (<els>) => (<els>)
1317                                    *e = cond
1318                                        .clone()
1319                                        .call_is_null()
1320                                        .not()
1321                                        .and(cond.take())
1322                                        .or(els.take());
1323                                }
1324                                (Some(Ok(Datum::False)), _) => {
1325                                    // Rewritten as ((NOT <cond>) OR (<cond> IS NULL)) AND (<els>)
1326                                    // NULL <cond> results in: (NULL OR TRUE) AND (<els>) => TRUE AND (<els>) => (<els>)
1327                                    *e = cond
1328                                        .clone()
1329                                        .not()
1330                                        .or(cond.take().call_is_null())
1331                                        .and(els.take());
1332                                }
1333                                (_, Some(Ok(Datum::True))) => {
1334                                    // Rewritten as (NOT <cond>) OR (<cond> IS NULL) OR (<then>)
1335                                    // NULL <cond> results in: NULL OR TRUE OR (<then>) => TRUE
1336                                    *e = cond
1337                                        .clone()
1338                                        .not()
1339                                        .or(cond.take().call_is_null())
1340                                        .or(then.take());
1341                                }
1342                                (_, Some(Ok(Datum::False))) => {
1343                                    // Rewritten as (<cond> IS NOT NULL) AND (<cond>) AND (<then>)
1344                                    // NULL <cond> results in: FALSE AND NULL AND (<then>) => FALSE
1345                                    *e = cond
1346                                        .clone()
1347                                        .call_is_null()
1348                                        .not()
1349                                        .and(cond.take())
1350                                        .and(then.take());
1351                                }
1352                                _ => {}
1353                            }
1354                        } else {
1355                            // Equivalent expression structure would allow us to push the `If` into the expression.
1356                            // For example, `IF <cond> THEN x = y ELSE x = z` becomes `x = IF <cond> THEN y ELSE z`.
1357                            //
1358                            // We have to also make sure that the expressions that will end up in
1359                            // the two `If` branches have unionable types. Otherwise, the `If` could
1360                            // not be typed by `typ`. An example where this could cause an issue is
1361                            // when pulling out `cast_jsonbable_to_jsonb`, which accepts a wide
1362                            // range of input types. (In theory, we could still do the optimization
1363                            // in this case by inserting appropriate casts, but this corner case is
1364                            // not worth the complication for now.)
1365                            // See https://github.com/MaterializeInc/database-issues/issues/9182
1366                            match (&mut **then, &mut **els) {
1367                                (
1368                                    MirScalarExpr::CallUnary { func: f1, expr: e1 },
1369                                    MirScalarExpr::CallUnary { func: f2, expr: e2 },
1370                                ) if f1 == f2
1371                                    && e1
1372                                        .typ(column_types)
1373                                        .union(&e2.typ(column_types))
1374                                        .is_ok() =>
1375                                {
1376                                    *e = cond
1377                                        .take()
1378                                        .if_then_else(e1.take(), e2.take())
1379                                        .call_unary(f1.clone());
1380                                }
1381                                (
1382                                    MirScalarExpr::CallBinary {
1383                                        func: f1,
1384                                        expr1: e1a,
1385                                        expr2: e2a,
1386                                    },
1387                                    MirScalarExpr::CallBinary {
1388                                        func: f2,
1389                                        expr1: e1b,
1390                                        expr2: e2b,
1391                                    },
1392                                ) if f1 == f2
1393                                    && e1a == e1b
1394                                    && e2a
1395                                        .typ(column_types)
1396                                        .union(&e2b.typ(column_types))
1397                                        .is_ok() =>
1398                                {
1399                                    *e = e1a.take().call_binary(
1400                                        cond.take().if_then_else(e2a.take(), e2b.take()),
1401                                        f1.clone(),
1402                                    );
1403                                }
1404                                (
1405                                    MirScalarExpr::CallBinary {
1406                                        func: f1,
1407                                        expr1: e1a,
1408                                        expr2: e2a,
1409                                    },
1410                                    MirScalarExpr::CallBinary {
1411                                        func: f2,
1412                                        expr1: e1b,
1413                                        expr2: e2b,
1414                                    },
1415                                ) if f1 == f2
1416                                    && e2a == e2b
1417                                    && e1a
1418                                        .typ(column_types)
1419                                        .union(&e1b.typ(column_types))
1420                                        .is_ok() =>
1421                                {
1422                                    *e = cond
1423                                        .take()
1424                                        .if_then_else(e1a.take(), e1b.take())
1425                                        .call_binary(e2a.take(), f1.clone());
1426                                }
1427                                _ => {}
1428                            }
1429                        }
1430                    }
1431                },
1432            );
1433        }
1434
1435        /* #region `reduce_list_create_list_index_literal` and helper functions */
1436
1437        fn list_create_type(list_create: &MirScalarExpr) -> SqlScalarType {
1438            if let MirScalarExpr::CallVariadic {
1439                func: VariadicFunc::ListCreate { elem_type: typ },
1440                ..
1441            } = list_create
1442            {
1443                (*typ).clone()
1444            } else {
1445                unreachable!()
1446            }
1447        }
1448
1449        fn is_list_create_call(expr: &MirScalarExpr) -> bool {
1450            matches!(
1451                expr,
1452                MirScalarExpr::CallVariadic {
1453                    func: VariadicFunc::ListCreate { .. },
1454                    ..
1455                }
1456            )
1457        }
1458
1459        /// Partial-evaluates a list indexing with a literal directly after a list creation.
1460        ///
1461        /// Multi-dimensional lists are handled by a single call to this function, with multiple
1462        /// elements in index_exprs (of which not all need to be literals), and nested ListCreates
1463        /// in list_create_to_reduce.
1464        ///
1465        /// # Examples
1466        ///
1467        /// `LIST[f1,f2][2]` --> `f2`.
1468        ///
1469        /// A multi-dimensional list, with only some of the indexes being literals:
1470        /// `LIST[[[f1, f2], [f3, f4]], [[f5, f6], [f7, f8]]] [2][n][2]` --> `LIST[f6, f8] [n]`
1471        ///
1472        /// See more examples in list.slt.
1473        fn reduce_list_create_list_index_literal(
1474            mut list_create_to_reduce: MirScalarExpr,
1475            mut index_exprs: Vec<MirScalarExpr>,
1476        ) -> MirScalarExpr {
1477            // We iterate over the index_exprs and remove literals, but keep non-literals.
1478            // When we encounter a non-literal, we need to dig into the nested ListCreates:
1479            // `list_create_mut_refs` will contain all the ListCreates of the current level. If an
1480            // element of `list_create_mut_refs` is not actually a ListCreate, then we break out of
1481            // the loop. When we remove a literal, we need to partial-evaluate all ListCreates
1482            // that are at the current level (except those that disappeared due to
1483            // literals at earlier levels), index into them with the literal, and change each
1484            // element in `list_create_mut_refs` to the result.
1485            // We also record mut refs to all the earlier `element_type` references that we have
1486            // seen in ListCreate calls, because when we process a literal index, we need to remove
1487            // one layer of list type from all these earlier ListCreate `element_type`s.
1488            let mut list_create_mut_refs = vec![&mut list_create_to_reduce];
1489            let mut earlier_list_create_types: Vec<&mut SqlScalarType> = vec![];
1490            let mut i = 0;
1491            while i < index_exprs.len()
1492                && list_create_mut_refs
1493                    .iter()
1494                    .all(|lc| is_list_create_call(lc))
1495            {
1496                if index_exprs[i].is_literal_ok() {
1497                    // We can remove this index.
1498                    let removed_index = index_exprs.remove(i);
1499                    let index_i64 = match removed_index.as_literal().unwrap().unwrap() {
1500                        Datum::Int64(sql_index_i64) => sql_index_i64 - 1,
1501                        _ => unreachable!(), // always an Int64, see plan_index_list
1502                    };
1503                    // For each list_create referenced by list_create_mut_refs, substitute it by its
1504                    // `index`th argument (or null).
1505                    for list_create in &mut list_create_mut_refs {
1506                        let list_create_args = match list_create {
1507                            MirScalarExpr::CallVariadic {
1508                                func: VariadicFunc::ListCreate { elem_type: _ },
1509                                exprs,
1510                            } => exprs,
1511                            _ => unreachable!(), // func cannot be anything else than a ListCreate
1512                        };
1513                        // ListIndex gives null on an out-of-bounds index
1514                        if index_i64 >= 0 && index_i64 < list_create_args.len().try_into().unwrap()
1515                        {
1516                            let index: usize = index_i64.try_into().unwrap();
1517                            **list_create = list_create_args.swap_remove(index);
1518                        } else {
1519                            let typ = list_create_type(list_create);
1520                            **list_create = MirScalarExpr::literal_null(typ);
1521                        }
1522                    }
1523                    // Peel one layer off of each of the earlier element types.
1524                    for t in earlier_list_create_types.iter_mut() {
1525                        if let SqlScalarType::List {
1526                            element_type,
1527                            custom_id: _,
1528                        } = t
1529                        {
1530                            **t = *element_type.clone();
1531                            // These are not the same types anymore, so remove custom_ids all the
1532                            // way down.
1533                            let mut u = &mut **t;
1534                            while let SqlScalarType::List {
1535                                element_type,
1536                                custom_id,
1537                            } = u
1538                            {
1539                                *custom_id = None;
1540                                u = &mut **element_type;
1541                            }
1542                        } else {
1543                            unreachable!("already matched below");
1544                        }
1545                    }
1546                } else {
1547                    // We can't remove this index, so we can't reduce any of the ListCreates at this
1548                    // level. So we change list_create_mut_refs to refer to all the arguments of all
1549                    // the ListCreates currently referenced by list_create_mut_refs.
1550                    list_create_mut_refs = list_create_mut_refs
1551                        .into_iter()
1552                        .flat_map(|list_create| match list_create {
1553                            MirScalarExpr::CallVariadic {
1554                                func: VariadicFunc::ListCreate { elem_type },
1555                                exprs: list_create_args,
1556                            } => {
1557                                earlier_list_create_types.push(elem_type);
1558                                list_create_args
1559                            }
1560                            // func cannot be anything else than a ListCreate
1561                            _ => unreachable!(),
1562                        })
1563                        .collect();
1564                    i += 1; // next index_expr
1565                }
1566            }
1567            // If all list indexes have been evaluated, return the reduced expression.
1568            // Otherwise, rebuild the ListIndex call with the remaining ListCreates and indexes.
1569            if index_exprs.is_empty() {
1570                assert_eq!(list_create_mut_refs.len(), 1);
1571                list_create_to_reduce
1572            } else {
1573                let mut exprs: Vec<MirScalarExpr> = vec![list_create_to_reduce];
1574                exprs.append(&mut index_exprs);
1575                MirScalarExpr::CallVariadic {
1576                    func: VariadicFunc::ListIndex,
1577                    exprs,
1578                }
1579            }
1580        }
1581
1582        /* #endregion */
1583    }
1584
1585    /// Decompose an IsNull expression into a disjunction of
1586    /// simpler expressions.
1587    ///
1588    /// Assumes that `self` is the expression inside of an IsNull.
1589    /// Returns `Some(expressions)` if the outer IsNull is to be
1590    /// replaced by some other expression. Note: if it returns
1591    /// None, it might still have mutated *self.
1592    fn decompose_is_null(&mut self) -> Option<MirScalarExpr> {
1593        // TODO: allow simplification of unmaterializable functions
1594
1595        match self {
1596            MirScalarExpr::CallUnary {
1597                func,
1598                expr: inner_expr,
1599            } => {
1600                if !func.introduces_nulls() {
1601                    if func.propagates_nulls() {
1602                        *self = inner_expr.take();
1603                        return self.decompose_is_null();
1604                    } else {
1605                        // Different from CallBinary and CallVariadic, because of determinism. See
1606                        // https://materializeinc.slack.com/archives/C01BE3RN82F/p1657644478517709
1607                        return Some(MirScalarExpr::literal_false());
1608                    }
1609                }
1610            }
1611            MirScalarExpr::CallBinary { func, expr1, expr2 } => {
1612                // (<expr1> <op> <expr2>) IS NULL can often be simplified to
1613                // (<expr1> IS NULL) OR (<expr2> IS NULL).
1614                if func.propagates_nulls() && !func.introduces_nulls() {
1615                    let expr1 = expr1.take().call_is_null();
1616                    let expr2 = expr2.take().call_is_null();
1617                    return Some(expr1.or(expr2));
1618                }
1619            }
1620            MirScalarExpr::CallVariadic { func, exprs } => {
1621                if func.propagates_nulls() && !func.introduces_nulls() {
1622                    let exprs = exprs.into_iter().map(|e| e.take().call_is_null()).collect();
1623                    return Some(MirScalarExpr::CallVariadic {
1624                        func: VariadicFunc::Or,
1625                        exprs,
1626                    });
1627                }
1628            }
1629            _ => {}
1630        }
1631
1632        None
1633    }
1634
1635    /// Flattens a chain of calls to associative variadic functions
1636    /// (For example: ORs or ANDs)
1637    pub fn flatten_associative(&mut self) {
1638        match self {
1639            MirScalarExpr::CallVariadic {
1640                exprs: outer_operands,
1641                func: outer_func,
1642            } if outer_func.is_associative() => {
1643                *outer_operands = outer_operands
1644                    .into_iter()
1645                    .flat_map(|o| {
1646                        if let MirScalarExpr::CallVariadic {
1647                            exprs: inner_operands,
1648                            func: inner_func,
1649                        } = o
1650                        {
1651                            if *inner_func == *outer_func {
1652                                mem::take(inner_operands)
1653                            } else {
1654                                vec![o.take()]
1655                            }
1656                        } else {
1657                            vec![o.take()]
1658                        }
1659                    })
1660                    .collect();
1661            }
1662            _ => {}
1663        }
1664    }
1665
1666    /* #region AND/OR canonicalization and transformations  */
1667
1668    /// Canonicalizes AND/OR, and does some straightforward simplifications
1669    fn reduce_and_canonicalize_and_or(&mut self) {
1670        // We do this until fixed point, because after undistribute_and_or calls us, it relies on
1671        // the property that self is not an 1-arg AND/OR. Just one application of our loop body
1672        // can't ensure this, because the application itself might create a 1-arg AND/OR.
1673        let mut old_self = MirScalarExpr::column(0);
1674        while old_self != *self {
1675            old_self = self.clone();
1676            match self {
1677                MirScalarExpr::CallVariadic {
1678                    func: func @ (VariadicFunc::And | VariadicFunc::Or),
1679                    exprs,
1680                } => {
1681                    // Canonically order elements so that various deduplications work better,
1682                    // e.g., in undistribute_and_or.
1683                    // Also, extract_equal_or_both_null_inner depends on the args being sorted.
1684                    exprs.sort();
1685
1686                    // x AND/OR x --> x
1687                    exprs.dedup(); // this also needs the above sorting
1688
1689                    if exprs.len() == 1 {
1690                        // AND/OR of 1 argument evaluates to that argument
1691                        *self = exprs.swap_remove(0);
1692                    } else if exprs.len() == 0 {
1693                        // AND/OR of 0 arguments evaluates to true/false
1694                        *self = func.unit_of_and_or();
1695                    } else if exprs.iter().any(|e| *e == func.zero_of_and_or()) {
1696                        // short-circuiting
1697                        *self = func.zero_of_and_or();
1698                    } else {
1699                        // a AND true --> a
1700                        // a OR false --> a
1701                        exprs.retain(|e| *e != func.unit_of_and_or());
1702                    }
1703                }
1704                _ => {}
1705            }
1706        }
1707    }
1708
1709    /// Transforms !(a && b) into !a || !b, and !(a || b) into !a && !b
1710    fn demorgans(&mut self) {
1711        if let MirScalarExpr::CallUnary {
1712            expr: inner,
1713            func: UnaryFunc::Not(func::Not),
1714        } = self
1715        {
1716            inner.flatten_associative();
1717            match &mut **inner {
1718                MirScalarExpr::CallVariadic {
1719                    func: inner_func @ (VariadicFunc::And | VariadicFunc::Or),
1720                    exprs,
1721                } => {
1722                    *inner_func = inner_func.switch_and_or();
1723                    *exprs = exprs.into_iter().map(|e| e.take().not()).collect();
1724                    *self = (*inner).take(); // Removes the outer not
1725                }
1726                _ => {}
1727            }
1728        }
1729    }
1730
1731    /// AND/OR undistribution (factoring out) to apply at each `MirScalarExpr`.
1732    ///
1733    /// This method attempts to apply one of the [distribution laws][distributivity]
1734    /// (in a direction opposite to the their name):
1735    /// ```text
1736    /// (a && b) || (a && c) --> a && (b || c)  // Undistribute-OR
1737    /// (a || b) && (a || c) --> a || (b && c)  // Undistribute-AND
1738    /// ```
1739    /// or one of their corresponding two [absorption law][absorption] special
1740    /// cases:
1741    /// ```text
1742    /// a || (a && c)  -->  a  // Absorb-OR
1743    /// a && (a || c)  -->  a  // Absorb-AND
1744    /// ```
1745    ///
1746    /// The method also works with more than 2 arguments at the top, e.g.
1747    /// ```text
1748    /// (a && b) || (a && c) || (a && d)  -->  a && (b || c || d)
1749    /// ```
1750    /// It can also factor out only a subset of the top arguments, e.g.
1751    /// ```text
1752    /// (a && b) || (a && c) || (d && e)  -->  (a && (b || c)) || (d && e)
1753    /// ```
1754    ///
1755    /// Note that sometimes there are two overlapping possibilities to factor
1756    /// out from, e.g.
1757    /// ```text
1758    /// (a && b) || (a && c) || (d && c)
1759    /// ```
1760    /// Here we can factor out `a` from from the 1. and 2. terms, or we can
1761    /// factor out `c` from the 2. and 3. terms. One of these might lead to
1762    /// more/better undistribution opportunities later, but we just pick one
1763    /// locally, because recursively trying out all of them would lead to
1764    /// exponential run time.
1765    ///
1766    /// The local heuristic is that we prefer a candidate that leads to an
1767    /// absorption, or if there is no such one then we simply pick the first. In
1768    /// case of multiple absorption candidates, it doesn't matter which one we
1769    /// pick, because applying an absorption cannot adversely effect the
1770    /// possibility of applying other absorptions.
1771    ///
1772    /// # Assumption
1773    ///
1774    /// Assumes that nested chains of AND/OR applications are flattened (this
1775    /// can be enforced with [`Self::flatten_associative`]).
1776    ///
1777    /// # Examples
1778    ///
1779    /// Absorb-OR:
1780    /// ```text
1781    /// a || (a && c) || (a && d)
1782    /// -->
1783    /// a && (true || c || d)
1784    /// -->
1785    /// a && true
1786    /// -->
1787    /// a
1788    /// ```
1789    /// Here only the first step is performed by this method. The rest is done
1790    /// by [`Self::reduce_and_canonicalize_and_or`] called after us in
1791    /// `reduce()`.
1792    ///
1793    /// [distributivity]: https://en.wikipedia.org/wiki/Distributive_property
1794    /// [absorption]: https://en.wikipedia.org/wiki/Absorption_law
1795    fn undistribute_and_or(&mut self) {
1796        // It wouldn't be strictly necessary to wrap this fn in this loop, because `reduce()` calls
1797        // us in a loop anyway. However, `reduce()` tries to do many other things, so the loop here
1798        // improves performance when there are several undistributions to apply in sequence, which
1799        // can occur in `CanonicalizeMfp` when undoing the DNF.
1800        let mut old_self = MirScalarExpr::column(0);
1801        while old_self != *self {
1802            old_self = self.clone();
1803            self.reduce_and_canonicalize_and_or(); // We don't want to deal with 1-arg AND/OR at the top
1804            if let MirScalarExpr::CallVariadic {
1805                exprs: outer_operands,
1806                func: outer_func @ (VariadicFunc::Or | VariadicFunc::And),
1807            } = self
1808            {
1809                let inner_func = outer_func.switch_and_or();
1810
1811                // Make sure that each outer operand is a call to inner_func, by wrapping in a 1-arg
1812                // call if necessary.
1813                outer_operands.iter_mut().for_each(|o| {
1814                    if !matches!(o, MirScalarExpr::CallVariadic {func: f, ..} if *f == inner_func) {
1815                        *o = MirScalarExpr::CallVariadic {
1816                            func: inner_func.clone(),
1817                            exprs: vec![o.take()],
1818                        };
1819                    }
1820                });
1821
1822                let mut inner_operands_refs: Vec<&mut Vec<MirScalarExpr>> = outer_operands
1823                    .iter_mut()
1824                    .map(|o| match o {
1825                        MirScalarExpr::CallVariadic { func: f, exprs } if *f == inner_func => exprs,
1826                        _ => unreachable!(), // the wrapping made sure that we'll get a match
1827                    })
1828                    .collect();
1829
1830                // Find inner operands to undistribute, i.e., which are in _all_ of the outer operands.
1831                let mut intersection = inner_operands_refs
1832                    .iter()
1833                    .map(|v| (*v).clone())
1834                    .reduce(|ops1, ops2| ops1.into_iter().filter(|e| ops2.contains(e)).collect())
1835                    .unwrap();
1836                intersection.sort();
1837                intersection.dedup();
1838
1839                if !intersection.is_empty() {
1840                    // Factor out the intersection from all the top-level args.
1841
1842                    // Remove the intersection from each inner operand vector.
1843                    inner_operands_refs
1844                        .iter_mut()
1845                        .for_each(|ops| (**ops).retain(|o| !intersection.contains(o)));
1846
1847                    // Simplify terms that now have only 0 or 1 args due to removing the intersection.
1848                    outer_operands
1849                        .iter_mut()
1850                        .for_each(|o| o.reduce_and_canonicalize_and_or());
1851
1852                    // Add the intersection at the beginning
1853                    *self = MirScalarExpr::CallVariadic {
1854                        func: inner_func,
1855                        exprs: intersection.into_iter().chain_one(self.clone()).collect(),
1856                    };
1857                } else {
1858                    // If the intersection was empty, that means that there is nothing we can factor out
1859                    // from _all_ the top-level args. However, we might still find something to factor
1860                    // out from a subset of the top-level args. To find such an opportunity, we look for
1861                    // duplicates across all inner args, e.g. if we have
1862                    // `(...) OR (... AND `a` AND ...) OR (...) OR (... AND `a` AND ...)`
1863                    // then we'll find that `a` occurs in more than one top-level arg, so
1864                    // `indexes_to_undistribute` will point us to the 2. and 4. top-level args.
1865
1866                    // Create (inner_operand, index) pairs, where the index is the position in
1867                    // outer_operands
1868                    let all_inner_operands = inner_operands_refs
1869                        .iter()
1870                        .enumerate()
1871                        .flat_map(|(i, inner_vec)| inner_vec.iter().map(move |a| ((*a).clone(), i)))
1872                        .sorted()
1873                        .collect_vec();
1874
1875                    // Find inner operand expressions that occur in more than one top-level arg.
1876                    // Each inner vector in `undistribution_opportunities` will belong to one such inner
1877                    // operand expression, and it is a set of indexes pointing to top-level args where
1878                    // that inner operand occurs.
1879                    let undistribution_opportunities = all_inner_operands
1880                        .iter()
1881                        .chunk_by(|(a, _i)| a)
1882                        .into_iter()
1883                        .map(|(_a, g)| g.map(|(_a, i)| *i).sorted().dedup().collect_vec())
1884                        .filter(|g| g.len() > 1)
1885                        .collect_vec();
1886
1887                    // Choose one of the inner vectors from `undistribution_opportunities`.
1888                    let indexes_to_undistribute = undistribution_opportunities
1889                        .iter()
1890                        // Let's prefer index sets that directly lead to an absorption.
1891                        .find(|index_set| {
1892                            index_set
1893                                .iter()
1894                                .any(|i| inner_operands_refs.get(*i).unwrap().len() == 1)
1895                        })
1896                        // If we didn't find any absorption, then any index set will do.
1897                        .or_else(|| undistribution_opportunities.first())
1898                        .cloned();
1899
1900                    // In any case, undo the 1-arg wrapping that we did at the beginning.
1901                    outer_operands
1902                        .iter_mut()
1903                        .for_each(|o| o.reduce_and_canonicalize_and_or());
1904
1905                    if let Some(indexes_to_undistribute) = indexes_to_undistribute {
1906                        // Found something to undistribute from a subset of the outer operands.
1907                        // We temporarily remove these from outer_operands, call ourselves on it, and
1908                        // then push back the result.
1909                        let mut undistribute_from = MirScalarExpr::CallVariadic {
1910                            func: outer_func.clone(),
1911                            exprs: swap_remove_multiple(outer_operands, indexes_to_undistribute),
1912                        };
1913                        // By construction, the recursive call is guaranteed to hit
1914                        // the `!intersection.is_empty()` branch.
1915                        undistribute_from.undistribute_and_or();
1916                        // Append the undistributed result to outer operands that were not included in
1917                        // indexes_to_undistribute.
1918                        outer_operands.push(undistribute_from);
1919                    }
1920                }
1921            }
1922        }
1923    }
1924
1925    /* #endregion */
1926
1927    /// Adds any columns that *must* be non-Null for `self` to be non-Null.
1928    pub fn non_null_requirements(&self, columns: &mut BTreeSet<usize>) {
1929        match self {
1930            MirScalarExpr::Column(col, _name) => {
1931                columns.insert(*col);
1932            }
1933            MirScalarExpr::Literal(..) => {}
1934            MirScalarExpr::CallUnmaterializable(_) => (),
1935            MirScalarExpr::CallUnary { func, expr } => {
1936                if func.propagates_nulls() {
1937                    expr.non_null_requirements(columns);
1938                }
1939            }
1940            MirScalarExpr::CallBinary { func, expr1, expr2 } => {
1941                if func.propagates_nulls() {
1942                    expr1.non_null_requirements(columns);
1943                    expr2.non_null_requirements(columns);
1944                }
1945            }
1946            MirScalarExpr::CallVariadic { func, exprs } => {
1947                if func.propagates_nulls() {
1948                    for expr in exprs {
1949                        expr.non_null_requirements(columns);
1950                    }
1951                }
1952            }
1953            MirScalarExpr::If { .. } => (),
1954        }
1955    }
1956
1957    pub fn typ(&self, column_types: &[SqlColumnType]) -> SqlColumnType {
1958        match self {
1959            MirScalarExpr::Column(i, _name) => column_types[*i].clone(),
1960            MirScalarExpr::Literal(_, typ) => typ.clone(),
1961            MirScalarExpr::CallUnmaterializable(func) => func.output_type(),
1962            MirScalarExpr::CallUnary { expr, func } => func.output_type(expr.typ(column_types)),
1963            MirScalarExpr::CallBinary { expr1, expr2, func } => {
1964                func.output_type(expr1.typ(column_types), expr2.typ(column_types))
1965            }
1966            MirScalarExpr::CallVariadic { exprs, func } => {
1967                func.output_type(exprs.iter().map(|e| e.typ(column_types)).collect())
1968            }
1969            MirScalarExpr::If { cond: _, then, els } => {
1970                let then_type = then.typ(column_types);
1971                let else_type = els.typ(column_types);
1972                then_type.union(&else_type).unwrap()
1973            }
1974        }
1975    }
1976
1977    pub fn repr_typ(&self, column_types: &[ReprColumnType]) -> ReprColumnType {
1978        match self {
1979            MirScalarExpr::Column(i, _name) => column_types[*i].clone(),
1980            MirScalarExpr::Literal(_, typ) => ReprColumnType::from(typ),
1981            MirScalarExpr::CallUnmaterializable(func) => ReprColumnType::from(&func.output_type()),
1982            MirScalarExpr::CallUnary { expr, func } => ReprColumnType::from(
1983                &func.output_type(SqlColumnType::from_repr(&expr.repr_typ(column_types))),
1984            ),
1985            MirScalarExpr::CallBinary { expr1, expr2, func } => {
1986                ReprColumnType::from(&func.output_type(
1987                    SqlColumnType::from_repr(&expr1.repr_typ(column_types)),
1988                    SqlColumnType::from_repr(&expr2.repr_typ(column_types)),
1989                ))
1990            }
1991            MirScalarExpr::CallVariadic { exprs, func } => ReprColumnType::from(
1992                &func.output_type(
1993                    exprs
1994                        .iter()
1995                        .map(|e| SqlColumnType::from_repr(&e.repr_typ(column_types)))
1996                        .collect(),
1997                ),
1998            ),
1999            MirScalarExpr::If { cond: _, then, els } => {
2000                let then_type = then.repr_typ(column_types);
2001                let else_type = els.repr_typ(column_types);
2002                then_type.union(&else_type).unwrap()
2003            }
2004        }
2005    }
2006
2007    pub fn eval<'a>(
2008        &'a self,
2009        datums: &[Datum<'a>],
2010        temp_storage: &'a RowArena,
2011    ) -> Result<Datum<'a>, EvalError> {
2012        match self {
2013            MirScalarExpr::Column(index, _name) => Ok(datums[*index].clone()),
2014            MirScalarExpr::Literal(res, _column_type) => match res {
2015                Ok(row) => Ok(row.unpack_first()),
2016                Err(e) => Err(e.clone()),
2017            },
2018            // Unmaterializable functions must be transformed away before
2019            // evaluation. Their purpose is as a placeholder for data that is
2020            // not known at plan time but can be inlined before runtime.
2021            MirScalarExpr::CallUnmaterializable(x) => Err(EvalError::Internal(
2022                format!("cannot evaluate unmaterializable function: {:?}", x).into(),
2023            )),
2024            MirScalarExpr::CallUnary { func, expr } => func.eval(datums, temp_storage, expr),
2025            MirScalarExpr::CallBinary { func, expr1, expr2 } => {
2026                func.eval(datums, temp_storage, expr1, expr2)
2027            }
2028            MirScalarExpr::CallVariadic { func, exprs } => func.eval(datums, temp_storage, exprs),
2029            MirScalarExpr::If { cond, then, els } => match cond.eval(datums, temp_storage)? {
2030                Datum::True => then.eval(datums, temp_storage),
2031                Datum::False | Datum::Null => els.eval(datums, temp_storage),
2032                d => Err(EvalError::Internal(
2033                    format!("if condition evaluated to non-boolean datum: {:?}", d).into(),
2034                )),
2035            },
2036        }
2037    }
2038
2039    /// True iff the expression contains
2040    /// `UnmaterializableFunc::MzNow`.
2041    pub fn contains_temporal(&self) -> bool {
2042        let mut contains = false;
2043        self.visit_pre(|e| {
2044            if let MirScalarExpr::CallUnmaterializable(UnmaterializableFunc::MzNow) = e {
2045                contains = true;
2046            }
2047        });
2048        contains
2049    }
2050
2051    /// True iff the expression contains an `UnmaterializableFunc`.
2052    pub fn contains_unmaterializable(&self) -> bool {
2053        let mut contains = false;
2054        self.visit_pre(|e| {
2055            if let MirScalarExpr::CallUnmaterializable(_) = e {
2056                contains = true;
2057            }
2058        });
2059        contains
2060    }
2061
2062    /// True iff the expression contains an `UnmaterializableFunc` that is not in the `exceptions`
2063    /// list.
2064    pub fn contains_unmaterializable_except(&self, exceptions: &[UnmaterializableFunc]) -> bool {
2065        let mut contains = false;
2066        self.visit_pre(|e| match e {
2067            MirScalarExpr::CallUnmaterializable(f) if !exceptions.contains(f) => contains = true,
2068            _ => (),
2069        });
2070        contains
2071    }
2072
2073    /// True iff the expression contains a `Column`.
2074    pub fn contains_column(&self) -> bool {
2075        let mut contains = false;
2076        self.visit_pre(|e| {
2077            if let MirScalarExpr::Column(_col, _name) = e {
2078                contains = true;
2079            }
2080        });
2081        contains
2082    }
2083
2084    /// True iff the expression contains a `Dummy`.
2085    pub fn contains_dummy(&self) -> bool {
2086        let mut contains = false;
2087        self.visit_pre(|e| {
2088            if let MirScalarExpr::Literal(row, _) = e {
2089                if let Ok(row) = row {
2090                    contains |= row.iter().any(|d| d.contains_dummy());
2091                }
2092            }
2093        });
2094        contains
2095    }
2096
2097    /// The size of the expression as a tree.
2098    pub fn size(&self) -> usize {
2099        let mut size = 0;
2100        self.visit_pre(&mut |_: &MirScalarExpr| {
2101            size += 1;
2102        });
2103        size
2104    }
2105}
2106
2107impl MirScalarExpr {
2108    /// True iff evaluation could possibly error on non-error input `Datum`.
2109    pub fn could_error(&self) -> bool {
2110        match self {
2111            MirScalarExpr::Column(_col, _name) => false,
2112            MirScalarExpr::Literal(row, ..) => row.is_err(),
2113            MirScalarExpr::CallUnmaterializable(_) => true,
2114            MirScalarExpr::CallUnary { func, expr } => func.could_error() || expr.could_error(),
2115            MirScalarExpr::CallBinary { func, expr1, expr2 } => {
2116                func.could_error() || expr1.could_error() || expr2.could_error()
2117            }
2118            MirScalarExpr::CallVariadic { func, exprs } => {
2119                func.could_error() || exprs.iter().any(|e| e.could_error())
2120            }
2121            MirScalarExpr::If { cond, then, els } => {
2122                cond.could_error() || then.could_error() || els.could_error()
2123            }
2124        }
2125    }
2126}
2127
2128impl VisitChildren<Self> for MirScalarExpr {
2129    fn visit_children<F>(&self, mut f: F)
2130    where
2131        F: FnMut(&Self),
2132    {
2133        use MirScalarExpr::*;
2134        match self {
2135            Column(_, _) | Literal(_, _) | CallUnmaterializable(_) => (),
2136            CallUnary { expr, .. } => {
2137                f(expr);
2138            }
2139            CallBinary { expr1, expr2, .. } => {
2140                f(expr1);
2141                f(expr2);
2142            }
2143            CallVariadic { exprs, .. } => {
2144                for expr in exprs {
2145                    f(expr);
2146                }
2147            }
2148            If { cond, then, els } => {
2149                f(cond);
2150                f(then);
2151                f(els);
2152            }
2153        }
2154    }
2155
2156    fn visit_mut_children<F>(&mut self, mut f: F)
2157    where
2158        F: FnMut(&mut Self),
2159    {
2160        use MirScalarExpr::*;
2161        match self {
2162            Column(_, _) | Literal(_, _) | CallUnmaterializable(_) => (),
2163            CallUnary { expr, .. } => {
2164                f(expr);
2165            }
2166            CallBinary { expr1, expr2, .. } => {
2167                f(expr1);
2168                f(expr2);
2169            }
2170            CallVariadic { exprs, .. } => {
2171                for expr in exprs {
2172                    f(expr);
2173                }
2174            }
2175            If { cond, then, els } => {
2176                f(cond);
2177                f(then);
2178                f(els);
2179            }
2180        }
2181    }
2182
2183    fn try_visit_children<F, E>(&self, mut f: F) -> Result<(), E>
2184    where
2185        F: FnMut(&Self) -> Result<(), E>,
2186        E: From<RecursionLimitError>,
2187    {
2188        use MirScalarExpr::*;
2189        match self {
2190            Column(_, _) | Literal(_, _) | CallUnmaterializable(_) => (),
2191            CallUnary { expr, .. } => {
2192                f(expr)?;
2193            }
2194            CallBinary { expr1, expr2, .. } => {
2195                f(expr1)?;
2196                f(expr2)?;
2197            }
2198            CallVariadic { exprs, .. } => {
2199                for expr in exprs {
2200                    f(expr)?;
2201                }
2202            }
2203            If { cond, then, els } => {
2204                f(cond)?;
2205                f(then)?;
2206                f(els)?;
2207            }
2208        }
2209        Ok(())
2210    }
2211
2212    fn try_visit_mut_children<F, E>(&mut self, mut f: F) -> Result<(), E>
2213    where
2214        F: FnMut(&mut Self) -> Result<(), E>,
2215        E: From<RecursionLimitError>,
2216    {
2217        use MirScalarExpr::*;
2218        match self {
2219            Column(_, _) | Literal(_, _) | CallUnmaterializable(_) => (),
2220            CallUnary { expr, .. } => {
2221                f(expr)?;
2222            }
2223            CallBinary { expr1, expr2, .. } => {
2224                f(expr1)?;
2225                f(expr2)?;
2226            }
2227            CallVariadic { exprs, .. } => {
2228                for expr in exprs {
2229                    f(expr)?;
2230                }
2231            }
2232            If { cond, then, els } => {
2233                f(cond)?;
2234                f(then)?;
2235                f(els)?;
2236            }
2237        }
2238        Ok(())
2239    }
2240}
2241
2242impl MirScalarExpr {
2243    /// Iterates through references to child expressions.
2244    pub fn children(&self) -> impl DoubleEndedIterator<Item = &Self> {
2245        let mut first = None;
2246        let mut second = None;
2247        let mut third = None;
2248        let mut variadic = None;
2249
2250        use MirScalarExpr::*;
2251        match self {
2252            Column(_, _) | Literal(_, _) | CallUnmaterializable(_) => (),
2253            CallUnary { expr, .. } => {
2254                first = Some(&**expr);
2255            }
2256            CallBinary { expr1, expr2, .. } => {
2257                first = Some(&**expr1);
2258                second = Some(&**expr2);
2259            }
2260            CallVariadic { exprs, .. } => {
2261                variadic = Some(exprs);
2262            }
2263            If { cond, then, els } => {
2264                first = Some(&**cond);
2265                second = Some(&**then);
2266                third = Some(&**els);
2267            }
2268        }
2269
2270        first
2271            .into_iter()
2272            .chain(second)
2273            .chain(third)
2274            .chain(variadic.into_iter().flatten())
2275    }
2276
2277    /// Iterates through mutable references to child expressions.
2278    pub fn children_mut(&mut self) -> impl DoubleEndedIterator<Item = &mut Self> {
2279        let mut first = None;
2280        let mut second = None;
2281        let mut third = None;
2282        let mut variadic = None;
2283
2284        use MirScalarExpr::*;
2285        match self {
2286            Column(_, _) | Literal(_, _) | CallUnmaterializable(_) => (),
2287            CallUnary { expr, .. } => {
2288                first = Some(&mut **expr);
2289            }
2290            CallBinary { expr1, expr2, .. } => {
2291                first = Some(&mut **expr1);
2292                second = Some(&mut **expr2);
2293            }
2294            CallVariadic { exprs, .. } => {
2295                variadic = Some(exprs);
2296            }
2297            If { cond, then, els } => {
2298                first = Some(&mut **cond);
2299                second = Some(&mut **then);
2300                third = Some(&mut **els);
2301            }
2302        }
2303
2304        first
2305            .into_iter()
2306            .chain(second)
2307            .chain(third)
2308            .chain(variadic.into_iter().flatten())
2309    }
2310
2311    /// Visits all subexpressions in DFS preorder.
2312    pub fn visit_pre<F>(&self, mut f: F)
2313    where
2314        F: FnMut(&Self),
2315    {
2316        let mut worklist = vec![self];
2317        while let Some(e) = worklist.pop() {
2318            f(e);
2319            worklist.extend(e.children().rev());
2320        }
2321    }
2322
2323    /// Iterative pre-order visitor.
2324    pub fn visit_pre_mut<F: FnMut(&mut Self)>(&mut self, mut f: F) {
2325        let mut worklist = vec![self];
2326        while let Some(expr) = worklist.pop() {
2327            f(expr);
2328            worklist.extend(expr.children_mut().rev());
2329        }
2330    }
2331}
2332
2333/// Filter characteristics that are used for ordering join inputs.
2334/// This can be created for a `Vec<MirScalarExpr>`, which represents an AND of predicates.
2335///
2336/// The fields are ordered based on heuristic assumptions about their typical selectivity, so that
2337/// Ord gives the right ordering for join inputs. Bigger is better, i.e., will tend to come earlier
2338/// than other inputs.
2339#[derive(Eq, PartialEq, Ord, PartialOrd, Debug, Clone, Serialize, Deserialize, Hash, MzReflect)]
2340pub struct FilterCharacteristics {
2341    // `<expr> = <literal>` appears in the filter.
2342    // Excludes cases where NOT appears anywhere above the literal equality.
2343    literal_equality: bool,
2344    // (Assuming a random string of lower-case characters, `LIKE 'a%'` has a selectivity of 1/26.)
2345    like: bool,
2346    is_null: bool,
2347    // Number of Vec elements that involve inequality predicates. (A BETWEEN is represented as two
2348    // inequality predicates.)
2349    // Excludes cases where NOT appears around the literal inequality.
2350    // Note that for inequality predicates, some databases assume 1/3 selectivity in the absence of
2351    // concrete statistics.
2352    literal_inequality: usize,
2353    /// Any filter, except ones involving `IS NOT NULL`, because those are too common.
2354    /// Can be true by itself, or any other field being true can also make this true.
2355    /// `NOT LIKE` is only in this category.
2356    /// `!=` is only in this category.
2357    /// `NOT (a = b)` is turned into `!=` by `reduce` before us!
2358    any_filter: bool,
2359}
2360
2361impl BitOrAssign for FilterCharacteristics {
2362    fn bitor_assign(&mut self, rhs: Self) {
2363        self.literal_equality |= rhs.literal_equality;
2364        self.like |= rhs.like;
2365        self.is_null |= rhs.is_null;
2366        self.literal_inequality += rhs.literal_inequality;
2367        self.any_filter |= rhs.any_filter;
2368    }
2369}
2370
2371impl FilterCharacteristics {
2372    pub fn none() -> FilterCharacteristics {
2373        FilterCharacteristics {
2374            literal_equality: false,
2375            like: false,
2376            is_null: false,
2377            literal_inequality: 0,
2378            any_filter: false,
2379        }
2380    }
2381
2382    pub fn explain(&self) -> String {
2383        let mut e = "".to_owned();
2384        if self.literal_equality {
2385            e.push_str("e");
2386        }
2387        if self.like {
2388            e.push_str("l");
2389        }
2390        if self.is_null {
2391            e.push_str("n");
2392        }
2393        for _ in 0..self.literal_inequality {
2394            e.push_str("i");
2395        }
2396        if self.any_filter {
2397            e.push_str("f");
2398        }
2399        e
2400    }
2401
2402    pub fn filter_characteristics(
2403        filters: &Vec<MirScalarExpr>,
2404    ) -> Result<FilterCharacteristics, RecursionLimitError> {
2405        let mut literal_equality = false;
2406        let mut like = false;
2407        let mut is_null = false;
2408        let mut literal_inequality = 0;
2409        let mut any_filter = false;
2410        filters.iter().try_for_each(|f| {
2411            let mut literal_inequality_in_current_filter = false;
2412            let mut is_not_null_in_current_filter = false;
2413            f.visit_pre_with_context(
2414                false,
2415                &mut |not_in_parent_chain, expr| {
2416                    not_in_parent_chain
2417                        || matches!(
2418                            expr,
2419                            MirScalarExpr::CallUnary {
2420                                func: UnaryFunc::Not(func::Not),
2421                                ..
2422                            }
2423                        )
2424                },
2425                &mut |not_in_parent_chain, expr| {
2426                    if !not_in_parent_chain {
2427                        if expr.any_expr_eq_literal().is_some() {
2428                            literal_equality = true;
2429                        }
2430                        if expr.any_expr_ineq_literal() {
2431                            literal_inequality_in_current_filter = true;
2432                        }
2433                        if matches!(
2434                            expr,
2435                            MirScalarExpr::CallUnary {
2436                                func: UnaryFunc::IsLikeMatch(_),
2437                                ..
2438                            }
2439                        ) {
2440                            like = true;
2441                        }
2442                    };
2443                    if matches!(
2444                        expr,
2445                        MirScalarExpr::CallUnary {
2446                            func: UnaryFunc::IsNull(crate::func::IsNull),
2447                            ..
2448                        }
2449                    ) {
2450                        if *not_in_parent_chain {
2451                            is_not_null_in_current_filter = true;
2452                        } else {
2453                            is_null = true;
2454                        }
2455                    }
2456                },
2457            )?;
2458            if literal_inequality_in_current_filter {
2459                literal_inequality += 1;
2460            }
2461            if !is_not_null_in_current_filter {
2462                // We want to ignore `IS NOT NULL` for `any_filter`.
2463                any_filter = true;
2464            }
2465            Ok(())
2466        })?;
2467        Ok(FilterCharacteristics {
2468            literal_equality,
2469            like,
2470            is_null,
2471            literal_inequality,
2472            any_filter,
2473        })
2474    }
2475
2476    pub fn add_literal_equality(&mut self) {
2477        self.literal_equality = true;
2478    }
2479
2480    pub fn worst_case_scaling_factor(&self) -> f64 {
2481        let mut factor = 1.0;
2482
2483        if self.literal_equality {
2484            factor *= 0.1;
2485        }
2486
2487        if self.is_null {
2488            factor *= 0.1;
2489        }
2490
2491        if self.literal_inequality >= 2 {
2492            factor *= 0.25;
2493        } else if self.literal_inequality == 1 {
2494            factor *= 0.33;
2495        }
2496
2497        // catch various negated filters, treat them pessimistically
2498        if !(self.literal_equality || self.is_null || self.literal_inequality > 0)
2499            && self.any_filter
2500        {
2501            factor *= 0.9;
2502        }
2503
2504        factor
2505    }
2506}
2507
2508#[derive(
2509    Arbitrary,
2510    Ord,
2511    PartialOrd,
2512    Copy,
2513    Clone,
2514    Debug,
2515    Eq,
2516    PartialEq,
2517    Serialize,
2518    Deserialize,
2519    Hash,
2520    MzReflect,
2521)]
2522pub enum DomainLimit {
2523    None,
2524    Inclusive(i64),
2525    Exclusive(i64),
2526}
2527
2528impl RustType<ProtoDomainLimit> for DomainLimit {
2529    fn into_proto(&self) -> ProtoDomainLimit {
2530        use proto_domain_limit::Kind::*;
2531        let kind = match self {
2532            DomainLimit::None => None(()),
2533            DomainLimit::Inclusive(v) => Inclusive(*v),
2534            DomainLimit::Exclusive(v) => Exclusive(*v),
2535        };
2536        ProtoDomainLimit { kind: Some(kind) }
2537    }
2538
2539    fn from_proto(proto: ProtoDomainLimit) -> Result<Self, TryFromProtoError> {
2540        use proto_domain_limit::Kind::*;
2541        if let Some(kind) = proto.kind {
2542            match kind {
2543                None(()) => Ok(DomainLimit::None),
2544                Inclusive(v) => Ok(DomainLimit::Inclusive(v)),
2545                Exclusive(v) => Ok(DomainLimit::Exclusive(v)),
2546            }
2547        } else {
2548            Err(TryFromProtoError::missing_field("ProtoDomainLimit::kind"))
2549        }
2550    }
2551}
2552
2553#[derive(
2554    Arbitrary, Ord, PartialOrd, Clone, Debug, Eq, PartialEq, Serialize, Deserialize, Hash, MzReflect,
2555)]
2556pub enum EvalError {
2557    CharacterNotValidForEncoding(i32),
2558    CharacterTooLargeForEncoding(i32),
2559    DateBinOutOfRange(Box<str>),
2560    DivisionByZero,
2561    Unsupported {
2562        feature: Box<str>,
2563        discussion_no: Option<usize>,
2564    },
2565    FloatOverflow,
2566    FloatUnderflow,
2567    NumericFieldOverflow,
2568    Float32OutOfRange(Box<str>),
2569    Float64OutOfRange(Box<str>),
2570    Int16OutOfRange(Box<str>),
2571    Int32OutOfRange(Box<str>),
2572    Int64OutOfRange(Box<str>),
2573    UInt16OutOfRange(Box<str>),
2574    UInt32OutOfRange(Box<str>),
2575    UInt64OutOfRange(Box<str>),
2576    MzTimestampOutOfRange(Box<str>),
2577    MzTimestampStepOverflow,
2578    OidOutOfRange(Box<str>),
2579    IntervalOutOfRange(Box<str>),
2580    TimestampCannotBeNan,
2581    TimestampOutOfRange,
2582    DateOutOfRange,
2583    CharOutOfRange,
2584    IndexOutOfRange {
2585        provided: i32,
2586        // The last valid index position, i.e. `v.len() - 1`
2587        valid_end: i32,
2588    },
2589    InvalidBase64Equals,
2590    InvalidBase64Symbol(char),
2591    InvalidBase64EndSequence,
2592    InvalidTimezone(Box<str>),
2593    InvalidTimezoneInterval,
2594    InvalidTimezoneConversion,
2595    InvalidIanaTimezoneId(Box<str>),
2596    InvalidLayer {
2597        max_layer: usize,
2598        val: i64,
2599    },
2600    InvalidArray(InvalidArrayError),
2601    InvalidEncodingName(Box<str>),
2602    InvalidHashAlgorithm(Box<str>),
2603    InvalidByteSequence {
2604        byte_sequence: Box<str>,
2605        encoding_name: Box<str>,
2606    },
2607    InvalidJsonbCast {
2608        from: Box<str>,
2609        to: Box<str>,
2610    },
2611    InvalidRegex(Box<str>),
2612    InvalidRegexFlag(char),
2613    InvalidParameterValue(Box<str>),
2614    InvalidDatePart(Box<str>),
2615    KeyCannotBeNull,
2616    NegSqrt,
2617    NegLimit,
2618    NullCharacterNotPermitted,
2619    UnknownUnits(Box<str>),
2620    UnsupportedUnits(Box<str>, Box<str>),
2621    UnterminatedLikeEscapeSequence,
2622    Parse(ParseError),
2623    ParseHex(ParseHexError),
2624    Internal(Box<str>),
2625    InfinityOutOfDomain(Box<str>),
2626    NegativeOutOfDomain(Box<str>),
2627    ZeroOutOfDomain(Box<str>),
2628    OutOfDomain(DomainLimit, DomainLimit, Box<str>),
2629    ComplexOutOfRange(Box<str>),
2630    MultipleRowsFromSubquery,
2631    Undefined(Box<str>),
2632    LikePatternTooLong,
2633    LikeEscapeTooLong,
2634    StringValueTooLong {
2635        target_type: Box<str>,
2636        length: usize,
2637    },
2638    MultidimensionalArrayRemovalNotSupported,
2639    IncompatibleArrayDimensions {
2640        dims: Option<(usize, usize)>,
2641    },
2642    TypeFromOid(Box<str>),
2643    InvalidRange(InvalidRangeError),
2644    InvalidRoleId(Box<str>),
2645    InvalidPrivileges(Box<str>),
2646    LetRecLimitExceeded(Box<str>),
2647    MultiDimensionalArraySearch,
2648    MustNotBeNull(Box<str>),
2649    InvalidIdentifier {
2650        ident: Box<str>,
2651        detail: Option<Box<str>>,
2652    },
2653    ArrayFillWrongArraySubscripts,
2654    // TODO: propagate this check more widely throughout the expr crate
2655    MaxArraySizeExceeded(usize),
2656    DateDiffOverflow {
2657        unit: Box<str>,
2658        a: Box<str>,
2659        b: Box<str>,
2660    },
2661    // The error for ErrorIfNull; this should not be used in other contexts as a generic error
2662    // printer.
2663    IfNullError(Box<str>),
2664    LengthTooLarge,
2665    AclArrayNullElement,
2666    MzAclArrayNullElement,
2667    PrettyError(Box<str>),
2668}
2669
2670impl fmt::Display for EvalError {
2671    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2672        match self {
2673            EvalError::CharacterNotValidForEncoding(v) => {
2674                write!(f, "requested character not valid for encoding: {v}")
2675            }
2676            EvalError::CharacterTooLargeForEncoding(v) => {
2677                write!(f, "requested character too large for encoding: {v}")
2678            }
2679            EvalError::DateBinOutOfRange(message) => f.write_str(message),
2680            EvalError::DivisionByZero => f.write_str("division by zero"),
2681            EvalError::Unsupported {
2682                feature,
2683                discussion_no,
2684            } => {
2685                write!(f, "{} not yet supported", feature)?;
2686                if let Some(discussion_no) = discussion_no {
2687                    write!(
2688                        f,
2689                        ", see https://github.com/MaterializeInc/materialize/discussions/{} for more details",
2690                        discussion_no
2691                    )?;
2692                }
2693                Ok(())
2694            }
2695            EvalError::FloatOverflow => f.write_str("value out of range: overflow"),
2696            EvalError::FloatUnderflow => f.write_str("value out of range: underflow"),
2697            EvalError::NumericFieldOverflow => f.write_str("numeric field overflow"),
2698            EvalError::Float32OutOfRange(val) => write!(f, "{} real out of range", val.quoted()),
2699            EvalError::Float64OutOfRange(val) => {
2700                write!(f, "{} double precision out of range", val.quoted())
2701            }
2702            EvalError::Int16OutOfRange(val) => write!(f, "{} smallint out of range", val.quoted()),
2703            EvalError::Int32OutOfRange(val) => write!(f, "{} integer out of range", val.quoted()),
2704            EvalError::Int64OutOfRange(val) => write!(f, "{} bigint out of range", val.quoted()),
2705            EvalError::UInt16OutOfRange(val) => write!(f, "{} uint2 out of range", val.quoted()),
2706            EvalError::UInt32OutOfRange(val) => write!(f, "{} uint4 out of range", val.quoted()),
2707            EvalError::UInt64OutOfRange(val) => write!(f, "{} uint8 out of range", val.quoted()),
2708            EvalError::MzTimestampOutOfRange(val) => {
2709                write!(f, "{} mz_timestamp out of range", val.quoted())
2710            }
2711            EvalError::MzTimestampStepOverflow => f.write_str("step mz_timestamp overflow"),
2712            EvalError::OidOutOfRange(val) => write!(f, "{} OID out of range", val.quoted()),
2713            EvalError::IntervalOutOfRange(val) => {
2714                write!(f, "{} interval out of range", val.quoted())
2715            }
2716            EvalError::TimestampCannotBeNan => f.write_str("timestamp cannot be NaN"),
2717            EvalError::TimestampOutOfRange => f.write_str("timestamp out of range"),
2718            EvalError::DateOutOfRange => f.write_str("date out of range"),
2719            EvalError::CharOutOfRange => f.write_str("\"char\" out of range"),
2720            EvalError::IndexOutOfRange {
2721                provided,
2722                valid_end,
2723            } => write!(f, "index {provided} out of valid range, 0..{valid_end}",),
2724            EvalError::InvalidBase64Equals => {
2725                f.write_str("unexpected \"=\" while decoding base64 sequence")
2726            }
2727            EvalError::InvalidBase64Symbol(c) => write!(
2728                f,
2729                "invalid symbol \"{}\" found while decoding base64 sequence",
2730                c.escape_default()
2731            ),
2732            EvalError::InvalidBase64EndSequence => f.write_str("invalid base64 end sequence"),
2733            EvalError::InvalidJsonbCast { from, to } => {
2734                write!(f, "cannot cast jsonb {} to type {}", from, to)
2735            }
2736            EvalError::InvalidTimezone(tz) => write!(f, "invalid time zone '{}'", tz),
2737            EvalError::InvalidTimezoneInterval => {
2738                f.write_str("timezone interval must not contain months or years")
2739            }
2740            EvalError::InvalidTimezoneConversion => f.write_str("invalid timezone conversion"),
2741            EvalError::InvalidIanaTimezoneId(tz) => {
2742                write!(f, "invalid IANA Time Zone Database identifier: '{}'", tz)
2743            }
2744            EvalError::InvalidLayer { max_layer, val } => write!(
2745                f,
2746                "invalid layer: {}; must use value within [1, {}]",
2747                val, max_layer
2748            ),
2749            EvalError::InvalidArray(e) => e.fmt(f),
2750            EvalError::InvalidEncodingName(name) => write!(f, "invalid encoding name '{}'", name),
2751            EvalError::InvalidHashAlgorithm(alg) => write!(f, "invalid hash algorithm '{}'", alg),
2752            EvalError::InvalidByteSequence {
2753                byte_sequence,
2754                encoding_name,
2755            } => write!(
2756                f,
2757                "invalid byte sequence '{}' for encoding '{}'",
2758                byte_sequence, encoding_name
2759            ),
2760            EvalError::InvalidDatePart(part) => write!(f, "invalid datepart {}", part.quoted()),
2761            EvalError::KeyCannotBeNull => f.write_str("key cannot be null"),
2762            EvalError::NegSqrt => f.write_str("cannot take square root of a negative number"),
2763            EvalError::NegLimit => f.write_str("LIMIT must not be negative"),
2764            EvalError::NullCharacterNotPermitted => f.write_str("null character not permitted"),
2765            EvalError::InvalidRegex(e) => write!(f, "invalid regular expression: {}", e),
2766            EvalError::InvalidRegexFlag(c) => write!(f, "invalid regular expression flag: {}", c),
2767            EvalError::InvalidParameterValue(s) => f.write_str(s),
2768            EvalError::UnknownUnits(units) => write!(f, "unit '{}' not recognized", units),
2769            EvalError::UnsupportedUnits(units, typ) => {
2770                write!(f, "unit '{}' not supported for type {}", units, typ)
2771            }
2772            EvalError::UnterminatedLikeEscapeSequence => {
2773                f.write_str("unterminated escape sequence in LIKE")
2774            }
2775            EvalError::Parse(e) => e.fmt(f),
2776            EvalError::PrettyError(e) => e.fmt(f),
2777            EvalError::ParseHex(e) => e.fmt(f),
2778            EvalError::Internal(s) => write!(f, "internal error: {}", s),
2779            EvalError::InfinityOutOfDomain(s) => {
2780                write!(f, "function {} is only defined for finite arguments", s)
2781            }
2782            EvalError::NegativeOutOfDomain(s) => {
2783                write!(f, "function {} is not defined for negative numbers", s)
2784            }
2785            EvalError::ZeroOutOfDomain(s) => {
2786                write!(f, "function {} is not defined for zero", s)
2787            }
2788            EvalError::OutOfDomain(lower, upper, s) => {
2789                use DomainLimit::*;
2790                write!(f, "function {s} is defined for numbers ")?;
2791                match (lower, upper) {
2792                    (Inclusive(n), None) => write!(f, "greater than or equal to {n}"),
2793                    (Exclusive(n), None) => write!(f, "greater than {n}"),
2794                    (None, Inclusive(n)) => write!(f, "less than or equal to {n}"),
2795                    (None, Exclusive(n)) => write!(f, "less than {n}"),
2796                    (Inclusive(lo), Inclusive(hi)) => write!(f, "between {lo} and {hi} inclusive"),
2797                    (Exclusive(lo), Exclusive(hi)) => write!(f, "between {lo} and {hi} exclusive"),
2798                    (Inclusive(lo), Exclusive(hi)) => {
2799                        write!(f, "between {lo} inclusive and {hi} exclusive")
2800                    }
2801                    (Exclusive(lo), Inclusive(hi)) => {
2802                        write!(f, "between {lo} exclusive and {hi} inclusive")
2803                    }
2804                    (None, None) => panic!("invalid domain error"),
2805                }
2806            }
2807            EvalError::ComplexOutOfRange(s) => {
2808                write!(f, "function {} cannot return complex numbers", s)
2809            }
2810            EvalError::MultipleRowsFromSubquery => {
2811                write!(f, "more than one record produced in subquery")
2812            }
2813            EvalError::Undefined(s) => {
2814                write!(f, "{} is undefined", s)
2815            }
2816            EvalError::LikePatternTooLong => {
2817                write!(f, "LIKE pattern exceeds maximum length")
2818            }
2819            EvalError::LikeEscapeTooLong => {
2820                write!(f, "invalid escape string")
2821            }
2822            EvalError::StringValueTooLong {
2823                target_type,
2824                length,
2825            } => {
2826                write!(f, "value too long for type {}({})", target_type, length)
2827            }
2828            EvalError::MultidimensionalArrayRemovalNotSupported => {
2829                write!(
2830                    f,
2831                    "removing elements from multidimensional arrays is not supported"
2832                )
2833            }
2834            EvalError::IncompatibleArrayDimensions { dims: _ } => {
2835                write!(f, "cannot concatenate incompatible arrays")
2836            }
2837            EvalError::TypeFromOid(msg) => write!(f, "{msg}"),
2838            EvalError::InvalidRange(e) => e.fmt(f),
2839            EvalError::InvalidRoleId(msg) => write!(f, "{msg}"),
2840            EvalError::InvalidPrivileges(privilege) => {
2841                write!(f, "unrecognized privilege type: {privilege}")
2842            }
2843            EvalError::LetRecLimitExceeded(max_iters) => {
2844                write!(
2845                    f,
2846                    "Recursive query exceeded the recursion limit {}. (Use RETURN AT RECURSION LIMIT to not error, but return the current state as the final result when reaching the limit.)",
2847                    max_iters
2848                )
2849            }
2850            EvalError::MultiDimensionalArraySearch => write!(
2851                f,
2852                "searching for elements in multidimensional arrays is not supported"
2853            ),
2854            EvalError::MustNotBeNull(v) => write!(f, "{v} must not be null"),
2855            EvalError::InvalidIdentifier { ident, .. } => {
2856                write!(f, "string is not a valid identifier: {}", ident.quoted())
2857            }
2858            EvalError::ArrayFillWrongArraySubscripts => {
2859                f.write_str("wrong number of array subscripts")
2860            }
2861            EvalError::MaxArraySizeExceeded(max_size) => {
2862                write!(
2863                    f,
2864                    "array size exceeds the maximum allowed ({max_size} bytes)"
2865                )
2866            }
2867            EvalError::DateDiffOverflow { unit, a, b } => {
2868                write!(f, "datediff overflow, {unit} of {a}, {b}")
2869            }
2870            EvalError::IfNullError(s) => f.write_str(s),
2871            EvalError::LengthTooLarge => write!(f, "requested length too large"),
2872            EvalError::AclArrayNullElement => write!(f, "ACL arrays must not contain null values"),
2873            EvalError::MzAclArrayNullElement => {
2874                write!(f, "MZ_ACL arrays must not contain null values")
2875            }
2876        }
2877    }
2878}
2879
2880impl EvalError {
2881    pub fn detail(&self) -> Option<String> {
2882        match self {
2883            EvalError::IncompatibleArrayDimensions { dims: None } => Some(
2884                "Arrays with differing dimensions are not compatible for concatenation.".into(),
2885            ),
2886            EvalError::IncompatibleArrayDimensions {
2887                dims: Some((a_dims, b_dims)),
2888            } => Some(format!(
2889                "Arrays of {} and {} dimensions are not compatible for concatenation.",
2890                a_dims, b_dims
2891            )),
2892            EvalError::InvalidIdentifier { detail, .. } => detail.as_deref().map(Into::into),
2893            EvalError::ArrayFillWrongArraySubscripts => {
2894                Some("Low bound array has different size than dimensions array.".into())
2895            }
2896            _ => None,
2897        }
2898    }
2899
2900    pub fn hint(&self) -> Option<String> {
2901        match self {
2902            EvalError::InvalidBase64EndSequence => Some(
2903                "Input data is missing padding, is truncated, or is otherwise corrupted.".into(),
2904            ),
2905            EvalError::LikeEscapeTooLong => {
2906                Some("Escape string must be empty or one character.".into())
2907            }
2908            EvalError::MzTimestampOutOfRange(_) => Some(
2909                "Integer, numeric, and text casts to mz_timestamp must be in the form of whole \
2910                milliseconds since the Unix epoch. Values with fractional parts cannot be \
2911                converted to mz_timestamp."
2912                    .into(),
2913            ),
2914            _ => None,
2915        }
2916    }
2917}
2918
2919impl std::error::Error for EvalError {}
2920
2921impl From<ParseError> for EvalError {
2922    fn from(e: ParseError) -> EvalError {
2923        EvalError::Parse(e)
2924    }
2925}
2926
2927impl From<ParseHexError> for EvalError {
2928    fn from(e: ParseHexError) -> EvalError {
2929        EvalError::ParseHex(e)
2930    }
2931}
2932
2933impl From<InvalidArrayError> for EvalError {
2934    fn from(e: InvalidArrayError) -> EvalError {
2935        EvalError::InvalidArray(e)
2936    }
2937}
2938
2939impl From<RegexCompilationError> for EvalError {
2940    fn from(e: RegexCompilationError) -> EvalError {
2941        EvalError::InvalidRegex(e.to_string().into())
2942    }
2943}
2944
2945impl From<TypeFromOidError> for EvalError {
2946    fn from(e: TypeFromOidError) -> EvalError {
2947        EvalError::TypeFromOid(e.to_string().into())
2948    }
2949}
2950
2951impl From<DateError> for EvalError {
2952    fn from(e: DateError) -> EvalError {
2953        match e {
2954            DateError::OutOfRange => EvalError::DateOutOfRange,
2955        }
2956    }
2957}
2958
2959impl From<TimestampError> for EvalError {
2960    fn from(e: TimestampError) -> EvalError {
2961        match e {
2962            TimestampError::OutOfRange => EvalError::TimestampOutOfRange,
2963        }
2964    }
2965}
2966
2967impl From<InvalidRangeError> for EvalError {
2968    fn from(e: InvalidRangeError) -> EvalError {
2969        EvalError::InvalidRange(e)
2970    }
2971}
2972
2973impl RustType<ProtoEvalError> for EvalError {
2974    fn into_proto(&self) -> ProtoEvalError {
2975        use proto_eval_error::Kind::*;
2976        use proto_eval_error::*;
2977        let kind = match self {
2978            EvalError::CharacterNotValidForEncoding(v) => CharacterNotValidForEncoding(*v),
2979            EvalError::CharacterTooLargeForEncoding(v) => CharacterTooLargeForEncoding(*v),
2980            EvalError::DateBinOutOfRange(v) => DateBinOutOfRange(v.into_proto()),
2981            EvalError::DivisionByZero => DivisionByZero(()),
2982            EvalError::Unsupported {
2983                feature,
2984                discussion_no,
2985            } => Unsupported(ProtoUnsupported {
2986                feature: feature.into_proto(),
2987                discussion_no: discussion_no.into_proto(),
2988            }),
2989            EvalError::FloatOverflow => FloatOverflow(()),
2990            EvalError::FloatUnderflow => FloatUnderflow(()),
2991            EvalError::NumericFieldOverflow => NumericFieldOverflow(()),
2992            EvalError::Float32OutOfRange(val) => Float32OutOfRange(ProtoValueOutOfRange {
2993                value: val.to_string(),
2994            }),
2995            EvalError::Float64OutOfRange(val) => Float64OutOfRange(ProtoValueOutOfRange {
2996                value: val.to_string(),
2997            }),
2998            EvalError::Int16OutOfRange(val) => Int16OutOfRange(ProtoValueOutOfRange {
2999                value: val.to_string(),
3000            }),
3001            EvalError::Int32OutOfRange(val) => Int32OutOfRange(ProtoValueOutOfRange {
3002                value: val.to_string(),
3003            }),
3004            EvalError::Int64OutOfRange(val) => Int64OutOfRange(ProtoValueOutOfRange {
3005                value: val.to_string(),
3006            }),
3007            EvalError::UInt16OutOfRange(val) => Uint16OutOfRange(ProtoValueOutOfRange {
3008                value: val.to_string(),
3009            }),
3010            EvalError::UInt32OutOfRange(val) => Uint32OutOfRange(ProtoValueOutOfRange {
3011                value: val.to_string(),
3012            }),
3013            EvalError::UInt64OutOfRange(val) => Uint64OutOfRange(ProtoValueOutOfRange {
3014                value: val.to_string(),
3015            }),
3016            EvalError::MzTimestampOutOfRange(val) => MzTimestampOutOfRange(ProtoValueOutOfRange {
3017                value: val.to_string(),
3018            }),
3019            EvalError::MzTimestampStepOverflow => MzTimestampStepOverflow(()),
3020            EvalError::OidOutOfRange(val) => OidOutOfRange(ProtoValueOutOfRange {
3021                value: val.to_string(),
3022            }),
3023            EvalError::IntervalOutOfRange(val) => IntervalOutOfRange(ProtoValueOutOfRange {
3024                value: val.to_string(),
3025            }),
3026            EvalError::TimestampCannotBeNan => TimestampCannotBeNan(()),
3027            EvalError::TimestampOutOfRange => TimestampOutOfRange(()),
3028            EvalError::DateOutOfRange => DateOutOfRange(()),
3029            EvalError::CharOutOfRange => CharOutOfRange(()),
3030            EvalError::IndexOutOfRange {
3031                provided,
3032                valid_end,
3033            } => IndexOutOfRange(ProtoIndexOutOfRange {
3034                provided: *provided,
3035                valid_end: *valid_end,
3036            }),
3037            EvalError::InvalidBase64Equals => InvalidBase64Equals(()),
3038            EvalError::InvalidBase64Symbol(sym) => InvalidBase64Symbol(sym.into_proto()),
3039            EvalError::InvalidBase64EndSequence => InvalidBase64EndSequence(()),
3040            EvalError::InvalidTimezone(tz) => InvalidTimezone(tz.into_proto()),
3041            EvalError::InvalidTimezoneInterval => InvalidTimezoneInterval(()),
3042            EvalError::InvalidTimezoneConversion => InvalidTimezoneConversion(()),
3043            EvalError::InvalidLayer { max_layer, val } => InvalidLayer(ProtoInvalidLayer {
3044                max_layer: max_layer.into_proto(),
3045                val: *val,
3046            }),
3047            EvalError::InvalidArray(error) => InvalidArray(error.into_proto()),
3048            EvalError::InvalidEncodingName(v) => InvalidEncodingName(v.into_proto()),
3049            EvalError::InvalidHashAlgorithm(v) => InvalidHashAlgorithm(v.into_proto()),
3050            EvalError::InvalidByteSequence {
3051                byte_sequence,
3052                encoding_name,
3053            } => InvalidByteSequence(ProtoInvalidByteSequence {
3054                byte_sequence: byte_sequence.into_proto(),
3055                encoding_name: encoding_name.into_proto(),
3056            }),
3057            EvalError::InvalidJsonbCast { from, to } => InvalidJsonbCast(ProtoInvalidJsonbCast {
3058                from: from.into_proto(),
3059                to: to.into_proto(),
3060            }),
3061            EvalError::InvalidRegex(v) => InvalidRegex(v.into_proto()),
3062            EvalError::InvalidRegexFlag(v) => InvalidRegexFlag(v.into_proto()),
3063            EvalError::InvalidParameterValue(v) => InvalidParameterValue(v.into_proto()),
3064            EvalError::InvalidDatePart(part) => InvalidDatePart(part.into_proto()),
3065            EvalError::KeyCannotBeNull => KeyCannotBeNull(()),
3066            EvalError::NegSqrt => NegSqrt(()),
3067            EvalError::NegLimit => NegLimit(()),
3068            EvalError::NullCharacterNotPermitted => NullCharacterNotPermitted(()),
3069            EvalError::UnknownUnits(v) => UnknownUnits(v.into_proto()),
3070            EvalError::UnsupportedUnits(units, typ) => UnsupportedUnits(ProtoUnsupportedUnits {
3071                units: units.into_proto(),
3072                typ: typ.into_proto(),
3073            }),
3074            EvalError::UnterminatedLikeEscapeSequence => UnterminatedLikeEscapeSequence(()),
3075            EvalError::Parse(error) => Parse(error.into_proto()),
3076            EvalError::PrettyError(error) => PrettyError(error.into_proto()),
3077            EvalError::ParseHex(error) => ParseHex(error.into_proto()),
3078            EvalError::Internal(v) => Internal(v.into_proto()),
3079            EvalError::InfinityOutOfDomain(v) => InfinityOutOfDomain(v.into_proto()),
3080            EvalError::NegativeOutOfDomain(v) => NegativeOutOfDomain(v.into_proto()),
3081            EvalError::ZeroOutOfDomain(v) => ZeroOutOfDomain(v.into_proto()),
3082            EvalError::OutOfDomain(lower, upper, id) => OutOfDomain(ProtoOutOfDomain {
3083                lower: Some(lower.into_proto()),
3084                upper: Some(upper.into_proto()),
3085                id: id.into_proto(),
3086            }),
3087            EvalError::ComplexOutOfRange(v) => ComplexOutOfRange(v.into_proto()),
3088            EvalError::MultipleRowsFromSubquery => MultipleRowsFromSubquery(()),
3089            EvalError::Undefined(v) => Undefined(v.into_proto()),
3090            EvalError::LikePatternTooLong => LikePatternTooLong(()),
3091            EvalError::LikeEscapeTooLong => LikeEscapeTooLong(()),
3092            EvalError::StringValueTooLong {
3093                target_type,
3094                length,
3095            } => StringValueTooLong(ProtoStringValueTooLong {
3096                target_type: target_type.into_proto(),
3097                length: length.into_proto(),
3098            }),
3099            EvalError::MultidimensionalArrayRemovalNotSupported => {
3100                MultidimensionalArrayRemovalNotSupported(())
3101            }
3102            EvalError::IncompatibleArrayDimensions { dims } => {
3103                IncompatibleArrayDimensions(ProtoIncompatibleArrayDimensions {
3104                    dims: dims.into_proto(),
3105                })
3106            }
3107            EvalError::TypeFromOid(v) => TypeFromOid(v.into_proto()),
3108            EvalError::InvalidRange(error) => InvalidRange(error.into_proto()),
3109            EvalError::InvalidRoleId(v) => InvalidRoleId(v.into_proto()),
3110            EvalError::InvalidPrivileges(v) => InvalidPrivileges(v.into_proto()),
3111            EvalError::LetRecLimitExceeded(v) => WmrRecursionLimitExceeded(v.into_proto()),
3112            EvalError::MultiDimensionalArraySearch => MultiDimensionalArraySearch(()),
3113            EvalError::MustNotBeNull(v) => MustNotBeNull(v.into_proto()),
3114            EvalError::InvalidIdentifier { ident, detail } => {
3115                InvalidIdentifier(ProtoInvalidIdentifier {
3116                    ident: ident.into_proto(),
3117                    detail: detail.into_proto(),
3118                })
3119            }
3120            EvalError::ArrayFillWrongArraySubscripts => ArrayFillWrongArraySubscripts(()),
3121            EvalError::MaxArraySizeExceeded(max_size) => {
3122                MaxArraySizeExceeded(u64::cast_from(*max_size))
3123            }
3124            EvalError::DateDiffOverflow { unit, a, b } => DateDiffOverflow(ProtoDateDiffOverflow {
3125                unit: unit.into_proto(),
3126                a: a.into_proto(),
3127                b: b.into_proto(),
3128            }),
3129            EvalError::IfNullError(s) => IfNullError(s.into_proto()),
3130            EvalError::LengthTooLarge => LengthTooLarge(()),
3131            EvalError::AclArrayNullElement => AclArrayNullElement(()),
3132            EvalError::MzAclArrayNullElement => MzAclArrayNullElement(()),
3133            EvalError::InvalidIanaTimezoneId(s) => InvalidIanaTimezoneId(s.into_proto()),
3134        };
3135        ProtoEvalError { kind: Some(kind) }
3136    }
3137
3138    fn from_proto(proto: ProtoEvalError) -> Result<Self, TryFromProtoError> {
3139        use proto_eval_error::Kind::*;
3140        match proto.kind {
3141            Some(kind) => match kind {
3142                CharacterNotValidForEncoding(v) => Ok(EvalError::CharacterNotValidForEncoding(v)),
3143                CharacterTooLargeForEncoding(v) => Ok(EvalError::CharacterTooLargeForEncoding(v)),
3144                DateBinOutOfRange(v) => Ok(EvalError::DateBinOutOfRange(v.into())),
3145                DivisionByZero(()) => Ok(EvalError::DivisionByZero),
3146                Unsupported(v) => Ok(EvalError::Unsupported {
3147                    feature: v.feature.into(),
3148                    discussion_no: v.discussion_no.into_rust()?,
3149                }),
3150                FloatOverflow(()) => Ok(EvalError::FloatOverflow),
3151                FloatUnderflow(()) => Ok(EvalError::FloatUnderflow),
3152                NumericFieldOverflow(()) => Ok(EvalError::NumericFieldOverflow),
3153                Float32OutOfRange(val) => Ok(EvalError::Float32OutOfRange(val.value.into())),
3154                Float64OutOfRange(val) => Ok(EvalError::Float64OutOfRange(val.value.into())),
3155                Int16OutOfRange(val) => Ok(EvalError::Int16OutOfRange(val.value.into())),
3156                Int32OutOfRange(val) => Ok(EvalError::Int32OutOfRange(val.value.into())),
3157                Int64OutOfRange(val) => Ok(EvalError::Int64OutOfRange(val.value.into())),
3158                Uint16OutOfRange(val) => Ok(EvalError::UInt16OutOfRange(val.value.into())),
3159                Uint32OutOfRange(val) => Ok(EvalError::UInt32OutOfRange(val.value.into())),
3160                Uint64OutOfRange(val) => Ok(EvalError::UInt64OutOfRange(val.value.into())),
3161                MzTimestampOutOfRange(val) => {
3162                    Ok(EvalError::MzTimestampOutOfRange(val.value.into()))
3163                }
3164                MzTimestampStepOverflow(()) => Ok(EvalError::MzTimestampStepOverflow),
3165                OidOutOfRange(val) => Ok(EvalError::OidOutOfRange(val.value.into())),
3166                IntervalOutOfRange(val) => Ok(EvalError::IntervalOutOfRange(val.value.into())),
3167                TimestampCannotBeNan(()) => Ok(EvalError::TimestampCannotBeNan),
3168                TimestampOutOfRange(()) => Ok(EvalError::TimestampOutOfRange),
3169                DateOutOfRange(()) => Ok(EvalError::DateOutOfRange),
3170                CharOutOfRange(()) => Ok(EvalError::CharOutOfRange),
3171                IndexOutOfRange(v) => Ok(EvalError::IndexOutOfRange {
3172                    provided: v.provided,
3173                    valid_end: v.valid_end,
3174                }),
3175                InvalidBase64Equals(()) => Ok(EvalError::InvalidBase64Equals),
3176                InvalidBase64Symbol(v) => char::from_proto(v).map(EvalError::InvalidBase64Symbol),
3177                InvalidBase64EndSequence(()) => Ok(EvalError::InvalidBase64EndSequence),
3178                InvalidTimezone(v) => Ok(EvalError::InvalidTimezone(v.into())),
3179                InvalidTimezoneInterval(()) => Ok(EvalError::InvalidTimezoneInterval),
3180                InvalidTimezoneConversion(()) => Ok(EvalError::InvalidTimezoneConversion),
3181                InvalidLayer(v) => Ok(EvalError::InvalidLayer {
3182                    max_layer: usize::from_proto(v.max_layer)?,
3183                    val: v.val,
3184                }),
3185                InvalidArray(error) => Ok(EvalError::InvalidArray(error.into_rust()?)),
3186                InvalidEncodingName(v) => Ok(EvalError::InvalidEncodingName(v.into())),
3187                InvalidHashAlgorithm(v) => Ok(EvalError::InvalidHashAlgorithm(v.into())),
3188                InvalidByteSequence(v) => Ok(EvalError::InvalidByteSequence {
3189                    byte_sequence: v.byte_sequence.into(),
3190                    encoding_name: v.encoding_name.into(),
3191                }),
3192                InvalidJsonbCast(v) => Ok(EvalError::InvalidJsonbCast {
3193                    from: v.from.into(),
3194                    to: v.to.into(),
3195                }),
3196                InvalidRegex(v) => Ok(EvalError::InvalidRegex(v.into())),
3197                InvalidRegexFlag(v) => Ok(EvalError::InvalidRegexFlag(char::from_proto(v)?)),
3198                InvalidParameterValue(v) => Ok(EvalError::InvalidParameterValue(v.into())),
3199                InvalidDatePart(part) => Ok(EvalError::InvalidDatePart(part.into())),
3200                KeyCannotBeNull(()) => Ok(EvalError::KeyCannotBeNull),
3201                NegSqrt(()) => Ok(EvalError::NegSqrt),
3202                NegLimit(()) => Ok(EvalError::NegLimit),
3203                NullCharacterNotPermitted(()) => Ok(EvalError::NullCharacterNotPermitted),
3204                UnknownUnits(v) => Ok(EvalError::UnknownUnits(v.into())),
3205                UnsupportedUnits(v) => {
3206                    Ok(EvalError::UnsupportedUnits(v.units.into(), v.typ.into()))
3207                }
3208                UnterminatedLikeEscapeSequence(()) => Ok(EvalError::UnterminatedLikeEscapeSequence),
3209                Parse(error) => Ok(EvalError::Parse(error.into_rust()?)),
3210                ParseHex(error) => Ok(EvalError::ParseHex(error.into_rust()?)),
3211                Internal(v) => Ok(EvalError::Internal(v.into())),
3212                InfinityOutOfDomain(v) => Ok(EvalError::InfinityOutOfDomain(v.into())),
3213                NegativeOutOfDomain(v) => Ok(EvalError::NegativeOutOfDomain(v.into())),
3214                ZeroOutOfDomain(v) => Ok(EvalError::ZeroOutOfDomain(v.into())),
3215                OutOfDomain(v) => Ok(EvalError::OutOfDomain(
3216                    v.lower.into_rust_if_some("ProtoDomainLimit::lower")?,
3217                    v.upper.into_rust_if_some("ProtoDomainLimit::upper")?,
3218                    v.id.into(),
3219                )),
3220                ComplexOutOfRange(v) => Ok(EvalError::ComplexOutOfRange(v.into())),
3221                MultipleRowsFromSubquery(()) => Ok(EvalError::MultipleRowsFromSubquery),
3222                Undefined(v) => Ok(EvalError::Undefined(v.into())),
3223                LikePatternTooLong(()) => Ok(EvalError::LikePatternTooLong),
3224                LikeEscapeTooLong(()) => Ok(EvalError::LikeEscapeTooLong),
3225                StringValueTooLong(v) => Ok(EvalError::StringValueTooLong {
3226                    target_type: v.target_type.into(),
3227                    length: usize::from_proto(v.length)?,
3228                }),
3229                MultidimensionalArrayRemovalNotSupported(()) => {
3230                    Ok(EvalError::MultidimensionalArrayRemovalNotSupported)
3231                }
3232                IncompatibleArrayDimensions(v) => Ok(EvalError::IncompatibleArrayDimensions {
3233                    dims: v.dims.into_rust()?,
3234                }),
3235                TypeFromOid(v) => Ok(EvalError::TypeFromOid(v.into())),
3236                InvalidRange(e) => Ok(EvalError::InvalidRange(e.into_rust()?)),
3237                InvalidRoleId(v) => Ok(EvalError::InvalidRoleId(v.into())),
3238                InvalidPrivileges(v) => Ok(EvalError::InvalidPrivileges(v.into())),
3239                WmrRecursionLimitExceeded(v) => Ok(EvalError::LetRecLimitExceeded(v.into())),
3240                MultiDimensionalArraySearch(()) => Ok(EvalError::MultiDimensionalArraySearch),
3241                MustNotBeNull(v) => Ok(EvalError::MustNotBeNull(v.into())),
3242                InvalidIdentifier(v) => Ok(EvalError::InvalidIdentifier {
3243                    ident: v.ident.into(),
3244                    detail: v.detail.into_rust()?,
3245                }),
3246                ArrayFillWrongArraySubscripts(()) => Ok(EvalError::ArrayFillWrongArraySubscripts),
3247                MaxArraySizeExceeded(max_size) => {
3248                    Ok(EvalError::MaxArraySizeExceeded(usize::cast_from(max_size)))
3249                }
3250                DateDiffOverflow(v) => Ok(EvalError::DateDiffOverflow {
3251                    unit: v.unit.into(),
3252                    a: v.a.into(),
3253                    b: v.b.into(),
3254                }),
3255                IfNullError(v) => Ok(EvalError::IfNullError(v.into())),
3256                LengthTooLarge(()) => Ok(EvalError::LengthTooLarge),
3257                AclArrayNullElement(()) => Ok(EvalError::AclArrayNullElement),
3258                MzAclArrayNullElement(()) => Ok(EvalError::MzAclArrayNullElement),
3259                InvalidIanaTimezoneId(s) => Ok(EvalError::InvalidIanaTimezoneId(s.into())),
3260                PrettyError(s) => Ok(EvalError::PrettyError(s.into())),
3261            },
3262            None => Err(TryFromProtoError::missing_field("ProtoEvalError::kind")),
3263        }
3264    }
3265}
3266
3267impl RustType<ProtoDims> for (usize, usize) {
3268    fn into_proto(&self) -> ProtoDims {
3269        ProtoDims {
3270            f0: self.0.into_proto(),
3271            f1: self.1.into_proto(),
3272        }
3273    }
3274
3275    fn from_proto(proto: ProtoDims) -> Result<Self, TryFromProtoError> {
3276        Ok((proto.f0.into_rust()?, proto.f1.into_rust()?))
3277    }
3278}
3279
3280#[cfg(test)]
3281mod tests {
3282    use super::*;
3283
3284    #[mz_ore::test]
3285    #[cfg_attr(miri, ignore)] // error: unsupported operation: can't call foreign function `rust_psm_stack_pointer` on OS `linux`
3286    fn test_reduce() {
3287        let relation_type = vec![
3288            SqlScalarType::Int64.nullable(true),
3289            SqlScalarType::Int64.nullable(true),
3290            SqlScalarType::Int64.nullable(false),
3291        ];
3292        let col = MirScalarExpr::column;
3293        let err = |e| MirScalarExpr::literal(Err(e), SqlScalarType::Int64);
3294        let lit = |i| MirScalarExpr::literal_ok(Datum::Int64(i), SqlScalarType::Int64);
3295        let null = || MirScalarExpr::literal_null(SqlScalarType::Int64);
3296
3297        struct TestCase {
3298            input: MirScalarExpr,
3299            output: MirScalarExpr,
3300        }
3301
3302        let test_cases = vec![
3303            TestCase {
3304                input: MirScalarExpr::CallVariadic {
3305                    func: VariadicFunc::Coalesce,
3306                    exprs: vec![lit(1)],
3307                },
3308                output: lit(1),
3309            },
3310            TestCase {
3311                input: MirScalarExpr::CallVariadic {
3312                    func: VariadicFunc::Coalesce,
3313                    exprs: vec![lit(1), lit(2)],
3314                },
3315                output: lit(1),
3316            },
3317            TestCase {
3318                input: MirScalarExpr::CallVariadic {
3319                    func: VariadicFunc::Coalesce,
3320                    exprs: vec![null(), lit(2), null()],
3321                },
3322                output: lit(2),
3323            },
3324            TestCase {
3325                input: MirScalarExpr::CallVariadic {
3326                    func: VariadicFunc::Coalesce,
3327                    exprs: vec![null(), col(0), null(), col(1), lit(2), lit(3)],
3328                },
3329                output: MirScalarExpr::CallVariadic {
3330                    func: VariadicFunc::Coalesce,
3331                    exprs: vec![col(0), col(1), lit(2)],
3332                },
3333            },
3334            TestCase {
3335                input: MirScalarExpr::CallVariadic {
3336                    func: VariadicFunc::Coalesce,
3337                    exprs: vec![col(0), col(2), col(1)],
3338                },
3339                output: MirScalarExpr::CallVariadic {
3340                    func: VariadicFunc::Coalesce,
3341                    exprs: vec![col(0), col(2)],
3342                },
3343            },
3344            TestCase {
3345                input: MirScalarExpr::CallVariadic {
3346                    func: VariadicFunc::Coalesce,
3347                    exprs: vec![lit(1), err(EvalError::DivisionByZero)],
3348                },
3349                output: lit(1),
3350            },
3351            TestCase {
3352                input: MirScalarExpr::CallVariadic {
3353                    func: VariadicFunc::Coalesce,
3354                    exprs: vec![
3355                        null(),
3356                        err(EvalError::DivisionByZero),
3357                        err(EvalError::NumericFieldOverflow),
3358                    ],
3359                },
3360                output: err(EvalError::DivisionByZero),
3361            },
3362        ];
3363
3364        for tc in test_cases {
3365            let mut actual = tc.input.clone();
3366            actual.reduce(&relation_type);
3367            assert!(
3368                actual == tc.output,
3369                "input: {}\nactual: {}\nexpected: {}",
3370                tc.input,
3371                actual,
3372                tc.output
3373            );
3374        }
3375    }
3376}