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