Skip to main content

reddb_engine/query/
evaluator.rs

1//! Scalar expression evaluator — single owner of value-level
2//! evaluation for SQL scalar `Expr` trees.
3//!
4//! Today scalar expression evaluation is fragmented:
5//!
6//! - `query::filter::Predicate::evaluate` runs comparison predicates
7//!   against a single column value.
8//! - `query::filter_compiled::CompiledFilter::evaluate` runs the
9//!   compiled filter opcode tape over a row slot, but still defers to
10//!   `Predicate::evaluate` per opcode for the actual comparison logic.
11//! - Several inlined arms in `query::core` and `query::executor`
12//!   compute projections, DEFAULT / CHECK expressions, RETURNING
13//!   columns, COMPUTED columns, and ON CONFLICT updates by walking
14//!   the AST and dispatching arithmetic / function calls inline.
15//! - `query::expr_typing` knows how to type an `Expr` against a
16//!   `Scope` but never produces a `Value` — it stops at `TypedExpr`.
17//!
18//! Operator / function / cast resolution is centralised in
19//! `schema::coercion_spine`, but **value-level dispatch** is not — so
20//! adding a new operator overload, a new implicit cast edge, or a
21//! new built-in function requires synchronised edits across each of
22//! the inline evaluators above.
23//!
24//! This module is the first vertical slice of the deep evaluator
25//! interface tracked by `draft-53-scalar-expression-evaluator`. It
26//! exposes:
27//!
28//! - [`Row`]: pluggable column-binding lookup so callers can wire
29//!   either a planner-resolved slot vector or a flat column-name map.
30//! - [`evaluate`]: the single entry point. Walks an `Expr`, resolves
31//!   operators / functions / casts through `coercion_spine`, applies
32//!   the implicit casts the spine asks for, and produces a `Value`.
33//! - [`EvalError`]: typed diagnostic surface — every failure mode the
34//!   evaluator can encounter at runtime is enumerated here so callers
35//!   don't have to parse strings.
36//!
37//! The slice is intentionally additive: callers in `filter.rs`,
38//! `filter_compiled.rs`, and `executor.rs` still own their own
39//! evaluation paths. Subsequent slices migrate those callers onto
40//! `evaluate` once the dispatch surface has proven out under the
41//! focused test set in this module.
42//!
43//! ## Semantics summary
44//!
45//! - **NULL propagation.** Arithmetic, comparison, concat, and CAST
46//!   propagate `Value::Null` — any `Null` operand short-circuits to
47//!   `Null`. `AND` / `OR` follow SQL three-valued logic.
48//! - **Arithmetic overflow.** Signed checked arithmetic; overflow
49//!   surfaces as [`EvalError::ArithmeticOverflow`] rather than wrap
50//!   or panic.
51//! - **Division.** Division by zero surfaces as
52//!   [`EvalError::DivisionByZero`]. Integer `/` truncates towards zero
53//!   and returns an integer, as does integer `%`.
54//! - **Implicit cast triggers.** When the operator catalog has no
55//!   exact-type overload, the spine returns the per-operand
56//!   coercions; this evaluator applies them via
57//!   [`coerce::coerce_via_catalog`] before dispatch.
58//! - **Unknown function rejection.** Calls that don't resolve in the
59//!   built-in function catalog produce
60//!   [`EvalError::UnknownFunction`]. Variadic / catalog-resolved
61//!   functions still return through the same dispatch.
62
63use std::sync::Arc;
64
65use super::runtime::text::{regex_is_match, RegexCache};
66use super::runtime::values::runtime_exact_numeric_cmp;
67use reddb_rql::ast::{BinOp, Expr, FieldRef, UnaryOp};
68use reddb_types::coerce::coerce_via_catalog;
69use reddb_types::coercion_spine;
70use reddb_types::function_catalog::FUNCTION_CATALOG;
71use reddb_types::operator_catalog::OperatorEntry;
72use reddb_types::{DataType, Value};
73
74/// Pluggable row-binding lookup. The evaluator stays agnostic of
75/// whether the caller has a slot vector indexed by planner-assigned
76/// position, a flat `HashMap<String, Value>`, or a graph binding —
77/// every consumer just provides a `Row` impl that resolves a
78/// `FieldRef` to a `Value`.
79pub trait Row {
80    /// Resolve a column / property reference. Returns `None` when the
81    /// reference is unknown (the evaluator surfaces this as
82    /// [`EvalError::UnknownColumn`]) or `Some(Value::Null)` when the
83    /// column exists but the row's value is null.
84    fn get(&self, field: &FieldRef) -> Option<Value>;
85
86    /// Hosts which decode stored values can report operating failures instead
87    /// of treating a denied read as an unknown or NULL column.
88    fn try_get(&self, field: &FieldRef) -> Result<Option<Value>, EvalError> {
89        Ok(self.get(field))
90    }
91
92    fn regex_cache(&self) -> Option<&RegexCache> {
93        None
94    }
95}
96
97/// Trivial `Row` impl over a flat `(table, column) -> Value` closure
98/// — useful for tests and for callers that only have a column-name
99/// map.
100impl<F> Row for F
101where
102    F: Fn(&FieldRef) -> Option<Value>,
103{
104    fn get(&self, field: &FieldRef) -> Option<Value> {
105        self(field)
106    }
107}
108
109/// Errors surfaced by [`evaluate`]. Every variant is a runtime
110/// failure shape — type-resolution failures live in
111/// `expr_typing::TypeError`, not here.
112#[derive(Debug, Clone, PartialEq)]
113pub enum EvalError {
114    /// Column / property not present in the row binding.
115    UnknownColumn(FieldRef),
116    /// Query parameter placeholders are not resolved at this layer
117    /// — the bind phase substitutes a concrete value before
118    /// evaluation.
119    UnboundParameter(usize),
120    /// Operator catalog has no overload that accepts these operand
121    /// types, even after considering implicit coercions.
122    OperatorMismatch {
123        op: BinOp,
124        lhs: DataType,
125        rhs: DataType,
126    },
127    /// Unary operator doesn't accept the operand type.
128    UnaryMismatch {
129        op: UnaryOp,
130        operand: DataType,
131    },
132    /// Function catalog has no overload matching this call's
133    /// argument types. Includes user-defined functions because
134    /// today's catalog is the static built-in table only.
135    UnknownFunction {
136        name: String,
137        args: Vec<DataType>,
138    },
139    /// Implicit cast required by the spine failed at runtime — the
140    /// catalog said the conversion was legal at `Implicit` context
141    /// but the value's bytes couldn't be converted (e.g. overflow on
142    /// `BigInt` → `Integer`).
143    ImplicitCastFailed {
144        from: DataType,
145        to: DataType,
146        reason: String,
147    },
148    /// Explicit `CAST(x AS T)` failed at runtime.
149    CastFailed {
150        from: DataType,
151        to: DataType,
152        reason: String,
153    },
154    /// Signed-integer overflow during arithmetic.
155    ArithmeticOverflow {
156        op: BinOp,
157    },
158    /// `n / 0` or `n % 0`.
159    DivisionByZero,
160    /// Numeric scalar evaluation produced an undefined or non-finite
161    /// float result (domain error, overflow, NaN, or infinity).
162    InvalidNumericResult {
163        function: String,
164        reason: String,
165    },
166    /// JSON_PARSE input was not valid JSON text.
167    JsonParseFailed {
168        reason: String,
169    },
170    InvalidRegularExpression,
171    RegexArgumentType,
172    CronFailed(String),
173    /// Decoding an expression input would exceed the host's read allowance.
174    ReadLimitExceeded {
175        required_bytes: usize,
176        limit_bytes: usize,
177    },
178    /// `IN (...)` against an empty value list — preserves the legacy
179    /// "always false" semantic but recorded explicitly so the
180    /// optimiser can fold it.
181    EmptyInList,
182}
183
184impl std::fmt::Display for EvalError {
185    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
186        match self {
187            EvalError::UnknownColumn(field) => write!(f, "unknown column: {field:?}"),
188            EvalError::UnboundParameter(idx) => {
189                write!(f, "unbound query parameter: ${idx}")
190            }
191            EvalError::OperatorMismatch { op, lhs, rhs } => {
192                write!(f, "operator {op:?} not defined for ({lhs:?}, {rhs:?})")
193            }
194            EvalError::UnaryMismatch { op, operand } => {
195                write!(f, "unary {op:?} not defined for {operand:?}")
196            }
197            EvalError::UnknownFunction { name, args } => {
198                write!(f, "unknown function: {name}({args:?})")
199            }
200            EvalError::ImplicitCastFailed { from, to, reason } => {
201                write!(f, "implicit cast {from:?} -> {to:?} failed: {reason}")
202            }
203            EvalError::CastFailed { from, to, reason } => {
204                write!(f, "cast {from:?} -> {to:?} failed: {reason}")
205            }
206            EvalError::ArithmeticOverflow { op } => {
207                write!(f, "arithmetic overflow in {op:?}")
208            }
209            EvalError::DivisionByZero => write!(f, "division by zero"),
210            EvalError::InvalidNumericResult { function, reason } => {
211                write!(f, "invalid numeric result in {function}: {reason}")
212            }
213            EvalError::CronFailed(message) => f.write_str(message),
214            EvalError::JsonParseFailed { reason } => {
215                write!(f, "JSON_PARSE failed to parse JSON: {reason}")
216            }
217            EvalError::InvalidRegularExpression => f.write_str("invalid regular expression"),
218            EvalError::RegexArgumentType => f.write_str("operator ~ requires text operands"),
219            EvalError::ReadLimitExceeded {
220                required_bytes,
221                limit_bytes,
222            } => write!(
223                f,
224                "read memory limit exceeded: requires {required_bytes} bytes, limit {limit_bytes} bytes"
225            ),
226            EvalError::EmptyInList => write!(f, "IN list is empty"),
227        }
228    }
229}
230
231impl std::error::Error for EvalError {}
232
233/// Evaluate a scalar `Expr` against a row binding. Single entry
234/// point for the deep evaluator interface — every recursive call
235/// folds back through this function so the resolution surface stays
236/// uniform.
237pub fn evaluate(expr: &Expr, row: &dyn Row) -> Result<Value, EvalError> {
238    evaluate_with_literal_decoder(expr, row, &|value| Ok(value.clone()))
239}
240
241/// Decode only literals reached by the typed walk. Hosts retain resource and
242/// secret policy without cloning the AST or eagerly expanding unused branches.
243pub fn evaluate_with_literal_decoder(
244    expr: &Expr,
245    row: &dyn Row,
246    decode_literal: &impl Fn(&Value) -> Result<Value, EvalError>,
247) -> Result<Value, EvalError> {
248    match expr {
249        Expr::Literal { value, .. } => decode_literal(value),
250        Expr::Column { field, .. } => row
251            .try_get(field)?
252            .ok_or_else(|| EvalError::UnknownColumn(field.clone())),
253        Expr::Parameter { index, .. } => Err(EvalError::UnboundParameter(*index)),
254        Expr::UnaryOp { op, operand, .. } => eval_unary(*op, operand, row, decode_literal),
255        Expr::BinaryOp { op, lhs, rhs, .. } => eval_binary(*op, lhs, rhs, row, decode_literal),
256        Expr::Cast { inner, target, .. } => eval_cast(inner, *target, row, decode_literal),
257        Expr::FunctionCall { name, args, .. } => eval_function(name, args, row, decode_literal),
258        Expr::Case {
259            branches, else_, ..
260        } => eval_case(branches, else_.as_deref(), row, decode_literal),
261        Expr::IsNull {
262            operand, negated, ..
263        } => {
264            let v = evaluate_with_literal_decoder(operand, row, decode_literal)?;
265            let is_null = v.is_null();
266            Ok(Value::Boolean(if *negated { !is_null } else { is_null }))
267        }
268        Expr::InList {
269            target,
270            values,
271            negated,
272            ..
273        } => eval_in_list(target, values, *negated, row, decode_literal),
274        Expr::Between {
275            target,
276            low,
277            high,
278            negated,
279            ..
280        } => eval_between(target, low, high, *negated, row, decode_literal),
281        Expr::Subquery { .. } => Err(EvalError::UnknownFunction {
282            name: "SUBQUERY".to_string(),
283            args: Vec::new(),
284        }),
285        Expr::WindowFunctionCall { name, .. } => Err(EvalError::UnknownFunction {
286            name: format!("{name} OVER (...)"),
287            args: Vec::new(),
288        }),
289    }
290}
291
292fn eval_unary(
293    op: UnaryOp,
294    operand: &Expr,
295    row: &dyn Row,
296    decode_literal: &impl Fn(&Value) -> Result<Value, EvalError>,
297) -> Result<Value, EvalError> {
298    let v = evaluate_with_literal_decoder(operand, row, decode_literal)?;
299    if v.is_null() {
300        return Ok(Value::Null);
301    }
302    match op {
303        UnaryOp::Neg => match &v {
304            Value::Integer(n) => n
305                .checked_neg()
306                .map(Value::Integer)
307                .ok_or(EvalError::ArithmeticOverflow { op: BinOp::Sub }),
308            Value::BigInt(n) => n
309                .checked_neg()
310                .map(Value::BigInt)
311                .ok_or(EvalError::ArithmeticOverflow { op: BinOp::Sub }),
312            Value::Float(n) => Ok(Value::Float(-*n)),
313            Value::Decimal(n) => n
314                .checked_neg()
315                .map(Value::Decimal)
316                .ok_or(EvalError::ArithmeticOverflow { op: BinOp::Sub }),
317            other => Err(EvalError::UnaryMismatch {
318                op,
319                operand: other.data_type(),
320            }),
321        },
322        UnaryOp::Not => match &v {
323            Value::Boolean(b) => Ok(Value::Boolean(!b)),
324            other => Err(EvalError::UnaryMismatch {
325                op,
326                operand: other.data_type(),
327            }),
328        },
329    }
330}
331
332fn eval_binary(
333    op: BinOp,
334    lhs: &Expr,
335    rhs: &Expr,
336    row: &dyn Row,
337    decode_literal: &impl Fn(&Value) -> Result<Value, EvalError>,
338) -> Result<Value, EvalError> {
339    // Logical ops use SQL three-valued logic so we eval both sides
340    // and short-circuit on Null *after* type-checking; arithmetic /
341    // comparison / concat short-circuit before dispatch.
342    let l = evaluate_with_literal_decoder(lhs, row, decode_literal)?;
343    let r = evaluate_with_literal_decoder(rhs, row, decode_literal)?;
344
345    match op {
346        BinOp::And => return three_valued_and(&l, &r),
347        BinOp::Or => return three_valued_or(&l, &r),
348        _ => {}
349    }
350
351    if l.is_null() || r.is_null() {
352        return Ok(Value::Null);
353    }
354
355    // Compare exact numerics before promotion can round large values or
356    // reject an unsigned integer outside the signed range.
357    if matches!(
358        op,
359        BinOp::Eq | BinOp::Ne | BinOp::Lt | BinOp::Le | BinOp::Gt | BinOp::Ge
360    ) {
361        if let Some(order) = runtime_exact_numeric_cmp(&l, &r) {
362            return Ok(Value::Boolean(match op {
363                BinOp::Eq => order.is_eq(),
364                BinOp::Ne => !order.is_eq(),
365                BinOp::Lt => order.is_lt(),
366                BinOp::Le => !order.is_gt(),
367                BinOp::Gt => order.is_gt(),
368                BinOp::Ge => !order.is_lt(),
369                _ => unreachable!("integer comparison operator was admitted"),
370            }));
371        }
372    }
373
374    let lhs_dt = l.data_type();
375    let rhs_dt = r.data_type();
376    let (entry, coercions) =
377        coercion_spine::resolve_binop(op, lhs_dt, rhs_dt).ok_or(EvalError::OperatorMismatch {
378            op,
379            lhs: lhs_dt,
380            rhs: rhs_dt,
381        })?;
382
383    let l = match coercions.at(0) {
384        Some(target) => apply_implicit_cast(&l, lhs_dt, target)?,
385        None => l,
386    };
387    let r = match coercions.at(1) {
388        Some(target) => apply_implicit_cast(&r, rhs_dt, target)?,
389        None => r,
390    };
391
392    dispatch_binop(op, entry, l, r)
393}
394
395fn dispatch_binop(
396    op: BinOp,
397    entry: &OperatorEntry,
398    l: Value,
399    r: Value,
400) -> Result<Value, EvalError> {
401    match op {
402        BinOp::Add => arith_add(entry, l, r),
403        BinOp::Sub => arith_sub(entry, l, r),
404        BinOp::Mul => arith_mul(entry, l, r),
405        BinOp::Div => arith_div(entry, l, r),
406        BinOp::Mod => arith_mod(entry, l, r),
407        BinOp::Concat => match (&l, &r) {
408            (Value::Text(a), Value::Text(b)) => {
409                let mut s = String::with_capacity(a.len() + b.len());
410                s.push_str(a);
411                s.push_str(b);
412                Ok(Value::Text(Arc::from(s)))
413            }
414            _ => Err(EvalError::OperatorMismatch {
415                op,
416                lhs: l.data_type(),
417                rhs: r.data_type(),
418            }),
419        },
420        BinOp::Eq => Ok(Value::Boolean(values_equal(&l, &r))),
421        BinOp::Ne => Ok(Value::Boolean(!values_equal(&l, &r))),
422        BinOp::Lt => cmp_op(op, l, r, |o| o == std::cmp::Ordering::Less),
423        BinOp::Le => cmp_op(op, l, r, |o| o != std::cmp::Ordering::Greater),
424        BinOp::Gt => cmp_op(op, l, r, |o| o == std::cmp::Ordering::Greater),
425        BinOp::Ge => cmp_op(op, l, r, |o| o != std::cmp::Ordering::Less),
426        BinOp::And | BinOp::Or => unreachable!("handled before dispatch"),
427    }
428}
429
430fn arith_add(entry: &OperatorEntry, l: Value, r: Value) -> Result<Value, EvalError> {
431    match entry.return_type {
432        DataType::Integer => match (l, r) {
433            (Value::Integer(a), Value::Integer(b)) => a
434                .checked_add(b)
435                .map(Value::Integer)
436                .ok_or(EvalError::ArithmeticOverflow { op: BinOp::Add }),
437            _ => unreachable_after_coercion("Add", DataType::Integer),
438        },
439        DataType::BigInt => match (l, r) {
440            (Value::BigInt(a), Value::BigInt(b)) => a
441                .checked_add(b)
442                .map(Value::BigInt)
443                .ok_or(EvalError::ArithmeticOverflow { op: BinOp::Add }),
444            _ => unreachable_after_coercion("Add", DataType::BigInt),
445        },
446        DataType::Float => checked_float_binop(BinOp::Add, as_f64(&l) + as_f64(&r)),
447        DataType::Decimal => match (l, r) {
448            (Value::Decimal(a), Value::Decimal(b)) => a
449                .checked_add(b)
450                .map(Value::Decimal)
451                .ok_or(EvalError::ArithmeticOverflow { op: BinOp::Add }),
452            _ => unreachable_after_coercion("Add", DataType::Decimal),
453        },
454        other => Err(EvalError::OperatorMismatch {
455            op: BinOp::Add,
456            lhs: other,
457            rhs: other,
458        }),
459    }
460}
461
462fn arith_sub(entry: &OperatorEntry, l: Value, r: Value) -> Result<Value, EvalError> {
463    match entry.return_type {
464        DataType::Integer => match (l, r) {
465            (Value::Integer(a), Value::Integer(b)) => a
466                .checked_sub(b)
467                .map(Value::Integer)
468                .ok_or(EvalError::ArithmeticOverflow { op: BinOp::Sub }),
469            _ => unreachable_after_coercion("Sub", DataType::Integer),
470        },
471        DataType::BigInt => match (l, r) {
472            (Value::BigInt(a), Value::BigInt(b)) => a
473                .checked_sub(b)
474                .map(Value::BigInt)
475                .ok_or(EvalError::ArithmeticOverflow { op: BinOp::Sub }),
476            _ => unreachable_after_coercion("Sub", DataType::BigInt),
477        },
478        DataType::Float => checked_float_binop(BinOp::Sub, as_f64(&l) - as_f64(&r)),
479        DataType::Decimal => match (l, r) {
480            (Value::Decimal(a), Value::Decimal(b)) => a
481                .checked_sub(b)
482                .map(Value::Decimal)
483                .ok_or(EvalError::ArithmeticOverflow { op: BinOp::Sub }),
484            _ => unreachable_after_coercion("Sub", DataType::Decimal),
485        },
486        other => Err(EvalError::OperatorMismatch {
487            op: BinOp::Sub,
488            lhs: other,
489            rhs: other,
490        }),
491    }
492}
493
494fn arith_mul(entry: &OperatorEntry, l: Value, r: Value) -> Result<Value, EvalError> {
495    match entry.return_type {
496        DataType::Integer => match (l, r) {
497            (Value::Integer(a), Value::Integer(b)) => a
498                .checked_mul(b)
499                .map(Value::Integer)
500                .ok_or(EvalError::ArithmeticOverflow { op: BinOp::Mul }),
501            _ => unreachable_after_coercion("Mul", DataType::Integer),
502        },
503        DataType::BigInt => match (l, r) {
504            (Value::BigInt(a), Value::BigInt(b)) => a
505                .checked_mul(b)
506                .map(Value::BigInt)
507                .ok_or(EvalError::ArithmeticOverflow { op: BinOp::Mul }),
508            _ => unreachable_after_coercion("Mul", DataType::BigInt),
509        },
510        DataType::Float => checked_float_binop(BinOp::Mul, as_f64(&l) * as_f64(&r)),
511        other => Err(EvalError::OperatorMismatch {
512            op: BinOp::Mul,
513            lhs: other,
514            rhs: other,
515        }),
516    }
517}
518
519fn arith_div(entry: &OperatorEntry, l: Value, r: Value) -> Result<Value, EvalError> {
520    match entry.return_type {
521        DataType::Integer | DataType::BigInt => divide_signed_integers(&l, &r)
522            .expect("integer division overload must have signed integer operands"),
523        DataType::Float => {
524            let denom = as_f64(&r);
525            if denom == 0.0 {
526                return Err(EvalError::DivisionByZero);
527            }
528            checked_float_binop(BinOp::Div, as_f64(&l) / denom)
529        }
530        other => Err(EvalError::OperatorMismatch {
531            op: BinOp::Div,
532            lhs: other,
533            rhs: other,
534        }),
535    }
536}
537
538pub(crate) fn divide_signed_integers(l: &Value, r: &Value) -> Option<Result<Value, EvalError>> {
539    let (numerator, denominator, result): (i64, i64, fn(i64) -> Value) = match (l, r) {
540        (Value::Integer(a), Value::Integer(b)) => (*a, *b, Value::Integer),
541        (Value::BigInt(a), Value::Integer(b) | Value::BigInt(b))
542        | (Value::Integer(a), Value::BigInt(b)) => (*a, *b, Value::BigInt),
543        _ => return None,
544    };
545    if denominator == 0 {
546        return Some(Err(EvalError::DivisionByZero));
547    }
548    Some(
549        numerator
550            .checked_div(denominator)
551            .map(result)
552            .ok_or(EvalError::ArithmeticOverflow { op: BinOp::Div }),
553    )
554}
555
556fn arith_mod(entry: &OperatorEntry, l: Value, r: Value) -> Result<Value, EvalError> {
557    match entry.return_type {
558        DataType::Integer => match (l, r) {
559            (Value::Integer(_), Value::Integer(0)) => Err(EvalError::DivisionByZero),
560            (Value::Integer(a), Value::Integer(b)) => a
561                .checked_rem(b)
562                .map(Value::Integer)
563                .ok_or(EvalError::ArithmeticOverflow { op: BinOp::Mod }),
564            _ => unreachable_after_coercion("Mod", DataType::Integer),
565        },
566        DataType::BigInt => match (l, r) {
567            (Value::BigInt(_), Value::BigInt(0)) => Err(EvalError::DivisionByZero),
568            (Value::BigInt(a), Value::BigInt(b)) => a
569                .checked_rem(b)
570                .map(Value::BigInt)
571                .ok_or(EvalError::ArithmeticOverflow { op: BinOp::Mod }),
572            _ => unreachable_after_coercion("Mod", DataType::BigInt),
573        },
574        other => Err(EvalError::OperatorMismatch {
575            op: BinOp::Mod,
576            lhs: other,
577            rhs: other,
578        }),
579    }
580}
581
582fn unreachable_after_coercion(op: &'static str, expected: DataType) -> Result<Value, EvalError> {
583    Err(EvalError::OperatorMismatch {
584        op: match op {
585            "Add" => BinOp::Add,
586            "Sub" => BinOp::Sub,
587            "Mul" => BinOp::Mul,
588            "Div" => BinOp::Div,
589            "Mod" => BinOp::Mod,
590            _ => BinOp::Add,
591        },
592        lhs: expected,
593        rhs: expected,
594    })
595}
596
597fn checked_float_binop(op: BinOp, value: f64) -> Result<Value, EvalError> {
598    if value.is_finite() {
599        Ok(Value::Float(value))
600    } else {
601        Err(EvalError::InvalidNumericResult {
602            function: format!("{op:?}"),
603            reason: "result is NaN or infinite".to_string(),
604        })
605    }
606}
607
608fn as_f64(v: &Value) -> f64 {
609    match v {
610        Value::Float(x) => *x,
611        Value::Integer(x) => *x as f64,
612        Value::BigInt(x) => *x as f64,
613        Value::UnsignedInteger(x) => *x as f64,
614        Value::Decimal(x) => reddb_types::types::decimal_to_f64(*x),
615        _ => 0.0,
616    }
617}
618
619fn cmp_op<F>(op: BinOp, l: Value, r: Value, pick: F) -> Result<Value, EvalError>
620where
621    F: Fn(std::cmp::Ordering) -> bool,
622{
623    let ord = compare_values(&l, &r).ok_or(EvalError::OperatorMismatch {
624        op,
625        lhs: l.data_type(),
626        rhs: r.data_type(),
627    })?;
628    Ok(Value::Boolean(pick(ord)))
629}
630
631/// Total ordering for the numeric and text families that the
632/// catalog declares comparison overloads for. Returns `None` when
633/// the values aren't comparable — callers surface this as
634/// [`EvalError::OperatorMismatch`].
635fn compare_values(a: &Value, b: &Value) -> Option<std::cmp::Ordering> {
636    if let Some(order) = runtime_exact_numeric_cmp(a, b) {
637        return Some(order);
638    }
639    match (a, b) {
640        (Value::Temperature(x), Value::Temperature(y)) => Some(x.cmp(y)),
641        (Value::Integer(x), Value::Integer(y)) => Some(x.cmp(y)),
642        (Value::BigInt(x), Value::BigInt(y)) => Some(x.cmp(y)),
643        (Value::Float(x), Value::Float(y)) => x.partial_cmp(y),
644        (Value::Text(x), Value::Text(y)) => Some(x.as_ref().cmp(y.as_ref())),
645        (Value::Boolean(x), Value::Boolean(y)) => Some(x.cmp(y)),
646        (Value::Timestamp(x), Value::Timestamp(y)) => Some(x.cmp(y)),
647        (Value::TimestampMs(x), Value::TimestampMs(y)) => Some(x.cmp(y)),
648        (Value::Date(x), Value::Date(y)) => Some(x.cmp(y)),
649        (Value::Time(x), Value::Time(y)) => Some(x.cmp(y)),
650        (Value::Uuid(x), Value::Uuid(y)) => Some(x.cmp(y)),
651        (Value::Decimal(x), Value::Decimal(y)) => Some(x.cmp(y)),
652        // Cross-numeric — operand coercion should have homogenised
653        // these but if a caller invokes the evaluator with mixed
654        // numerics directly, fall back to f64 ordering.
655        (Value::Integer(_) | Value::Float(_) | Value::BigInt(_), _) => {
656            let l = as_f64(a);
657            let r = as_f64(b);
658            l.partial_cmp(&r)
659        }
660        _ => None,
661    }
662}
663
664fn values_equal(a: &Value, b: &Value) -> bool {
665    if let Some(order) = runtime_exact_numeric_cmp(a, b) {
666        return order.is_eq();
667    }
668    match (a, b) {
669        (Value::Float(x), Value::Float(y)) => x == y,
670        _ => a == b,
671    }
672}
673
674fn three_valued_and(l: &Value, r: &Value) -> Result<Value, EvalError> {
675    match (l, r) {
676        (Value::Boolean(false), _) | (_, Value::Boolean(false)) => Ok(Value::Boolean(false)),
677        (Value::Boolean(true), Value::Boolean(true)) => Ok(Value::Boolean(true)),
678        (Value::Null, _) | (_, Value::Null) => Ok(Value::Null),
679        _ => Err(EvalError::OperatorMismatch {
680            op: BinOp::And,
681            lhs: l.data_type(),
682            rhs: r.data_type(),
683        }),
684    }
685}
686
687fn three_valued_or(l: &Value, r: &Value) -> Result<Value, EvalError> {
688    match (l, r) {
689        (Value::Boolean(true), _) | (_, Value::Boolean(true)) => Ok(Value::Boolean(true)),
690        (Value::Boolean(false), Value::Boolean(false)) => Ok(Value::Boolean(false)),
691        (Value::Null, _) | (_, Value::Null) => Ok(Value::Null),
692        _ => Err(EvalError::OperatorMismatch {
693            op: BinOp::Or,
694            lhs: l.data_type(),
695            rhs: r.data_type(),
696        }),
697    }
698}
699
700fn apply_implicit_cast(value: &Value, src: DataType, target: DataType) -> Result<Value, EvalError> {
701    if src == target {
702        return Ok(value.clone());
703    }
704    coerce_via_catalog(value, src, target, None).map_err(|reason| EvalError::ImplicitCastFailed {
705        from: src,
706        to: target,
707        reason,
708    })
709}
710
711fn eval_cast(
712    inner: &Expr,
713    target: DataType,
714    row: &dyn Row,
715    decode_literal: &impl Fn(&Value) -> Result<Value, EvalError>,
716) -> Result<Value, EvalError> {
717    let v = evaluate_with_literal_decoder(inner, row, decode_literal)?;
718    if v.is_null() {
719        return Ok(Value::Null);
720    }
721    let src = v.data_type();
722    if src == target {
723        return Ok(v);
724    }
725    coerce_via_catalog(&v, src, target, None).map_err(|reason| EvalError::CastFailed {
726        from: src,
727        to: target,
728        reason,
729    })
730}
731
732fn eval_function(
733    name: &str,
734    args: &[Expr],
735    row: &dyn Row,
736    decode_literal: &impl Fn(&Value) -> Result<Value, EvalError>,
737) -> Result<Value, EvalError> {
738    if name.eq_ignore_ascii_case("CRON_OCCURRENCES") {
739        return Err(EvalError::CronFailed(
740            "cron_occurrences requires a top-level SELECT projection".into(),
741        ));
742    }
743    // COALESCE has SQL-special semantics that the catalog can't
744    // express (variadic + uniform arg type unifies poorly with
745    // first-non-null). Handle it before catalog dispatch so we
746    // preserve `COALESCE(int, int) -> int` rather than coercing
747    // every argument to Text.
748    if name.eq_ignore_ascii_case("COALESCE") {
749        for arg in args {
750            let v = evaluate_with_literal_decoder(arg, row, decode_literal)?;
751            if !v.is_null() {
752                return Ok(v);
753            }
754        }
755        return Ok(Value::Null);
756    }
757
758    let arg_values: Vec<Value> = args
759        .iter()
760        .map(|a| evaluate_with_literal_decoder(a, row, decode_literal))
761        .collect::<Result<Vec<_>, _>>()?;
762    if name.eq_ignore_ascii_case("REGEXP_LIKE") {
763        return match arg_values.as_slice() {
764            [Value::Text(text), Value::Text(pattern)] => row
765                .regex_cache()
766                .map_or_else(
767                    || regex_is_match(text, pattern),
768                    |cache| cache.is_match(text, pattern),
769                )
770                .map(Value::Boolean)
771                .map_err(|_| EvalError::InvalidRegularExpression),
772            [Value::Null, Value::Null | Value::Text(_)] | [Value::Text(_), Value::Null] => {
773                Ok(Value::Null)
774            }
775            _ => Err(EvalError::RegexArgumentType),
776        };
777    }
778    let arg_types: Vec<DataType> = arg_values.iter().map(|v| v.data_type()).collect();
779
780    // Strict NULL propagation applies only to non-variadic built-ins.
781    // Variadic functions such as CONCAT own their NULL semantics.
782    // Unknown functions with NULL arguments must still surface as
783    // `UnknownFunction` rather than silently returning NULL.
784    if arg_values.iter().any(Value::is_null)
785        && FUNCTION_CATALOG
786            .iter()
787            .any(|entry| entry.name.eq_ignore_ascii_case(name))
788        && FUNCTION_CATALOG
789            .iter()
790            .filter(|entry| entry.name.eq_ignore_ascii_case(name))
791            .all(|entry| !entry.variadic)
792    {
793        return Ok(Value::Null);
794    }
795
796    let (entry, coercions) =
797        coercion_spine::resolve_function(name, &arg_types).ok_or_else(|| {
798            EvalError::UnknownFunction {
799                name: name.to_string(),
800                args: arg_types.clone(),
801            }
802        })?;
803
804    // Apply per-arg implicit casts.
805    let mut coerced: Vec<Value> = Vec::with_capacity(arg_values.len());
806    for (idx, value) in arg_values.into_iter().enumerate() {
807        let src = arg_types[idx];
808        match coercions.at(idx) {
809            Some(target) if src != target => {
810                coerced.push(apply_implicit_cast(&value, src, target)?);
811            }
812            _ => coerced.push(value),
813        }
814    }
815
816    // NULL propagation for built-ins: if any non-variadic argument
817    // is null, return null. Variadic / aggregate semantics handle
818    // null differently and aren't in scope for this slice.
819    if !entry.variadic && coerced.iter().any(|v| v.is_null()) {
820        return Ok(Value::Null);
821    }
822
823    dispatch_function(entry.name, &coerced)
824}
825
826fn dispatch_function(name: &str, args: &[Value]) -> Result<Value, EvalError> {
827    match name {
828        "CRON" | "CRON_NEXT" | "CRON_OVERLAPS" => {
829            super::runtime::value_functions::evaluate_cron_function(name, args)
830                .map_err(|reason| EvalError::CronFailed(format!("{name}: {reason}")))
831        }
832        "TEMPERATURE" | "TEMPERATURE_UNIT" | "TEMPERATURE_VALUE" => {
833            super::runtime::value_functions::temperature_function(name, args).ok_or_else(|| {
834                EvalError::UnknownFunction {
835                    name: name.into(),
836                    args: args.iter().map(Value::data_type).collect(),
837                }
838            })
839        }
840        "UPPER" => match &args[0] {
841            Value::Text(s) => Ok(Value::Text(Arc::from(s.to_uppercase()))),
842            other => Err(EvalError::UnknownFunction {
843                name: name.to_string(),
844                args: vec![other.data_type()],
845            }),
846        },
847        "LOWER" => match &args[0] {
848            Value::Text(s) => Ok(Value::Text(Arc::from(s.to_lowercase()))),
849            other => Err(EvalError::UnknownFunction {
850                name: name.to_string(),
851                args: vec![other.data_type()],
852            }),
853        },
854        "TRIM" => trim_function(name, args, true, true),
855        "LTRIM" => trim_function(name, args, true, false),
856        "RTRIM" => trim_function(name, args, false, true),
857        "LENGTH" | "CHAR_LENGTH" | "CHARACTER_LENGTH" => match &args[0] {
858            Value::Text(s) => Ok(Value::Integer(s.chars().count() as i64)),
859            other => Err(EvalError::UnknownFunction {
860                name: name.to_string(),
861                args: vec![other.data_type()],
862            }),
863        },
864        "OCTET_LENGTH" => match &args[0] {
865            Value::Text(s) => Ok(Value::Integer(s.len() as i64)),
866            Value::Blob(b) => Ok(Value::Integer(b.len() as i64)),
867            other => Err(EvalError::UnknownFunction {
868                name: name.to_string(),
869                args: vec![other.data_type()],
870            }),
871        },
872        "CONCAT" => {
873            let mut out = String::new();
874            for arg in args {
875                match arg {
876                    Value::Null => {}
877                    Value::Text(value) => out.push_str(value),
878                    _ => {
879                        return Err(EvalError::UnknownFunction {
880                            name: name.to_string(),
881                            args: args.iter().map(Value::data_type).collect(),
882                        })
883                    }
884                }
885            }
886            Ok(Value::Text(Arc::from(out)))
887        }
888        "JSON_PARSE" => json_parse_value(&args[0]),
889        "JSON_EXTRACT" => Ok(json_extract_value(&args[0], &args[1], false)),
890        "JSON_EXTRACT_TEXT" => Ok(json_extract_value(&args[0], &args[1], true)),
891        "CONTAINS" => Ok(contains_value(&args[0], &args[1])),
892        "ABS" => match &args[0] {
893            Value::Integer(n) => n
894                .checked_abs()
895                .map(Value::Integer)
896                .ok_or(EvalError::ArithmeticOverflow { op: BinOp::Sub }),
897            Value::BigInt(n) => n
898                .checked_abs()
899                .map(Value::BigInt)
900                .ok_or(EvalError::ArithmeticOverflow { op: BinOp::Sub }),
901            Value::Float(n) => Ok(Value::Float(n.abs())),
902            Value::Decimal(n) => n
903                .checked_abs()
904                .map(Value::Decimal)
905                .ok_or(EvalError::ArithmeticOverflow { op: BinOp::Sub }),
906            other => Err(EvalError::UnknownFunction {
907                name: name.to_string(),
908                args: vec![other.data_type()],
909            }),
910        },
911        "SQRT" => unary_math(name, args, |x| {
912            if x < 0.0 {
913                return Err("input must be greater than or equal to zero");
914            }
915            Ok(x.sqrt())
916        }),
917        "POWER" | "POW" => binary_math(name, args, |base, exp| Ok(base.powf(exp))),
918        "EXP" => unary_math(name, args, |x| Ok(x.exp())),
919        "LN" => unary_math(name, args, |x| {
920            if x <= 0.0 {
921                return Err("input must be greater than zero");
922            }
923            Ok(x.ln())
924        }),
925        "LOG" if args.len() == 1 => unary_math(name, args, |x| {
926            if x <= 0.0 {
927                return Err("input must be greater than zero");
928            }
929            Ok(x.log10())
930        }),
931        "LOG" => binary_math(name, args, |base, x| {
932            if base <= 0.0 {
933                return Err("base must be greater than zero");
934            }
935            if base == 1.0 {
936                return Err("base must not equal one");
937            }
938            if x <= 0.0 {
939                return Err("input must be greater than zero");
940            }
941            Ok(x.log(base))
942        }),
943        "LOG10" => unary_math(name, args, |x| {
944            if x <= 0.0 {
945                return Err("input must be greater than zero");
946            }
947            Ok(x.log10())
948        }),
949        "SIN" => unary_math(name, args, |x| Ok(x.sin())),
950        "COS" => unary_math(name, args, |x| Ok(x.cos())),
951        "TAN" => unary_math(name, args, |x| Ok(x.tan())),
952        "ASIN" | "ARCSIN" => unary_math(name, args, |x| {
953            if !(-1.0..=1.0).contains(&x) {
954                return Err("input must be between -1 and 1");
955            }
956            Ok(x.asin())
957        }),
958        "ACOS" | "ARCCOS" => unary_math(name, args, |x| {
959            if !(-1.0..=1.0).contains(&x) {
960                return Err("input must be between -1 and 1");
961            }
962            Ok(x.acos())
963        }),
964        "ATAN" | "ARCTAN" => unary_math(name, args, |x| Ok(x.atan())),
965        "ATAN2" => binary_math(name, args, |y, x| Ok(y.atan2(x))),
966        "COT" => unary_math(name, args, |x| {
967            let tan = x.tan();
968            if tan == 0.0 {
969                return Err("input must not produce zero tangent");
970            }
971            Ok(1.0 / tan)
972        }),
973        "DEGREES" => unary_math(name, args, |x| Ok(x.to_degrees())),
974        "RADIANS" => unary_math(name, args, |x| Ok(x.to_radians())),
975        "PI" => checked_math_result(name, std::f64::consts::PI),
976        // Functions whose runtime body the slice doesn't yet cover
977        // surface as UnknownFunction with the resolved arg types so
978        // callers can see the catalog matched but the dispatch
979        // didn't. Subsequent slices fill in CONCAT, time functions, …
980        other => Err(EvalError::UnknownFunction {
981            name: other.to_string(),
982            args: args.iter().map(|v| v.data_type()).collect(),
983        }),
984    }
985}
986
987fn trim_function(name: &str, args: &[Value], left: bool, right: bool) -> Result<Value, EvalError> {
988    if args.len() != 1 {
989        return Err(EvalError::UnknownFunction {
990            name: name.to_string(),
991            args: args.iter().map(|v| v.data_type()).collect(),
992        });
993    }
994
995    match &args[0] {
996        Value::Text(s) => {
997            let trimmed = match (left, right) {
998                (true, true) => s.trim(),
999                (true, false) => s.trim_start(),
1000                (false, true) => s.trim_end(),
1001                (false, false) => s,
1002            };
1003            Ok(Value::Text(Arc::from(trimmed)))
1004        }
1005        other => Err(EvalError::UnknownFunction {
1006            name: name.to_string(),
1007            args: vec![other.data_type()],
1008        }),
1009    }
1010}
1011
1012fn unary_math<F>(name: &str, args: &[Value], op: F) -> Result<Value, EvalError>
1013where
1014    F: FnOnce(f64) -> Result<f64, &'static str>,
1015{
1016    let input = math_arg(name, args.first(), 0)?;
1017    let value = op(input).map_err(|reason| EvalError::InvalidNumericResult {
1018        function: name.to_string(),
1019        reason: reason.to_string(),
1020    })?;
1021    checked_math_result(name, value)
1022}
1023
1024fn binary_math<F>(name: &str, args: &[Value], op: F) -> Result<Value, EvalError>
1025where
1026    F: FnOnce(f64, f64) -> Result<f64, &'static str>,
1027{
1028    let left = math_arg(name, args.first(), 0)?;
1029    let right = math_arg(name, args.get(1), 1)?;
1030    let value = op(left, right).map_err(|reason| EvalError::InvalidNumericResult {
1031        function: name.to_string(),
1032        reason: reason.to_string(),
1033    })?;
1034    checked_math_result(name, value)
1035}
1036
1037fn math_arg(name: &str, value: Option<&Value>, index: usize) -> Result<f64, EvalError> {
1038    let value = value.ok_or_else(|| EvalError::UnknownFunction {
1039        name: name.to_string(),
1040        args: Vec::new(),
1041    })?;
1042    let numeric = as_f64(value);
1043    if numeric.is_finite() {
1044        Ok(numeric)
1045    } else {
1046        Err(EvalError::InvalidNumericResult {
1047            function: name.to_string(),
1048            reason: format!("argument {index} is NaN or infinite"),
1049        })
1050    }
1051}
1052
1053fn checked_math_result(name: &str, value: f64) -> Result<Value, EvalError> {
1054    if value.is_finite() {
1055        Ok(Value::Float(value))
1056    } else {
1057        Err(EvalError::InvalidNumericResult {
1058            function: name.to_string(),
1059            reason: "result is NaN or infinite".to_string(),
1060        })
1061    }
1062}
1063
1064fn json_extract_value(input: &Value, path: &Value, as_text: bool) -> Value {
1065    let Value::Text(path) = path else {
1066        return Value::Null;
1067    };
1068    let Some(json) = value_to_json(input) else {
1069        return Value::Null;
1070    };
1071    let Some(steps) = parse_json_path(path) else {
1072        return Value::Null;
1073    };
1074    let Some(target) = json_path_get(&json, &steps) else {
1075        return Value::Null;
1076    };
1077
1078    if as_text {
1079        match target {
1080            crate::serde_json::Value::String(value) => Value::text(value.clone()),
1081            crate::serde_json::Value::Null => Value::Null,
1082            crate::serde_json::Value::Bool(value) => Value::text(value.to_string()),
1083            crate::serde_json::Value::Integer(value) => Value::text(value.to_string()),
1084            crate::serde_json::Value::Number(value) => Value::text(value.to_string()),
1085            other => Value::text(other.to_string_compact()),
1086        }
1087    } else {
1088        Value::text(target.to_string_compact())
1089    }
1090}
1091
1092fn json_parse_value(input: &Value) -> Result<Value, EvalError> {
1093    let Value::Text(text) = input else {
1094        return Err(EvalError::UnknownFunction {
1095            name: "JSON_PARSE".to_string(),
1096            args: vec![input.data_type()],
1097        });
1098    };
1099    crate::serde_json::from_str::<crate::serde_json::Value>(text)
1100        .map(|json| Value::Json(json.to_string_compact().into_bytes()))
1101        .map_err(|err| EvalError::JsonParseFailed {
1102            reason: err.to_string(),
1103        })
1104}
1105
1106fn contains_value(input: &Value, needle: &Value) -> Value {
1107    let Value::Text(needle) = needle else {
1108        return Value::Null;
1109    };
1110    Value::Boolean(value_contains(input, needle))
1111}
1112
1113fn value_contains(value: &Value, needle: &str) -> bool {
1114    match value {
1115        Value::Array(values) => values.iter().any(|value| value_contains(value, needle)),
1116        Value::Json(_) => value_to_json(value)
1117            .as_ref()
1118            .is_some_and(|json| json_value_contains(json, needle)),
1119        Value::Text(value) => value.contains(needle),
1120        other => other.display_string().contains(needle),
1121    }
1122}
1123
1124fn json_value_contains(value: &crate::serde_json::Value, needle: &str) -> bool {
1125    match value {
1126        crate::serde_json::Value::Array(values) => values
1127            .iter()
1128            .any(|value| json_value_contains(value, needle)),
1129        // Recurse into object *values* so a needle nested inside a JSON
1130        // object matches — e.g. `CONTAINS(vision_detections, 'person')`
1131        // over a derived `[{"label":"person",...}]` array (#1275). Keys
1132        // are deliberately not matched: containment is about the data, not
1133        // the field names.
1134        crate::serde_json::Value::Object(map) => {
1135            map.values().any(|value| json_value_contains(value, needle))
1136        }
1137        crate::serde_json::Value::String(value) => value == needle,
1138        crate::serde_json::Value::Integer(value) => value.to_string() == needle,
1139        crate::serde_json::Value::Number(value) => value.to_string() == needle,
1140        crate::serde_json::Value::Decimal(value) => value == needle,
1141        crate::serde_json::Value::Bool(value) => value.to_string() == needle,
1142        crate::serde_json::Value::Null => false,
1143    }
1144}
1145
1146fn value_to_json(value: &Value) -> Option<crate::serde_json::Value> {
1147    match value {
1148        Value::Null => Some(crate::serde_json::Value::Null),
1149        // A document body may be the native binary container (PRD-1398); decode
1150        // it to JSON so json_extract / CONTAINS see the same shape as a plain
1151        // JSON body.
1152        Value::Json(bytes) => reddb_types::document_body_codec::decode_container_to_json(bytes)
1153            .or_else(|| crate::serde_json::from_slice(bytes).ok()),
1154        Value::Text(value) => crate::serde_json::from_str(value).ok(),
1155        _ => None,
1156    }
1157}
1158
1159enum JsonPathStep<'a> {
1160    Field(&'a str),
1161    Index(usize),
1162}
1163
1164fn parse_json_path(path: &str) -> Option<Vec<JsonPathStep<'_>>> {
1165    let path = path.trim();
1166    let rest = path.strip_prefix('$').unwrap_or(path);
1167    let mut steps = Vec::new();
1168    let bytes = rest.as_bytes();
1169    let mut index = 0;
1170    while index < bytes.len() {
1171        match bytes[index] {
1172            b'.' => {
1173                index += 1;
1174                let start = index;
1175                while index < bytes.len() && bytes[index] != b'.' && bytes[index] != b'[' {
1176                    index += 1;
1177                }
1178                if start == index {
1179                    return None;
1180                }
1181                steps.push(JsonPathStep::Field(
1182                    std::str::from_utf8(&bytes[start..index]).ok()?,
1183                ));
1184            }
1185            b'[' => {
1186                index += 1;
1187                let start = index;
1188                while index < bytes.len() && bytes[index] != b']' {
1189                    index += 1;
1190                }
1191                if index >= bytes.len() {
1192                    return None;
1193                }
1194                steps.push(JsonPathStep::Index(
1195                    std::str::from_utf8(&bytes[start..index])
1196                        .ok()?
1197                        .parse()
1198                        .ok()?,
1199                ));
1200                index += 1;
1201            }
1202            _ => return None,
1203        }
1204    }
1205    Some(steps)
1206}
1207
1208fn json_path_get<'a>(
1209    root: &'a crate::serde_json::Value,
1210    steps: &[JsonPathStep<'_>],
1211) -> Option<&'a crate::serde_json::Value> {
1212    let mut current = root;
1213    for step in steps {
1214        current = match (step, current) {
1215            (JsonPathStep::Field(name), crate::serde_json::Value::Object(map)) => map.get(*name)?,
1216            (JsonPathStep::Index(index), crate::serde_json::Value::Array(values)) => {
1217                values.get(*index)?
1218            }
1219            _ => return None,
1220        };
1221    }
1222    Some(current)
1223}
1224
1225fn eval_case(
1226    branches: &[(Expr, Expr)],
1227    else_: Option<&Expr>,
1228    row: &dyn Row,
1229    decode_literal: &impl Fn(&Value) -> Result<Value, EvalError>,
1230) -> Result<Value, EvalError> {
1231    for (cond, value) in branches {
1232        let c = evaluate_with_literal_decoder(cond, row, decode_literal)?;
1233        if matches!(c, Value::Boolean(true)) {
1234            return evaluate_with_literal_decoder(value, row, decode_literal);
1235        }
1236    }
1237    match else_ {
1238        Some(e) => evaluate_with_literal_decoder(e, row, decode_literal),
1239        None => Ok(Value::Null),
1240    }
1241}
1242
1243fn eval_in_list(
1244    target: &Expr,
1245    values: &[Expr],
1246    negated: bool,
1247    row: &dyn Row,
1248    decode_literal: &impl Fn(&Value) -> Result<Value, EvalError>,
1249) -> Result<Value, EvalError> {
1250    if values.is_empty() {
1251        return Err(EvalError::EmptyInList);
1252    }
1253    let needle = evaluate_with_literal_decoder(target, row, decode_literal)?;
1254    if needle.is_null() {
1255        return Ok(Value::Null);
1256    }
1257    let mut saw_null = false;
1258    for v in values {
1259        let candidate = evaluate_with_literal_decoder(v, row, decode_literal)?;
1260        if candidate.is_null() {
1261            saw_null = true;
1262            continue;
1263        }
1264        if values_equal(&needle, &candidate) {
1265            return Ok(Value::Boolean(!negated));
1266        }
1267    }
1268    if saw_null {
1269        return Ok(Value::Null);
1270    }
1271    Ok(Value::Boolean(negated))
1272}
1273
1274fn eval_between(
1275    target: &Expr,
1276    low: &Expr,
1277    high: &Expr,
1278    negated: bool,
1279    row: &dyn Row,
1280    decode_literal: &impl Fn(&Value) -> Result<Value, EvalError>,
1281) -> Result<Value, EvalError> {
1282    let v = evaluate_with_literal_decoder(target, row, decode_literal)?;
1283    let lo = evaluate_with_literal_decoder(low, row, decode_literal)?;
1284    let hi = evaluate_with_literal_decoder(high, row, decode_literal)?;
1285    if v.is_null() || lo.is_null() || hi.is_null() {
1286        return Ok(Value::Null);
1287    }
1288    let lo_ok = compare_values(&v, &lo)
1289        .ok_or(EvalError::OperatorMismatch {
1290            op: BinOp::Ge,
1291            lhs: v.data_type(),
1292            rhs: lo.data_type(),
1293        })
1294        .map(|o| o != std::cmp::Ordering::Less)?;
1295    let hi_ok = compare_values(&v, &hi)
1296        .ok_or(EvalError::OperatorMismatch {
1297            op: BinOp::Le,
1298            lhs: v.data_type(),
1299            rhs: hi.data_type(),
1300        })
1301        .map(|o| o != std::cmp::Ordering::Greater)?;
1302    let inside = lo_ok && hi_ok;
1303    Ok(Value::Boolean(if negated { !inside } else { inside }))
1304}
1305
1306#[cfg(test)]
1307mod tests {
1308    use super::*;
1309    use reddb_rql::ast::Span;
1310
1311    fn lit(v: Value) -> Expr {
1312        Expr::Literal {
1313            value: v,
1314            span: Span::synthetic(),
1315        }
1316    }
1317
1318    fn binop(op: BinOp, l: Expr, r: Expr) -> Expr {
1319        Expr::BinaryOp {
1320            op,
1321            lhs: Box::new(l),
1322            rhs: Box::new(r),
1323            span: Span::synthetic(),
1324        }
1325    }
1326
1327    fn empty_row() -> impl Row {
1328        |_field: &FieldRef| -> Option<Value> { None }
1329    }
1330
1331    #[test]
1332    fn contains_descends_into_json_object_values() {
1333        // A derived component-detections array (#1275): CONTAINS must find
1334        // a label nested inside the object elements, not just top-level
1335        // array strings.
1336        let detections = br#"[{"label":"person","confidence":0.9,"bbox":[0,0,1,1]},
1337                              {"label":"car","confidence":0.7,"bbox":[1,1,2,2]}]"#;
1338        let json = Value::Json(detections.to_vec());
1339        assert!(value_contains(&json, "person"));
1340        assert!(value_contains(&json, "car"));
1341        assert!(!value_contains(&json, "bicycle"));
1342        // Keys are not matched — only the data.
1343        assert!(!value_contains(&json, "label"));
1344    }
1345
1346    #[test]
1347    fn integer_addition_overflow_surfaces_as_eval_error() {
1348        let expr = binop(
1349            BinOp::Add,
1350            lit(Value::Integer(i64::MAX)),
1351            lit(Value::Integer(1)),
1352        );
1353        let err = evaluate(&expr, &empty_row()).unwrap_err();
1354        assert_eq!(err, EvalError::ArithmeticOverflow { op: BinOp::Add });
1355    }
1356
1357    #[test]
1358    fn integer_multiplication_overflow_surfaces_as_eval_error() {
1359        let expr = binop(
1360            BinOp::Mul,
1361            lit(Value::Integer(i64::MAX)),
1362            lit(Value::Integer(2)),
1363        );
1364        let err = evaluate(&expr, &empty_row()).unwrap_err();
1365        assert_eq!(err, EvalError::ArithmeticOverflow { op: BinOp::Mul });
1366    }
1367
1368    #[test]
1369    fn integer_subtraction_overflow_surfaces_as_eval_error() {
1370        let expr = binop(
1371            BinOp::Sub,
1372            lit(Value::Integer(i64::MIN)),
1373            lit(Value::Integer(1)),
1374        );
1375        let err = evaluate(&expr, &empty_row()).unwrap_err();
1376        assert_eq!(err, EvalError::ArithmeticOverflow { op: BinOp::Sub });
1377    }
1378
1379    #[test]
1380    fn unary_neg_overflow_on_min_int_surfaces_as_eval_error() {
1381        let expr = Expr::UnaryOp {
1382            op: UnaryOp::Neg,
1383            operand: Box::new(lit(Value::Integer(i64::MIN))),
1384            span: Span::synthetic(),
1385        };
1386        let err = evaluate(&expr, &empty_row()).unwrap_err();
1387        assert_eq!(err, EvalError::ArithmeticOverflow { op: BinOp::Sub });
1388    }
1389
1390    #[test]
1391    fn null_propagates_through_arithmetic() {
1392        let expr = binop(BinOp::Add, lit(Value::Null), lit(Value::Integer(7)));
1393        let v = evaluate(&expr, &empty_row()).unwrap();
1394        assert_eq!(v, Value::Null);
1395    }
1396
1397    #[test]
1398    fn null_propagates_through_comparison() {
1399        let expr = binop(BinOp::Lt, lit(Value::Integer(1)), lit(Value::Null));
1400        let v = evaluate(&expr, &empty_row()).unwrap();
1401        assert_eq!(v, Value::Null);
1402    }
1403
1404    #[test]
1405    fn null_propagates_through_concat() {
1406        let expr = binop(
1407            BinOp::Concat,
1408            lit(Value::Text(Arc::from("hi"))),
1409            lit(Value::Null),
1410        );
1411        let v = evaluate(&expr, &empty_row()).unwrap();
1412        assert_eq!(v, Value::Null);
1413    }
1414
1415    #[test]
1416    fn three_valued_and_returns_false_when_one_side_false_even_with_null() {
1417        let expr = binop(BinOp::And, lit(Value::Null), lit(Value::Boolean(false)));
1418        let v = evaluate(&expr, &empty_row()).unwrap();
1419        assert_eq!(v, Value::Boolean(false));
1420    }
1421
1422    #[test]
1423    fn three_valued_or_returns_true_when_one_side_true_even_with_null() {
1424        let expr = binop(BinOp::Or, lit(Value::Null), lit(Value::Boolean(true)));
1425        let v = evaluate(&expr, &empty_row()).unwrap();
1426        assert_eq!(v, Value::Boolean(true));
1427    }
1428
1429    #[test]
1430    fn three_valued_and_returns_null_for_null_and_true() {
1431        let expr = binop(BinOp::And, lit(Value::Null), lit(Value::Boolean(true)));
1432        let v = evaluate(&expr, &empty_row()).unwrap();
1433        assert_eq!(v, Value::Null);
1434    }
1435
1436    #[test]
1437    fn implicit_cast_triggers_for_decimal_plus_integer() {
1438        // Operator catalog has +(Decimal, Decimal) -> Decimal as
1439        // the only overload that survives coercion (no Decimal ->
1440        // numeric implicit casts exist in the cast catalog). The
1441        // spine therefore inserts an Integer -> Decimal cast on
1442        // the rhs and dispatches the Decimal addition.
1443        // parse_decimal scales by 10^4, so Integer(2) coerces to
1444        // Decimal(20000) and Decimal(10000) + Decimal(20000) =
1445        // Decimal(30000) (fixed-point 3.0000).
1446        let expr = binop(
1447            BinOp::Add,
1448            lit(Value::Decimal(10000)),
1449            lit(Value::Integer(2)),
1450        );
1451        let v = evaluate(&expr, &empty_row()).unwrap();
1452        assert_eq!(v, Value::Decimal(30000));
1453    }
1454
1455    #[test]
1456    fn integer_plus_bigint_resolves_to_preferred_float_overload() {
1457        // (Integer, BigInt) has no exact match. The spine ties
1458        // between +(Integer, Float, Float) (rhs cast BigInt->Float)
1459        // and +(BigInt, BigInt, BigInt) (lhs cast Integer->BigInt).
1460        // Float wins on the preferred-return-type tie-break, so the
1461        // BigInt operand is coerced to Float and the result is Float.
1462        let expr = binop(
1463            BinOp::Add,
1464            lit(Value::Integer(5)),
1465            lit(Value::BigInt(40_000_000_000)),
1466        );
1467        let v = evaluate(&expr, &empty_row()).unwrap();
1468        assert_eq!(v, Value::Float(40_000_000_005.0));
1469    }
1470
1471    #[test]
1472    fn integer_predicates_preserve_precision_across_signed_and_unsigned_boundaries() {
1473        let mut values = Vec::new();
1474        for number in [
1475            i64::MIN,
1476            -1,
1477            0,
1478            9_007_199_254_740_992,
1479            9_007_199_254_740_993,
1480            i64::MAX,
1481        ] {
1482            values.push((Value::Integer(number), i128::from(number)));
1483            values.push((Value::BigInt(number), i128::from(number)));
1484        }
1485        for number in [
1486            0,
1487            9_007_199_254_740_992,
1488            9_007_199_254_740_993,
1489            i64::MAX as u64,
1490            u64::MAX - 1,
1491            u64::MAX,
1492        ] {
1493            values.push((Value::UnsignedInteger(number), i128::from(number)));
1494        }
1495        for (left, left_exact) in &values {
1496            for (right, right_exact) in &values {
1497                for (operator, expected) in [
1498                    (BinOp::Eq, left_exact == right_exact),
1499                    (BinOp::Ne, left_exact != right_exact),
1500                    (BinOp::Lt, left_exact < right_exact),
1501                    (BinOp::Le, left_exact <= right_exact),
1502                    (BinOp::Gt, left_exact > right_exact),
1503                    (BinOp::Ge, left_exact >= right_exact),
1504                ] {
1505                    let expression = binop(operator, lit(left.clone()), lit(right.clone()));
1506                    assert_eq!(
1507                        evaluate(&expression, &empty_row())
1508                            .expect("integer comparison is supported"),
1509                        Value::Boolean(expected),
1510                        "{left:?} {operator:?} {right:?}"
1511                    );
1512                }
1513                for negated in [false, true] {
1514                    let expected = (*left_exact == *right_exact) != negated;
1515                    let membership = Expr::InList {
1516                        target: Box::new(lit(left.clone())),
1517                        values: vec![lit(right.clone())],
1518                        negated,
1519                        span: Span::synthetic(),
1520                    };
1521                    let interval = Expr::Between {
1522                        target: Box::new(lit(left.clone())),
1523                        low: Box::new(lit(right.clone())),
1524                        high: Box::new(lit(right.clone())),
1525                        negated,
1526                        span: Span::synthetic(),
1527                    };
1528                    for expression in [membership, interval] {
1529                        assert_eq!(
1530                            evaluate(&expression, &empty_row())
1531                                .expect("integer predicate is supported"),
1532                            Value::Boolean(expected),
1533                            "{expression:?}"
1534                        );
1535                    }
1536                }
1537            }
1538        }
1539    }
1540
1541    #[test]
1542    fn implicit_cast_promotes_integer_to_float_for_float_addition() {
1543        // The catalog has +(Integer, Float) -> Float as a direct
1544        // entry, so no actual coercion is inserted, but the result
1545        // must still be Float.
1546        let expr = binop(BinOp::Add, lit(Value::Integer(2)), lit(Value::Float(0.5)));
1547        let v = evaluate(&expr, &empty_row()).unwrap();
1548        assert_eq!(v, Value::Float(2.5));
1549    }
1550
1551    #[test]
1552    fn integer_division_truncates_towards_zero() {
1553        let cases = [
1554            (Value::Integer(7), Value::Integer(2), Value::Integer(3)),
1555            (Value::Integer(-7), Value::Integer(2), Value::Integer(-3)),
1556            (Value::Integer(7), Value::BigInt(-2), Value::BigInt(-3)),
1557            (
1558                Value::BigInt(9_007_199_254_740_995),
1559                Value::Integer(2),
1560                Value::BigInt(4_503_599_627_370_497),
1561            ),
1562            (Value::BigInt(-7), Value::BigInt(-2), Value::BigInt(3)),
1563            (Value::Integer(7), Value::Float(2.0), Value::Float(3.5)),
1564            (Value::Float(7.0), Value::BigInt(2), Value::Float(3.5)),
1565            (Value::Null, Value::Integer(0), Value::Null),
1566        ];
1567        for (lhs, rhs, expected) in cases {
1568            let expr = binop(BinOp::Div, lit(lhs), lit(rhs));
1569            assert_eq!(evaluate(&expr, &empty_row()), Ok(expected));
1570        }
1571    }
1572
1573    #[test]
1574    fn integer_division_overflow_is_eval_error() {
1575        let expr = binop(
1576            BinOp::Div,
1577            lit(Value::BigInt(i64::MIN)),
1578            lit(Value::Integer(-1)),
1579        );
1580        assert_eq!(
1581            evaluate(&expr, &empty_row()),
1582            Err(EvalError::ArithmeticOverflow { op: BinOp::Div })
1583        );
1584    }
1585
1586    #[test]
1587    fn division_by_zero_is_eval_error() {
1588        let expr = binop(BinOp::Div, lit(Value::Integer(7)), lit(Value::Integer(0)));
1589        let err = evaluate(&expr, &empty_row()).unwrap_err();
1590        assert_eq!(err, EvalError::DivisionByZero);
1591    }
1592
1593    #[test]
1594    fn unknown_function_surfaces_as_eval_error() {
1595        let expr = Expr::FunctionCall {
1596            name: "no_such_fn".to_string(),
1597            args: vec![lit(Value::Integer(1))],
1598            span: Span::synthetic(),
1599        };
1600        let err = evaluate(&expr, &empty_row()).unwrap_err();
1601        match err {
1602            EvalError::UnknownFunction { name, args } => {
1603                assert_eq!(name, "no_such_fn");
1604                assert_eq!(args, vec![DataType::Integer]);
1605            }
1606            other => panic!("expected UnknownFunction, got {other:?}"),
1607        }
1608    }
1609
1610    #[test]
1611    fn coalesce_returns_first_non_null() {
1612        let expr = Expr::FunctionCall {
1613            name: "COALESCE".to_string(),
1614            args: vec![
1615                lit(Value::Null),
1616                lit(Value::Null),
1617                lit(Value::Integer(42)),
1618                lit(Value::Integer(99)),
1619            ],
1620            span: Span::synthetic(),
1621        };
1622        let v = evaluate(&expr, &empty_row()).unwrap();
1623        assert_eq!(v, Value::Integer(42));
1624    }
1625
1626    #[test]
1627    fn coalesce_all_null_returns_null() {
1628        let expr = Expr::FunctionCall {
1629            name: "COALESCE".to_string(),
1630            args: vec![lit(Value::Null), lit(Value::Null)],
1631            span: Span::synthetic(),
1632        };
1633        let v = evaluate(&expr, &empty_row()).unwrap();
1634        assert_eq!(v, Value::Null);
1635    }
1636
1637    #[test]
1638    fn variadic_concat_owns_null_semantics() {
1639        let expr = Expr::FunctionCall {
1640            name: "CONCAT".to_string(),
1641            args: vec![
1642                lit(Value::Text(Arc::from("red"))),
1643                lit(Value::Null),
1644                lit(Value::Text(Arc::from("db"))),
1645            ],
1646            span: Span::synthetic(),
1647        };
1648        let value = evaluate(&expr, &empty_row()).unwrap();
1649        assert_eq!(value, Value::Text(Arc::from("reddb")));
1650    }
1651
1652    #[test]
1653    fn upper_lower_dispatch_through_function_catalog() {
1654        let expr = Expr::FunctionCall {
1655            name: "UPPER".to_string(),
1656            args: vec![lit(Value::Text(Arc::from("hello")))],
1657            span: Span::synthetic(),
1658        };
1659        let v = evaluate(&expr, &empty_row()).unwrap();
1660        assert_eq!(v, Value::Text(Arc::from("HELLO")));
1661    }
1662
1663    #[test]
1664    fn length_of_null_propagates() {
1665        let expr = Expr::FunctionCall {
1666            name: "LENGTH".to_string(),
1667            args: vec![lit(Value::Null)],
1668            span: Span::synthetic(),
1669        };
1670        let v = evaluate(&expr, &empty_row()).unwrap();
1671        assert_eq!(v, Value::Null);
1672    }
1673
1674    #[test]
1675    fn case_when_picks_first_true_branch() {
1676        let expr = Expr::Case {
1677            branches: vec![
1678                (lit(Value::Boolean(false)), lit(Value::Integer(1))),
1679                (lit(Value::Boolean(true)), lit(Value::Integer(2))),
1680                (lit(Value::Boolean(true)), lit(Value::Integer(3))),
1681            ],
1682            else_: Some(Box::new(lit(Value::Integer(99)))),
1683            span: Span::synthetic(),
1684        };
1685        let v = evaluate(&expr, &empty_row()).unwrap();
1686        assert_eq!(v, Value::Integer(2));
1687    }
1688
1689    #[test]
1690    fn case_falls_through_to_else_when_no_branch_matches() {
1691        let expr = Expr::Case {
1692            branches: vec![(lit(Value::Boolean(false)), lit(Value::Integer(1)))],
1693            else_: Some(Box::new(lit(Value::Integer(99)))),
1694            span: Span::synthetic(),
1695        };
1696        let v = evaluate(&expr, &empty_row()).unwrap();
1697        assert_eq!(v, Value::Integer(99));
1698    }
1699
1700    #[test]
1701    fn case_returns_null_when_no_branch_matches_and_no_else() {
1702        let expr = Expr::Case {
1703            branches: vec![(lit(Value::Boolean(false)), lit(Value::Integer(1)))],
1704            else_: None,
1705            span: Span::synthetic(),
1706        };
1707        let v = evaluate(&expr, &empty_row()).unwrap();
1708        assert_eq!(v, Value::Null);
1709    }
1710
1711    #[test]
1712    fn is_null_handles_null_and_non_null() {
1713        let null_expr = Expr::IsNull {
1714            operand: Box::new(lit(Value::Null)),
1715            negated: false,
1716            span: Span::synthetic(),
1717        };
1718        assert_eq!(
1719            evaluate(&null_expr, &empty_row()).unwrap(),
1720            Value::Boolean(true)
1721        );
1722
1723        let non_null_expr = Expr::IsNull {
1724            operand: Box::new(lit(Value::Integer(7))),
1725            negated: false,
1726            span: Span::synthetic(),
1727        };
1728        assert_eq!(
1729            evaluate(&non_null_expr, &empty_row()).unwrap(),
1730            Value::Boolean(false)
1731        );
1732    }
1733
1734    #[test]
1735    fn between_inclusive_bounds() {
1736        let expr = Expr::Between {
1737            target: Box::new(lit(Value::Integer(5))),
1738            low: Box::new(lit(Value::Integer(1))),
1739            high: Box::new(lit(Value::Integer(10))),
1740            negated: false,
1741            span: Span::synthetic(),
1742        };
1743        assert_eq!(evaluate(&expr, &empty_row()).unwrap(), Value::Boolean(true));
1744    }
1745
1746    #[test]
1747    fn in_list_match_and_miss() {
1748        let hit = Expr::InList {
1749            target: Box::new(lit(Value::Integer(2))),
1750            values: vec![
1751                lit(Value::Integer(1)),
1752                lit(Value::Integer(2)),
1753                lit(Value::Integer(3)),
1754            ],
1755            negated: false,
1756            span: Span::synthetic(),
1757        };
1758        assert_eq!(evaluate(&hit, &empty_row()).unwrap(), Value::Boolean(true));
1759
1760        let miss = Expr::InList {
1761            target: Box::new(lit(Value::Integer(99))),
1762            values: vec![lit(Value::Integer(1)), lit(Value::Integer(2))],
1763            negated: false,
1764            span: Span::synthetic(),
1765        };
1766        assert_eq!(
1767            evaluate(&miss, &empty_row()).unwrap(),
1768            Value::Boolean(false)
1769        );
1770    }
1771
1772    #[test]
1773    fn column_lookup_walks_field_ref() {
1774        let row = |field: &FieldRef| -> Option<Value> {
1775            match field {
1776                FieldRef::TableColumn { table, column } if table == "t" && column == "x" => {
1777                    Some(Value::Integer(11))
1778                }
1779                _ => None,
1780            }
1781        };
1782        let expr = Expr::Column {
1783            field: FieldRef::TableColumn {
1784                table: "t".to_string(),
1785                column: "x".to_string(),
1786            },
1787            span: Span::synthetic(),
1788        };
1789        assert_eq!(evaluate(&expr, &row).unwrap(), Value::Integer(11));
1790    }
1791
1792    #[test]
1793    fn missing_column_surfaces_unknown_column() {
1794        let row = |_: &FieldRef| -> Option<Value> { None };
1795        let expr = Expr::Column {
1796            field: FieldRef::TableColumn {
1797                table: "t".to_string(),
1798                column: "missing".to_string(),
1799            },
1800            span: Span::synthetic(),
1801        };
1802        let err = evaluate(&expr, &row).unwrap_err();
1803        match err {
1804            EvalError::UnknownColumn(_) => {}
1805            other => panic!("expected UnknownColumn, got {other:?}"),
1806        }
1807    }
1808
1809    #[test]
1810    fn parameter_without_bind_is_eval_error() {
1811        let expr = Expr::Parameter {
1812            index: 1,
1813            span: Span::synthetic(),
1814        };
1815        let err = evaluate(&expr, &empty_row()).unwrap_err();
1816        assert_eq!(err, EvalError::UnboundParameter(1));
1817    }
1818
1819    #[test]
1820    fn cast_integer_to_text_uses_explicit_path() {
1821        let expr = Expr::Cast {
1822            inner: Box::new(lit(Value::Integer(42))),
1823            target: DataType::Text,
1824            span: Span::synthetic(),
1825        };
1826        assert_eq!(
1827            evaluate(&expr, &empty_row()).unwrap(),
1828            Value::Text(Arc::from("42"))
1829        );
1830    }
1831
1832    #[test]
1833    fn concat_returns_text() {
1834        let expr = binop(
1835            BinOp::Concat,
1836            lit(Value::Text(Arc::from("foo"))),
1837            lit(Value::Text(Arc::from("bar"))),
1838        );
1839        assert_eq!(
1840            evaluate(&expr, &empty_row()).unwrap(),
1841            Value::Text(Arc::from("foobar"))
1842        );
1843    }
1844}