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    // COALESCE has SQL-special semantics that the catalog can't
712    // express (variadic + uniform arg type unifies poorly with
713    // first-non-null). Handle it before catalog dispatch so we
714    // preserve `COALESCE(int, int) -> int` rather than coercing
715    // every argument to Text.
716    if name.eq_ignore_ascii_case("COALESCE") {
717        for arg in args {
718            let v = evaluate_with_literal_decoder(arg, row, decode_literal)?;
719            if !v.is_null() {
720                return Ok(v);
721            }
722        }
723        return Ok(Value::Null);
724    }
725
726    let arg_values: Vec<Value> = args
727        .iter()
728        .map(|a| evaluate_with_literal_decoder(a, row, decode_literal))
729        .collect::<Result<Vec<_>, _>>()?;
730    let arg_types: Vec<DataType> = arg_values.iter().map(|v| v.data_type()).collect();
731
732    // Strict NULL propagation applies only to non-variadic built-ins.
733    // Variadic functions such as CONCAT own their NULL semantics.
734    // Unknown functions with NULL arguments must still surface as
735    // `UnknownFunction` rather than silently returning NULL.
736    if arg_values.iter().any(Value::is_null)
737        && FUNCTION_CATALOG
738            .iter()
739            .any(|entry| entry.name.eq_ignore_ascii_case(name))
740        && FUNCTION_CATALOG
741            .iter()
742            .filter(|entry| entry.name.eq_ignore_ascii_case(name))
743            .all(|entry| !entry.variadic)
744    {
745        return Ok(Value::Null);
746    }
747
748    let (entry, coercions) =
749        coercion_spine::resolve_function(name, &arg_types).ok_or_else(|| {
750            EvalError::UnknownFunction {
751                name: name.to_string(),
752                args: arg_types.clone(),
753            }
754        })?;
755
756    // Apply per-arg implicit casts.
757    let mut coerced: Vec<Value> = Vec::with_capacity(arg_values.len());
758    for (idx, value) in arg_values.into_iter().enumerate() {
759        let src = arg_types[idx];
760        match coercions.at(idx) {
761            Some(target) if src != target => {
762                coerced.push(apply_implicit_cast(&value, src, target)?);
763            }
764            _ => coerced.push(value),
765        }
766    }
767
768    // NULL propagation for built-ins: if any non-variadic argument
769    // is null, return null. Variadic / aggregate semantics handle
770    // null differently and aren't in scope for this slice.
771    if !entry.variadic && coerced.iter().any(|v| v.is_null()) {
772        return Ok(Value::Null);
773    }
774
775    dispatch_function(entry.name, &coerced)
776}
777
778fn dispatch_function(name: &str, args: &[Value]) -> Result<Value, EvalError> {
779    match name {
780        "CRON" | "CRON_NEXT" | "CRON_OVERLAPS" => {
781            super::runtime::value_functions::evaluate_cron_function(name, args)
782                .map_err(|reason| EvalError::CronFailed(format!("{name}: {reason}")))
783        }
784        "TEMPERATURE" | "TEMPERATURE_UNIT" | "TEMPERATURE_VALUE" => {
785            super::runtime::value_functions::temperature_function(name, args).ok_or_else(|| {
786                EvalError::UnknownFunction {
787                    name: name.into(),
788                    args: args.iter().map(Value::data_type).collect(),
789                }
790            })
791        }
792        "UPPER" => match &args[0] {
793            Value::Text(s) => Ok(Value::Text(Arc::from(s.to_uppercase()))),
794            other => Err(EvalError::UnknownFunction {
795                name: name.to_string(),
796                args: vec![other.data_type()],
797            }),
798        },
799        "LOWER" => match &args[0] {
800            Value::Text(s) => Ok(Value::Text(Arc::from(s.to_lowercase()))),
801            other => Err(EvalError::UnknownFunction {
802                name: name.to_string(),
803                args: vec![other.data_type()],
804            }),
805        },
806        "TRIM" => trim_function(name, args, true, true),
807        "LTRIM" => trim_function(name, args, true, false),
808        "RTRIM" => trim_function(name, args, false, true),
809        "LENGTH" | "CHAR_LENGTH" | "CHARACTER_LENGTH" => match &args[0] {
810            Value::Text(s) => Ok(Value::Integer(s.chars().count() as i64)),
811            other => Err(EvalError::UnknownFunction {
812                name: name.to_string(),
813                args: vec![other.data_type()],
814            }),
815        },
816        "OCTET_LENGTH" => match &args[0] {
817            Value::Text(s) => Ok(Value::Integer(s.len() as i64)),
818            Value::Blob(b) => Ok(Value::Integer(b.len() as i64)),
819            other => Err(EvalError::UnknownFunction {
820                name: name.to_string(),
821                args: vec![other.data_type()],
822            }),
823        },
824        "CONCAT" => {
825            let mut out = String::new();
826            for arg in args {
827                match arg {
828                    Value::Null => {}
829                    Value::Text(value) => out.push_str(value),
830                    _ => {
831                        return Err(EvalError::UnknownFunction {
832                            name: name.to_string(),
833                            args: args.iter().map(Value::data_type).collect(),
834                        })
835                    }
836                }
837            }
838            Ok(Value::Text(Arc::from(out)))
839        }
840        "JSON_PARSE" => json_parse_value(&args[0]),
841        "JSON_EXTRACT" => Ok(json_extract_value(&args[0], &args[1], false)),
842        "JSON_EXTRACT_TEXT" => Ok(json_extract_value(&args[0], &args[1], true)),
843        "CONTAINS" => Ok(contains_value(&args[0], &args[1])),
844        "ABS" => match &args[0] {
845            Value::Integer(n) => n
846                .checked_abs()
847                .map(Value::Integer)
848                .ok_or(EvalError::ArithmeticOverflow { op: BinOp::Sub }),
849            Value::BigInt(n) => n
850                .checked_abs()
851                .map(Value::BigInt)
852                .ok_or(EvalError::ArithmeticOverflow { op: BinOp::Sub }),
853            Value::Float(n) => Ok(Value::Float(n.abs())),
854            Value::Decimal(n) => n
855                .checked_abs()
856                .map(Value::Decimal)
857                .ok_or(EvalError::ArithmeticOverflow { op: BinOp::Sub }),
858            other => Err(EvalError::UnknownFunction {
859                name: name.to_string(),
860                args: vec![other.data_type()],
861            }),
862        },
863        "SQRT" => unary_math(name, args, |x| {
864            if x < 0.0 {
865                return Err("input must be greater than or equal to zero");
866            }
867            Ok(x.sqrt())
868        }),
869        "POWER" | "POW" => binary_math(name, args, |base, exp| Ok(base.powf(exp))),
870        "EXP" => unary_math(name, args, |x| Ok(x.exp())),
871        "LN" => unary_math(name, args, |x| {
872            if x <= 0.0 {
873                return Err("input must be greater than zero");
874            }
875            Ok(x.ln())
876        }),
877        "LOG" if args.len() == 1 => unary_math(name, args, |x| {
878            if x <= 0.0 {
879                return Err("input must be greater than zero");
880            }
881            Ok(x.log10())
882        }),
883        "LOG" => binary_math(name, args, |base, x| {
884            if base <= 0.0 {
885                return Err("base must be greater than zero");
886            }
887            if base == 1.0 {
888                return Err("base must not equal one");
889            }
890            if x <= 0.0 {
891                return Err("input must be greater than zero");
892            }
893            Ok(x.log(base))
894        }),
895        "LOG10" => unary_math(name, args, |x| {
896            if x <= 0.0 {
897                return Err("input must be greater than zero");
898            }
899            Ok(x.log10())
900        }),
901        "SIN" => unary_math(name, args, |x| Ok(x.sin())),
902        "COS" => unary_math(name, args, |x| Ok(x.cos())),
903        "TAN" => unary_math(name, args, |x| Ok(x.tan())),
904        "ASIN" | "ARCSIN" => unary_math(name, args, |x| {
905            if !(-1.0..=1.0).contains(&x) {
906                return Err("input must be between -1 and 1");
907            }
908            Ok(x.asin())
909        }),
910        "ACOS" | "ARCCOS" => unary_math(name, args, |x| {
911            if !(-1.0..=1.0).contains(&x) {
912                return Err("input must be between -1 and 1");
913            }
914            Ok(x.acos())
915        }),
916        "ATAN" | "ARCTAN" => unary_math(name, args, |x| Ok(x.atan())),
917        "ATAN2" => binary_math(name, args, |y, x| Ok(y.atan2(x))),
918        "COT" => unary_math(name, args, |x| {
919            let tan = x.tan();
920            if tan == 0.0 {
921                return Err("input must not produce zero tangent");
922            }
923            Ok(1.0 / tan)
924        }),
925        "DEGREES" => unary_math(name, args, |x| Ok(x.to_degrees())),
926        "RADIANS" => unary_math(name, args, |x| Ok(x.to_radians())),
927        "PI" => checked_math_result(name, std::f64::consts::PI),
928        // Functions whose runtime body the slice doesn't yet cover
929        // surface as UnknownFunction with the resolved arg types so
930        // callers can see the catalog matched but the dispatch
931        // didn't. Subsequent slices fill in CONCAT, time functions, …
932        other => Err(EvalError::UnknownFunction {
933            name: other.to_string(),
934            args: args.iter().map(|v| v.data_type()).collect(),
935        }),
936    }
937}
938
939fn trim_function(name: &str, args: &[Value], left: bool, right: bool) -> Result<Value, EvalError> {
940    if args.len() != 1 {
941        return Err(EvalError::UnknownFunction {
942            name: name.to_string(),
943            args: args.iter().map(|v| v.data_type()).collect(),
944        });
945    }
946
947    match &args[0] {
948        Value::Text(s) => {
949            let trimmed = match (left, right) {
950                (true, true) => s.trim(),
951                (true, false) => s.trim_start(),
952                (false, true) => s.trim_end(),
953                (false, false) => s,
954            };
955            Ok(Value::Text(Arc::from(trimmed)))
956        }
957        other => Err(EvalError::UnknownFunction {
958            name: name.to_string(),
959            args: vec![other.data_type()],
960        }),
961    }
962}
963
964fn unary_math<F>(name: &str, args: &[Value], op: F) -> Result<Value, EvalError>
965where
966    F: FnOnce(f64) -> Result<f64, &'static str>,
967{
968    let input = math_arg(name, args.first(), 0)?;
969    let value = op(input).map_err(|reason| EvalError::InvalidNumericResult {
970        function: name.to_string(),
971        reason: reason.to_string(),
972    })?;
973    checked_math_result(name, value)
974}
975
976fn binary_math<F>(name: &str, args: &[Value], op: F) -> Result<Value, EvalError>
977where
978    F: FnOnce(f64, f64) -> Result<f64, &'static str>,
979{
980    let left = math_arg(name, args.first(), 0)?;
981    let right = math_arg(name, args.get(1), 1)?;
982    let value = op(left, right).map_err(|reason| EvalError::InvalidNumericResult {
983        function: name.to_string(),
984        reason: reason.to_string(),
985    })?;
986    checked_math_result(name, value)
987}
988
989fn math_arg(name: &str, value: Option<&Value>, index: usize) -> Result<f64, EvalError> {
990    let value = value.ok_or_else(|| EvalError::UnknownFunction {
991        name: name.to_string(),
992        args: Vec::new(),
993    })?;
994    let numeric = as_f64(value);
995    if numeric.is_finite() {
996        Ok(numeric)
997    } else {
998        Err(EvalError::InvalidNumericResult {
999            function: name.to_string(),
1000            reason: format!("argument {index} is NaN or infinite"),
1001        })
1002    }
1003}
1004
1005fn checked_math_result(name: &str, value: f64) -> Result<Value, EvalError> {
1006    if value.is_finite() {
1007        Ok(Value::Float(value))
1008    } else {
1009        Err(EvalError::InvalidNumericResult {
1010            function: name.to_string(),
1011            reason: "result is NaN or infinite".to_string(),
1012        })
1013    }
1014}
1015
1016fn json_extract_value(input: &Value, path: &Value, as_text: bool) -> Value {
1017    let Value::Text(path) = path else {
1018        return Value::Null;
1019    };
1020    let Some(json) = value_to_json(input) else {
1021        return Value::Null;
1022    };
1023    let Some(steps) = parse_json_path(path) else {
1024        return Value::Null;
1025    };
1026    let Some(target) = json_path_get(&json, &steps) else {
1027        return Value::Null;
1028    };
1029
1030    if as_text {
1031        match target {
1032            crate::serde_json::Value::String(value) => Value::text(value.clone()),
1033            crate::serde_json::Value::Null => Value::Null,
1034            crate::serde_json::Value::Bool(value) => Value::text(value.to_string()),
1035            crate::serde_json::Value::Integer(value) => Value::text(value.to_string()),
1036            crate::serde_json::Value::Number(value) => Value::text(value.to_string()),
1037            other => Value::text(other.to_string_compact()),
1038        }
1039    } else {
1040        Value::text(target.to_string_compact())
1041    }
1042}
1043
1044fn json_parse_value(input: &Value) -> Result<Value, EvalError> {
1045    let Value::Text(text) = input else {
1046        return Err(EvalError::UnknownFunction {
1047            name: "JSON_PARSE".to_string(),
1048            args: vec![input.data_type()],
1049        });
1050    };
1051    crate::serde_json::from_str::<crate::serde_json::Value>(text)
1052        .map(|json| Value::Json(json.to_string_compact().into_bytes()))
1053        .map_err(|err| EvalError::JsonParseFailed {
1054            reason: err.to_string(),
1055        })
1056}
1057
1058fn contains_value(input: &Value, needle: &Value) -> Value {
1059    let Value::Text(needle) = needle else {
1060        return Value::Null;
1061    };
1062    Value::Boolean(value_contains(input, needle))
1063}
1064
1065fn value_contains(value: &Value, needle: &str) -> bool {
1066    match value {
1067        Value::Array(values) => values.iter().any(|value| value_contains(value, needle)),
1068        Value::Json(_) => value_to_json(value)
1069            .as_ref()
1070            .is_some_and(|json| json_value_contains(json, needle)),
1071        Value::Text(value) => value.contains(needle),
1072        other => other.display_string().contains(needle),
1073    }
1074}
1075
1076fn json_value_contains(value: &crate::serde_json::Value, needle: &str) -> bool {
1077    match value {
1078        crate::serde_json::Value::Array(values) => values
1079            .iter()
1080            .any(|value| json_value_contains(value, needle)),
1081        // Recurse into object *values* so a needle nested inside a JSON
1082        // object matches — e.g. `CONTAINS(vision_detections, 'person')`
1083        // over a derived `[{"label":"person",...}]` array (#1275). Keys
1084        // are deliberately not matched: containment is about the data, not
1085        // the field names.
1086        crate::serde_json::Value::Object(map) => {
1087            map.values().any(|value| json_value_contains(value, needle))
1088        }
1089        crate::serde_json::Value::String(value) => value == needle,
1090        crate::serde_json::Value::Integer(value) => value.to_string() == needle,
1091        crate::serde_json::Value::Number(value) => value.to_string() == needle,
1092        crate::serde_json::Value::Decimal(value) => value == needle,
1093        crate::serde_json::Value::Bool(value) => value.to_string() == needle,
1094        crate::serde_json::Value::Null => false,
1095    }
1096}
1097
1098fn value_to_json(value: &Value) -> Option<crate::serde_json::Value> {
1099    match value {
1100        Value::Null => Some(crate::serde_json::Value::Null),
1101        // A document body may be the native binary container (PRD-1398); decode
1102        // it to JSON so json_extract / CONTAINS see the same shape as a plain
1103        // JSON body.
1104        Value::Json(bytes) => reddb_types::document_body_codec::decode_container_to_json(bytes)
1105            .or_else(|| crate::serde_json::from_slice(bytes).ok()),
1106        Value::Text(value) => crate::serde_json::from_str(value).ok(),
1107        _ => None,
1108    }
1109}
1110
1111enum JsonPathStep<'a> {
1112    Field(&'a str),
1113    Index(usize),
1114}
1115
1116fn parse_json_path(path: &str) -> Option<Vec<JsonPathStep<'_>>> {
1117    let path = path.trim();
1118    let rest = path.strip_prefix('$').unwrap_or(path);
1119    let mut steps = Vec::new();
1120    let bytes = rest.as_bytes();
1121    let mut index = 0;
1122    while index < bytes.len() {
1123        match bytes[index] {
1124            b'.' => {
1125                index += 1;
1126                let start = index;
1127                while index < bytes.len() && bytes[index] != b'.' && bytes[index] != b'[' {
1128                    index += 1;
1129                }
1130                if start == index {
1131                    return None;
1132                }
1133                steps.push(JsonPathStep::Field(
1134                    std::str::from_utf8(&bytes[start..index]).ok()?,
1135                ));
1136            }
1137            b'[' => {
1138                index += 1;
1139                let start = index;
1140                while index < bytes.len() && bytes[index] != b']' {
1141                    index += 1;
1142                }
1143                if index >= bytes.len() {
1144                    return None;
1145                }
1146                steps.push(JsonPathStep::Index(
1147                    std::str::from_utf8(&bytes[start..index])
1148                        .ok()?
1149                        .parse()
1150                        .ok()?,
1151                ));
1152                index += 1;
1153            }
1154            _ => return None,
1155        }
1156    }
1157    Some(steps)
1158}
1159
1160fn json_path_get<'a>(
1161    root: &'a crate::serde_json::Value,
1162    steps: &[JsonPathStep<'_>],
1163) -> Option<&'a crate::serde_json::Value> {
1164    let mut current = root;
1165    for step in steps {
1166        current = match (step, current) {
1167            (JsonPathStep::Field(name), crate::serde_json::Value::Object(map)) => map.get(*name)?,
1168            (JsonPathStep::Index(index), crate::serde_json::Value::Array(values)) => {
1169                values.get(*index)?
1170            }
1171            _ => return None,
1172        };
1173    }
1174    Some(current)
1175}
1176
1177fn eval_case(
1178    branches: &[(Expr, Expr)],
1179    else_: Option<&Expr>,
1180    row: &dyn Row,
1181    decode_literal: &impl Fn(&Value) -> Result<Value, EvalError>,
1182) -> Result<Value, EvalError> {
1183    for (cond, value) in branches {
1184        let c = evaluate_with_literal_decoder(cond, row, decode_literal)?;
1185        if matches!(c, Value::Boolean(true)) {
1186            return evaluate_with_literal_decoder(value, row, decode_literal);
1187        }
1188    }
1189    match else_ {
1190        Some(e) => evaluate_with_literal_decoder(e, row, decode_literal),
1191        None => Ok(Value::Null),
1192    }
1193}
1194
1195fn eval_in_list(
1196    target: &Expr,
1197    values: &[Expr],
1198    negated: bool,
1199    row: &dyn Row,
1200    decode_literal: &impl Fn(&Value) -> Result<Value, EvalError>,
1201) -> Result<Value, EvalError> {
1202    if values.is_empty() {
1203        return Err(EvalError::EmptyInList);
1204    }
1205    let needle = evaluate_with_literal_decoder(target, row, decode_literal)?;
1206    if needle.is_null() {
1207        return Ok(Value::Null);
1208    }
1209    let mut saw_null = false;
1210    for v in values {
1211        let candidate = evaluate_with_literal_decoder(v, row, decode_literal)?;
1212        if candidate.is_null() {
1213            saw_null = true;
1214            continue;
1215        }
1216        if values_equal(&needle, &candidate) {
1217            return Ok(Value::Boolean(!negated));
1218        }
1219    }
1220    if saw_null {
1221        return Ok(Value::Null);
1222    }
1223    Ok(Value::Boolean(negated))
1224}
1225
1226fn eval_between(
1227    target: &Expr,
1228    low: &Expr,
1229    high: &Expr,
1230    negated: bool,
1231    row: &dyn Row,
1232    decode_literal: &impl Fn(&Value) -> Result<Value, EvalError>,
1233) -> Result<Value, EvalError> {
1234    let v = evaluate_with_literal_decoder(target, row, decode_literal)?;
1235    let lo = evaluate_with_literal_decoder(low, row, decode_literal)?;
1236    let hi = evaluate_with_literal_decoder(high, row, decode_literal)?;
1237    if v.is_null() || lo.is_null() || hi.is_null() {
1238        return Ok(Value::Null);
1239    }
1240    let lo_ok = compare_values(&v, &lo)
1241        .ok_or(EvalError::OperatorMismatch {
1242            op: BinOp::Ge,
1243            lhs: v.data_type(),
1244            rhs: lo.data_type(),
1245        })
1246        .map(|o| o != std::cmp::Ordering::Less)?;
1247    let hi_ok = compare_values(&v, &hi)
1248        .ok_or(EvalError::OperatorMismatch {
1249            op: BinOp::Le,
1250            lhs: v.data_type(),
1251            rhs: hi.data_type(),
1252        })
1253        .map(|o| o != std::cmp::Ordering::Greater)?;
1254    let inside = lo_ok && hi_ok;
1255    Ok(Value::Boolean(if negated { !inside } else { inside }))
1256}
1257
1258#[cfg(test)]
1259mod tests {
1260    use super::*;
1261    use reddb_rql::ast::Span;
1262
1263    fn lit(v: Value) -> Expr {
1264        Expr::Literal {
1265            value: v,
1266            span: Span::synthetic(),
1267        }
1268    }
1269
1270    fn binop(op: BinOp, l: Expr, r: Expr) -> Expr {
1271        Expr::BinaryOp {
1272            op,
1273            lhs: Box::new(l),
1274            rhs: Box::new(r),
1275            span: Span::synthetic(),
1276        }
1277    }
1278
1279    fn empty_row() -> impl Row {
1280        |_field: &FieldRef| -> Option<Value> { None }
1281    }
1282
1283    #[test]
1284    fn contains_descends_into_json_object_values() {
1285        // A derived component-detections array (#1275): CONTAINS must find
1286        // a label nested inside the object elements, not just top-level
1287        // array strings.
1288        let detections = br#"[{"label":"person","confidence":0.9,"bbox":[0,0,1,1]},
1289                              {"label":"car","confidence":0.7,"bbox":[1,1,2,2]}]"#;
1290        let json = Value::Json(detections.to_vec());
1291        assert!(value_contains(&json, "person"));
1292        assert!(value_contains(&json, "car"));
1293        assert!(!value_contains(&json, "bicycle"));
1294        // Keys are not matched — only the data.
1295        assert!(!value_contains(&json, "label"));
1296    }
1297
1298    #[test]
1299    fn integer_addition_overflow_surfaces_as_eval_error() {
1300        let expr = binop(
1301            BinOp::Add,
1302            lit(Value::Integer(i64::MAX)),
1303            lit(Value::Integer(1)),
1304        );
1305        let err = evaluate(&expr, &empty_row()).unwrap_err();
1306        assert_eq!(err, EvalError::ArithmeticOverflow { op: BinOp::Add });
1307    }
1308
1309    #[test]
1310    fn integer_multiplication_overflow_surfaces_as_eval_error() {
1311        let expr = binop(
1312            BinOp::Mul,
1313            lit(Value::Integer(i64::MAX)),
1314            lit(Value::Integer(2)),
1315        );
1316        let err = evaluate(&expr, &empty_row()).unwrap_err();
1317        assert_eq!(err, EvalError::ArithmeticOverflow { op: BinOp::Mul });
1318    }
1319
1320    #[test]
1321    fn integer_subtraction_overflow_surfaces_as_eval_error() {
1322        let expr = binop(
1323            BinOp::Sub,
1324            lit(Value::Integer(i64::MIN)),
1325            lit(Value::Integer(1)),
1326        );
1327        let err = evaluate(&expr, &empty_row()).unwrap_err();
1328        assert_eq!(err, EvalError::ArithmeticOverflow { op: BinOp::Sub });
1329    }
1330
1331    #[test]
1332    fn unary_neg_overflow_on_min_int_surfaces_as_eval_error() {
1333        let expr = Expr::UnaryOp {
1334            op: UnaryOp::Neg,
1335            operand: Box::new(lit(Value::Integer(i64::MIN))),
1336            span: Span::synthetic(),
1337        };
1338        let err = evaluate(&expr, &empty_row()).unwrap_err();
1339        assert_eq!(err, EvalError::ArithmeticOverflow { op: BinOp::Sub });
1340    }
1341
1342    #[test]
1343    fn null_propagates_through_arithmetic() {
1344        let expr = binop(BinOp::Add, lit(Value::Null), lit(Value::Integer(7)));
1345        let v = evaluate(&expr, &empty_row()).unwrap();
1346        assert_eq!(v, Value::Null);
1347    }
1348
1349    #[test]
1350    fn null_propagates_through_comparison() {
1351        let expr = binop(BinOp::Lt, lit(Value::Integer(1)), lit(Value::Null));
1352        let v = evaluate(&expr, &empty_row()).unwrap();
1353        assert_eq!(v, Value::Null);
1354    }
1355
1356    #[test]
1357    fn null_propagates_through_concat() {
1358        let expr = binop(
1359            BinOp::Concat,
1360            lit(Value::Text(Arc::from("hi"))),
1361            lit(Value::Null),
1362        );
1363        let v = evaluate(&expr, &empty_row()).unwrap();
1364        assert_eq!(v, Value::Null);
1365    }
1366
1367    #[test]
1368    fn three_valued_and_returns_false_when_one_side_false_even_with_null() {
1369        let expr = binop(BinOp::And, lit(Value::Null), lit(Value::Boolean(false)));
1370        let v = evaluate(&expr, &empty_row()).unwrap();
1371        assert_eq!(v, Value::Boolean(false));
1372    }
1373
1374    #[test]
1375    fn three_valued_or_returns_true_when_one_side_true_even_with_null() {
1376        let expr = binop(BinOp::Or, lit(Value::Null), lit(Value::Boolean(true)));
1377        let v = evaluate(&expr, &empty_row()).unwrap();
1378        assert_eq!(v, Value::Boolean(true));
1379    }
1380
1381    #[test]
1382    fn three_valued_and_returns_null_for_null_and_true() {
1383        let expr = binop(BinOp::And, lit(Value::Null), lit(Value::Boolean(true)));
1384        let v = evaluate(&expr, &empty_row()).unwrap();
1385        assert_eq!(v, Value::Null);
1386    }
1387
1388    #[test]
1389    fn implicit_cast_triggers_for_decimal_plus_integer() {
1390        // Operator catalog has +(Decimal, Decimal) -> Decimal as
1391        // the only overload that survives coercion (no Decimal ->
1392        // numeric implicit casts exist in the cast catalog). The
1393        // spine therefore inserts an Integer -> Decimal cast on
1394        // the rhs and dispatches the Decimal addition.
1395        // parse_decimal scales by 10^4, so Integer(2) coerces to
1396        // Decimal(20000) and Decimal(10000) + Decimal(20000) =
1397        // Decimal(30000) (fixed-point 3.0000).
1398        let expr = binop(
1399            BinOp::Add,
1400            lit(Value::Decimal(10000)),
1401            lit(Value::Integer(2)),
1402        );
1403        let v = evaluate(&expr, &empty_row()).unwrap();
1404        assert_eq!(v, Value::Decimal(30000));
1405    }
1406
1407    #[test]
1408    fn integer_plus_bigint_resolves_to_preferred_float_overload() {
1409        // (Integer, BigInt) has no exact match. The spine ties
1410        // between +(Integer, Float, Float) (rhs cast BigInt->Float)
1411        // and +(BigInt, BigInt, BigInt) (lhs cast Integer->BigInt).
1412        // Float wins on the preferred-return-type tie-break, so the
1413        // BigInt operand is coerced to Float and the result is Float.
1414        let expr = binop(
1415            BinOp::Add,
1416            lit(Value::Integer(5)),
1417            lit(Value::BigInt(40_000_000_000)),
1418        );
1419        let v = evaluate(&expr, &empty_row()).unwrap();
1420        assert_eq!(v, Value::Float(40_000_000_005.0));
1421    }
1422
1423    #[test]
1424    fn integer_predicates_preserve_precision_across_signed_and_unsigned_boundaries() {
1425        let mut values = Vec::new();
1426        for number in [
1427            i64::MIN,
1428            -1,
1429            0,
1430            9_007_199_254_740_992,
1431            9_007_199_254_740_993,
1432            i64::MAX,
1433        ] {
1434            values.push((Value::Integer(number), i128::from(number)));
1435            values.push((Value::BigInt(number), i128::from(number)));
1436        }
1437        for number in [
1438            0,
1439            9_007_199_254_740_992,
1440            9_007_199_254_740_993,
1441            i64::MAX as u64,
1442            u64::MAX - 1,
1443            u64::MAX,
1444        ] {
1445            values.push((Value::UnsignedInteger(number), i128::from(number)));
1446        }
1447        for (left, left_exact) in &values {
1448            for (right, right_exact) in &values {
1449                for (operator, expected) in [
1450                    (BinOp::Eq, left_exact == right_exact),
1451                    (BinOp::Ne, left_exact != right_exact),
1452                    (BinOp::Lt, left_exact < right_exact),
1453                    (BinOp::Le, left_exact <= right_exact),
1454                    (BinOp::Gt, left_exact > right_exact),
1455                    (BinOp::Ge, left_exact >= right_exact),
1456                ] {
1457                    let expression = binop(operator, lit(left.clone()), lit(right.clone()));
1458                    assert_eq!(
1459                        evaluate(&expression, &empty_row())
1460                            .expect("integer comparison is supported"),
1461                        Value::Boolean(expected),
1462                        "{left:?} {operator:?} {right:?}"
1463                    );
1464                }
1465                for negated in [false, true] {
1466                    let expected = (*left_exact == *right_exact) != negated;
1467                    let membership = Expr::InList {
1468                        target: Box::new(lit(left.clone())),
1469                        values: vec![lit(right.clone())],
1470                        negated,
1471                        span: Span::synthetic(),
1472                    };
1473                    let interval = Expr::Between {
1474                        target: Box::new(lit(left.clone())),
1475                        low: Box::new(lit(right.clone())),
1476                        high: Box::new(lit(right.clone())),
1477                        negated,
1478                        span: Span::synthetic(),
1479                    };
1480                    for expression in [membership, interval] {
1481                        assert_eq!(
1482                            evaluate(&expression, &empty_row())
1483                                .expect("integer predicate is supported"),
1484                            Value::Boolean(expected),
1485                            "{expression:?}"
1486                        );
1487                    }
1488                }
1489            }
1490        }
1491    }
1492
1493    #[test]
1494    fn implicit_cast_promotes_integer_to_float_for_float_addition() {
1495        // The catalog has +(Integer, Float) -> Float as a direct
1496        // entry, so no actual coercion is inserted, but the result
1497        // must still be Float.
1498        let expr = binop(BinOp::Add, lit(Value::Integer(2)), lit(Value::Float(0.5)));
1499        let v = evaluate(&expr, &empty_row()).unwrap();
1500        assert_eq!(v, Value::Float(2.5));
1501    }
1502
1503    #[test]
1504    fn integer_division_promotes_to_float() {
1505        let expr = binop(BinOp::Div, lit(Value::Integer(7)), lit(Value::Integer(2)));
1506        let v = evaluate(&expr, &empty_row()).unwrap();
1507        assert_eq!(v, Value::Float(3.5));
1508    }
1509
1510    #[test]
1511    fn division_by_zero_is_eval_error() {
1512        let expr = binop(BinOp::Div, lit(Value::Integer(7)), lit(Value::Integer(0)));
1513        let err = evaluate(&expr, &empty_row()).unwrap_err();
1514        assert_eq!(err, EvalError::DivisionByZero);
1515    }
1516
1517    #[test]
1518    fn unknown_function_surfaces_as_eval_error() {
1519        let expr = Expr::FunctionCall {
1520            name: "no_such_fn".to_string(),
1521            args: vec![lit(Value::Integer(1))],
1522            span: Span::synthetic(),
1523        };
1524        let err = evaluate(&expr, &empty_row()).unwrap_err();
1525        match err {
1526            EvalError::UnknownFunction { name, args } => {
1527                assert_eq!(name, "no_such_fn");
1528                assert_eq!(args, vec![DataType::Integer]);
1529            }
1530            other => panic!("expected UnknownFunction, got {other:?}"),
1531        }
1532    }
1533
1534    #[test]
1535    fn coalesce_returns_first_non_null() {
1536        let expr = Expr::FunctionCall {
1537            name: "COALESCE".to_string(),
1538            args: vec![
1539                lit(Value::Null),
1540                lit(Value::Null),
1541                lit(Value::Integer(42)),
1542                lit(Value::Integer(99)),
1543            ],
1544            span: Span::synthetic(),
1545        };
1546        let v = evaluate(&expr, &empty_row()).unwrap();
1547        assert_eq!(v, Value::Integer(42));
1548    }
1549
1550    #[test]
1551    fn coalesce_all_null_returns_null() {
1552        let expr = Expr::FunctionCall {
1553            name: "COALESCE".to_string(),
1554            args: vec![lit(Value::Null), lit(Value::Null)],
1555            span: Span::synthetic(),
1556        };
1557        let v = evaluate(&expr, &empty_row()).unwrap();
1558        assert_eq!(v, Value::Null);
1559    }
1560
1561    #[test]
1562    fn variadic_concat_owns_null_semantics() {
1563        let expr = Expr::FunctionCall {
1564            name: "CONCAT".to_string(),
1565            args: vec![
1566                lit(Value::Text(Arc::from("red"))),
1567                lit(Value::Null),
1568                lit(Value::Text(Arc::from("db"))),
1569            ],
1570            span: Span::synthetic(),
1571        };
1572        let value = evaluate(&expr, &empty_row()).unwrap();
1573        assert_eq!(value, Value::Text(Arc::from("reddb")));
1574    }
1575
1576    #[test]
1577    fn upper_lower_dispatch_through_function_catalog() {
1578        let expr = Expr::FunctionCall {
1579            name: "UPPER".to_string(),
1580            args: vec![lit(Value::Text(Arc::from("hello")))],
1581            span: Span::synthetic(),
1582        };
1583        let v = evaluate(&expr, &empty_row()).unwrap();
1584        assert_eq!(v, Value::Text(Arc::from("HELLO")));
1585    }
1586
1587    #[test]
1588    fn length_of_null_propagates() {
1589        let expr = Expr::FunctionCall {
1590            name: "LENGTH".to_string(),
1591            args: vec![lit(Value::Null)],
1592            span: Span::synthetic(),
1593        };
1594        let v = evaluate(&expr, &empty_row()).unwrap();
1595        assert_eq!(v, Value::Null);
1596    }
1597
1598    #[test]
1599    fn case_when_picks_first_true_branch() {
1600        let expr = Expr::Case {
1601            branches: vec![
1602                (lit(Value::Boolean(false)), lit(Value::Integer(1))),
1603                (lit(Value::Boolean(true)), lit(Value::Integer(2))),
1604                (lit(Value::Boolean(true)), lit(Value::Integer(3))),
1605            ],
1606            else_: Some(Box::new(lit(Value::Integer(99)))),
1607            span: Span::synthetic(),
1608        };
1609        let v = evaluate(&expr, &empty_row()).unwrap();
1610        assert_eq!(v, Value::Integer(2));
1611    }
1612
1613    #[test]
1614    fn case_falls_through_to_else_when_no_branch_matches() {
1615        let expr = Expr::Case {
1616            branches: vec![(lit(Value::Boolean(false)), lit(Value::Integer(1)))],
1617            else_: Some(Box::new(lit(Value::Integer(99)))),
1618            span: Span::synthetic(),
1619        };
1620        let v = evaluate(&expr, &empty_row()).unwrap();
1621        assert_eq!(v, Value::Integer(99));
1622    }
1623
1624    #[test]
1625    fn case_returns_null_when_no_branch_matches_and_no_else() {
1626        let expr = Expr::Case {
1627            branches: vec![(lit(Value::Boolean(false)), lit(Value::Integer(1)))],
1628            else_: None,
1629            span: Span::synthetic(),
1630        };
1631        let v = evaluate(&expr, &empty_row()).unwrap();
1632        assert_eq!(v, Value::Null);
1633    }
1634
1635    #[test]
1636    fn is_null_handles_null_and_non_null() {
1637        let null_expr = Expr::IsNull {
1638            operand: Box::new(lit(Value::Null)),
1639            negated: false,
1640            span: Span::synthetic(),
1641        };
1642        assert_eq!(
1643            evaluate(&null_expr, &empty_row()).unwrap(),
1644            Value::Boolean(true)
1645        );
1646
1647        let non_null_expr = Expr::IsNull {
1648            operand: Box::new(lit(Value::Integer(7))),
1649            negated: false,
1650            span: Span::synthetic(),
1651        };
1652        assert_eq!(
1653            evaluate(&non_null_expr, &empty_row()).unwrap(),
1654            Value::Boolean(false)
1655        );
1656    }
1657
1658    #[test]
1659    fn between_inclusive_bounds() {
1660        let expr = Expr::Between {
1661            target: Box::new(lit(Value::Integer(5))),
1662            low: Box::new(lit(Value::Integer(1))),
1663            high: Box::new(lit(Value::Integer(10))),
1664            negated: false,
1665            span: Span::synthetic(),
1666        };
1667        assert_eq!(evaluate(&expr, &empty_row()).unwrap(), Value::Boolean(true));
1668    }
1669
1670    #[test]
1671    fn in_list_match_and_miss() {
1672        let hit = Expr::InList {
1673            target: Box::new(lit(Value::Integer(2))),
1674            values: vec![
1675                lit(Value::Integer(1)),
1676                lit(Value::Integer(2)),
1677                lit(Value::Integer(3)),
1678            ],
1679            negated: false,
1680            span: Span::synthetic(),
1681        };
1682        assert_eq!(evaluate(&hit, &empty_row()).unwrap(), Value::Boolean(true));
1683
1684        let miss = Expr::InList {
1685            target: Box::new(lit(Value::Integer(99))),
1686            values: vec![lit(Value::Integer(1)), lit(Value::Integer(2))],
1687            negated: false,
1688            span: Span::synthetic(),
1689        };
1690        assert_eq!(
1691            evaluate(&miss, &empty_row()).unwrap(),
1692            Value::Boolean(false)
1693        );
1694    }
1695
1696    #[test]
1697    fn column_lookup_walks_field_ref() {
1698        let row = |field: &FieldRef| -> Option<Value> {
1699            match field {
1700                FieldRef::TableColumn { table, column } if table == "t" && column == "x" => {
1701                    Some(Value::Integer(11))
1702                }
1703                _ => None,
1704            }
1705        };
1706        let expr = Expr::Column {
1707            field: FieldRef::TableColumn {
1708                table: "t".to_string(),
1709                column: "x".to_string(),
1710            },
1711            span: Span::synthetic(),
1712        };
1713        assert_eq!(evaluate(&expr, &row).unwrap(), Value::Integer(11));
1714    }
1715
1716    #[test]
1717    fn missing_column_surfaces_unknown_column() {
1718        let row = |_: &FieldRef| -> Option<Value> { None };
1719        let expr = Expr::Column {
1720            field: FieldRef::TableColumn {
1721                table: "t".to_string(),
1722                column: "missing".to_string(),
1723            },
1724            span: Span::synthetic(),
1725        };
1726        let err = evaluate(&expr, &row).unwrap_err();
1727        match err {
1728            EvalError::UnknownColumn(_) => {}
1729            other => panic!("expected UnknownColumn, got {other:?}"),
1730        }
1731    }
1732
1733    #[test]
1734    fn parameter_without_bind_is_eval_error() {
1735        let expr = Expr::Parameter {
1736            index: 1,
1737            span: Span::synthetic(),
1738        };
1739        let err = evaluate(&expr, &empty_row()).unwrap_err();
1740        assert_eq!(err, EvalError::UnboundParameter(1));
1741    }
1742
1743    #[test]
1744    fn cast_integer_to_text_uses_explicit_path() {
1745        let expr = Expr::Cast {
1746            inner: Box::new(lit(Value::Integer(42))),
1747            target: DataType::Text,
1748            span: Span::synthetic(),
1749        };
1750        assert_eq!(
1751            evaluate(&expr, &empty_row()).unwrap(),
1752            Value::Text(Arc::from("42"))
1753        );
1754    }
1755
1756    #[test]
1757    fn concat_returns_text() {
1758        let expr = binop(
1759            BinOp::Concat,
1760            lit(Value::Text(Arc::from("foo"))),
1761            lit(Value::Text(Arc::from("bar"))),
1762        );
1763        assert_eq!(
1764            evaluate(&expr, &empty_row()).unwrap(),
1765            Value::Text(Arc::from("foobar"))
1766        );
1767    }
1768}