Skip to main content

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