Skip to main content

reddb_engine/query/
evaluator.rs

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