Skip to main content

spg_engine/
eval.rs

1//! Expression evaluator. Given a parsed `Expr`, a `Row`, and the row's column
2//! schema, produce a `Value`. v0.4 implements:
3//!
4//! - literals
5//! - column lookups (bare and qualified `t.col`)
6//! - unary minus / NOT
7//! - binary arithmetic, comparison, AND, OR
8//! - numeric widening (`Int → BigInt → Float`) at evaluation time
9//! - SQL three-valued logic for NULL:
10//!     * any arithmetic / comparison op with a NULL operand → NULL
11//!     * `TRUE OR NULL` → TRUE, `FALSE OR NULL` → NULL,
12//!     * `FALSE AND NULL` → FALSE, `TRUE AND NULL` → NULL,
13//!     * `NOT NULL` → NULL
14//!
15//! v0.4 deliberately does *not* implement: function calls, string
16//! concatenation, IS NULL / IS NOT NULL, BETWEEN, IN, etc. Those come later.
17
18use alloc::format;
19use alloc::string::{String, ToString};
20use alloc::vec::Vec;
21
22use spg_sql::ast::{BinOp, CastTarget, ColumnName, Expr, Literal, UnOp};
23use spg_storage::{ColumnSchema, DataType, Row, Value};
24
25/// Resolution context for evaluating a single row. `table_alias` is the alias
26/// (or table name) callers should accept as the qualifier on a column ref —
27/// e.g. `FROM users AS u` makes `u.name` valid and rejects `other.name`.
28#[derive(Debug, Clone)]
29pub struct EvalContext<'a> {
30    pub columns: &'a [ColumnSchema],
31    pub table_alias: Option<&'a str>,
32    /// v6.1.1 — bound parameters for `$N` placeholders inside the
33    /// expression tree. Empty for simple queries; populated by the
34    /// prepared-statement Execute path with Bind values converted
35    /// to `Value`. Index N (1-based per PG) hits `params[N-1]`.
36    pub params: &'a [Value],
37}
38
39impl<'a> EvalContext<'a> {
40    pub const fn new(columns: &'a [ColumnSchema], table_alias: Option<&'a str>) -> Self {
41        Self {
42            columns,
43            table_alias,
44            params: &[],
45        }
46    }
47
48    /// v6.1.1 — attach a parameter buffer for `$N` placeholder
49    /// resolution. The slice must outlive the context; callers
50    /// construct it from the prepared statement's Bind values.
51    #[must_use]
52    pub const fn with_params(mut self, params: &'a [Value]) -> Self {
53        self.params = params;
54        self
55    }
56}
57
58#[derive(Debug, Clone, PartialEq)]
59pub enum EvalError {
60    ColumnNotFound { name: String },
61    UnknownQualifier { qualifier: String },
62    DivisionByZero,
63    TypeMismatch { detail: String },
64    /// v6.1.1 — `$N` reference past the number of bound parameters.
65    /// Either the client sent too few in Bind, or the SQL has a
66    /// placeholder the prepared statement didn't account for.
67    PlaceholderOutOfRange { n: u16, bound: u16 },
68}
69
70impl core::fmt::Display for EvalError {
71    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
72        match self {
73            Self::ColumnNotFound { name } => write!(f, "column not found: {name}"),
74            Self::UnknownQualifier { qualifier } => {
75                write!(f, "unknown table qualifier: {qualifier}")
76            }
77            Self::DivisionByZero => f.write_str("division by zero"),
78            Self::TypeMismatch { detail } => write!(f, "type mismatch: {detail}"),
79            Self::PlaceholderOutOfRange { n, bound } => write!(
80                f,
81                "parameter ${n} referenced but only {bound} bound by client"
82            ),
83        }
84    }
85}
86
87pub fn eval_expr(expr: &Expr, row: &Row, ctx: &EvalContext<'_>) -> Result<Value, EvalError> {
88    match expr {
89        Expr::Literal(l) => Ok(literal_to_value(l)),
90        Expr::Column(c) => resolve_column(c, row, ctx),
91        Expr::Placeholder(n) => {
92            let idx = usize::from(*n).saturating_sub(1);
93            ctx.params
94                .get(idx)
95                .cloned()
96                .ok_or_else(|| EvalError::PlaceholderOutOfRange {
97                    n: *n,
98                    bound: u16::try_from(ctx.params.len()).unwrap_or(u16::MAX),
99                })
100        }
101        Expr::Unary { op, expr } => {
102            let v = eval_expr(expr, row, ctx)?;
103            apply_unary(*op, v)
104        }
105        Expr::Binary { lhs, op, rhs } => {
106            let l = eval_expr(lhs, row, ctx)?;
107            let r = eval_expr(rhs, row, ctx)?;
108            apply_binary(*op, l, r)
109        }
110        Expr::Cast { expr, target } => {
111            let v = eval_expr(expr, row, ctx)?;
112            cast_value(v, *target)
113        }
114        Expr::IsNull { expr, negated } => {
115            let v = eval_expr(expr, row, ctx)?;
116            let is_null = matches!(v, Value::Null);
117            Ok(Value::Bool(if *negated { !is_null } else { is_null }))
118        }
119        Expr::FunctionCall { name, args } => {
120            let evaluated: Result<Vec<Value>, _> =
121                args.iter().map(|a| eval_expr(a, row, ctx)).collect();
122            apply_function(name, &evaluated?)
123        }
124        Expr::Like {
125            expr,
126            pattern,
127            negated,
128        } => {
129            let v = eval_expr(expr, row, ctx)?;
130            let p = eval_expr(pattern, row, ctx)?;
131            // NULL on either side propagates to NULL — same as PG.
132            let (text, pat) = match (v, p) {
133                (Value::Null, _) | (_, Value::Null) => return Ok(Value::Null),
134                (Value::Text(a), Value::Text(b)) => (a, b),
135                (Value::Text(_), other) | (other, _) => {
136                    return Err(EvalError::TypeMismatch {
137                        detail: format!("LIKE requires text operands, got {:?}", other.data_type()),
138                    });
139                }
140            };
141            let m = like_match(&text, &pat);
142            Ok(Value::Bool(if *negated { !m } else { m }))
143        }
144        Expr::Extract { field, source } => {
145            let v = eval_expr(source, row, ctx)?;
146            extract_field(*field, &v)
147        }
148        // v4.10: subquery nodes should have been resolved into
149        // Literal / Binary-Eq-OR chains by Engine::resolve_select_subqueries
150        // before the row loop. Anything reaching here is a bug.
151        Expr::ScalarSubquery(_) | Expr::Exists { .. } | Expr::InSubquery { .. } => {
152            Err(EvalError::TypeMismatch {
153                detail: "subquery reached row eval — engine resolver bug".into(),
154            })
155        }
156        // v4.12: window functions should have been rewritten into
157        // synthetic __win_N column references by
158        // exec_select_with_window before row eval. Anything
159        // reaching here is similarly a bug.
160        Expr::WindowFunction { .. } => Err(EvalError::TypeMismatch {
161            detail: "window function reached row eval — engine rewrite bug".into(),
162        }),
163    }
164}
165
166/// Pull an integer component (year / month / ... / microsecond) out
167/// of a `DATE` or `TIMESTAMP`. Returns NULL on a NULL source, errors
168/// when the source isn't a calendar type.
169fn extract_field(field: spg_sql::ast::ExtractField, v: &Value) -> Result<Value, EvalError> {
170    use spg_sql::ast::ExtractField as F;
171    if matches!(v, Value::Null) {
172        return Ok(Value::Null);
173    }
174    // INTERVAL has its own decomposition — `YEAR` / `MONTH` come from
175    // the months part, the rest from the microseconds part. PG matches
176    // this convention (months is normalised modulo 12 for MONTH).
177    if let Value::Interval { months, micros } = *v {
178        let years = months / 12;
179        let mons = months % 12;
180        let secs_total = micros / 1_000_000;
181        let frac = micros % 1_000_000;
182        let result = match field {
183            F::Year => i64::from(years),
184            F::Month => i64::from(mons),
185            F::Day => micros / 86_400_000_000,
186            F::Hour => (secs_total / 3600) % 24,
187            F::Minute => (secs_total / 60) % 60,
188            F::Second => secs_total % 60,
189            F::Microsecond => (secs_total % 60) * 1_000_000 + frac,
190        };
191        return Ok(Value::BigInt(result));
192    }
193    let (days, day_micros) = match *v {
194        Value::Date(d) => (d, 0_i64),
195        Value::Timestamp(t) => {
196            let days = t.div_euclid(86_400_000_000);
197            let day_micros = t.rem_euclid(86_400_000_000);
198            (i32::try_from(days).unwrap_or(i32::MAX), day_micros)
199        }
200        _ => {
201            return Err(EvalError::TypeMismatch {
202                detail: format!(
203                    "EXTRACT requires DATE / TIMESTAMP / INTERVAL, got {:?}",
204                    v.data_type()
205                ),
206            });
207        }
208    };
209    let (y, m, d) = civil_components(days);
210    let secs = day_micros / 1_000_000;
211    let hh = secs / 3600;
212    let mm = (secs / 60) % 60;
213    let ss = secs % 60;
214    let frac = day_micros % 1_000_000;
215    let result = match field {
216        F::Year => i64::from(y),
217        F::Month => i64::from(m),
218        F::Day => i64::from(d),
219        F::Hour => hh,
220        F::Minute => mm,
221        F::Second => ss,
222        F::Microsecond => ss * 1_000_000 + frac,
223    };
224    Ok(Value::BigInt(result))
225}
226
227/// Internal wrapper around the file-private `civil_from_days` so the
228/// public surface area doesn't change. Returns `(year, month, day)`.
229fn civil_components(days: i32) -> (i32, u32, u32) {
230    civil_from_days(days)
231}
232
233/// SQL `LIKE` matcher. Wildcards are `%` (any run, possibly empty) and `_`
234/// (exactly one char). `\` escapes the next pattern char so `\%` matches a
235/// literal `%`. Matches the whole input — no implicit anchoring needed
236/// since SQL `LIKE` is always full-string.
237fn like_match(text: &str, pattern: &str) -> bool {
238    let text: Vec<char> = text.chars().collect();
239    let pat: Vec<char> = pattern.chars().collect();
240    like_match_inner(&text, 0, &pat, 0)
241}
242
243fn like_match_inner(text: &[char], mut ti: usize, pat: &[char], mut pi: usize) -> bool {
244    while pi < pat.len() {
245        match pat[pi] {
246            '%' => {
247                // Collapse consecutive `%` and try every possible split.
248                while pi < pat.len() && pat[pi] == '%' {
249                    pi += 1;
250                }
251                if pi == pat.len() {
252                    return true;
253                }
254                for k in ti..=text.len() {
255                    if like_match_inner(text, k, pat, pi) {
256                        return true;
257                    }
258                }
259                return false;
260            }
261            '_' => {
262                if ti >= text.len() {
263                    return false;
264                }
265                ti += 1;
266                pi += 1;
267            }
268            '\\' if pi + 1 < pat.len() => {
269                let want = pat[pi + 1];
270                if ti >= text.len() || text[ti] != want {
271                    return false;
272                }
273                ti += 1;
274                pi += 2;
275            }
276            c => {
277                if ti >= text.len() || text[ti] != c {
278                    return false;
279                }
280                ti += 1;
281                pi += 1;
282            }
283        }
284    }
285    ti == text.len()
286}
287
288/// Dispatch on lowercased function name. v1.4 implements only a handful of
289/// scalar functions; aggregates land in v1.5 alongside GROUP BY.
290fn apply_function(name: &str, args: &[Value]) -> Result<Value, EvalError> {
291    match name.to_ascii_lowercase().as_str() {
292        "length" => {
293            if args.len() != 1 {
294                return Err(EvalError::TypeMismatch {
295                    detail: format!("length() takes 1 arg, got {}", args.len()),
296                });
297            }
298            match &args[0] {
299                Value::Null => Ok(Value::Null),
300                Value::Text(s) => {
301                    let n = i32::try_from(s.chars().count()).unwrap_or(i32::MAX);
302                    Ok(Value::Int(n))
303                }
304                other => Err(EvalError::TypeMismatch {
305                    detail: format!("length() needs text, got {:?}", other.data_type()),
306                }),
307            }
308        }
309        "upper" => {
310            if args.len() != 1 {
311                return Err(EvalError::TypeMismatch {
312                    detail: format!("upper() takes 1 arg, got {}", args.len()),
313                });
314            }
315            match &args[0] {
316                Value::Null => Ok(Value::Null),
317                Value::Text(s) => Ok(Value::Text(s.to_uppercase())),
318                other => Err(EvalError::TypeMismatch {
319                    detail: format!("upper() needs text, got {:?}", other.data_type()),
320                }),
321            }
322        }
323        "lower" => {
324            if args.len() != 1 {
325                return Err(EvalError::TypeMismatch {
326                    detail: format!("lower() takes 1 arg, got {}", args.len()),
327                });
328            }
329            match &args[0] {
330                Value::Null => Ok(Value::Null),
331                Value::Text(s) => Ok(Value::Text(s.to_lowercase())),
332                other => Err(EvalError::TypeMismatch {
333                    detail: format!("lower() needs text, got {:?}", other.data_type()),
334                }),
335            }
336        }
337        "abs" => {
338            if args.len() != 1 {
339                return Err(EvalError::TypeMismatch {
340                    detail: format!("abs() takes 1 arg, got {}", args.len()),
341                });
342            }
343            match &args[0] {
344                Value::Null => Ok(Value::Null),
345                Value::Int(n) => Ok(Value::Int(n.wrapping_abs())),
346                Value::BigInt(n) => Ok(Value::BigInt(n.wrapping_abs())),
347                Value::Float(x) => Ok(Value::Float(x.abs())),
348                other => Err(EvalError::TypeMismatch {
349                    detail: format!("abs() needs numeric, got {:?}", other.data_type()),
350                }),
351            }
352        }
353        "coalesce" => {
354            for a in args {
355                if !matches!(a, Value::Null) {
356                    return Ok(a.clone());
357                }
358            }
359            Ok(Value::Null)
360        }
361        "date_trunc" => date_trunc(args),
362        "date_part" => date_part(args),
363        "age" => age(args),
364        "to_char" => to_char(args),
365        // v6.4.3 — encode/decode + error_on_null SQL function bundle.
366        "encode" => encode_text(args),
367        "decode" => decode_text(args),
368        "error_on_null" => error_on_null(args),
369        other => Err(EvalError::TypeMismatch {
370            detail: format!("unknown function `{other}`"),
371        }),
372    }
373}
374
375/// v6.4.3 — `encode(bytes_as_text, format)`. PG works on bytea
376/// arguments; SPG's value space treats Text as the byte container
377/// (raw UTF-8 bytes). Supported formats: base64 (PG default),
378/// base64url (RFC 4648 §5), base32hex (RFC 4648 §7 extended-hex),
379/// hex.
380fn encode_text(args: &[Value]) -> Result<Value, EvalError> {
381    if args.len() != 2 {
382        return Err(EvalError::TypeMismatch {
383            detail: format!("encode() takes 2 args, got {}", args.len()),
384        });
385    }
386    if matches!(args[0], Value::Null) || matches!(args[1], Value::Null) {
387        return Ok(Value::Null);
388    }
389    let bytes: &[u8] = match &args[0] {
390        Value::Text(s) => s.as_bytes(),
391        other => {
392            return Err(EvalError::TypeMismatch {
393                detail: format!(
394                    "encode() expects text bytes, got {:?}",
395                    other.data_type()
396                ),
397            });
398        }
399    };
400    let fmt = match &args[1] {
401        Value::Text(s) => s.to_ascii_lowercase(),
402        other => {
403            return Err(EvalError::TypeMismatch {
404                detail: format!(
405                    "encode() format must be text, got {:?}",
406                    other.data_type()
407                ),
408            });
409        }
410    };
411    let out = match fmt.as_str() {
412        "base64" => b64_encode(bytes, B64_STD),
413        "base64url" => b64_encode(bytes, B64_URL),
414        "base32hex" => b32hex_encode(bytes),
415        "hex" => hex_encode(bytes),
416        other => {
417            return Err(EvalError::TypeMismatch {
418                detail: format!("encode(): unknown format `{other}`"),
419            });
420        }
421    };
422    Ok(Value::Text(out))
423}
424
425/// v6.4.3 — `decode(text, format)`. Inverse of `encode`; returns
426/// Text containing the raw decoded bytes (caller may CAST to bytea
427/// equivalent if SPG adds bytea later).
428fn decode_text(args: &[Value]) -> Result<Value, EvalError> {
429    if args.len() != 2 {
430        return Err(EvalError::TypeMismatch {
431            detail: format!("decode() takes 2 args, got {}", args.len()),
432        });
433    }
434    if matches!(args[0], Value::Null) || matches!(args[1], Value::Null) {
435        return Ok(Value::Null);
436    }
437    let text = match &args[0] {
438        Value::Text(s) => s.as_str(),
439        other => {
440            return Err(EvalError::TypeMismatch {
441                detail: format!("decode() expects text, got {:?}", other.data_type()),
442            });
443        }
444    };
445    let fmt = match &args[1] {
446        Value::Text(s) => s.to_ascii_lowercase(),
447        other => {
448            return Err(EvalError::TypeMismatch {
449                detail: format!(
450                    "decode() format must be text, got {:?}",
451                    other.data_type()
452                ),
453            });
454        }
455    };
456    let bytes = match fmt.as_str() {
457        "base64" => b64_decode(text, B64_STD)?,
458        "base64url" => b64_decode(text, B64_URL)?,
459        "base32hex" => b32hex_decode(text)?,
460        "hex" => hex_decode(text)?,
461        other => {
462            return Err(EvalError::TypeMismatch {
463                detail: format!("decode(): unknown format `{other}`"),
464            });
465        }
466    };
467    let s = String::from_utf8(bytes).map_err(|_| EvalError::TypeMismatch {
468        detail: "decode(): result bytes are not valid UTF-8 (SPG stores raw bytes as Text)".into(),
469    })?;
470    Ok(Value::Text(s))
471}
472
473/// v6.4.3 — `error_on_null(v)`. Returns `v` unchanged if non-NULL;
474/// errors otherwise. Convenience to assert NOT NULL inside an
475/// expression without wrapping it in COALESCE + raise hacks.
476fn error_on_null(args: &[Value]) -> Result<Value, EvalError> {
477    if args.len() != 1 {
478        return Err(EvalError::TypeMismatch {
479            detail: format!("error_on_null() takes 1 arg, got {}", args.len()),
480        });
481    }
482    if matches!(args[0], Value::Null) {
483        return Err(EvalError::TypeMismatch {
484            detail: "error_on_null(): argument is NULL".into(),
485        });
486    }
487    Ok(args[0].clone())
488}
489
490// ── byte-level encoders ───────────────────────────────────────────
491
492const B64_STD: &[u8; 64] =
493    b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
494const B64_URL: &[u8; 64] =
495    b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
496const B32HEX_ALPHABET: &[u8; 32] = b"0123456789ABCDEFGHIJKLMNOPQRSTUV";
497
498fn b64_encode(bytes: &[u8], alpha: &[u8; 64]) -> String {
499    let mut out = String::with_capacity((bytes.len() + 2) / 3 * 4);
500    let mut i = 0;
501    while i + 3 <= bytes.len() {
502        let n = ((bytes[i] as u32) << 16) | ((bytes[i + 1] as u32) << 8) | (bytes[i + 2] as u32);
503        out.push(alpha[((n >> 18) & 0x3f) as usize] as char);
504        out.push(alpha[((n >> 12) & 0x3f) as usize] as char);
505        out.push(alpha[((n >> 6) & 0x3f) as usize] as char);
506        out.push(alpha[(n & 0x3f) as usize] as char);
507        i += 3;
508    }
509    let rem = bytes.len() - i;
510    if rem == 1 {
511        let n = (bytes[i] as u32) << 16;
512        out.push(alpha[((n >> 18) & 0x3f) as usize] as char);
513        out.push(alpha[((n >> 12) & 0x3f) as usize] as char);
514        out.push('=');
515        out.push('=');
516    } else if rem == 2 {
517        let n = ((bytes[i] as u32) << 16) | ((bytes[i + 1] as u32) << 8);
518        out.push(alpha[((n >> 18) & 0x3f) as usize] as char);
519        out.push(alpha[((n >> 12) & 0x3f) as usize] as char);
520        out.push(alpha[((n >> 6) & 0x3f) as usize] as char);
521        out.push('=');
522    }
523    out
524}
525
526fn b64_decode(text: &str, alpha: &[u8; 64]) -> Result<Vec<u8>, EvalError> {
527    let mut lookup = [255u8; 256];
528    for (i, &c) in alpha.iter().enumerate() {
529        lookup[c as usize] = i as u8;
530    }
531    let mut out = Vec::with_capacity(text.len() * 3 / 4);
532    let mut buf: u32 = 0;
533    let mut bits: u32 = 0;
534    for c in text.bytes() {
535        if c == b'=' {
536            break;
537        }
538        if c == b'\n' || c == b'\r' || c == b' ' {
539            continue;
540        }
541        let v = lookup[c as usize];
542        if v == 255 {
543            return Err(EvalError::TypeMismatch {
544                detail: format!("decode(base64): invalid char {:?}", c as char),
545            });
546        }
547        buf = (buf << 6) | v as u32;
548        bits += 6;
549        if bits >= 8 {
550            bits -= 8;
551            out.push(((buf >> bits) & 0xff) as u8);
552        }
553    }
554    Ok(out)
555}
556
557fn b32hex_encode(bytes: &[u8]) -> String {
558    let mut out = String::with_capacity((bytes.len() * 8 + 4) / 5);
559    let mut buf: u64 = 0;
560    let mut bits: u32 = 0;
561    for &b in bytes {
562        buf = (buf << 8) | b as u64;
563        bits += 8;
564        while bits >= 5 {
565            bits -= 5;
566            out.push(B32HEX_ALPHABET[((buf >> bits) & 0x1f) as usize] as char);
567        }
568    }
569    if bits > 0 {
570        out.push(B32HEX_ALPHABET[((buf << (5 - bits)) & 0x1f) as usize] as char);
571    }
572    // Pad to multiple of 8.
573    while out.len() % 8 != 0 {
574        out.push('=');
575    }
576    out
577}
578
579fn b32hex_decode(text: &str) -> Result<Vec<u8>, EvalError> {
580    let mut lookup = [255u8; 256];
581    for (i, &c) in B32HEX_ALPHABET.iter().enumerate() {
582        lookup[c as usize] = i as u8;
583        // base32hex is case-insensitive — also map lowercase.
584        let lower = (c as char).to_ascii_lowercase() as u8;
585        lookup[lower as usize] = i as u8;
586    }
587    let mut out = Vec::with_capacity(text.len() * 5 / 8);
588    let mut buf: u64 = 0;
589    let mut bits: u32 = 0;
590    for c in text.bytes() {
591        if c == b'=' {
592            break;
593        }
594        if c == b'\n' || c == b'\r' || c == b' ' {
595            continue;
596        }
597        let v = lookup[c as usize];
598        if v == 255 {
599            return Err(EvalError::TypeMismatch {
600                detail: format!("decode(base32hex): invalid char {:?}", c as char),
601            });
602        }
603        buf = (buf << 5) | v as u64;
604        bits += 5;
605        if bits >= 8 {
606            bits -= 8;
607            out.push(((buf >> bits) & 0xff) as u8);
608        }
609    }
610    Ok(out)
611}
612
613fn hex_encode(bytes: &[u8]) -> String {
614    const HEX: &[u8; 16] = b"0123456789abcdef";
615    let mut out = String::with_capacity(bytes.len() * 2);
616    for &b in bytes {
617        out.push(HEX[(b >> 4) as usize] as char);
618        out.push(HEX[(b & 0xf) as usize] as char);
619    }
620    out
621}
622
623fn hex_decode(text: &str) -> Result<Vec<u8>, EvalError> {
624    let trimmed = text.trim();
625    if trimmed.len() % 2 != 0 {
626        return Err(EvalError::TypeMismatch {
627            detail: "decode(hex): input length must be even".into(),
628        });
629    }
630    let mut out = Vec::with_capacity(trimmed.len() / 2);
631    let mut hi: u8 = 0;
632    for (i, c) in trimmed.bytes().enumerate() {
633        let v = match c {
634            b'0'..=b'9' => c - b'0',
635            b'a'..=b'f' => c - b'a' + 10,
636            b'A'..=b'F' => c - b'A' + 10,
637            _ => {
638                return Err(EvalError::TypeMismatch {
639                    detail: format!("decode(hex): invalid char {:?}", c as char),
640                });
641            }
642        };
643        if i % 2 == 0 {
644            hi = v;
645        } else {
646            out.push((hi << 4) | v);
647        }
648    }
649    Ok(out)
650}
651
652/// `date_part(field_text, source)` — function form of `EXTRACT(field FROM
653/// source)`. Same component dispatch (DATE / TIMESTAMP / INTERVAL) and
654/// same `BigInt` return shape; PG returns double precision but we keep the
655/// integer convention so the runner's `query I` shape works unchanged.
656fn date_part(args: &[Value]) -> Result<Value, EvalError> {
657    use spg_sql::ast::ExtractField as F;
658    if args.len() != 2 {
659        return Err(EvalError::TypeMismatch {
660            detail: format!("date_part() takes 2 args, got {}", args.len()),
661        });
662    }
663    if matches!(&args[0], Value::Null) || matches!(&args[1], Value::Null) {
664        return Ok(Value::Null);
665    }
666    let Value::Text(field_name) = &args[0] else {
667        return Err(EvalError::TypeMismatch {
668            detail: format!(
669                "date_part() needs a text field, got {:?}",
670                args[0].data_type()
671            ),
672        });
673    };
674    let field = match field_name.to_ascii_lowercase().as_str() {
675        "year" => F::Year,
676        "month" => F::Month,
677        "day" => F::Day,
678        "hour" => F::Hour,
679        "minute" => F::Minute,
680        "second" => F::Second,
681        "microsecond" | "microseconds" => F::Microsecond,
682        other => {
683            return Err(EvalError::TypeMismatch {
684                detail: format!(
685                    "unknown date_part field {other:?}; \
686                     supported: year, month, day, hour, minute, second, microsecond"
687                ),
688            });
689        }
690    };
691    extract_field(field, &args[1])
692}
693
694/// `age(t1, t2)` — return `t1 - t2` as an INTERVAL. v2.12 produces a
695/// micros-only interval (no months normalisation) because PG's
696/// month-justification rule is sensitive to the day-of-month walk and
697/// adds material complexity for marginal corpus value.
698///
699/// `age(t)` (single-arg form) is intentionally unsupported in v2.12:
700/// the dispatcher errors instead of guessing a clock source. Callers
701/// who want PG's `age(t)` semantics should write `age(CURRENT_DATE, t)`
702/// explicitly so the clock reference is visible at the SQL layer.
703fn age(args: &[Value]) -> Result<Value, EvalError> {
704    if args.is_empty() || args.len() > 2 {
705        return Err(EvalError::TypeMismatch {
706            detail: format!("age() takes 1 or 2 args, got {}", args.len()),
707        });
708    }
709    if args.iter().any(|v| matches!(v, Value::Null)) {
710        return Ok(Value::Null);
711    }
712    // Coerce to TIMESTAMP micros — DATE lifts to midnight; TIMESTAMP
713    // stays as-is; anything else errors.
714    let to_micros = |v: &Value| -> Result<i64, EvalError> {
715        match v {
716            Value::Timestamp(t) => Ok(*t),
717            Value::Date(d) => Ok(i64::from(*d) * 86_400_000_000),
718            other => Err(EvalError::TypeMismatch {
719                detail: format!("age() needs DATE or TIMESTAMP, got {:?}", other.data_type()),
720            }),
721        }
722    };
723    if args.len() == 1 {
724        return Err(EvalError::TypeMismatch {
725            detail: "single-arg age() is unsupported in v2.12 \
726                     (use age(CURRENT_DATE, t) explicitly)"
727                .into(),
728        });
729    }
730    let a = to_micros(&args[0])?;
731    let b = to_micros(&args[1])?;
732    let delta = a.checked_sub(b).ok_or(EvalError::TypeMismatch {
733        detail: "age() subtraction overflows i64 microseconds".into(),
734    })?;
735    Ok(Value::Interval {
736        months: 0,
737        micros: delta,
738    })
739}
740
741/// `to_char(value, format)` — render a DATE / TIMESTAMP through a PG
742/// format template. Supports the high-traffic placeholders:
743///   YYYY YY MM Mon Month DD HH24 HH12 MI SS MS US AM PM
744/// Unrecognised characters pass through literally so the template's
745/// punctuation ('-', ':', ' ', '/') needs no escape mechanism.
746fn to_char(args: &[Value]) -> Result<Value, EvalError> {
747    use core::fmt::Write as _;
748    if args.len() != 2 {
749        return Err(EvalError::TypeMismatch {
750            detail: format!("to_char() takes 2 args, got {}", args.len()),
751        });
752    }
753    if matches!(&args[0], Value::Null) || matches!(&args[1], Value::Null) {
754        return Ok(Value::Null);
755    }
756    let Value::Text(fmt) = &args[1] else {
757        return Err(EvalError::TypeMismatch {
758            detail: format!(
759                "to_char() needs a text format, got {:?}",
760                args[1].data_type()
761            ),
762        });
763    };
764    let (days, day_micros) = match &args[0] {
765        Value::Date(d) => (*d, 0_i64),
766        Value::Timestamp(t) => {
767            let days = t.div_euclid(86_400_000_000);
768            (
769                i32::try_from(days).unwrap_or(i32::MAX),
770                t.rem_euclid(86_400_000_000),
771            )
772        }
773        other => {
774            return Err(EvalError::TypeMismatch {
775                detail: format!(
776                    "to_char() needs DATE or TIMESTAMP, got {:?}",
777                    other.data_type()
778                ),
779            });
780        }
781    };
782    let (y, mo, d) = civil_from_days(days);
783    let secs = day_micros / 1_000_000;
784    let frac = day_micros % 1_000_000;
785    // div_euclid keeps every value non-negative — the casts below are
786    // sign-safe by construction. `secs ∈ [0, 86400)`, `frac ∈ [0,
787    // 1_000_000)`, so all three quantities fit in u32.
788    let hh24 = u32::try_from(secs / 3600).unwrap_or(0);
789    let mi = u32::try_from((secs / 60) % 60).unwrap_or(0);
790    let ss = u32::try_from(secs % 60).unwrap_or(0);
791    let hh12 = match hh24 % 12 {
792        0 => 12,
793        x => x,
794    };
795    let ampm = if hh24 < 12 { "AM" } else { "PM" };
796    let ms = u32::try_from(frac / 1_000).unwrap_or(0); // millisecond
797    let us = u32::try_from(frac).unwrap_or(0); // microsecond (0..1_000_000)
798
799    let mut out = String::with_capacity(fmt.len() + 8);
800    let bytes = fmt.as_bytes();
801    let mut i = 0;
802    // write! against a String never fails — discard the Result.
803    while i < bytes.len() {
804        // Try the longest prefixes first so "YYYY" wins over "YY".
805        let rest = &bytes[i..];
806        if rest.starts_with(b"YYYY") {
807            let _ = write!(out, "{y:04}");
808            i += 4;
809        } else if rest.starts_with(b"YY") {
810            #[allow(clippy::cast_sign_loss, clippy::cast_possible_truncation)]
811            let yy = (y.rem_euclid(100)) as u32;
812            let _ = write!(out, "{yy:02}");
813            i += 2;
814        } else if rest.starts_with(b"Month") {
815            out.push_str(MONTH_FULL[(mo - 1) as usize]);
816            i += 5;
817        } else if rest.starts_with(b"Mon") {
818            out.push_str(MONTH_ABBR[(mo - 1) as usize]);
819            i += 3;
820        } else if rest.starts_with(b"MM") {
821            let _ = write!(out, "{mo:02}");
822            i += 2;
823        } else if rest.starts_with(b"DD") {
824            let _ = write!(out, "{d:02}");
825            i += 2;
826        } else if rest.starts_with(b"HH24") {
827            let _ = write!(out, "{hh24:02}");
828            i += 4;
829        } else if rest.starts_with(b"HH12") {
830            let _ = write!(out, "{hh12:02}");
831            i += 4;
832        } else if rest.starts_with(b"MI") {
833            let _ = write!(out, "{mi:02}");
834            i += 2;
835        } else if rest.starts_with(b"SS") {
836            let _ = write!(out, "{ss:02}");
837            i += 2;
838        } else if rest.starts_with(b"MS") {
839            let _ = write!(out, "{ms:03}");
840            i += 2;
841        } else if rest.starts_with(b"US") {
842            let _ = write!(out, "{us:06}");
843            i += 2;
844        } else if rest.starts_with(b"AM") || rest.starts_with(b"PM") {
845            out.push_str(ampm);
846            i += 2;
847        } else {
848            // Pass any non-placeholder byte through verbatim.
849            out.push(bytes[i] as char);
850            i += 1;
851        }
852    }
853    Ok(Value::Text(out))
854}
855
856const MONTH_FULL: [&str; 12] = [
857    "January",
858    "February",
859    "March",
860    "April",
861    "May",
862    "June",
863    "July",
864    "August",
865    "September",
866    "October",
867    "November",
868    "December",
869];
870const MONTH_ABBR: [&str; 12] = [
871    "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
872];
873
874/// `date_trunc(unit, timestamp)` — round a `TIMESTAMP` down to the
875/// requested calendar boundary (year / month / day / hour / minute /
876/// second). Returns the truncated `TIMESTAMP`. NULL on either side
877/// propagates to NULL.
878fn date_trunc(args: &[Value]) -> Result<Value, EvalError> {
879    if args.len() != 2 {
880        return Err(EvalError::TypeMismatch {
881            detail: format!("date_trunc() takes 2 args, got {}", args.len()),
882        });
883    }
884    if matches!(&args[0], Value::Null) || matches!(&args[1], Value::Null) {
885        return Ok(Value::Null);
886    }
887    let Value::Text(unit) = &args[0] else {
888        return Err(EvalError::TypeMismatch {
889            detail: format!(
890                "date_trunc() needs a text unit, got {:?}",
891                args[0].data_type()
892            ),
893        });
894    };
895    // Both DATE and TIMESTAMP sources are accepted. DATE lifts to
896    // midnight first; the result is always TIMESTAMP.
897    let micros = match &args[1] {
898        Value::Timestamp(t) => *t,
899        Value::Date(d) => i64::from(*d) * 86_400_000_000,
900        other => {
901            return Err(EvalError::TypeMismatch {
902                detail: format!(
903                    "date_trunc() needs DATE or TIMESTAMP, got {:?}",
904                    other.data_type()
905                ),
906            });
907        }
908    };
909    let unit_lc = unit.to_ascii_lowercase();
910    let days = micros.div_euclid(86_400_000_000);
911    let day_micros = micros.rem_euclid(86_400_000_000);
912    let day_i32 = i32::try_from(days).unwrap_or(i32::MAX);
913    let (y, m, _) = civil_from_days(day_i32);
914    let truncated = match unit_lc.as_str() {
915        "year" => i64::from(days_from_civil(y, 1, 1)) * 86_400_000_000,
916        "month" => i64::from(days_from_civil(y, m, 1)) * 86_400_000_000,
917        "day" => days * 86_400_000_000,
918        "hour" => days * 86_400_000_000 + (day_micros / 3_600_000_000) * 3_600_000_000,
919        "minute" => days * 86_400_000_000 + (day_micros / 60_000_000) * 60_000_000,
920        "second" => days * 86_400_000_000 + (day_micros / 1_000_000) * 1_000_000,
921        other => {
922            return Err(EvalError::TypeMismatch {
923                detail: format!(
924                    "unknown date_trunc unit {other:?}; \
925                     supported: year, month, day, hour, minute, second"
926                ),
927            });
928        }
929    };
930    Ok(Value::Timestamp(truncated))
931}
932
933/// PG-style `expr::TYPE` coercion. NULL always casts as NULL.
934pub fn cast_value(v: Value, target: CastTarget) -> Result<Value, EvalError> {
935    if matches!(v, Value::Null) {
936        return Ok(Value::Null);
937    }
938    match target {
939        CastTarget::Vector => cast_to_vector(v),
940        CastTarget::Text => Ok(Value::Text(value_to_text(&v))),
941        CastTarget::Int => cast_numeric_to_int(v),
942        CastTarget::BigInt => cast_numeric_to_bigint(v),
943        CastTarget::Float => cast_numeric_to_float(v),
944        CastTarget::Bool => cast_to_bool(v),
945        CastTarget::Date => cast_to_date(v),
946        CastTarget::Timestamp => cast_to_timestamp(v),
947    }
948}
949
950fn cast_to_date(v: Value) -> Result<Value, EvalError> {
951    match v {
952        Value::Date(d) => Ok(Value::Date(d)),
953        // Integer literals carry days since the Unix epoch — used by
954        // the `CURRENT_DATE` AST rewrite to inject the wall clock.
955        Value::Int(n) => Ok(Value::Date(n)),
956        Value::BigInt(n) => {
957            i32::try_from(n)
958                .map(Value::Date)
959                .map_err(|_| EvalError::TypeMismatch {
960                    detail: "bigint days-since-epoch out of DATE range".into(),
961                })
962        }
963        // Timestamp truncates to its day boundary.
964        Value::Timestamp(t) => {
965            let days = t.div_euclid(86_400_000_000);
966            i32::try_from(days)
967                .map(Value::Date)
968                .map_err(|_| EvalError::TypeMismatch {
969                    detail: "timestamp out of DATE range".into(),
970                })
971        }
972        Value::Text(s) => parse_date_literal(&s)
973            .map(Value::Date)
974            .ok_or(EvalError::TypeMismatch {
975                detail: format!("cannot parse {s:?} as DATE (expected YYYY-MM-DD)"),
976            }),
977        other => Err(EvalError::TypeMismatch {
978            detail: format!("cannot cast {:?} to DATE", other.data_type()),
979        }),
980    }
981}
982
983fn cast_to_timestamp(v: Value) -> Result<Value, EvalError> {
984    match v {
985        Value::Timestamp(t) => Ok(Value::Timestamp(t)),
986        // Int / BigInt carry microseconds since the Unix epoch — used
987        // by the `NOW()` / `CURRENT_TIMESTAMP` AST rewrite to inject
988        // the wall clock as a plain integer literal.
989        Value::Int(n) => Ok(Value::Timestamp(i64::from(n))),
990        Value::BigInt(n) => Ok(Value::Timestamp(n)),
991        // DATE → TIMESTAMP picks midnight on the date.
992        Value::Date(d) => Ok(Value::Timestamp(i64::from(d) * 86_400_000_000)),
993        Value::Text(s) => {
994            parse_timestamp_literal(&s)
995                .map(Value::Timestamp)
996                .ok_or(EvalError::TypeMismatch {
997                    detail: format!(
998                        "cannot parse {s:?} as TIMESTAMP \
999                     (expected YYYY-MM-DD[ HH:MM:SS[.ffffff]])"
1000                    ),
1001                })
1002        }
1003        other => Err(EvalError::TypeMismatch {
1004            detail: format!("cannot cast {:?} to TIMESTAMP", other.data_type()),
1005        }),
1006    }
1007}
1008
1009fn value_to_text(v: &Value) -> String {
1010    match v {
1011        // v7.5.0 — Value is #[non_exhaustive]; any future variant
1012        // without explicit text rendering hits the Debug fallback
1013        // at the end.
1014        Value::SmallInt(n) => format!("{n}"),
1015        Value::Int(n) => format!("{n}"),
1016        Value::BigInt(n) => format!("{n}"),
1017        Value::Float(x) => format!("{x}"),
1018        // v4.9: JSON renders identically to Text — both are raw UTF-8.
1019        Value::Text(s) | Value::Json(s) => s.clone(),
1020        Value::Bool(b) => (if *b { "true" } else { "false" }).into(),
1021        Value::Vector(v) => {
1022            let cells: Vec<String> = v.iter().map(|x| format!("{x}")).collect();
1023            format!("[{}]", cells.join(", "))
1024        }
1025        // v6.0.1: render SQ8 cells dequantised, so SELECT output
1026        // matches the pgvector wire shape clients expect. The
1027        // recall envelope already absorbs the ≤ (max-min)/255/2
1028        // dequantisation error.
1029        Value::Sq8Vector(q) => {
1030            let cells: Vec<String> = spg_storage::quantize::dequantize(q)
1031                .iter()
1032                .map(|x| format!("{x}"))
1033                .collect();
1034            format!("[{}]", cells.join(", "))
1035        }
1036        // v6.0.3: HalfVector cells dequantise bit-exactly to f32
1037        // for SELECT output.
1038        Value::HalfVector(h) => {
1039            let cells: Vec<String> = h.to_f32_vec().iter().map(|x| format!("{x}")).collect();
1040            format!("[{}]", cells.join(", "))
1041        }
1042        Value::Numeric { scaled, scale } => format_numeric(*scaled, *scale),
1043        Value::Date(d) => format_date(*d),
1044        Value::Timestamp(t) => format_timestamp(*t),
1045        Value::Interval { months, micros } => format_interval(*months, *micros),
1046        Value::Null => "NULL".into(),
1047        // v7.5.0 — #[non_exhaustive] fallback for future Value variants.
1048        _ => format!("{v:?}"),
1049    }
1050}
1051
1052/// Render a `Date` (days since epoch) as `YYYY-MM-DD`. Negative values
1053/// for pre-1970 dates render with a leading `-` on the year.
1054pub fn format_date(days: i32) -> String {
1055    let (y, m, d) = civil_from_days(days);
1056    format!("{y:04}-{m:02}-{d:02}")
1057}
1058
1059/// Render a `Timestamp` (microseconds since epoch) as
1060/// `YYYY-MM-DD HH:MM:SS[.fff...]`. Trailing-zero fractional digits are
1061/// dropped; a whole-second value has no fractional part.
1062pub fn format_timestamp(micros: i64) -> String {
1063    const MICROS_PER_DAY: i64 = 86_400_000_000;
1064    // Split into day + intra-day part with proper floor division so
1065    // negative timestamps render right too.
1066    let days = micros.div_euclid(MICROS_PER_DAY);
1067    let day_micros = micros.rem_euclid(MICROS_PER_DAY);
1068    let day_i32 = i32::try_from(days).unwrap_or(i32::MAX);
1069    let (y, m, d) = civil_from_days(day_i32);
1070    let secs = day_micros / 1_000_000;
1071    let frac = day_micros % 1_000_000;
1072    let hh = secs / 3600;
1073    let mm = (secs / 60) % 60;
1074    let ss = secs % 60;
1075    if frac == 0 {
1076        format!("{y:04}-{m:02}-{d:02} {hh:02}:{mm:02}:{ss:02}")
1077    } else {
1078        // Strip trailing zeros from the 6-digit fractional component.
1079        let raw = format!("{frac:06}");
1080        let trimmed = raw.trim_end_matches('0');
1081        format!("{y:04}-{m:02}-{d:02} {hh:02}:{mm:02}:{ss:02}.{trimmed}")
1082    }
1083}
1084
1085/// Howard Hinnant's `civil_from_days` — converts days since the Unix
1086/// epoch back to a proleptic-Gregorian (year, month, day) triple. Both
1087/// directions of this calendar conversion live in `eval.rs` so the
1088/// engine never reaches for `std` time facilities.
1089#[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
1090fn civil_from_days(days: i32) -> (i32, u32, u32) {
1091    let z = i64::from(days) + 719_468;
1092    let era = z.div_euclid(146_097);
1093    // doe ∈ [0, 146_097); fits in u32 with room to spare. Same for
1094    // every other quantity below — `as u32` truncations are safe by
1095    // construction.
1096    let doe = (z - era * 146_097) as u32;
1097    let yoe = (doe.saturating_sub(doe / 1460) + doe / 36524 - doe / 146_096) / 365;
1098    let y_base = i64::from(yoe) + era * 400;
1099    let doy = doe.saturating_sub(365 * yoe + yoe / 4 - yoe / 100);
1100    let mp = (5 * doy + 2) / 153;
1101    let d = doy.saturating_sub((153 * mp + 2) / 5) + 1;
1102    let m = if mp < 10 { mp + 3 } else { mp - 9 };
1103    let y = if m <= 2 { y_base + 1 } else { y_base };
1104    (y as i32, m, d)
1105}
1106
1107/// Inverse of `civil_from_days` — converts (year, month, day) to days
1108/// since 1970-01-01. Out-of-range months / days saturate.
1109#[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
1110pub fn days_from_civil(y: i32, m: u32, d: u32) -> i32 {
1111    let y_adj = if m <= 2 {
1112        i64::from(y) - 1
1113    } else {
1114        i64::from(y)
1115    };
1116    let era = y_adj.div_euclid(400);
1117    let yoe = (y_adj - era * 400) as u32;
1118    let doy = (153 * (if m > 2 { m - 3 } else { m + 9 }) + 2) / 5 + d.saturating_sub(1);
1119    let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
1120    let total = era * 146_097 + i64::from(doe) - 719_468;
1121    i32::try_from(total).unwrap_or(i32::MAX)
1122}
1123
1124/// Parse `YYYY-MM-DD` into a `Date` (days since Unix epoch). Returns
1125/// `None` on shape / numeric failure; the engine surfaces that as a
1126/// `TypeMismatch` with the original text included.
1127pub fn parse_date_literal(s: &str) -> Option<i32> {
1128    let bytes = s.as_bytes();
1129    if bytes.len() != 10 || bytes[4] != b'-' || bytes[7] != b'-' {
1130        return None;
1131    }
1132    let y: i32 = s[0..4].parse().ok()?;
1133    let m: u32 = s[5..7].parse().ok()?;
1134    let d: u32 = s[8..10].parse().ok()?;
1135    if !(1..=12).contains(&m) || !(1..=31).contains(&d) {
1136        return None;
1137    }
1138    Some(days_from_civil(y, m, d))
1139}
1140
1141/// Parse `YYYY-MM-DD[ HH:MM:SS[.ffffff]]` into a `Timestamp`
1142/// (microseconds since Unix epoch). The time portion is optional;
1143/// missing → midnight. The fractional portion accepts 1–6 digits and
1144/// pads with zeros to microseconds.
1145pub fn parse_timestamp_literal(s: &str) -> Option<i64> {
1146    let trimmed = s.trim();
1147    let (date_part, time_part) = match trimmed.find([' ', 'T']) {
1148        Some(i) => (&trimmed[..i], Some(&trimmed[i + 1..])),
1149        None => (trimmed, None),
1150    };
1151    let days = parse_date_literal(date_part)?;
1152    let day_micros = match time_part {
1153        None => 0,
1154        Some(t) => parse_time_of_day_micros(t)?,
1155    };
1156    Some(i64::from(days) * 86_400_000_000 + day_micros)
1157}
1158
1159fn parse_time_of_day_micros(t: &str) -> Option<i64> {
1160    let (time, frac_str) = match t.split_once('.') {
1161        Some((a, b)) => (a, Some(b)),
1162        None => (t, None),
1163    };
1164    let bytes = time.as_bytes();
1165    if bytes.len() != 8 || bytes[2] != b':' || bytes[5] != b':' {
1166        return None;
1167    }
1168    let hh: i64 = time[0..2].parse().ok()?;
1169    let mm: i64 = time[3..5].parse().ok()?;
1170    let ss: i64 = time[6..8].parse().ok()?;
1171    if !(0..24).contains(&hh) || !(0..60).contains(&mm) || !(0..60).contains(&ss) {
1172        return None;
1173    }
1174    let frac_micros: i64 = match frac_str {
1175        None => 0,
1176        Some(f) => {
1177            // Pad right with zeros to 6 digits, then truncate extras.
1178            if f.is_empty() || f.len() > 9 {
1179                return None;
1180            }
1181            let mut padded = String::with_capacity(6);
1182            padded.push_str(&f[..f.len().min(6)]);
1183            while padded.len() < 6 {
1184                padded.push('0');
1185            }
1186            padded.parse().ok()?
1187        }
1188    };
1189    Some(((hh * 3600 + mm * 60 + ss) * 1_000_000) + frac_micros)
1190}
1191
1192/// Render an `Interval { months, micros }` in a PG-ish shape. The output
1193/// mirrors `psql`'s text format: years/months from the months part,
1194/// days/HH:MM:SS[.frac] from the microsecond part. Empty parts are
1195/// omitted; an all-zero interval renders as `0`.
1196pub fn format_interval(months: i32, micros: i64) -> String {
1197    const MICROS_PER_DAY: i64 = 86_400_000_000;
1198    let mut parts: Vec<String> = Vec::new();
1199    let years = months / 12;
1200    let mons = months % 12;
1201    // PG renders the unit in the singular only for `+1`; `-1` and any
1202    // other value pluralise. Helper closes over that rule.
1203    let unit = |n: i64, singular: &'static str, plural: &'static str| -> &'static str {
1204        if n == 1 { singular } else { plural }
1205    };
1206    if years != 0 {
1207        parts.push(format!(
1208            "{years} {}",
1209            unit(i64::from(years), "year", "years")
1210        ));
1211    }
1212    if mons != 0 {
1213        parts.push(format!("{mons} {}", unit(i64::from(mons), "mon", "mons")));
1214    }
1215    let days = micros / MICROS_PER_DAY;
1216    let mut rem = micros % MICROS_PER_DAY;
1217    if days != 0 {
1218        parts.push(format!("{days} {}", unit(days, "day", "days")));
1219    }
1220    if rem != 0 {
1221        let neg = rem < 0;
1222        if neg {
1223            rem = -rem;
1224        }
1225        let secs = rem / 1_000_000;
1226        let frac = rem % 1_000_000;
1227        let hh = secs / 3600;
1228        let mm = (secs / 60) % 60;
1229        let ss = secs % 60;
1230        let sign = if neg { "-" } else { "" };
1231        if frac == 0 {
1232            parts.push(format!("{sign}{hh:02}:{mm:02}:{ss:02}"));
1233        } else {
1234            let raw = format!("{frac:06}");
1235            let trimmed = raw.trim_end_matches('0');
1236            parts.push(format!("{sign}{hh:02}:{mm:02}:{ss:02}.{trimmed}"));
1237        }
1238    }
1239    if parts.is_empty() {
1240        "0".into()
1241    } else {
1242        parts.join(" ")
1243    }
1244}
1245
1246/// Add `months` (signed) to a `(year, month, day)` triple using PG's
1247/// clamp-to-last-day rule (so `'2024-01-31' + 1 month` → `'2024-02-29'`).
1248fn add_months_to_civil(y: i32, m: u32, d: u32, months: i32) -> (i32, u32, u32) {
1249    let total_months = i64::from(y) * 12 + i64::from(m) - 1 + i64::from(months);
1250    let new_year = i32::try_from(total_months.div_euclid(12)).unwrap_or(i32::MAX);
1251    let new_month_zero = total_months.rem_euclid(12);
1252    #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
1253    let new_month = (new_month_zero as u32) + 1;
1254    let max_day = days_in_month(new_year, new_month);
1255    (new_year, new_month, d.min(max_day))
1256}
1257
1258const fn days_in_month(y: i32, m: u32) -> u32 {
1259    match m {
1260        1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
1261        2 => {
1262            // Proleptic Gregorian leap rule.
1263            if y.rem_euclid(4) == 0 && (y.rem_euclid(100) != 0 || y.rem_euclid(400) == 0) {
1264                29
1265            } else {
1266                28
1267            }
1268        }
1269        // 4 / 6 / 9 / 11 plus any out-of-range month (callers normalise
1270        // first, but be defensive) get the 30-day fallback.
1271        _ => 30,
1272    }
1273}
1274
1275/// Render a `Numeric { scaled, scale }` as its decimal text form.
1276/// Negative `scaled` prepends `-` to the absolute value's digits; the
1277/// integer / fractional split is by character count, padding the
1278/// fractional side with leading zeros to exactly `scale` chars.
1279pub fn format_numeric(scaled: i128, scale: u8) -> String {
1280    if scale == 0 {
1281        return format!("{scaled}");
1282    }
1283    let negative = scaled < 0;
1284    let mag_str = scaled.unsigned_abs().to_string();
1285    let mag_bytes = mag_str.as_bytes();
1286    let scale_u = scale as usize;
1287    let mut out = String::with_capacity(mag_str.len() + 3);
1288    if negative {
1289        out.push('-');
1290    }
1291    if mag_bytes.len() <= scale_u {
1292        out.push('0');
1293        out.push('.');
1294        for _ in mag_bytes.len()..scale_u {
1295            out.push('0');
1296        }
1297        out.push_str(&mag_str);
1298    } else {
1299        let split = mag_bytes.len() - scale_u;
1300        out.push_str(&mag_str[..split]);
1301        out.push('.');
1302        out.push_str(&mag_str[split..]);
1303    }
1304    out
1305}
1306
1307fn cast_numeric_to_int(v: Value) -> Result<Value, EvalError> {
1308    match v {
1309        Value::Int(n) => Ok(Value::Int(n)),
1310        Value::BigInt(n) => i32::try_from(n)
1311            .map(Value::Int)
1312            .map_err(|_| EvalError::TypeMismatch {
1313                detail: format!("bigint {n} does not fit in int"),
1314            }),
1315        #[allow(clippy::cast_possible_truncation)]
1316        Value::Float(x) => Ok(Value::Int(x as i32)),
1317        Value::Text(s) => {
1318            s.trim()
1319                .parse::<i32>()
1320                .map(Value::Int)
1321                .map_err(|_| EvalError::TypeMismatch {
1322                    detail: format!("cannot parse {s:?} as int"),
1323                })
1324        }
1325        Value::Bool(b) => Ok(Value::Int(i32::from(b))),
1326        other => Err(EvalError::TypeMismatch {
1327            detail: format!("cannot cast {:?} to int", other.data_type()),
1328        }),
1329    }
1330}
1331
1332fn cast_numeric_to_bigint(v: Value) -> Result<Value, EvalError> {
1333    match v {
1334        Value::Int(n) => Ok(Value::BigInt(i64::from(n))),
1335        Value::BigInt(n) => Ok(Value::BigInt(n)),
1336        #[allow(clippy::cast_possible_truncation)]
1337        Value::Float(x) => Ok(Value::BigInt(x as i64)),
1338        Value::Text(s) => {
1339            s.trim()
1340                .parse::<i64>()
1341                .map(Value::BigInt)
1342                .map_err(|_| EvalError::TypeMismatch {
1343                    detail: format!("cannot parse {s:?} as bigint"),
1344                })
1345        }
1346        Value::Bool(b) => Ok(Value::BigInt(i64::from(b))),
1347        other => Err(EvalError::TypeMismatch {
1348            detail: format!("cannot cast {:?} to bigint", other.data_type()),
1349        }),
1350    }
1351}
1352
1353fn cast_numeric_to_float(v: Value) -> Result<Value, EvalError> {
1354    match v {
1355        Value::Int(n) => Ok(Value::Float(f64::from(n))),
1356        #[allow(clippy::cast_precision_loss)]
1357        Value::BigInt(n) => Ok(Value::Float(n as f64)),
1358        Value::Float(x) => Ok(Value::Float(x)),
1359        Value::Text(s) => {
1360            s.trim()
1361                .parse::<f64>()
1362                .map(Value::Float)
1363                .map_err(|_| EvalError::TypeMismatch {
1364                    detail: format!("cannot parse {s:?} as float"),
1365                })
1366        }
1367        other => Err(EvalError::TypeMismatch {
1368            detail: format!("cannot cast {:?} to float", other.data_type()),
1369        }),
1370    }
1371}
1372
1373fn cast_to_bool(v: Value) -> Result<Value, EvalError> {
1374    match v {
1375        Value::Bool(b) => Ok(Value::Bool(b)),
1376        Value::Int(n) => Ok(Value::Bool(n != 0)),
1377        Value::BigInt(n) => Ok(Value::Bool(n != 0)),
1378        Value::Text(s) => {
1379            let lo = s.trim().to_ascii_lowercase();
1380            match lo.as_str() {
1381                "true" | "t" | "yes" | "y" | "1" | "on" => Ok(Value::Bool(true)),
1382                "false" | "f" | "no" | "n" | "0" | "off" => Ok(Value::Bool(false)),
1383                _ => Err(EvalError::TypeMismatch {
1384                    detail: format!("cannot parse {s:?} as bool"),
1385                }),
1386            }
1387        }
1388        other => Err(EvalError::TypeMismatch {
1389            detail: format!("cannot cast {:?} to bool", other.data_type()),
1390        }),
1391    }
1392}
1393
1394/// Parse a `Value::Text("[1.0, 2.0, 3.0]")` into a `Value::Vector(..)`. Mirrors
1395/// pgvector's `'[..]'::vector` cast. NULL casts as NULL.
1396pub fn cast_to_vector(v: Value) -> Result<Value, EvalError> {
1397    match v {
1398        Value::Null => Ok(Value::Null),
1399        Value::Vector(v) => Ok(Value::Vector(v)),
1400        Value::Text(s) => parse_vector_text(&s)
1401            .map(Value::Vector)
1402            .ok_or(EvalError::TypeMismatch {
1403                detail: format!("cannot parse {s:?} as a vector literal"),
1404            }),
1405        other => Err(EvalError::TypeMismatch {
1406            detail: format!("::vector requires text input, got {:?}", other.data_type()),
1407        }),
1408    }
1409}
1410
1411/// Parse `"[1.0, 2.0, -3]"` into `Vec<f32>`. Returns `None` on malformed input.
1412fn parse_vector_text(s: &str) -> Option<Vec<f32>> {
1413    let trimmed = s.trim();
1414    let inner = trimmed.strip_prefix('[')?.strip_suffix(']')?;
1415    let trimmed_inner = inner.trim();
1416    if trimmed_inner.is_empty() {
1417        return Some(Vec::new());
1418    }
1419    let mut out = Vec::new();
1420    for part in trimmed_inner.split(',') {
1421        let f: f32 = part.trim().parse().ok()?;
1422        out.push(f);
1423    }
1424    Some(out)
1425}
1426
1427fn literal_to_value(l: &Literal) -> Value {
1428    match l {
1429        Literal::Integer(n) => {
1430            if let Ok(small) = i32::try_from(*n) {
1431                Value::Int(small)
1432            } else {
1433                Value::BigInt(*n)
1434            }
1435        }
1436        Literal::Float(x) => Value::Float(*x),
1437        Literal::String(s) => Value::Text(s.clone()),
1438        Literal::Vector(v) => Value::Vector(v.clone()),
1439        Literal::Bool(b) => Value::Bool(*b),
1440        Literal::Null => Value::Null,
1441        Literal::Interval { months, micros, .. } => Value::Interval {
1442            months: *months,
1443            micros: *micros,
1444        },
1445    }
1446}
1447
1448fn resolve_column(c: &ColumnName, row: &Row, ctx: &EvalContext<'_>) -> Result<Value, EvalError> {
1449    if let Some(q) = &c.qualifier {
1450        // Multi-table evaluation (joins): the synthesised schema uses
1451        // composite column names "alias.column" so we look that up
1452        // directly. Falls back to the single-table case below if the
1453        // composite isn't present.
1454        let composite = alloc::format!("{q}.{name}", name = c.name);
1455        if let Some(pos) = ctx.columns.iter().position(|s| s.name == composite) {
1456            return Ok(row.values[pos].clone());
1457        }
1458        let expected = ctx.table_alias.ok_or_else(|| EvalError::UnknownQualifier {
1459            qualifier: q.clone(),
1460        })?;
1461        if q != expected {
1462            return Err(EvalError::UnknownQualifier {
1463                qualifier: q.clone(),
1464            });
1465        }
1466    }
1467    if let Some(pos) = ctx.columns.iter().position(|s| s.name == c.name) {
1468        return Ok(row.values[pos].clone());
1469    }
1470    // Bare-name fallback for joined schemas: match any single composite
1471    // column ending in ".<name>"; ambiguity is an error.
1472    let suffix = alloc::format!(".{name}", name = c.name);
1473    let mut matches = ctx
1474        .columns
1475        .iter()
1476        .enumerate()
1477        .filter(|(_, s)| s.name.ends_with(&suffix));
1478    let first = matches.next();
1479    let extra = matches.next();
1480    match (first, extra) {
1481        (Some((pos, _)), None) => Ok(row.values[pos].clone()),
1482        (Some(_), Some(_)) => Err(EvalError::TypeMismatch {
1483            detail: alloc::format!("ambiguous column reference: {}", c.name),
1484        }),
1485        _ => Err(EvalError::ColumnNotFound {
1486            name: c.name.clone(),
1487        }),
1488    }
1489}
1490
1491fn apply_unary(op: UnOp, v: Value) -> Result<Value, EvalError> {
1492    match (op, v) {
1493        (_, Value::Null) => Ok(Value::Null),
1494        (UnOp::Neg, Value::Int(n)) => {
1495            n.checked_neg()
1496                .map(Value::Int)
1497                .ok_or(EvalError::TypeMismatch {
1498                    detail: "integer overflow on unary -".into(),
1499                })
1500        }
1501        (UnOp::Neg, Value::BigInt(n)) => {
1502            n.checked_neg()
1503                .map(Value::BigInt)
1504                .ok_or(EvalError::TypeMismatch {
1505                    detail: "bigint overflow on unary -".into(),
1506                })
1507        }
1508        (UnOp::Neg, Value::Float(x)) => Ok(Value::Float(-x)),
1509        (UnOp::Neg, other) => Err(EvalError::TypeMismatch {
1510            detail: format!("unary - applied to {:?}", other.data_type()),
1511        }),
1512        (UnOp::Not, Value::Bool(b)) => Ok(Value::Bool(!b)),
1513        (UnOp::Not, other) => Err(EvalError::TypeMismatch {
1514            detail: format!("NOT applied to {:?}", other.data_type()),
1515        }),
1516    }
1517}
1518
1519fn apply_binary(op: BinOp, l: Value, r: Value) -> Result<Value, EvalError> {
1520    // SQL three-valued logic for AND / OR with NULL is special — handle before
1521    // the general NULL-propagation rule.
1522    if let BinOp::And = op {
1523        return and_3vl(l, r);
1524    }
1525    if let BinOp::Or = op {
1526        return or_3vl(l, r);
1527    }
1528    // Everything else: any NULL operand → NULL.
1529    if l.is_null() || r.is_null() {
1530        return Ok(Value::Null);
1531    }
1532    // NUMERIC arithmetic and comparisons run in fixed-point; promote
1533    // integers to a common NUMERIC scale and stay in i128 throughout.
1534    if matches!(l, Value::Numeric { .. }) || matches!(r, Value::Numeric { .. }) {
1535        return apply_binary_numeric(op, l, r);
1536    }
1537    // Date / Timestamp arithmetic. PG semantics:
1538    //   * date + int      → date  (int is days)
1539    //   * int + date      → date
1540    //   * date - int      → date
1541    //   * date - date     → int   (days, signed)
1542    //   * timestamp - timestamp → bigint (microseconds, signed)
1543    // Other date/time math (`timestamp + int`, INTERVAL) lands later.
1544    if let Some(result) = apply_binary_calendar(op, &l, &r)? {
1545        return Ok(result);
1546    }
1547    match op {
1548        BinOp::Add => arith(l, r, i64::checked_add, |a, b| a + b, "+"),
1549        BinOp::Sub => arith(l, r, i64::checked_sub, |a, b| a - b, "-"),
1550        BinOp::Mul => arith(l, r, i64::checked_mul, |a, b| a * b, "*"),
1551        BinOp::Div => div_op(l, r),
1552        BinOp::L2Distance => l2_distance(l, r),
1553        BinOp::InnerProduct => inner_product(l, r),
1554        BinOp::CosineDistance => cosine_distance(l, r),
1555        BinOp::Concat => Ok(text_concat(&l, &r)),
1556        BinOp::JsonGet => crate::json::path_get(&l, &r, false),
1557        BinOp::JsonGetText => crate::json::path_get(&l, &r, true),
1558        BinOp::JsonGetPath => crate::json::path_walk(&l, &r, false),
1559        BinOp::JsonGetPathText => crate::json::path_walk(&l, &r, true),
1560        BinOp::JsonContains => crate::json::contains(&l, &r),
1561        BinOp::Eq | BinOp::NotEq | BinOp::Lt | BinOp::LtEq | BinOp::Gt | BinOp::GtEq => {
1562            compare(op, &l, &r)
1563        }
1564        BinOp::And | BinOp::Or => unreachable!("handled above"),
1565    }
1566}
1567
1568/// Calendar arithmetic. Returns `Some(value)` when the operand pair
1569/// is a date/time combo this function understands, `None` to let the
1570/// caller fall through to the regular numeric / text paths.
1571fn apply_binary_calendar(op: BinOp, l: &Value, r: &Value) -> Result<Option<Value>, EvalError> {
1572    let int_value = |v: &Value| -> Option<i64> {
1573        match v {
1574            Value::SmallInt(n) => Some(i64::from(*n)),
1575            Value::Int(n) => Some(i64::from(*n)),
1576            Value::BigInt(n) => Some(*n),
1577            _ => None,
1578        }
1579    };
1580    // Most-specific cases first — DATE-DATE / TS-TS subtraction before
1581    // DATE-integer subtraction, otherwise the latter swallows the
1582    // former with an `int_value(Date) = None` no-op fall-through.
1583    match (l, r) {
1584        (Value::Date(a), Value::Date(b)) if op == BinOp::Sub => {
1585            return Ok(Some(Value::BigInt(i64::from(*a) - i64::from(*b))));
1586        }
1587        (Value::Timestamp(a), Value::Timestamp(b)) if op == BinOp::Sub => {
1588            let delta = a.checked_sub(*b).ok_or(EvalError::TypeMismatch {
1589                detail: "TIMESTAMP - TIMESTAMP overflows i64 microseconds".into(),
1590            })?;
1591            return Ok(Some(Value::BigInt(delta)));
1592        }
1593        _ => {}
1594    }
1595    // INTERVAL arithmetic. PG: timestamp ± interval → timestamp,
1596    // date ± interval → date (if interval is pure days/months with no
1597    // sub-day component) else timestamp, interval ± interval → interval.
1598    if let Some(out) = apply_binary_interval(op, l, r)? {
1599        return Ok(Some(out));
1600    }
1601    match (l, r) {
1602        (Value::Date(d), other) if op == BinOp::Add => {
1603            if let Some(n) = int_value(other) {
1604                let days = i64::from(*d).saturating_add(n);
1605                let days32 = i32::try_from(days).map_err(|_| EvalError::TypeMismatch {
1606                    detail: "DATE + integer overflows DATE range".into(),
1607                })?;
1608                return Ok(Some(Value::Date(days32)));
1609            }
1610        }
1611        (other, Value::Date(d)) if op == BinOp::Add => {
1612            if let Some(n) = int_value(other) {
1613                let days = i64::from(*d).saturating_add(n);
1614                let days32 = i32::try_from(days).map_err(|_| EvalError::TypeMismatch {
1615                    detail: "integer + DATE overflows DATE range".into(),
1616                })?;
1617                return Ok(Some(Value::Date(days32)));
1618            }
1619        }
1620        (Value::Date(d), other) if op == BinOp::Sub => {
1621            if let Some(n) = int_value(other) {
1622                let days = i64::from(*d).saturating_sub(n);
1623                let days32 = i32::try_from(days).map_err(|_| EvalError::TypeMismatch {
1624                    detail: "DATE - integer overflows DATE range".into(),
1625                })?;
1626                return Ok(Some(Value::Date(days32)));
1627            }
1628        }
1629        _ => {}
1630    }
1631    Ok(None)
1632}
1633
1634/// INTERVAL-aware binary ops. Recognises:
1635///   timestamp ± interval → timestamp
1636///   date ± interval      → date (if interval is integral days/months only)
1637///                       → timestamp (if interval has sub-day micros)
1638///   interval ± interval  → interval
1639/// Commutative for `+`. Returns `None` for unrecognised operand pairs so
1640/// the caller can fall through.
1641fn apply_binary_interval(op: BinOp, l: &Value, r: &Value) -> Result<Option<Value>, EvalError> {
1642    // Normalise so the interval (if any) is always on the right for Add;
1643    // Sub stays left-handed because it isn't commutative.
1644    let (lhs, rhs, sign): (&Value, &Value, i64) = match (l, r, op) {
1645        (Value::Interval { .. }, _, BinOp::Add) => (r, l, 1),
1646        (_, Value::Interval { .. }, BinOp::Add) => (l, r, 1),
1647        (_, Value::Interval { .. }, BinOp::Sub) => (l, r, -1),
1648        _ => return Ok(None),
1649    };
1650    let Value::Interval {
1651        months: rhs_months,
1652        micros: rhs_us,
1653    } = rhs
1654    else {
1655        unreachable!("rhs guaranteed to be Interval by the match above");
1656    };
1657    let signed_months = i64::from(*rhs_months) * sign;
1658    let signed_micros = rhs_us.checked_mul(sign).ok_or(EvalError::TypeMismatch {
1659        detail: "INTERVAL micros overflows on negation".into(),
1660    })?;
1661    match lhs {
1662        Value::Timestamp(t) => Ok(Some(Value::Timestamp(add_interval_to_micros(
1663            *t,
1664            signed_months,
1665            signed_micros,
1666        )?))),
1667        Value::Date(d) => {
1668            // Date + interval stays a date when the interval has zero
1669            // sub-day microseconds; otherwise promote to TIMESTAMP at
1670            // midnight of the (months-shifted) date first.
1671            let day_aligned = signed_micros.rem_euclid(86_400_000_000) == 0;
1672            if day_aligned {
1673                let micros_per_day = 86_400_000_000_i64;
1674                let days_delta = signed_micros / micros_per_day;
1675                let shifted = shift_date_by_months(*d, signed_months)?;
1676                let new_days =
1677                    i64::from(shifted)
1678                        .checked_add(days_delta)
1679                        .ok_or(EvalError::TypeMismatch {
1680                            detail: "DATE ± INTERVAL overflows DATE range".into(),
1681                        })?;
1682                let days32 = i32::try_from(new_days).map_err(|_| EvalError::TypeMismatch {
1683                    detail: "DATE ± INTERVAL overflows DATE range".into(),
1684                })?;
1685                Ok(Some(Value::Date(days32)))
1686            } else {
1687                let base =
1688                    i64::from(*d)
1689                        .checked_mul(86_400_000_000)
1690                        .ok_or(EvalError::TypeMismatch {
1691                            detail: "DATE → TIMESTAMP lift overflows for INTERVAL math".into(),
1692                        })?;
1693                Ok(Some(Value::Timestamp(add_interval_to_micros(
1694                    base,
1695                    signed_months,
1696                    signed_micros,
1697                )?)))
1698            }
1699        }
1700        Value::Interval {
1701            months: lhs_months,
1702            micros: lhs_us,
1703        } => {
1704            let new_months = i64::from(*lhs_months)
1705                .checked_add(signed_months)
1706                .and_then(|n| i32::try_from(n).ok())
1707                .ok_or(EvalError::TypeMismatch {
1708                    detail: "INTERVAL ± INTERVAL months overflows i32".into(),
1709                })?;
1710            let new_micros = lhs_us
1711                .checked_add(signed_micros)
1712                .ok_or(EvalError::TypeMismatch {
1713                    detail: "INTERVAL ± INTERVAL micros overflows i64".into(),
1714                })?;
1715            Ok(Some(Value::Interval {
1716                months: new_months,
1717                micros: new_micros,
1718            }))
1719        }
1720        _ => Err(EvalError::TypeMismatch {
1721            detail: format!(
1722                "operator {op:?} not defined for {:?} and INTERVAL",
1723                lhs.data_type()
1724            ),
1725        }),
1726    }
1727}
1728
1729/// Shift a `Date` by a signed number of months using the PG clamp rule.
1730fn shift_date_by_months(d: i32, months: i64) -> Result<i32, EvalError> {
1731    let (y, m, day) = civil_from_days(d);
1732    let months_i32 = i32::try_from(months).map_err(|_| EvalError::TypeMismatch {
1733        detail: "INTERVAL months delta out of i32 range".into(),
1734    })?;
1735    let (ny, nm, nd) = add_months_to_civil(y, m, day, months_i32);
1736    Ok(days_from_civil(ny, nm, nd))
1737}
1738
1739/// Add (months, micros) to a `Timestamp` (microseconds since epoch).
1740/// Months part is applied through civil calendar with clamp-to-last-day;
1741/// micros part is plain i64 addition with overflow guard.
1742fn add_interval_to_micros(t: i64, months: i64, micros: i64) -> Result<i64, EvalError> {
1743    let mut out = t;
1744    if months != 0 {
1745        const MICROS_PER_DAY: i64 = 86_400_000_000;
1746        let days = out.div_euclid(MICROS_PER_DAY);
1747        let day_micros = out.rem_euclid(MICROS_PER_DAY);
1748        let day_i32 = i32::try_from(days).map_err(|_| EvalError::TypeMismatch {
1749            detail: "TIMESTAMP day component out of i32 range for INTERVAL months math".into(),
1750        })?;
1751        let shifted_days = shift_date_by_months(day_i32, months)?;
1752        out = i64::from(shifted_days)
1753            .checked_mul(MICROS_PER_DAY)
1754            .and_then(|n| n.checked_add(day_micros))
1755            .ok_or(EvalError::TypeMismatch {
1756                detail: "TIMESTAMP ± INTERVAL months overflows i64 microseconds".into(),
1757            })?;
1758    }
1759    out.checked_add(micros).ok_or(EvalError::TypeMismatch {
1760        detail: "TIMESTAMP ± INTERVAL micros overflows i64".into(),
1761    })
1762}
1763
1764/// Dispatch for any binary op when at least one operand is NUMERIC.
1765/// Other-side integers / floats are promoted to a NUMERIC at a common
1766/// scale; all add / sub / mul / div / compare paths stay in i128.
1767#[allow(clippy::needless_pass_by_value)] // mirrors `apply_binary`'s by-value calling convention
1768fn apply_binary_numeric(op: BinOp, l: Value, r: Value) -> Result<Value, EvalError> {
1769    // Float still wins — Numeric + Float coerces both to f64 and runs
1770    // through the float path. PG demotes Numeric to float in this mix
1771    // too (the documented behaviour for `numeric + double precision`).
1772    let float_path = matches!(l, Value::Float(_)) || matches!(r, Value::Float(_));
1773    if float_path {
1774        let af = as_f64(&l)?;
1775        let bf = as_f64(&r)?;
1776        return match op {
1777            BinOp::Add => Ok(Value::Float(af + bf)),
1778            BinOp::Sub => Ok(Value::Float(af - bf)),
1779            BinOp::Mul => Ok(Value::Float(af * bf)),
1780            BinOp::Div => {
1781                if bf == 0.0 {
1782                    Err(EvalError::DivisionByZero)
1783                } else {
1784                    Ok(Value::Float(af / bf))
1785                }
1786            }
1787            BinOp::Eq | BinOp::NotEq | BinOp::Lt | BinOp::LtEq | BinOp::Gt | BinOp::GtEq => {
1788                let ord = af.partial_cmp(&bf).ok_or(EvalError::TypeMismatch {
1789                    detail: "NaN in NUMERIC/Float comparison".into(),
1790                })?;
1791                Ok(Value::Bool(cmp_to_bool(op, ord)))
1792            }
1793            BinOp::Concat => Ok(text_concat(&l, &r)),
1794            other => Err(EvalError::TypeMismatch {
1795                detail: format!("operator {other:?} not defined for NUMERIC and Float"),
1796            }),
1797        };
1798    }
1799    // Promote integer ↔ numeric to a shared scale (max of both sides).
1800    let (a, sa) = numeric_or_widen(&l).ok_or_else(|| EvalError::TypeMismatch {
1801        detail: format!("NUMERIC op against non-numeric {:?}", l.data_type()),
1802    })?;
1803    let (b, sb) = numeric_or_widen(&r).ok_or_else(|| EvalError::TypeMismatch {
1804        detail: format!("NUMERIC op against non-numeric {:?}", r.data_type()),
1805    })?;
1806    match op {
1807        BinOp::Add | BinOp::Sub => {
1808            let target_scale = sa.max(sb);
1809            let lhs = rescale(a, sa, target_scale).ok_or(EvalError::TypeMismatch {
1810                detail: "NUMERIC overflow on rescale".into(),
1811            })?;
1812            let rhs = rescale(b, sb, target_scale).ok_or(EvalError::TypeMismatch {
1813                detail: "NUMERIC overflow on rescale".into(),
1814            })?;
1815            let r = match op {
1816                BinOp::Add => lhs.checked_add(rhs),
1817                BinOp::Sub => lhs.checked_sub(rhs),
1818                _ => unreachable!(),
1819            }
1820            .ok_or(EvalError::TypeMismatch {
1821                detail: "NUMERIC overflow on +/-".into(),
1822            })?;
1823            Ok(Value::Numeric {
1824                scaled: r,
1825                scale: target_scale,
1826            })
1827        }
1828        BinOp::Mul => {
1829            let scaled = a.checked_mul(b).ok_or(EvalError::TypeMismatch {
1830                detail: "NUMERIC overflow on *".into(),
1831            })?;
1832            Ok(Value::Numeric {
1833                scaled,
1834                scale: sa.saturating_add(sb),
1835            })
1836        }
1837        BinOp::Div => {
1838            if b == 0 {
1839                return Err(EvalError::DivisionByZero);
1840            }
1841            // Result scale: keep the wider operand's scale. Pre-scale
1842            // the numerator so the integer division retains that many
1843            // fractional digits. Round half-away-from-zero.
1844            let target_scale = sa.max(sb);
1845            // Numerator effective scale becomes sa + target_scale; we
1846            // bring it up to (target_scale + sb) so the divisor's scale
1847            // cancels cleanly.
1848            let bump = pow10_i128(target_scale.saturating_add(sb).saturating_sub(sa));
1849            let num = a.checked_mul(bump).ok_or(EvalError::TypeMismatch {
1850                detail: "NUMERIC overflow on / scaling".into(),
1851            })?;
1852            let half = if b >= 0 { b / 2 } else { -(b / 2) };
1853            let adj = if (num >= 0) == (b >= 0) {
1854                num + half
1855            } else {
1856                num - half
1857            };
1858            Ok(Value::Numeric {
1859                scaled: adj / b,
1860                scale: target_scale,
1861            })
1862        }
1863        BinOp::Eq | BinOp::NotEq | BinOp::Lt | BinOp::LtEq | BinOp::Gt | BinOp::GtEq => {
1864            let target_scale = sa.max(sb);
1865            let lhs = rescale(a, sa, target_scale).ok_or(EvalError::TypeMismatch {
1866                detail: "NUMERIC overflow on rescale".into(),
1867            })?;
1868            let rhs = rescale(b, sb, target_scale).ok_or(EvalError::TypeMismatch {
1869                detail: "NUMERIC overflow on rescale".into(),
1870            })?;
1871            Ok(Value::Bool(cmp_to_bool(op, lhs.cmp(&rhs))))
1872        }
1873        BinOp::Concat => Ok(text_concat(&l, &r)),
1874        other => Err(EvalError::TypeMismatch {
1875            detail: format!("operator {other:?} not defined for NUMERIC"),
1876        }),
1877    }
1878}
1879
1880/// Express `v` as a `(scaled_i128, scale)` pair. Plain integers come
1881/// back with `scale=0`; NUMERIC keeps its own scale. Anything else
1882/// returns `None` and the caller raises a type error.
1883fn numeric_or_widen(v: &Value) -> Option<(i128, u8)> {
1884    match v {
1885        Value::Numeric { scaled, scale } => Some((*scaled, *scale)),
1886        Value::Int(n) => Some((i128::from(*n), 0)),
1887        Value::SmallInt(n) => Some((i128::from(*n), 0)),
1888        Value::BigInt(n) => Some((i128::from(*n), 0)),
1889        _ => None,
1890    }
1891}
1892
1893fn rescale(scaled: i128, src: u8, dst: u8) -> Option<i128> {
1894    if src == dst {
1895        return Some(scaled);
1896    }
1897    if dst > src {
1898        scaled.checked_mul(pow10_i128(dst - src))
1899    } else {
1900        let drop = pow10_i128(src - dst);
1901        let half = drop / 2;
1902        let r = if scaled >= 0 {
1903            scaled + half
1904        } else {
1905            scaled - half
1906        };
1907        Some(r / drop)
1908    }
1909}
1910
1911const fn pow10_i128(p: u8) -> i128 {
1912    let mut acc: i128 = 1;
1913    let mut i = 0;
1914    while i < p {
1915        acc *= 10;
1916        i += 1;
1917    }
1918    acc
1919}
1920
1921const fn cmp_to_bool(op: BinOp, ord: core::cmp::Ordering) -> bool {
1922    use core::cmp::Ordering::{Equal, Greater, Less};
1923    match op {
1924        BinOp::Eq => matches!(ord, Equal),
1925        BinOp::NotEq => !matches!(ord, Equal),
1926        BinOp::Lt => matches!(ord, Less),
1927        BinOp::LtEq => matches!(ord, Less | Equal),
1928        BinOp::Gt => matches!(ord, Greater),
1929        BinOp::GtEq => matches!(ord, Greater | Equal),
1930        _ => false,
1931    }
1932}
1933
1934/// SQL `||` string concatenation. Operands are coerced to text via the same
1935/// rule as `::text` cast. NULL propagates (handled above; this function only
1936/// runs with non-NULL operands).
1937fn text_concat(l: &Value, r: &Value) -> Value {
1938    let a = value_to_text(l);
1939    let b = value_to_text(r);
1940    Value::Text(a + &b)
1941}
1942
1943/// pgvector inner-product `<#>`. Returns the *negative* dot product so
1944/// smaller still means more similar — same convention as pgvector.
1945fn inner_product(l: Value, r: Value) -> Result<Value, EvalError> {
1946    let (a, b) = unwrap_vec_pair(l, r, "<#>")?;
1947    let mut dot: f64 = 0.0;
1948    for (x, y) in a.iter().zip(b.iter()) {
1949        dot += f64::from(*x) * f64::from(*y);
1950    }
1951    Ok(Value::Float(-dot))
1952}
1953
1954/// pgvector cosine distance `<=>` — `1 - (a·b) / (‖a‖ ‖b‖)`. A zero-norm
1955/// operand produces NaN (matches pgvector).
1956fn cosine_distance(l: Value, r: Value) -> Result<Value, EvalError> {
1957    let (a, b) = unwrap_vec_pair(l, r, "<=>")?;
1958    let mut dot: f64 = 0.0;
1959    let mut na: f64 = 0.0;
1960    let mut nb: f64 = 0.0;
1961    for (x, y) in a.iter().zip(b.iter()) {
1962        let xf = f64::from(*x);
1963        let yf = f64::from(*y);
1964        dot += xf * yf;
1965        na += xf * xf;
1966        nb += yf * yf;
1967    }
1968    let denom = sqrt_newton(na) * sqrt_newton(nb);
1969    if denom == 0.0 {
1970        return Ok(Value::Float(f64::NAN));
1971    }
1972    Ok(Value::Float(1.0 - dot / denom))
1973}
1974
1975fn unwrap_vec_pair(l: Value, r: Value, op: &str) -> Result<(Vec<f32>, Vec<f32>), EvalError> {
1976    // v6.0.1: SQ8 cells coming through the SQL evaluator are
1977    // dequantised to f32 here so the existing scalar distance
1978    // arithmetic stays intact. HNSW kNN search continues to use
1979    // the asymmetric ADC variant inside `cell_to_query_metric_
1980    // distance` — this path only runs when a vector expression
1981    // lands in the evaluator (full-scan ORDER BY, SELECT
1982    // projection of `v <-> $1`, etc.).
1983    let to_f32 = |v: Value| -> Option<Vec<f32>> {
1984        match v {
1985            Value::Vector(a) => Some(a),
1986            Value::Sq8Vector(q) => Some(spg_storage::quantize::dequantize(&q)),
1987            // v6.0.3: bit-exact dequant for halfvec cells.
1988            Value::HalfVector(h) => Some(h.to_f32_vec()),
1989            _ => None,
1990        }
1991    };
1992    let l_ty = l.data_type();
1993    let r_ty = r.data_type();
1994    match (to_f32(l), to_f32(r)) {
1995        (Some(a), Some(b)) => {
1996            if a.len() != b.len() {
1997                return Err(EvalError::TypeMismatch {
1998                    detail: format!("vector dim mismatch in {op}: {} vs {}", a.len(), b.len()),
1999                });
2000            }
2001            Ok((a, b))
2002        }
2003        _ => Err(EvalError::TypeMismatch {
2004            detail: format!("{op} requires two vectors, got {l_ty:?} and {r_ty:?}"),
2005        }),
2006    }
2007}
2008
2009/// Numeric arithmetic with widening.
2010/// - both `Int` → `Int` (with overflow check)
2011/// - `Int` op `BigInt` (either side) → `BigInt`
2012/// - any `Float` involved → `Float`
2013fn arith(
2014    l: Value,
2015    r: Value,
2016    int_op: impl Fn(i64, i64) -> Option<i64>,
2017    float_op: impl Fn(f64, f64) -> f64,
2018    op_name: &str,
2019) -> Result<Value, EvalError> {
2020    // Widen SmallInt to Int up front so the rest of the arithmetic
2021    // table only deals with Int / BigInt / Float pairs.
2022    let widen = |v: Value| -> Value {
2023        match v {
2024            Value::SmallInt(n) => Value::Int(i32::from(n)),
2025            other => other,
2026        }
2027    };
2028    let l = widen(l);
2029    let r = widen(r);
2030    match (l, r) {
2031        (Value::Int(a), Value::Int(b)) => {
2032            let result = int_op(i64::from(a), i64::from(b)).ok_or(EvalError::TypeMismatch {
2033                detail: format!("integer overflow on {op_name}"),
2034            })?;
2035            if let Ok(small) = i32::try_from(result) {
2036                Ok(Value::Int(small))
2037            } else {
2038                Ok(Value::BigInt(result))
2039            }
2040        }
2041        (Value::Int(a), Value::BigInt(b)) | (Value::BigInt(b), Value::Int(a)) => {
2042            let result = int_op(i64::from(a), b).ok_or(EvalError::TypeMismatch {
2043                detail: format!("bigint overflow on {op_name}"),
2044            })?;
2045            Ok(Value::BigInt(result))
2046        }
2047        (Value::BigInt(a), Value::BigInt(b)) => {
2048            let result = int_op(a, b).ok_or(EvalError::TypeMismatch {
2049                detail: format!("bigint overflow on {op_name}"),
2050            })?;
2051            Ok(Value::BigInt(result))
2052        }
2053        (a, b)
2054            if a.data_type() == Some(DataType::Float) || b.data_type() == Some(DataType::Float) =>
2055        {
2056            let af = as_f64(&a)?;
2057            let bf = as_f64(&b)?;
2058            Ok(Value::Float(float_op(af, bf)))
2059        }
2060        (a, b) => Err(EvalError::TypeMismatch {
2061            detail: format!(
2062                "{op_name} applied to non-numeric: {:?} vs {:?}",
2063                a.data_type(),
2064                b.data_type()
2065            ),
2066        }),
2067    }
2068}
2069
2070/// L2 (Euclidean) distance between two vectors of equal dimension.
2071/// Returned as `Value::Float(d)` so it composes with the existing
2072/// comparison / sort plumbing. Mismatched dims or non-vector operands
2073/// raise `TypeMismatch`.
2074#[allow(clippy::many_single_char_names)] // l, r, a, b, d are the natural names
2075fn l2_distance(l: Value, r: Value) -> Result<Value, EvalError> {
2076    // v6.0.1: route both operands through `unwrap_vec_pair` so SQ8
2077    // cells dequantise on the way in. Sub-f64 precision loss is
2078    // negligible vs the dequantisation noise the SQ8 path already
2079    // ships with.
2080    let (a, b) = unwrap_vec_pair(l, r, "<->")?;
2081    let mut sum: f64 = 0.0;
2082    for (x, y) in a.iter().zip(b.iter()) {
2083        let d = f64::from(*x) - f64::from(*y);
2084        sum += d * d;
2085    }
2086    Ok(Value::Float(sqrt_newton(sum)))
2087}
2088
2089/// Self-built `sqrt` for `f64` — `std::f64::sqrt` lives in `std`, which the
2090/// engine's `no_std` constraint disallows. Newton-Raphson with a few rounds
2091/// reaches IEEE-754 precision for the inputs we'll see (sum of squares of
2092/// f32-derived distances, always non-negative, never NaN).
2093fn sqrt_newton(x: f64) -> f64 {
2094    if x <= 0.0 {
2095        return 0.0;
2096    }
2097    let mut g = x;
2098    // 10 iterations is conservative; 6 already converges to ulp for typical
2099    // distances.
2100    for _ in 0..10 {
2101        g = 0.5 * (g + x / g);
2102    }
2103    g
2104}
2105
2106fn div_op(l: Value, r: Value) -> Result<Value, EvalError> {
2107    let any_float = matches!(l.data_type(), Some(DataType::Float))
2108        || matches!(r.data_type(), Some(DataType::Float));
2109    if any_float {
2110        let a = as_f64(&l)?;
2111        let b = as_f64(&r)?;
2112        if b == 0.0 {
2113            return Err(EvalError::DivisionByZero);
2114        }
2115        return Ok(Value::Float(a / b));
2116    }
2117    arith(
2118        l,
2119        r,
2120        |a, b| {
2121            if b == 0 { None } else { Some(a / b) }
2122        },
2123        |a, b| a / b,
2124        "/",
2125    )
2126    .map_err(|e| match e {
2127        // The closure returns None on b == 0; translate that into the dedicated
2128        // DivisionByZero variant instead of "integer overflow on /".
2129        EvalError::TypeMismatch { detail } if detail.contains('/') => EvalError::DivisionByZero,
2130        other => other,
2131    })
2132}
2133
2134fn as_f64(v: &Value) -> Result<f64, EvalError> {
2135    match v {
2136        Value::SmallInt(n) => Ok(f64::from(*n)),
2137        Value::Int(n) => Ok(f64::from(*n)),
2138        #[allow(clippy::cast_precision_loss)]
2139        Value::BigInt(n) => Ok(*n as f64),
2140        Value::Float(x) => Ok(*x),
2141        #[allow(clippy::cast_precision_loss)]
2142        Value::Numeric { scaled, scale } => {
2143            let mut div = 1.0_f64;
2144            for _ in 0..*scale {
2145                div *= 10.0;
2146            }
2147            Ok((*scaled as f64) / div)
2148        }
2149        other => Err(EvalError::TypeMismatch {
2150            detail: format!("cannot convert {:?} to FLOAT", other.data_type()),
2151        }),
2152    }
2153}
2154
2155fn compare(op: BinOp, l: &Value, r: &Value) -> Result<Value, EvalError> {
2156    let ord = match (l, r) {
2157        (Value::Int(a), Value::Int(b)) => i64::from(*a).cmp(&i64::from(*b)),
2158        (Value::Int(a), Value::BigInt(b)) => i64::from(*a).cmp(b),
2159        (Value::BigInt(a), Value::Int(b)) => a.cmp(&i64::from(*b)),
2160        (Value::BigInt(a), Value::BigInt(b)) => a.cmp(b),
2161        (a, b)
2162            if matches!(a.data_type(), Some(DataType::Float))
2163                || matches!(b.data_type(), Some(DataType::Float)) =>
2164        {
2165            let af = as_f64(a)?;
2166            let bf = as_f64(b)?;
2167            af.partial_cmp(&bf).ok_or(EvalError::TypeMismatch {
2168                detail: "NaN in comparison".into(),
2169            })?
2170        }
2171        (Value::Text(a), Value::Text(b)) => a.cmp(b),
2172        (Value::Bool(a), Value::Bool(b)) => a.cmp(b),
2173        // Date / Timestamp compare on their integer storage repr.
2174        // Cross-domain (Date vs Timestamp) lifts the Date to the
2175        // matching midnight TIMESTAMP first.
2176        (Value::Date(a), Value::Date(b)) => a.cmp(b),
2177        (Value::Timestamp(a), Value::Timestamp(b)) => a.cmp(b),
2178        (Value::Date(a), Value::Timestamp(b)) => (i64::from(*a) * 86_400_000_000).cmp(b),
2179        (Value::Timestamp(a), Value::Date(b)) => a.cmp(&(i64::from(*b) * 86_400_000_000)),
2180        // PG-style implicit coercion: comparing a DATE / TIMESTAMP
2181        // column against a text literal lifts the literal into the
2182        // matching domain (e.g. `day >= '2024-01-01'`).
2183        (Value::Date(a), Value::Text(b)) => {
2184            let bd = parse_date_literal(b).ok_or_else(|| EvalError::TypeMismatch {
2185                detail: format!("cannot parse {b:?} as DATE for comparison"),
2186            })?;
2187            a.cmp(&bd)
2188        }
2189        (Value::Text(a), Value::Date(b)) => {
2190            let ad = parse_date_literal(a).ok_or_else(|| EvalError::TypeMismatch {
2191                detail: format!("cannot parse {a:?} as DATE for comparison"),
2192            })?;
2193            ad.cmp(b)
2194        }
2195        (Value::Timestamp(a), Value::Text(b)) => {
2196            let bt = parse_timestamp_literal(b).ok_or_else(|| EvalError::TypeMismatch {
2197                detail: format!("cannot parse {b:?} as TIMESTAMP for comparison"),
2198            })?;
2199            a.cmp(&bt)
2200        }
2201        (Value::Text(a), Value::Timestamp(b)) => {
2202            let at = parse_timestamp_literal(a).ok_or_else(|| EvalError::TypeMismatch {
2203                detail: format!("cannot parse {a:?} as TIMESTAMP for comparison"),
2204            })?;
2205            at.cmp(b)
2206        }
2207        (a, b) => {
2208            return Err(EvalError::TypeMismatch {
2209                detail: format!(
2210                    "comparison between {:?} and {:?}",
2211                    a.data_type(),
2212                    b.data_type()
2213                ),
2214            });
2215        }
2216    };
2217    let result = match op {
2218        BinOp::Eq => ord.is_eq(),
2219        BinOp::NotEq => !ord.is_eq(),
2220        BinOp::Lt => ord.is_lt(),
2221        BinOp::LtEq => ord.is_le(),
2222        BinOp::Gt => ord.is_gt(),
2223        BinOp::GtEq => ord.is_ge(),
2224        BinOp::And
2225        | BinOp::Or
2226        | BinOp::Add
2227        | BinOp::Sub
2228        | BinOp::Mul
2229        | BinOp::Div
2230        | BinOp::L2Distance
2231        | BinOp::InnerProduct
2232        | BinOp::CosineDistance
2233        | BinOp::Concat
2234        | BinOp::JsonGet
2235        | BinOp::JsonGetText
2236        | BinOp::JsonGetPath
2237        | BinOp::JsonGetPathText
2238        | BinOp::JsonContains => {
2239            unreachable!("compare() only called with comparison ops")
2240        }
2241    };
2242    Ok(Value::Bool(result))
2243}
2244
2245// SQL three-valued AND / OR.
2246fn and_3vl(l: Value, r: Value) -> Result<Value, EvalError> {
2247    match (l, r) {
2248        (Value::Bool(false), _) | (_, Value::Bool(false)) => Ok(Value::Bool(false)),
2249        (Value::Bool(true), Value::Bool(true)) => Ok(Value::Bool(true)),
2250        (Value::Null, _) | (_, Value::Null) => Ok(Value::Null),
2251        (a, b) => Err(EvalError::TypeMismatch {
2252            detail: format!(
2253                "AND on non-boolean: {:?} and {:?}",
2254                a.data_type(),
2255                b.data_type()
2256            ),
2257        }),
2258    }
2259}
2260
2261fn or_3vl(l: Value, r: Value) -> Result<Value, EvalError> {
2262    match (l, r) {
2263        (Value::Bool(true), _) | (_, Value::Bool(true)) => Ok(Value::Bool(true)),
2264        (Value::Bool(false), Value::Bool(false)) => Ok(Value::Bool(false)),
2265        (Value::Null, _) | (_, Value::Null) => Ok(Value::Null),
2266        (a, b) => Err(EvalError::TypeMismatch {
2267            detail: format!(
2268                "OR on non-boolean: {:?} and {:?}",
2269                a.data_type(),
2270                b.data_type()
2271            ),
2272        }),
2273    }
2274}
2275
2276#[cfg(test)]
2277mod tests {
2278    use super::*;
2279    use alloc::vec;
2280    use spg_storage::{ColumnSchema, Row};
2281
2282    fn col(name: &str, ty: DataType) -> ColumnSchema {
2283        ColumnSchema::new(name, ty, true)
2284    }
2285
2286    fn ctx<'a>(cols: &'a [ColumnSchema], alias: Option<&'a str>) -> EvalContext<'a> {
2287        EvalContext::new(cols, alias)
2288    }
2289
2290    fn lit(n: i64) -> Expr {
2291        Expr::Literal(Literal::Integer(n))
2292    }
2293
2294    fn null() -> Expr {
2295        Expr::Literal(Literal::Null)
2296    }
2297
2298    fn col_ref(name: &str) -> Expr {
2299        Expr::Column(ColumnName {
2300            qualifier: None,
2301            name: name.into(),
2302        })
2303    }
2304
2305    #[test]
2306    fn literal_evaluates_to_value() {
2307        let r = Row::new(vec![]);
2308        let cs: [ColumnSchema; 0] = [];
2309        let c = ctx(&cs, None);
2310        assert_eq!(eval_expr(&lit(42), &r, &c).unwrap(), Value::Int(42));
2311        assert_eq!(
2312            eval_expr(&Expr::Literal(Literal::Float(1.5)), &r, &c).unwrap(),
2313            Value::Float(1.5)
2314        );
2315        assert_eq!(eval_expr(&null(), &r, &c).unwrap(), Value::Null);
2316    }
2317
2318    #[test]
2319    fn column_lookup_unqualified() {
2320        let cs = vec![col("a", DataType::Int), col("b", DataType::Text)];
2321        let r = Row::new(vec![Value::Int(7), Value::Text("hi".into())]);
2322        let c = ctx(&cs, None);
2323        assert_eq!(eval_expr(&col_ref("a"), &r, &c).unwrap(), Value::Int(7));
2324        assert_eq!(
2325            eval_expr(&col_ref("b"), &r, &c).unwrap(),
2326            Value::Text("hi".into())
2327        );
2328    }
2329
2330    #[test]
2331    fn column_not_found_errors() {
2332        let cs = vec![col("a", DataType::Int)];
2333        let r = Row::new(vec![Value::Int(0)]);
2334        let c = ctx(&cs, None);
2335        let err = eval_expr(&col_ref("ghost"), &r, &c).unwrap_err();
2336        assert!(matches!(err, EvalError::ColumnNotFound { ref name } if name == "ghost"));
2337    }
2338
2339    #[test]
2340    fn qualified_column_matches_alias() {
2341        let cs = vec![col("a", DataType::Int)];
2342        let r = Row::new(vec![Value::Int(5)]);
2343        let c = ctx(&cs, Some("u"));
2344        let qualified = Expr::Column(ColumnName {
2345            qualifier: Some("u".into()),
2346            name: "a".into(),
2347        });
2348        assert_eq!(eval_expr(&qualified, &r, &c).unwrap(), Value::Int(5));
2349    }
2350
2351    #[test]
2352    fn qualified_column_unknown_alias_errors() {
2353        let cs = vec![col("a", DataType::Int)];
2354        let r = Row::new(vec![Value::Int(5)]);
2355        let c = ctx(&cs, Some("u"));
2356        let wrong = Expr::Column(ColumnName {
2357            qualifier: Some("x".into()),
2358            name: "a".into(),
2359        });
2360        assert!(matches!(
2361            eval_expr(&wrong, &r, &c).unwrap_err(),
2362            EvalError::UnknownQualifier { .. }
2363        ));
2364    }
2365
2366    #[test]
2367    fn arithmetic_with_widening() {
2368        let r = Row::new(vec![]);
2369        let cs: [ColumnSchema; 0] = [];
2370        let c = ctx(&cs, None);
2371        let e = Expr::Binary {
2372            lhs: alloc::boxed::Box::new(lit(2)),
2373            op: BinOp::Add,
2374            rhs: alloc::boxed::Box::new(Expr::Literal(Literal::Float(0.5))),
2375        };
2376        assert_eq!(eval_expr(&e, &r, &c).unwrap(), Value::Float(2.5));
2377    }
2378
2379    #[test]
2380    fn division_by_zero_errors() {
2381        let r = Row::new(vec![]);
2382        let cs: [ColumnSchema; 0] = [];
2383        let c = ctx(&cs, None);
2384        let e = Expr::Binary {
2385            lhs: alloc::boxed::Box::new(lit(1)),
2386            op: BinOp::Div,
2387            rhs: alloc::boxed::Box::new(lit(0)),
2388        };
2389        assert_eq!(
2390            eval_expr(&e, &r, &c).unwrap_err(),
2391            EvalError::DivisionByZero
2392        );
2393    }
2394
2395    #[test]
2396    fn comparison_returns_bool() {
2397        let r = Row::new(vec![]);
2398        let cs: [ColumnSchema; 0] = [];
2399        let c = ctx(&cs, None);
2400        let e = Expr::Binary {
2401            lhs: alloc::boxed::Box::new(lit(1)),
2402            op: BinOp::Lt,
2403            rhs: alloc::boxed::Box::new(lit(2)),
2404        };
2405        assert_eq!(eval_expr(&e, &r, &c).unwrap(), Value::Bool(true));
2406    }
2407
2408    #[test]
2409    fn null_propagates_through_arithmetic() {
2410        let r = Row::new(vec![]);
2411        let cs: [ColumnSchema; 0] = [];
2412        let c = ctx(&cs, None);
2413        let e = Expr::Binary {
2414            lhs: alloc::boxed::Box::new(lit(1)),
2415            op: BinOp::Add,
2416            rhs: alloc::boxed::Box::new(null()),
2417        };
2418        assert_eq!(eval_expr(&e, &r, &c).unwrap(), Value::Null);
2419    }
2420
2421    #[test]
2422    fn and_three_valued_logic() {
2423        let r = Row::new(vec![]);
2424        let cs: [ColumnSchema; 0] = [];
2425        let c = ctx(&cs, None);
2426        let tt = |a: bool, b_null: bool| Expr::Binary {
2427            lhs: alloc::boxed::Box::new(Expr::Literal(Literal::Bool(a))),
2428            op: BinOp::And,
2429            rhs: alloc::boxed::Box::new(if b_null {
2430                null()
2431            } else {
2432                Expr::Literal(Literal::Bool(true))
2433            }),
2434        };
2435        // FALSE AND NULL → FALSE
2436        assert_eq!(
2437            eval_expr(&tt(false, true), &r, &c).unwrap(),
2438            Value::Bool(false)
2439        );
2440        // TRUE AND NULL → NULL
2441        assert_eq!(eval_expr(&tt(true, true), &r, &c).unwrap(), Value::Null);
2442        // TRUE AND TRUE → TRUE
2443        assert_eq!(
2444            eval_expr(&tt(true, false), &r, &c).unwrap(),
2445            Value::Bool(true)
2446        );
2447    }
2448
2449    #[test]
2450    fn or_three_valued_logic() {
2451        let r = Row::new(vec![]);
2452        let cs: [ColumnSchema; 0] = [];
2453        let c = ctx(&cs, None);
2454        let or_with_null = |a: bool| Expr::Binary {
2455            lhs: alloc::boxed::Box::new(Expr::Literal(Literal::Bool(a))),
2456            op: BinOp::Or,
2457            rhs: alloc::boxed::Box::new(null()),
2458        };
2459        // TRUE OR NULL → TRUE
2460        assert_eq!(
2461            eval_expr(&or_with_null(true), &r, &c).unwrap(),
2462            Value::Bool(true)
2463        );
2464        // FALSE OR NULL → NULL
2465        assert_eq!(
2466            eval_expr(&or_with_null(false), &r, &c).unwrap(),
2467            Value::Null
2468        );
2469    }
2470
2471    #[test]
2472    fn not_on_null_is_null() {
2473        let r = Row::new(vec![]);
2474        let cs: [ColumnSchema; 0] = [];
2475        let c = ctx(&cs, None);
2476        let e = Expr::Unary {
2477            op: UnOp::Not,
2478            expr: alloc::boxed::Box::new(null()),
2479        };
2480        assert_eq!(eval_expr(&e, &r, &c).unwrap(), Value::Null);
2481    }
2482
2483    #[test]
2484    fn text_comparison_lexicographic() {
2485        let r = Row::new(vec![]);
2486        let cs: [ColumnSchema; 0] = [];
2487        let c = ctx(&cs, None);
2488        let e = Expr::Binary {
2489            lhs: alloc::boxed::Box::new(Expr::Literal(Literal::String("apple".into()))),
2490            op: BinOp::Lt,
2491            rhs: alloc::boxed::Box::new(Expr::Literal(Literal::String("banana".into()))),
2492        };
2493        assert_eq!(eval_expr(&e, &r, &c).unwrap(), Value::Bool(true));
2494    }
2495
2496    #[test]
2497    fn interval_format_basics() {
2498        assert_eq!(format_interval(0, 0), "0");
2499        assert_eq!(format_interval(0, 86_400_000_000), "1 day");
2500        assert_eq!(format_interval(0, -86_400_000_000), "-1 days");
2501        assert_eq!(format_interval(0, 3_600_000_000), "01:00:00");
2502        assert_eq!(
2503            format_interval(0, 86_400_000_000 + 9_000_000),
2504            "1 day 00:00:09"
2505        );
2506        assert_eq!(format_interval(14, 0), "1 year 2 mons");
2507        assert_eq!(format_interval(-1, 0), "-1 mons");
2508    }
2509
2510    #[test]
2511    fn interval_add_to_timestamp_micros_part() {
2512        // 2024-01-01 00:00:00 + INTERVAL '1 hour' = 2024-01-01 01:00:00
2513        let ts = i64::from(days_from_civil(2024, 1, 1)) * 86_400_000_000;
2514        let r = add_interval_to_micros(ts, 0, 3_600_000_000).unwrap();
2515        let expected = ts + 3_600_000_000;
2516        assert_eq!(r, expected);
2517    }
2518
2519    #[test]
2520    fn interval_clamp_month_end() {
2521        // 2024-01-31 + 1 month = 2024-02-29 (leap year).
2522        let d = days_from_civil(2024, 1, 31);
2523        let shifted = shift_date_by_months(d, 1).unwrap();
2524        let (y, m, day) = civil_from_days(shifted);
2525        assert_eq!((y, m, day), (2024, 2, 29));
2526        // 2023-01-31 + 1 month = 2023-02-28 (non-leap).
2527        let d = days_from_civil(2023, 1, 31);
2528        let shifted = shift_date_by_months(d, 1).unwrap();
2529        let (y, m, day) = civil_from_days(shifted);
2530        assert_eq!((y, m, day), (2023, 2, 28));
2531        // 2024-03-31 - 1 month = 2024-02-29.
2532        let d = days_from_civil(2024, 3, 31);
2533        let shifted = shift_date_by_months(d, -1).unwrap();
2534        let (y, m, day) = civil_from_days(shifted);
2535        assert_eq!((y, m, day), (2024, 2, 29));
2536    }
2537
2538    #[test]
2539    fn interval_date_plus_pure_days_stays_date() {
2540        // DATE + INTERVAL '7 days' must stay DATE.
2541        let d = days_from_civil(2024, 6, 1);
2542        let lhs = Value::Date(d);
2543        let rhs = Value::Interval {
2544            months: 0,
2545            micros: 7 * 86_400_000_000,
2546        };
2547        let v = apply_binary_interval(BinOp::Add, &lhs, &rhs)
2548            .unwrap()
2549            .unwrap();
2550        let expected = days_from_civil(2024, 6, 8);
2551        assert_eq!(v, Value::Date(expected));
2552    }
2553
2554    #[test]
2555    fn interval_date_plus_sub_day_lifts_to_timestamp() {
2556        // DATE + INTERVAL '1 hour' must lift to TIMESTAMP.
2557        let d = days_from_civil(2024, 6, 1);
2558        let lhs = Value::Date(d);
2559        let rhs = Value::Interval {
2560            months: 0,
2561            micros: 3_600_000_000,
2562        };
2563        let v = apply_binary_interval(BinOp::Add, &lhs, &rhs)
2564            .unwrap()
2565            .unwrap();
2566        let expected = i64::from(d) * 86_400_000_000 + 3_600_000_000;
2567        assert_eq!(v, Value::Timestamp(expected));
2568    }
2569}