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