Skip to main content

reddb_engine/query/
evaluator.rs

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