Skip to main content

reddb_engine/query/
evaluator.rs

1//! Scalar expression evaluator — single owner of value-level
2//! evaluation for SQL scalar `Expr` trees.
3//!
4//! Today scalar expression evaluation is fragmented:
5//!
6//! - `query::filter::Predicate::evaluate` runs comparison predicates
7//!   against a single column value.
8//! - `query::filter_compiled::CompiledFilter::evaluate` runs the
9//!   compiled filter opcode tape over a row slot, but still defers to
10//!   `Predicate::evaluate` per opcode for the actual comparison logic.
11//! - Several inlined arms in `query::core` and `query::executor`
12//!   compute projections, DEFAULT / CHECK expressions, RETURNING
13//!   columns, COMPUTED columns, and ON CONFLICT updates by walking
14//!   the AST and dispatching arithmetic / function calls inline.
15//! - `query::expr_typing` knows how to type an `Expr` against a
16//!   `Scope` but never produces a `Value` — it stops at `TypedExpr`.
17//!
18//! Operator / function / cast resolution is centralised in
19//! `schema::coercion_spine`, but **value-level dispatch** is not — so
20//! adding a new operator overload, a new implicit cast edge, or a
21//! new built-in function requires synchronised edits across each of
22//! the inline evaluators above.
23//!
24//! This module is the first vertical slice of the deep evaluator
25//! interface tracked by `draft-53-scalar-expression-evaluator`. It
26//! exposes:
27//!
28//! - [`Row`]: pluggable column-binding lookup so callers can wire
29//!   either a planner-resolved slot vector or a flat column-name map.
30//! - [`evaluate`]: the single entry point. Walks an `Expr`, resolves
31//!   operators / functions / casts through `coercion_spine`, applies
32//!   the implicit casts the spine asks for, and produces a `Value`.
33//! - [`EvalError`]: typed diagnostic surface — every failure mode the
34//!   evaluator can encounter at runtime is enumerated here so callers
35//!   don't have to parse strings.
36//!
37//! The slice is intentionally additive: callers in `filter.rs`,
38//! `filter_compiled.rs`, and `executor.rs` still own their own
39//! evaluation paths. Subsequent slices migrate those callers onto
40//! `evaluate` once the dispatch surface has proven out under the
41//! focused test set in this module.
42//!
43//! ## Semantics summary
44//!
45//! - **NULL propagation.** Arithmetic, comparison, concat, and CAST
46//!   propagate `Value::Null` — any `Null` operand short-circuits to
47//!   `Null`. `AND` / `OR` follow SQL three-valued logic.
48//! - **Arithmetic overflow.** Signed checked arithmetic; overflow
49//!   surfaces as [`EvalError::ArithmeticOverflow`] rather than wrap
50//!   or panic.
51//! - **Division.** Division by zero surfaces as
52//!   [`EvalError::DivisionByZero`]. Integer `/` always promotes to
53//!   `Float` per the operator catalog; integer `%` stays integer.
54//! - **Implicit cast triggers.** When the operator catalog has no
55//!   exact-type overload, the spine returns the per-operand
56//!   coercions; this evaluator applies them via
57//!   [`coerce::coerce_via_catalog`] before dispatch.
58//! - **Unknown function rejection.** Calls that don't resolve in the
59//!   built-in function catalog produce
60//!   [`EvalError::UnknownFunction`]. Variadic / catalog-resolved
61//!   functions still return through the same dispatch.
62
63use std::sync::Arc;
64
65use super::runtime::values::runtime_exact_integer_cmp;
66use reddb_rql::ast::{BinOp, Expr, FieldRef, UnaryOp};
67use reddb_types::coerce::coerce_via_catalog;
68use reddb_types::coercion_spine;
69use reddb_types::function_catalog::FUNCTION_CATALOG;
70use reddb_types::operator_catalog::OperatorEntry;
71use reddb_types::{DataType, Value};
72
73/// Pluggable row-binding lookup. The evaluator stays agnostic of
74/// whether the caller has a slot vector indexed by planner-assigned
75/// position, a flat `HashMap<String, Value>`, or a graph binding —
76/// every consumer just provides a `Row` impl that resolves a
77/// `FieldRef` to a `Value`.
78pub trait Row {
79    /// Resolve a column / property reference. Returns `None` when the
80    /// reference is unknown (the evaluator surfaces this as
81    /// [`EvalError::UnknownColumn`]) or `Some(Value::Null)` when the
82    /// column exists but the row's value is null.
83    fn get(&self, field: &FieldRef) -> Option<Value>;
84
85    /// Hosts which decode stored values can report operating failures instead
86    /// of treating a denied read as an unknown or NULL column.
87    fn try_get(&self, field: &FieldRef) -> Result<Option<Value>, EvalError> {
88        Ok(self.get(field))
89    }
90}
91
92/// Trivial `Row` impl over a flat `(table, column) -> Value` closure
93/// — useful for tests and for callers that only have a column-name
94/// map.
95impl<F> Row for F
96where
97    F: Fn(&FieldRef) -> Option<Value>,
98{
99    fn get(&self, field: &FieldRef) -> Option<Value> {
100        self(field)
101    }
102}
103
104/// Errors surfaced by [`evaluate`]. Every variant is a runtime
105/// failure shape — type-resolution failures live in
106/// `expr_typing::TypeError`, not here.
107#[derive(Debug, Clone, PartialEq)]
108pub enum EvalError {
109    /// Column / property not present in the row binding.
110    UnknownColumn(FieldRef),
111    /// Query parameter placeholders are not resolved at this layer
112    /// — the bind phase substitutes a concrete value before
113    /// evaluation.
114    UnboundParameter(usize),
115    /// Operator catalog has no overload that accepts these operand
116    /// types, even after considering implicit coercions.
117    OperatorMismatch {
118        op: BinOp,
119        lhs: DataType,
120        rhs: DataType,
121    },
122    /// Unary operator doesn't accept the operand type.
123    UnaryMismatch {
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 integer representations before numeric promotion can round large
347    // values or reject a u64 that exceeds 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_integer_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    // Operator catalog promotes integer / integer to Float —
512    // mirror that here so behavior stays identical to the typer.
513    match entry.return_type {
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
529fn arith_mod(entry: &OperatorEntry, l: Value, r: Value) -> Result<Value, EvalError> {
530    match entry.return_type {
531        DataType::Integer => match (l, r) {
532            (Value::Integer(_), Value::Integer(0)) => Err(EvalError::DivisionByZero),
533            (Value::Integer(a), Value::Integer(b)) => a
534                .checked_rem(b)
535                .map(Value::Integer)
536                .ok_or(EvalError::ArithmeticOverflow { op: BinOp::Mod }),
537            _ => unreachable_after_coercion("Mod", DataType::Integer),
538        },
539        DataType::BigInt => match (l, r) {
540            (Value::BigInt(_), Value::BigInt(0)) => Err(EvalError::DivisionByZero),
541            (Value::BigInt(a), Value::BigInt(b)) => a
542                .checked_rem(b)
543                .map(Value::BigInt)
544                .ok_or(EvalError::ArithmeticOverflow { op: BinOp::Mod }),
545            _ => unreachable_after_coercion("Mod", DataType::BigInt),
546        },
547        other => Err(EvalError::OperatorMismatch {
548            op: BinOp::Mod,
549            lhs: other,
550            rhs: other,
551        }),
552    }
553}
554
555fn unreachable_after_coercion(op: &'static str, expected: DataType) -> Result<Value, EvalError> {
556    Err(EvalError::OperatorMismatch {
557        op: match op {
558            "Add" => BinOp::Add,
559            "Sub" => BinOp::Sub,
560            "Mul" => BinOp::Mul,
561            "Div" => BinOp::Div,
562            "Mod" => BinOp::Mod,
563            _ => BinOp::Add,
564        },
565        lhs: expected,
566        rhs: expected,
567    })
568}
569
570fn checked_float_binop(op: BinOp, value: f64) -> Result<Value, EvalError> {
571    if value.is_finite() {
572        Ok(Value::Float(value))
573    } else {
574        Err(EvalError::InvalidNumericResult {
575            function: format!("{op:?}"),
576            reason: "result is NaN or infinite".to_string(),
577        })
578    }
579}
580
581fn as_f64(v: &Value) -> f64 {
582    match v {
583        Value::Float(x) => *x,
584        Value::Integer(x) => *x as f64,
585        Value::BigInt(x) => *x as f64,
586        Value::UnsignedInteger(x) => *x as f64,
587        Value::Decimal(x) => reddb_types::types::decimal_to_f64(*x),
588        _ => 0.0,
589    }
590}
591
592fn cmp_op<F>(op: BinOp, l: Value, r: Value, pick: F) -> Result<Value, EvalError>
593where
594    F: Fn(std::cmp::Ordering) -> bool,
595{
596    let ord = compare_values(&l, &r).ok_or(EvalError::OperatorMismatch {
597        op,
598        lhs: l.data_type(),
599        rhs: r.data_type(),
600    })?;
601    Ok(Value::Boolean(pick(ord)))
602}
603
604/// Total ordering for the numeric and text families that the
605/// catalog declares comparison overloads for. Returns `None` when
606/// the values aren't comparable — callers surface this as
607/// [`EvalError::OperatorMismatch`].
608fn compare_values(a: &Value, b: &Value) -> Option<std::cmp::Ordering> {
609    if let Some(order) = runtime_exact_integer_cmp(a, b) {
610        return Some(order);
611    }
612    match (a, b) {
613        (Value::Temperature(x), Value::Temperature(y)) => Some(x.cmp(y)),
614        (Value::Integer(x), Value::Integer(y)) => Some(x.cmp(y)),
615        (Value::BigInt(x), Value::BigInt(y)) => Some(x.cmp(y)),
616        (Value::Float(x), Value::Float(y)) => x.partial_cmp(y),
617        (Value::Text(x), Value::Text(y)) => Some(x.as_ref().cmp(y.as_ref())),
618        (Value::Boolean(x), Value::Boolean(y)) => Some(x.cmp(y)),
619        (Value::Timestamp(x), Value::Timestamp(y)) => Some(x.cmp(y)),
620        (Value::TimestampMs(x), Value::TimestampMs(y)) => Some(x.cmp(y)),
621        (Value::Date(x), Value::Date(y)) => Some(x.cmp(y)),
622        (Value::Time(x), Value::Time(y)) => Some(x.cmp(y)),
623        (Value::Uuid(x), Value::Uuid(y)) => Some(x.cmp(y)),
624        (Value::Decimal(x), Value::Decimal(y)) => Some(x.cmp(y)),
625        // Cross-numeric — operand coercion should have homogenised
626        // these but if a caller invokes the evaluator with mixed
627        // numerics directly, fall back to f64 ordering.
628        (Value::Integer(_) | Value::Float(_) | Value::BigInt(_), _) => {
629            let l = as_f64(a);
630            let r = as_f64(b);
631            l.partial_cmp(&r)
632        }
633        _ => None,
634    }
635}
636
637fn values_equal(a: &Value, b: &Value) -> bool {
638    if let Some(order) = runtime_exact_integer_cmp(a, b) {
639        return order.is_eq();
640    }
641    match (a, b) {
642        (Value::Float(x), Value::Float(y)) => x == y,
643        _ => a == b,
644    }
645}
646
647fn three_valued_and(l: &Value, r: &Value) -> Result<Value, EvalError> {
648    match (l, r) {
649        (Value::Boolean(false), _) | (_, Value::Boolean(false)) => Ok(Value::Boolean(false)),
650        (Value::Boolean(true), Value::Boolean(true)) => Ok(Value::Boolean(true)),
651        (Value::Null, _) | (_, Value::Null) => Ok(Value::Null),
652        _ => Err(EvalError::OperatorMismatch {
653            op: BinOp::And,
654            lhs: l.data_type(),
655            rhs: r.data_type(),
656        }),
657    }
658}
659
660fn three_valued_or(l: &Value, r: &Value) -> Result<Value, EvalError> {
661    match (l, r) {
662        (Value::Boolean(true), _) | (_, Value::Boolean(true)) => Ok(Value::Boolean(true)),
663        (Value::Boolean(false), Value::Boolean(false)) => Ok(Value::Boolean(false)),
664        (Value::Null, _) | (_, Value::Null) => Ok(Value::Null),
665        _ => Err(EvalError::OperatorMismatch {
666            op: BinOp::Or,
667            lhs: l.data_type(),
668            rhs: r.data_type(),
669        }),
670    }
671}
672
673fn apply_implicit_cast(value: &Value, src: DataType, target: DataType) -> Result<Value, EvalError> {
674    if src == target {
675        return Ok(value.clone());
676    }
677    coerce_via_catalog(value, src, target, None).map_err(|reason| EvalError::ImplicitCastFailed {
678        from: src,
679        to: target,
680        reason,
681    })
682}
683
684fn eval_cast(
685    inner: &Expr,
686    target: DataType,
687    row: &dyn Row,
688    decode_literal: &impl Fn(&Value) -> Result<Value, EvalError>,
689) -> Result<Value, EvalError> {
690    let v = evaluate_with_literal_decoder(inner, row, decode_literal)?;
691    if v.is_null() {
692        return Ok(Value::Null);
693    }
694    let src = v.data_type();
695    if src == target {
696        return Ok(v);
697    }
698    coerce_via_catalog(&v, src, target, None).map_err(|reason| EvalError::CastFailed {
699        from: src,
700        to: target,
701        reason,
702    })
703}
704
705fn eval_function(
706    name: &str,
707    args: &[Expr],
708    row: &dyn Row,
709    decode_literal: &impl Fn(&Value) -> Result<Value, EvalError>,
710) -> Result<Value, EvalError> {
711    if name.eq_ignore_ascii_case("CRON_OCCURRENCES") {
712        return Err(EvalError::CronFailed(
713            "cron_occurrences requires a top-level SELECT projection".into(),
714        ));
715    }
716    // COALESCE has SQL-special semantics that the catalog can't
717    // express (variadic + uniform arg type unifies poorly with
718    // first-non-null). Handle it before catalog dispatch so we
719    // preserve `COALESCE(int, int) -> int` rather than coercing
720    // every argument to Text.
721    if name.eq_ignore_ascii_case("COALESCE") {
722        for arg in args {
723            let v = evaluate_with_literal_decoder(arg, row, decode_literal)?;
724            if !v.is_null() {
725                return Ok(v);
726            }
727        }
728        return Ok(Value::Null);
729    }
730
731    let arg_values: Vec<Value> = args
732        .iter()
733        .map(|a| evaluate_with_literal_decoder(a, row, decode_literal))
734        .collect::<Result<Vec<_>, _>>()?;
735    let arg_types: Vec<DataType> = arg_values.iter().map(|v| v.data_type()).collect();
736
737    // Strict NULL propagation applies only to non-variadic built-ins.
738    // Variadic functions such as CONCAT own their NULL semantics.
739    // Unknown functions with NULL arguments must still surface as
740    // `UnknownFunction` rather than silently returning NULL.
741    if arg_values.iter().any(Value::is_null)
742        && FUNCTION_CATALOG
743            .iter()
744            .any(|entry| entry.name.eq_ignore_ascii_case(name))
745        && FUNCTION_CATALOG
746            .iter()
747            .filter(|entry| entry.name.eq_ignore_ascii_case(name))
748            .all(|entry| !entry.variadic)
749    {
750        return Ok(Value::Null);
751    }
752
753    let (entry, coercions) =
754        coercion_spine::resolve_function(name, &arg_types).ok_or_else(|| {
755            EvalError::UnknownFunction {
756                name: name.to_string(),
757                args: arg_types.clone(),
758            }
759        })?;
760
761    // Apply per-arg implicit casts.
762    let mut coerced: Vec<Value> = Vec::with_capacity(arg_values.len());
763    for (idx, value) in arg_values.into_iter().enumerate() {
764        let src = arg_types[idx];
765        match coercions.at(idx) {
766            Some(target) if src != target => {
767                coerced.push(apply_implicit_cast(&value, src, target)?);
768            }
769            _ => coerced.push(value),
770        }
771    }
772
773    // NULL propagation for built-ins: if any non-variadic argument
774    // is null, return null. Variadic / aggregate semantics handle
775    // null differently and aren't in scope for this slice.
776    if !entry.variadic && coerced.iter().any(|v| v.is_null()) {
777        return Ok(Value::Null);
778    }
779
780    dispatch_function(entry.name, &coerced)
781}
782
783fn dispatch_function(name: &str, args: &[Value]) -> Result<Value, EvalError> {
784    match name {
785        "CRON" | "CRON_NEXT" | "CRON_OVERLAPS" => {
786            super::runtime::value_functions::evaluate_cron_function(name, args)
787                .map_err(|reason| EvalError::CronFailed(format!("{name}: {reason}")))
788        }
789        "TEMPERATURE" | "TEMPERATURE_UNIT" | "TEMPERATURE_VALUE" => {
790            super::runtime::value_functions::temperature_function(name, args).ok_or_else(|| {
791                EvalError::UnknownFunction {
792                    name: name.into(),
793                    args: args.iter().map(Value::data_type).collect(),
794                }
795            })
796        }
797        "UPPER" => match &args[0] {
798            Value::Text(s) => Ok(Value::Text(Arc::from(s.to_uppercase()))),
799            other => Err(EvalError::UnknownFunction {
800                name: name.to_string(),
801                args: vec![other.data_type()],
802            }),
803        },
804        "LOWER" => match &args[0] {
805            Value::Text(s) => Ok(Value::Text(Arc::from(s.to_lowercase()))),
806            other => Err(EvalError::UnknownFunction {
807                name: name.to_string(),
808                args: vec![other.data_type()],
809            }),
810        },
811        "TRIM" => trim_function(name, args, true, true),
812        "LTRIM" => trim_function(name, args, true, false),
813        "RTRIM" => trim_function(name, args, false, true),
814        "LENGTH" | "CHAR_LENGTH" | "CHARACTER_LENGTH" => match &args[0] {
815            Value::Text(s) => Ok(Value::Integer(s.chars().count() as i64)),
816            other => Err(EvalError::UnknownFunction {
817                name: name.to_string(),
818                args: vec![other.data_type()],
819            }),
820        },
821        "OCTET_LENGTH" => match &args[0] {
822            Value::Text(s) => Ok(Value::Integer(s.len() as i64)),
823            Value::Blob(b) => Ok(Value::Integer(b.len() as i64)),
824            other => Err(EvalError::UnknownFunction {
825                name: name.to_string(),
826                args: vec![other.data_type()],
827            }),
828        },
829        "CONCAT" => {
830            let mut out = String::new();
831            for arg in args {
832                match arg {
833                    Value::Null => {}
834                    Value::Text(value) => out.push_str(value),
835                    _ => {
836                        return Err(EvalError::UnknownFunction {
837                            name: name.to_string(),
838                            args: args.iter().map(Value::data_type).collect(),
839                        })
840                    }
841                }
842            }
843            Ok(Value::Text(Arc::from(out)))
844        }
845        "JSON_PARSE" => json_parse_value(&args[0]),
846        "JSON_EXTRACT" => Ok(json_extract_value(&args[0], &args[1], false)),
847        "JSON_EXTRACT_TEXT" => Ok(json_extract_value(&args[0], &args[1], true)),
848        "CONTAINS" => Ok(contains_value(&args[0], &args[1])),
849        "ABS" => match &args[0] {
850            Value::Integer(n) => n
851                .checked_abs()
852                .map(Value::Integer)
853                .ok_or(EvalError::ArithmeticOverflow { op: BinOp::Sub }),
854            Value::BigInt(n) => n
855                .checked_abs()
856                .map(Value::BigInt)
857                .ok_or(EvalError::ArithmeticOverflow { op: BinOp::Sub }),
858            Value::Float(n) => Ok(Value::Float(n.abs())),
859            Value::Decimal(n) => n
860                .checked_abs()
861                .map(Value::Decimal)
862                .ok_or(EvalError::ArithmeticOverflow { op: BinOp::Sub }),
863            other => Err(EvalError::UnknownFunction {
864                name: name.to_string(),
865                args: vec![other.data_type()],
866            }),
867        },
868        "SQRT" => unary_math(name, args, |x| {
869            if x < 0.0 {
870                return Err("input must be greater than or equal to zero");
871            }
872            Ok(x.sqrt())
873        }),
874        "POWER" | "POW" => binary_math(name, args, |base, exp| Ok(base.powf(exp))),
875        "EXP" => unary_math(name, args, |x| Ok(x.exp())),
876        "LN" => unary_math(name, args, |x| {
877            if x <= 0.0 {
878                return Err("input must be greater than zero");
879            }
880            Ok(x.ln())
881        }),
882        "LOG" if args.len() == 1 => unary_math(name, args, |x| {
883            if x <= 0.0 {
884                return Err("input must be greater than zero");
885            }
886            Ok(x.log10())
887        }),
888        "LOG" => binary_math(name, args, |base, x| {
889            if base <= 0.0 {
890                return Err("base must be greater than zero");
891            }
892            if base == 1.0 {
893                return Err("base must not equal one");
894            }
895            if x <= 0.0 {
896                return Err("input must be greater than zero");
897            }
898            Ok(x.log(base))
899        }),
900        "LOG10" => 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        "SIN" => unary_math(name, args, |x| Ok(x.sin())),
907        "COS" => unary_math(name, args, |x| Ok(x.cos())),
908        "TAN" => unary_math(name, args, |x| Ok(x.tan())),
909        "ASIN" | "ARCSIN" => unary_math(name, args, |x| {
910            if !(-1.0..=1.0).contains(&x) {
911                return Err("input must be between -1 and 1");
912            }
913            Ok(x.asin())
914        }),
915        "ACOS" | "ARCCOS" => unary_math(name, args, |x| {
916            if !(-1.0..=1.0).contains(&x) {
917                return Err("input must be between -1 and 1");
918            }
919            Ok(x.acos())
920        }),
921        "ATAN" | "ARCTAN" => unary_math(name, args, |x| Ok(x.atan())),
922        "ATAN2" => binary_math(name, args, |y, x| Ok(y.atan2(x))),
923        "COT" => unary_math(name, args, |x| {
924            let tan = x.tan();
925            if tan == 0.0 {
926                return Err("input must not produce zero tangent");
927            }
928            Ok(1.0 / tan)
929        }),
930        "DEGREES" => unary_math(name, args, |x| Ok(x.to_degrees())),
931        "RADIANS" => unary_math(name, args, |x| Ok(x.to_radians())),
932        "PI" => checked_math_result(name, std::f64::consts::PI),
933        // Functions whose runtime body the slice doesn't yet cover
934        // surface as UnknownFunction with the resolved arg types so
935        // callers can see the catalog matched but the dispatch
936        // didn't. Subsequent slices fill in CONCAT, time functions, …
937        other => Err(EvalError::UnknownFunction {
938            name: other.to_string(),
939            args: args.iter().map(|v| v.data_type()).collect(),
940        }),
941    }
942}
943
944fn trim_function(name: &str, args: &[Value], left: bool, right: bool) -> Result<Value, EvalError> {
945    if args.len() != 1 {
946        return Err(EvalError::UnknownFunction {
947            name: name.to_string(),
948            args: args.iter().map(|v| v.data_type()).collect(),
949        });
950    }
951
952    match &args[0] {
953        Value::Text(s) => {
954            let trimmed = match (left, right) {
955                (true, true) => s.trim(),
956                (true, false) => s.trim_start(),
957                (false, true) => s.trim_end(),
958                (false, false) => s,
959            };
960            Ok(Value::Text(Arc::from(trimmed)))
961        }
962        other => Err(EvalError::UnknownFunction {
963            name: name.to_string(),
964            args: vec![other.data_type()],
965        }),
966    }
967}
968
969fn unary_math<F>(name: &str, args: &[Value], op: F) -> Result<Value, EvalError>
970where
971    F: FnOnce(f64) -> Result<f64, &'static str>,
972{
973    let input = math_arg(name, args.first(), 0)?;
974    let value = op(input).map_err(|reason| EvalError::InvalidNumericResult {
975        function: name.to_string(),
976        reason: reason.to_string(),
977    })?;
978    checked_math_result(name, value)
979}
980
981fn binary_math<F>(name: &str, args: &[Value], op: F) -> Result<Value, EvalError>
982where
983    F: FnOnce(f64, f64) -> Result<f64, &'static str>,
984{
985    let left = math_arg(name, args.first(), 0)?;
986    let right = math_arg(name, args.get(1), 1)?;
987    let value = op(left, right).map_err(|reason| EvalError::InvalidNumericResult {
988        function: name.to_string(),
989        reason: reason.to_string(),
990    })?;
991    checked_math_result(name, value)
992}
993
994fn math_arg(name: &str, value: Option<&Value>, index: usize) -> Result<f64, EvalError> {
995    let value = value.ok_or_else(|| EvalError::UnknownFunction {
996        name: name.to_string(),
997        args: Vec::new(),
998    })?;
999    let numeric = as_f64(value);
1000    if numeric.is_finite() {
1001        Ok(numeric)
1002    } else {
1003        Err(EvalError::InvalidNumericResult {
1004            function: name.to_string(),
1005            reason: format!("argument {index} is NaN or infinite"),
1006        })
1007    }
1008}
1009
1010fn checked_math_result(name: &str, value: f64) -> Result<Value, EvalError> {
1011    if value.is_finite() {
1012        Ok(Value::Float(value))
1013    } else {
1014        Err(EvalError::InvalidNumericResult {
1015            function: name.to_string(),
1016            reason: "result is NaN or infinite".to_string(),
1017        })
1018    }
1019}
1020
1021fn json_extract_value(input: &Value, path: &Value, as_text: bool) -> Value {
1022    let Value::Text(path) = path else {
1023        return Value::Null;
1024    };
1025    let Some(json) = value_to_json(input) else {
1026        return Value::Null;
1027    };
1028    let Some(steps) = parse_json_path(path) else {
1029        return Value::Null;
1030    };
1031    let Some(target) = json_path_get(&json, &steps) else {
1032        return Value::Null;
1033    };
1034
1035    if as_text {
1036        match target {
1037            crate::serde_json::Value::String(value) => Value::text(value.clone()),
1038            crate::serde_json::Value::Null => Value::Null,
1039            crate::serde_json::Value::Bool(value) => Value::text(value.to_string()),
1040            crate::serde_json::Value::Integer(value) => Value::text(value.to_string()),
1041            crate::serde_json::Value::Number(value) => Value::text(value.to_string()),
1042            other => Value::text(other.to_string_compact()),
1043        }
1044    } else {
1045        Value::text(target.to_string_compact())
1046    }
1047}
1048
1049fn json_parse_value(input: &Value) -> Result<Value, EvalError> {
1050    let Value::Text(text) = input else {
1051        return Err(EvalError::UnknownFunction {
1052            name: "JSON_PARSE".to_string(),
1053            args: vec![input.data_type()],
1054        });
1055    };
1056    crate::serde_json::from_str::<crate::serde_json::Value>(text)
1057        .map(|json| Value::Json(json.to_string_compact().into_bytes()))
1058        .map_err(|err| EvalError::JsonParseFailed {
1059            reason: err.to_string(),
1060        })
1061}
1062
1063fn contains_value(input: &Value, needle: &Value) -> Value {
1064    let Value::Text(needle) = needle else {
1065        return Value::Null;
1066    };
1067    Value::Boolean(value_contains(input, needle))
1068}
1069
1070fn value_contains(value: &Value, needle: &str) -> bool {
1071    match value {
1072        Value::Array(values) => values.iter().any(|value| value_contains(value, needle)),
1073        Value::Json(_) => value_to_json(value)
1074            .as_ref()
1075            .is_some_and(|json| json_value_contains(json, needle)),
1076        Value::Text(value) => value.contains(needle),
1077        other => other.display_string().contains(needle),
1078    }
1079}
1080
1081fn json_value_contains(value: &crate::serde_json::Value, needle: &str) -> bool {
1082    match value {
1083        crate::serde_json::Value::Array(values) => values
1084            .iter()
1085            .any(|value| json_value_contains(value, needle)),
1086        // Recurse into object *values* so a needle nested inside a JSON
1087        // object matches — e.g. `CONTAINS(vision_detections, 'person')`
1088        // over a derived `[{"label":"person",...}]` array (#1275). Keys
1089        // are deliberately not matched: containment is about the data, not
1090        // the field names.
1091        crate::serde_json::Value::Object(map) => {
1092            map.values().any(|value| json_value_contains(value, needle))
1093        }
1094        crate::serde_json::Value::String(value) => value == needle,
1095        crate::serde_json::Value::Integer(value) => value.to_string() == needle,
1096        crate::serde_json::Value::Number(value) => value.to_string() == needle,
1097        crate::serde_json::Value::Decimal(value) => value == needle,
1098        crate::serde_json::Value::Bool(value) => value.to_string() == needle,
1099        crate::serde_json::Value::Null => false,
1100    }
1101}
1102
1103fn value_to_json(value: &Value) -> Option<crate::serde_json::Value> {
1104    match value {
1105        Value::Null => Some(crate::serde_json::Value::Null),
1106        // A document body may be the native binary container (PRD-1398); decode
1107        // it to JSON so json_extract / CONTAINS see the same shape as a plain
1108        // JSON body.
1109        Value::Json(bytes) => reddb_types::document_body_codec::decode_container_to_json(bytes)
1110            .or_else(|| crate::serde_json::from_slice(bytes).ok()),
1111        Value::Text(value) => crate::serde_json::from_str(value).ok(),
1112        _ => None,
1113    }
1114}
1115
1116enum JsonPathStep<'a> {
1117    Field(&'a str),
1118    Index(usize),
1119}
1120
1121fn parse_json_path(path: &str) -> Option<Vec<JsonPathStep<'_>>> {
1122    let path = path.trim();
1123    let rest = path.strip_prefix('$').unwrap_or(path);
1124    let mut steps = Vec::new();
1125    let bytes = rest.as_bytes();
1126    let mut index = 0;
1127    while index < bytes.len() {
1128        match bytes[index] {
1129            b'.' => {
1130                index += 1;
1131                let start = index;
1132                while index < bytes.len() && bytes[index] != b'.' && bytes[index] != b'[' {
1133                    index += 1;
1134                }
1135                if start == index {
1136                    return None;
1137                }
1138                steps.push(JsonPathStep::Field(
1139                    std::str::from_utf8(&bytes[start..index]).ok()?,
1140                ));
1141            }
1142            b'[' => {
1143                index += 1;
1144                let start = index;
1145                while index < bytes.len() && bytes[index] != b']' {
1146                    index += 1;
1147                }
1148                if index >= bytes.len() {
1149                    return None;
1150                }
1151                steps.push(JsonPathStep::Index(
1152                    std::str::from_utf8(&bytes[start..index])
1153                        .ok()?
1154                        .parse()
1155                        .ok()?,
1156                ));
1157                index += 1;
1158            }
1159            _ => return None,
1160        }
1161    }
1162    Some(steps)
1163}
1164
1165fn json_path_get<'a>(
1166    root: &'a crate::serde_json::Value,
1167    steps: &[JsonPathStep<'_>],
1168) -> Option<&'a crate::serde_json::Value> {
1169    let mut current = root;
1170    for step in steps {
1171        current = match (step, current) {
1172            (JsonPathStep::Field(name), crate::serde_json::Value::Object(map)) => map.get(*name)?,
1173            (JsonPathStep::Index(index), crate::serde_json::Value::Array(values)) => {
1174                values.get(*index)?
1175            }
1176            _ => return None,
1177        };
1178    }
1179    Some(current)
1180}
1181
1182fn eval_case(
1183    branches: &[(Expr, Expr)],
1184    else_: Option<&Expr>,
1185    row: &dyn Row,
1186    decode_literal: &impl Fn(&Value) -> Result<Value, EvalError>,
1187) -> Result<Value, EvalError> {
1188    for (cond, value) in branches {
1189        let c = evaluate_with_literal_decoder(cond, row, decode_literal)?;
1190        if matches!(c, Value::Boolean(true)) {
1191            return evaluate_with_literal_decoder(value, row, decode_literal);
1192        }
1193    }
1194    match else_ {
1195        Some(e) => evaluate_with_literal_decoder(e, row, decode_literal),
1196        None => Ok(Value::Null),
1197    }
1198}
1199
1200fn eval_in_list(
1201    target: &Expr,
1202    values: &[Expr],
1203    negated: bool,
1204    row: &dyn Row,
1205    decode_literal: &impl Fn(&Value) -> Result<Value, EvalError>,
1206) -> Result<Value, EvalError> {
1207    if values.is_empty() {
1208        return Err(EvalError::EmptyInList);
1209    }
1210    let needle = evaluate_with_literal_decoder(target, row, decode_literal)?;
1211    if needle.is_null() {
1212        return Ok(Value::Null);
1213    }
1214    let mut saw_null = false;
1215    for v in values {
1216        let candidate = evaluate_with_literal_decoder(v, row, decode_literal)?;
1217        if candidate.is_null() {
1218            saw_null = true;
1219            continue;
1220        }
1221        if values_equal(&needle, &candidate) {
1222            return Ok(Value::Boolean(!negated));
1223        }
1224    }
1225    if saw_null {
1226        return Ok(Value::Null);
1227    }
1228    Ok(Value::Boolean(negated))
1229}
1230
1231fn eval_between(
1232    target: &Expr,
1233    low: &Expr,
1234    high: &Expr,
1235    negated: bool,
1236    row: &dyn Row,
1237    decode_literal: &impl Fn(&Value) -> Result<Value, EvalError>,
1238) -> Result<Value, EvalError> {
1239    let v = evaluate_with_literal_decoder(target, row, decode_literal)?;
1240    let lo = evaluate_with_literal_decoder(low, row, decode_literal)?;
1241    let hi = evaluate_with_literal_decoder(high, row, decode_literal)?;
1242    if v.is_null() || lo.is_null() || hi.is_null() {
1243        return Ok(Value::Null);
1244    }
1245    let lo_ok = compare_values(&v, &lo)
1246        .ok_or(EvalError::OperatorMismatch {
1247            op: BinOp::Ge,
1248            lhs: v.data_type(),
1249            rhs: lo.data_type(),
1250        })
1251        .map(|o| o != std::cmp::Ordering::Less)?;
1252    let hi_ok = compare_values(&v, &hi)
1253        .ok_or(EvalError::OperatorMismatch {
1254            op: BinOp::Le,
1255            lhs: v.data_type(),
1256            rhs: hi.data_type(),
1257        })
1258        .map(|o| o != std::cmp::Ordering::Greater)?;
1259    let inside = lo_ok && hi_ok;
1260    Ok(Value::Boolean(if negated { !inside } else { inside }))
1261}
1262
1263#[cfg(test)]
1264mod tests {
1265    use super::*;
1266    use reddb_rql::ast::Span;
1267
1268    fn lit(v: Value) -> Expr {
1269        Expr::Literal {
1270            value: v,
1271            span: Span::synthetic(),
1272        }
1273    }
1274
1275    fn binop(op: BinOp, l: Expr, r: Expr) -> Expr {
1276        Expr::BinaryOp {
1277            op,
1278            lhs: Box::new(l),
1279            rhs: Box::new(r),
1280            span: Span::synthetic(),
1281        }
1282    }
1283
1284    fn empty_row() -> impl Row {
1285        |_field: &FieldRef| -> Option<Value> { None }
1286    }
1287
1288    #[test]
1289    fn contains_descends_into_json_object_values() {
1290        // A derived component-detections array (#1275): CONTAINS must find
1291        // a label nested inside the object elements, not just top-level
1292        // array strings.
1293        let detections = br#"[{"label":"person","confidence":0.9,"bbox":[0,0,1,1]},
1294                              {"label":"car","confidence":0.7,"bbox":[1,1,2,2]}]"#;
1295        let json = Value::Json(detections.to_vec());
1296        assert!(value_contains(&json, "person"));
1297        assert!(value_contains(&json, "car"));
1298        assert!(!value_contains(&json, "bicycle"));
1299        // Keys are not matched — only the data.
1300        assert!(!value_contains(&json, "label"));
1301    }
1302
1303    #[test]
1304    fn integer_addition_overflow_surfaces_as_eval_error() {
1305        let expr = binop(
1306            BinOp::Add,
1307            lit(Value::Integer(i64::MAX)),
1308            lit(Value::Integer(1)),
1309        );
1310        let err = evaluate(&expr, &empty_row()).unwrap_err();
1311        assert_eq!(err, EvalError::ArithmeticOverflow { op: BinOp::Add });
1312    }
1313
1314    #[test]
1315    fn integer_multiplication_overflow_surfaces_as_eval_error() {
1316        let expr = binop(
1317            BinOp::Mul,
1318            lit(Value::Integer(i64::MAX)),
1319            lit(Value::Integer(2)),
1320        );
1321        let err = evaluate(&expr, &empty_row()).unwrap_err();
1322        assert_eq!(err, EvalError::ArithmeticOverflow { op: BinOp::Mul });
1323    }
1324
1325    #[test]
1326    fn integer_subtraction_overflow_surfaces_as_eval_error() {
1327        let expr = binop(
1328            BinOp::Sub,
1329            lit(Value::Integer(i64::MIN)),
1330            lit(Value::Integer(1)),
1331        );
1332        let err = evaluate(&expr, &empty_row()).unwrap_err();
1333        assert_eq!(err, EvalError::ArithmeticOverflow { op: BinOp::Sub });
1334    }
1335
1336    #[test]
1337    fn unary_neg_overflow_on_min_int_surfaces_as_eval_error() {
1338        let expr = Expr::UnaryOp {
1339            op: UnaryOp::Neg,
1340            operand: Box::new(lit(Value::Integer(i64::MIN))),
1341            span: Span::synthetic(),
1342        };
1343        let err = evaluate(&expr, &empty_row()).unwrap_err();
1344        assert_eq!(err, EvalError::ArithmeticOverflow { op: BinOp::Sub });
1345    }
1346
1347    #[test]
1348    fn null_propagates_through_arithmetic() {
1349        let expr = binop(BinOp::Add, lit(Value::Null), lit(Value::Integer(7)));
1350        let v = evaluate(&expr, &empty_row()).unwrap();
1351        assert_eq!(v, Value::Null);
1352    }
1353
1354    #[test]
1355    fn null_propagates_through_comparison() {
1356        let expr = binop(BinOp::Lt, lit(Value::Integer(1)), lit(Value::Null));
1357        let v = evaluate(&expr, &empty_row()).unwrap();
1358        assert_eq!(v, Value::Null);
1359    }
1360
1361    #[test]
1362    fn null_propagates_through_concat() {
1363        let expr = binop(
1364            BinOp::Concat,
1365            lit(Value::Text(Arc::from("hi"))),
1366            lit(Value::Null),
1367        );
1368        let v = evaluate(&expr, &empty_row()).unwrap();
1369        assert_eq!(v, Value::Null);
1370    }
1371
1372    #[test]
1373    fn three_valued_and_returns_false_when_one_side_false_even_with_null() {
1374        let expr = binop(BinOp::And, lit(Value::Null), lit(Value::Boolean(false)));
1375        let v = evaluate(&expr, &empty_row()).unwrap();
1376        assert_eq!(v, Value::Boolean(false));
1377    }
1378
1379    #[test]
1380    fn three_valued_or_returns_true_when_one_side_true_even_with_null() {
1381        let expr = binop(BinOp::Or, lit(Value::Null), lit(Value::Boolean(true)));
1382        let v = evaluate(&expr, &empty_row()).unwrap();
1383        assert_eq!(v, Value::Boolean(true));
1384    }
1385
1386    #[test]
1387    fn three_valued_and_returns_null_for_null_and_true() {
1388        let expr = binop(BinOp::And, lit(Value::Null), lit(Value::Boolean(true)));
1389        let v = evaluate(&expr, &empty_row()).unwrap();
1390        assert_eq!(v, Value::Null);
1391    }
1392
1393    #[test]
1394    fn implicit_cast_triggers_for_decimal_plus_integer() {
1395        // Operator catalog has +(Decimal, Decimal) -> Decimal as
1396        // the only overload that survives coercion (no Decimal ->
1397        // numeric implicit casts exist in the cast catalog). The
1398        // spine therefore inserts an Integer -> Decimal cast on
1399        // the rhs and dispatches the Decimal addition.
1400        // parse_decimal scales by 10^4, so Integer(2) coerces to
1401        // Decimal(20000) and Decimal(10000) + Decimal(20000) =
1402        // Decimal(30000) (fixed-point 3.0000).
1403        let expr = binop(
1404            BinOp::Add,
1405            lit(Value::Decimal(10000)),
1406            lit(Value::Integer(2)),
1407        );
1408        let v = evaluate(&expr, &empty_row()).unwrap();
1409        assert_eq!(v, Value::Decimal(30000));
1410    }
1411
1412    #[test]
1413    fn integer_plus_bigint_resolves_to_preferred_float_overload() {
1414        // (Integer, BigInt) has no exact match. The spine ties
1415        // between +(Integer, Float, Float) (rhs cast BigInt->Float)
1416        // and +(BigInt, BigInt, BigInt) (lhs cast Integer->BigInt).
1417        // Float wins on the preferred-return-type tie-break, so the
1418        // BigInt operand is coerced to Float and the result is Float.
1419        let expr = binop(
1420            BinOp::Add,
1421            lit(Value::Integer(5)),
1422            lit(Value::BigInt(40_000_000_000)),
1423        );
1424        let v = evaluate(&expr, &empty_row()).unwrap();
1425        assert_eq!(v, Value::Float(40_000_000_005.0));
1426    }
1427
1428    #[test]
1429    fn integer_predicates_preserve_precision_across_signed_and_unsigned_boundaries() {
1430        let mut values = Vec::new();
1431        for number in [
1432            i64::MIN,
1433            -1,
1434            0,
1435            9_007_199_254_740_992,
1436            9_007_199_254_740_993,
1437            i64::MAX,
1438        ] {
1439            values.push((Value::Integer(number), i128::from(number)));
1440            values.push((Value::BigInt(number), i128::from(number)));
1441        }
1442        for number in [
1443            0,
1444            9_007_199_254_740_992,
1445            9_007_199_254_740_993,
1446            i64::MAX as u64,
1447            u64::MAX - 1,
1448            u64::MAX,
1449        ] {
1450            values.push((Value::UnsignedInteger(number), i128::from(number)));
1451        }
1452        for (left, left_exact) in &values {
1453            for (right, right_exact) in &values {
1454                for (operator, expected) in [
1455                    (BinOp::Eq, left_exact == right_exact),
1456                    (BinOp::Ne, left_exact != right_exact),
1457                    (BinOp::Lt, left_exact < right_exact),
1458                    (BinOp::Le, left_exact <= right_exact),
1459                    (BinOp::Gt, left_exact > right_exact),
1460                    (BinOp::Ge, left_exact >= right_exact),
1461                ] {
1462                    let expression = binop(operator, lit(left.clone()), lit(right.clone()));
1463                    assert_eq!(
1464                        evaluate(&expression, &empty_row())
1465                            .expect("integer comparison is supported"),
1466                        Value::Boolean(expected),
1467                        "{left:?} {operator:?} {right:?}"
1468                    );
1469                }
1470                for negated in [false, true] {
1471                    let expected = (*left_exact == *right_exact) != negated;
1472                    let membership = Expr::InList {
1473                        target: Box::new(lit(left.clone())),
1474                        values: vec![lit(right.clone())],
1475                        negated,
1476                        span: Span::synthetic(),
1477                    };
1478                    let interval = Expr::Between {
1479                        target: Box::new(lit(left.clone())),
1480                        low: Box::new(lit(right.clone())),
1481                        high: Box::new(lit(right.clone())),
1482                        negated,
1483                        span: Span::synthetic(),
1484                    };
1485                    for expression in [membership, interval] {
1486                        assert_eq!(
1487                            evaluate(&expression, &empty_row())
1488                                .expect("integer predicate is supported"),
1489                            Value::Boolean(expected),
1490                            "{expression:?}"
1491                        );
1492                    }
1493                }
1494            }
1495        }
1496    }
1497
1498    #[test]
1499    fn implicit_cast_promotes_integer_to_float_for_float_addition() {
1500        // The catalog has +(Integer, Float) -> Float as a direct
1501        // entry, so no actual coercion is inserted, but the result
1502        // must still be Float.
1503        let expr = binop(BinOp::Add, lit(Value::Integer(2)), lit(Value::Float(0.5)));
1504        let v = evaluate(&expr, &empty_row()).unwrap();
1505        assert_eq!(v, Value::Float(2.5));
1506    }
1507
1508    #[test]
1509    fn integer_division_promotes_to_float() {
1510        let expr = binop(BinOp::Div, lit(Value::Integer(7)), lit(Value::Integer(2)));
1511        let v = evaluate(&expr, &empty_row()).unwrap();
1512        assert_eq!(v, Value::Float(3.5));
1513    }
1514
1515    #[test]
1516    fn division_by_zero_is_eval_error() {
1517        let expr = binop(BinOp::Div, lit(Value::Integer(7)), lit(Value::Integer(0)));
1518        let err = evaluate(&expr, &empty_row()).unwrap_err();
1519        assert_eq!(err, EvalError::DivisionByZero);
1520    }
1521
1522    #[test]
1523    fn unknown_function_surfaces_as_eval_error() {
1524        let expr = Expr::FunctionCall {
1525            name: "no_such_fn".to_string(),
1526            args: vec![lit(Value::Integer(1))],
1527            span: Span::synthetic(),
1528        };
1529        let err = evaluate(&expr, &empty_row()).unwrap_err();
1530        match err {
1531            EvalError::UnknownFunction { name, args } => {
1532                assert_eq!(name, "no_such_fn");
1533                assert_eq!(args, vec![DataType::Integer]);
1534            }
1535            other => panic!("expected UnknownFunction, got {other:?}"),
1536        }
1537    }
1538
1539    #[test]
1540    fn coalesce_returns_first_non_null() {
1541        let expr = Expr::FunctionCall {
1542            name: "COALESCE".to_string(),
1543            args: vec![
1544                lit(Value::Null),
1545                lit(Value::Null),
1546                lit(Value::Integer(42)),
1547                lit(Value::Integer(99)),
1548            ],
1549            span: Span::synthetic(),
1550        };
1551        let v = evaluate(&expr, &empty_row()).unwrap();
1552        assert_eq!(v, Value::Integer(42));
1553    }
1554
1555    #[test]
1556    fn coalesce_all_null_returns_null() {
1557        let expr = Expr::FunctionCall {
1558            name: "COALESCE".to_string(),
1559            args: vec![lit(Value::Null), lit(Value::Null)],
1560            span: Span::synthetic(),
1561        };
1562        let v = evaluate(&expr, &empty_row()).unwrap();
1563        assert_eq!(v, Value::Null);
1564    }
1565
1566    #[test]
1567    fn variadic_concat_owns_null_semantics() {
1568        let expr = Expr::FunctionCall {
1569            name: "CONCAT".to_string(),
1570            args: vec![
1571                lit(Value::Text(Arc::from("red"))),
1572                lit(Value::Null),
1573                lit(Value::Text(Arc::from("db"))),
1574            ],
1575            span: Span::synthetic(),
1576        };
1577        let value = evaluate(&expr, &empty_row()).unwrap();
1578        assert_eq!(value, Value::Text(Arc::from("reddb")));
1579    }
1580
1581    #[test]
1582    fn upper_lower_dispatch_through_function_catalog() {
1583        let expr = Expr::FunctionCall {
1584            name: "UPPER".to_string(),
1585            args: vec![lit(Value::Text(Arc::from("hello")))],
1586            span: Span::synthetic(),
1587        };
1588        let v = evaluate(&expr, &empty_row()).unwrap();
1589        assert_eq!(v, Value::Text(Arc::from("HELLO")));
1590    }
1591
1592    #[test]
1593    fn length_of_null_propagates() {
1594        let expr = Expr::FunctionCall {
1595            name: "LENGTH".to_string(),
1596            args: vec![lit(Value::Null)],
1597            span: Span::synthetic(),
1598        };
1599        let v = evaluate(&expr, &empty_row()).unwrap();
1600        assert_eq!(v, Value::Null);
1601    }
1602
1603    #[test]
1604    fn case_when_picks_first_true_branch() {
1605        let expr = Expr::Case {
1606            branches: vec![
1607                (lit(Value::Boolean(false)), lit(Value::Integer(1))),
1608                (lit(Value::Boolean(true)), lit(Value::Integer(2))),
1609                (lit(Value::Boolean(true)), lit(Value::Integer(3))),
1610            ],
1611            else_: Some(Box::new(lit(Value::Integer(99)))),
1612            span: Span::synthetic(),
1613        };
1614        let v = evaluate(&expr, &empty_row()).unwrap();
1615        assert_eq!(v, Value::Integer(2));
1616    }
1617
1618    #[test]
1619    fn case_falls_through_to_else_when_no_branch_matches() {
1620        let expr = Expr::Case {
1621            branches: vec![(lit(Value::Boolean(false)), lit(Value::Integer(1)))],
1622            else_: Some(Box::new(lit(Value::Integer(99)))),
1623            span: Span::synthetic(),
1624        };
1625        let v = evaluate(&expr, &empty_row()).unwrap();
1626        assert_eq!(v, Value::Integer(99));
1627    }
1628
1629    #[test]
1630    fn case_returns_null_when_no_branch_matches_and_no_else() {
1631        let expr = Expr::Case {
1632            branches: vec![(lit(Value::Boolean(false)), lit(Value::Integer(1)))],
1633            else_: None,
1634            span: Span::synthetic(),
1635        };
1636        let v = evaluate(&expr, &empty_row()).unwrap();
1637        assert_eq!(v, Value::Null);
1638    }
1639
1640    #[test]
1641    fn is_null_handles_null_and_non_null() {
1642        let null_expr = Expr::IsNull {
1643            operand: Box::new(lit(Value::Null)),
1644            negated: false,
1645            span: Span::synthetic(),
1646        };
1647        assert_eq!(
1648            evaluate(&null_expr, &empty_row()).unwrap(),
1649            Value::Boolean(true)
1650        );
1651
1652        let non_null_expr = Expr::IsNull {
1653            operand: Box::new(lit(Value::Integer(7))),
1654            negated: false,
1655            span: Span::synthetic(),
1656        };
1657        assert_eq!(
1658            evaluate(&non_null_expr, &empty_row()).unwrap(),
1659            Value::Boolean(false)
1660        );
1661    }
1662
1663    #[test]
1664    fn between_inclusive_bounds() {
1665        let expr = Expr::Between {
1666            target: Box::new(lit(Value::Integer(5))),
1667            low: Box::new(lit(Value::Integer(1))),
1668            high: Box::new(lit(Value::Integer(10))),
1669            negated: false,
1670            span: Span::synthetic(),
1671        };
1672        assert_eq!(evaluate(&expr, &empty_row()).unwrap(), Value::Boolean(true));
1673    }
1674
1675    #[test]
1676    fn in_list_match_and_miss() {
1677        let hit = Expr::InList {
1678            target: Box::new(lit(Value::Integer(2))),
1679            values: vec![
1680                lit(Value::Integer(1)),
1681                lit(Value::Integer(2)),
1682                lit(Value::Integer(3)),
1683            ],
1684            negated: false,
1685            span: Span::synthetic(),
1686        };
1687        assert_eq!(evaluate(&hit, &empty_row()).unwrap(), Value::Boolean(true));
1688
1689        let miss = Expr::InList {
1690            target: Box::new(lit(Value::Integer(99))),
1691            values: vec![lit(Value::Integer(1)), lit(Value::Integer(2))],
1692            negated: false,
1693            span: Span::synthetic(),
1694        };
1695        assert_eq!(
1696            evaluate(&miss, &empty_row()).unwrap(),
1697            Value::Boolean(false)
1698        );
1699    }
1700
1701    #[test]
1702    fn column_lookup_walks_field_ref() {
1703        let row = |field: &FieldRef| -> Option<Value> {
1704            match field {
1705                FieldRef::TableColumn { table, column } if table == "t" && column == "x" => {
1706                    Some(Value::Integer(11))
1707                }
1708                _ => None,
1709            }
1710        };
1711        let expr = Expr::Column {
1712            field: FieldRef::TableColumn {
1713                table: "t".to_string(),
1714                column: "x".to_string(),
1715            },
1716            span: Span::synthetic(),
1717        };
1718        assert_eq!(evaluate(&expr, &row).unwrap(), Value::Integer(11));
1719    }
1720
1721    #[test]
1722    fn missing_column_surfaces_unknown_column() {
1723        let row = |_: &FieldRef| -> Option<Value> { None };
1724        let expr = Expr::Column {
1725            field: FieldRef::TableColumn {
1726                table: "t".to_string(),
1727                column: "missing".to_string(),
1728            },
1729            span: Span::synthetic(),
1730        };
1731        let err = evaluate(&expr, &row).unwrap_err();
1732        match err {
1733            EvalError::UnknownColumn(_) => {}
1734            other => panic!("expected UnknownColumn, got {other:?}"),
1735        }
1736    }
1737
1738    #[test]
1739    fn parameter_without_bind_is_eval_error() {
1740        let expr = Expr::Parameter {
1741            index: 1,
1742            span: Span::synthetic(),
1743        };
1744        let err = evaluate(&expr, &empty_row()).unwrap_err();
1745        assert_eq!(err, EvalError::UnboundParameter(1));
1746    }
1747
1748    #[test]
1749    fn cast_integer_to_text_uses_explicit_path() {
1750        let expr = Expr::Cast {
1751            inner: Box::new(lit(Value::Integer(42))),
1752            target: DataType::Text,
1753            span: Span::synthetic(),
1754        };
1755        assert_eq!(
1756            evaluate(&expr, &empty_row()).unwrap(),
1757            Value::Text(Arc::from("42"))
1758        );
1759    }
1760
1761    #[test]
1762    fn concat_returns_text() {
1763        let expr = binop(
1764            BinOp::Concat,
1765            lit(Value::Text(Arc::from("foo"))),
1766            lit(Value::Text(Arc::from("bar"))),
1767        );
1768        assert_eq!(
1769            evaluate(&expr, &empty_row()).unwrap(),
1770            Value::Text(Arc::from("foobar"))
1771        );
1772    }
1773}