Skip to main content

reddb_engine/query/
evaluator.rs

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