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::boxed::Box;
19use alloc::format;
20use alloc::string::{String, ToString};
21use alloc::vec::Vec;
22
23use spg_sql::ast::{BinOp, CastTarget, ColumnName, Expr, Literal, UnOp};
24use spg_storage::{ColumnSchema, DataType, Row, TsLexeme, TsQueryAst, Value};
25
26/// Resolution context for evaluating a single row. `table_alias` is the alias
27/// (or table name) callers should accept as the qualifier on a column ref —
28/// e.g. `FROM users AS u` makes `u.name` valid and rejects `other.name`.
29#[derive(Debug, Clone)]
30pub struct EvalContext<'a> {
31    pub columns: &'a [ColumnSchema],
32    pub table_alias: Option<&'a str>,
33    /// v6.1.1 — bound parameters for `$N` placeholders inside the
34    /// expression tree. Empty for simple queries; populated by the
35    /// prepared-statement Execute path with Bind values converted
36    /// to `Value`. Index N (1-based per PG) hits `params[N-1]`.
37    pub params: &'a [Value],
38    /// v7.12.1 — session text-search config (from `SET
39    /// default_text_search_config = '<name>'`). Resolved when the
40    /// engine builds an `EvalContext` and consumed by the FTS
41    /// function dispatcher when `to_tsvector(text)` /
42    /// `plainto_tsquery(text)` etc are called without an explicit
43    /// config arg. `None` falls through to `simple`.
44    pub default_text_search_config: Option<&'a str>,
45}
46
47impl<'a> EvalContext<'a> {
48    pub const fn new(columns: &'a [ColumnSchema], table_alias: Option<&'a str>) -> Self {
49        Self {
50            columns,
51            table_alias,
52            params: &[],
53            default_text_search_config: None,
54        }
55    }
56
57    /// v6.1.1 — attach a parameter buffer for `$N` placeholder
58    /// resolution. The slice must outlive the context; callers
59    /// construct it from the prepared statement's Bind values.
60    #[must_use]
61    pub const fn with_params(mut self, params: &'a [Value]) -> Self {
62        self.params = params;
63        self
64    }
65
66    /// v7.12.1 — attach the session's
67    /// `default_text_search_config`. Used by the FTS function
68    /// dispatcher when no explicit config arg is given.
69    #[must_use]
70    pub const fn with_default_text_search_config(mut self, cfg: Option<&'a str>) -> Self {
71        self.default_text_search_config = cfg;
72        self
73    }
74}
75
76#[derive(Debug, Clone, PartialEq)]
77pub enum EvalError {
78    ColumnNotFound {
79        name: String,
80    },
81    UnknownQualifier {
82        qualifier: String,
83    },
84    DivisionByZero,
85    TypeMismatch {
86        detail: String,
87    },
88    /// v6.1.1 — `$N` reference past the number of bound parameters.
89    /// Either the client sent too few in Bind, or the SQL has a
90    /// placeholder the prepared statement didn't account for.
91    PlaceholderOutOfRange {
92        n: u16,
93        bound: u16,
94    },
95}
96
97impl core::fmt::Display for EvalError {
98    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
99        match self {
100            Self::ColumnNotFound { name } => write!(f, "column not found: {name}"),
101            Self::UnknownQualifier { qualifier } => {
102                write!(f, "unknown table qualifier: {qualifier}")
103            }
104            Self::DivisionByZero => f.write_str("division by zero"),
105            Self::TypeMismatch { detail } => write!(f, "type mismatch: {detail}"),
106            Self::PlaceholderOutOfRange { n, bound } => write!(
107                f,
108                "parameter ${n} referenced but only {bound} bound by client"
109            ),
110        }
111    }
112}
113
114pub fn eval_expr(expr: &Expr, row: &Row, ctx: &EvalContext<'_>) -> Result<Value, EvalError> {
115    match expr {
116        Expr::Literal(l) => Ok(literal_to_value(l)),
117        Expr::Column(c) => resolve_column(c, row, ctx),
118        Expr::Placeholder(n) => {
119            let idx = usize::from(*n).saturating_sub(1);
120            ctx.params
121                .get(idx)
122                .cloned()
123                .ok_or_else(|| EvalError::PlaceholderOutOfRange {
124                    n: *n,
125                    bound: u16::try_from(ctx.params.len()).unwrap_or(u16::MAX),
126                })
127        }
128        Expr::Unary { op, expr } => {
129            let v = eval_expr(expr, row, ctx)?;
130            apply_unary(*op, v)
131        }
132        Expr::Binary { lhs, op, rhs } => {
133            let l = eval_expr(lhs, row, ctx)?;
134            let r = eval_expr(rhs, row, ctx)?;
135            apply_binary(*op, l, r)
136        }
137        Expr::Cast { expr, target } => {
138            let v = eval_expr(expr, row, ctx)?;
139            cast_value(v, *target)
140        }
141        Expr::IsNull { expr, negated } => {
142            let v = eval_expr(expr, row, ctx)?;
143            let is_null = matches!(v, Value::Null);
144            Ok(Value::Bool(if *negated { !is_null } else { is_null }))
145        }
146        Expr::FunctionCall { name, args } => {
147            let evaluated: Result<Vec<Value>, _> =
148                args.iter().map(|a| eval_expr(a, row, ctx)).collect();
149            apply_function(name, &evaluated?, ctx)
150        }
151        Expr::Like {
152            expr,
153            pattern,
154            negated,
155        } => {
156            let v = eval_expr(expr, row, ctx)?;
157            let p = eval_expr(pattern, row, ctx)?;
158            // NULL on either side propagates to NULL — same as PG.
159            let (text, pat) = match (v, p) {
160                (Value::Null, _) | (_, Value::Null) => return Ok(Value::Null),
161                (Value::Text(a), Value::Text(b)) => (a, b),
162                (Value::Text(_), other) | (other, _) => {
163                    return Err(EvalError::TypeMismatch {
164                        detail: format!("LIKE requires text operands, got {:?}", other.data_type()),
165                    });
166                }
167            };
168            let m = like_match(&text, &pat);
169            Ok(Value::Bool(if *negated { !m } else { m }))
170        }
171        Expr::Extract { field, source } => {
172            let v = eval_expr(source, row, ctx)?;
173            extract_field(*field, &v)
174        }
175        // v4.10: subquery nodes should have been resolved into
176        // Literal / Binary-Eq-OR chains by Engine::resolve_select_subqueries
177        // before the row loop. Anything reaching here is a bug.
178        Expr::ScalarSubquery(_) | Expr::Exists { .. } | Expr::InSubquery { .. } => {
179            Err(EvalError::TypeMismatch {
180                detail: "subquery reached row eval — engine resolver bug".into(),
181            })
182        }
183        // v4.12: window functions should have been rewritten into
184        // synthetic __win_N column references by
185        // exec_select_with_window before row eval. Anything
186        // reaching here is similarly a bug.
187        Expr::WindowFunction { .. } => Err(EvalError::TypeMismatch {
188            detail: "window function reached row eval — engine rewrite bug".into(),
189        }),
190        // v7.10.10 — `ARRAY[expr, expr, …]` constructor.
191        // v7.11.13 — element-type detection: all integers →
192        // IntArray (or BigIntArray when widening), any Text →
193        // TextArray. Non-TEXT non-integer elements (Bool, Float)
194        // stringify into TextArray as the safe default.
195        Expr::Array(items) => {
196            let mut materialised: Vec<Value> = Vec::with_capacity(items.len());
197            for elem in items {
198                materialised.push(eval_expr(elem, row, ctx)?);
199            }
200            let mut has_text = false;
201            let mut has_bigint = false;
202            let mut has_int = false;
203            for v in &materialised {
204                match v {
205                    Value::Null => {}
206                    Value::Int(_) | Value::SmallInt(_) => has_int = true,
207                    Value::BigInt(_) => has_bigint = true,
208                    Value::Text(_) | Value::Json(_) => has_text = true,
209                    _ => has_text = true,
210                }
211            }
212            if has_text || (!has_int && !has_bigint) {
213                let out: Vec<Option<String>> = materialised
214                    .into_iter()
215                    .map(|v| match v {
216                        Value::Null => None,
217                        Value::Text(s) | Value::Json(s) => Some(s),
218                        other => Some(value_to_text_for_array(&other)),
219                    })
220                    .collect();
221                return Ok(Value::TextArray(out));
222            }
223            if has_bigint {
224                let out: Vec<Option<i64>> = materialised
225                    .into_iter()
226                    .map(|v| match v {
227                        Value::Null => None,
228                        Value::Int(n) => Some(i64::from(n)),
229                        Value::SmallInt(n) => Some(i64::from(n)),
230                        Value::BigInt(n) => Some(n),
231                        _ => unreachable!(),
232                    })
233                    .collect();
234                return Ok(Value::BigIntArray(out));
235            }
236            let out: Vec<Option<i32>> = materialised
237                .into_iter()
238                .map(|v| match v {
239                    Value::Null => None,
240                    Value::Int(n) => Some(n),
241                    Value::SmallInt(n) => Some(i32::from(n)),
242                    _ => unreachable!(),
243                })
244                .collect();
245            Ok(Value::IntArray(out))
246        }
247        // v7.10.12 — `arr[i]` PG-style 1-based indexing.
248        // Out-of-range indices (including i ≤ 0) return NULL.
249        Expr::ArraySubscript { target, index } => {
250            let target_v = eval_expr(target, row, ctx)?;
251            let idx_v = eval_expr(index, row, ctx)?;
252            if matches!(target_v, Value::Null) || matches!(idx_v, Value::Null) {
253                return Ok(Value::Null);
254            }
255            let i: i64 = match idx_v {
256                Value::Int(n) => i64::from(n),
257                Value::BigInt(n) => n,
258                Value::SmallInt(n) => i64::from(n),
259                other => {
260                    return Err(EvalError::TypeMismatch {
261                        detail: format!(
262                            "array subscript must be integer, got {:?}",
263                            other.data_type()
264                        ),
265                    });
266                }
267            };
268            if i < 1 {
269                return Ok(Value::Null);
270            }
271            let pos = (i - 1) as usize;
272            match target_v {
273                Value::TextArray(items) => match items.get(pos) {
274                    Some(Some(s)) => Ok(Value::Text(s.clone())),
275                    Some(None) | None => Ok(Value::Null),
276                },
277                Value::IntArray(items) => match items.get(pos) {
278                    Some(Some(n)) => Ok(Value::Int(*n)),
279                    Some(None) | None => Ok(Value::Null),
280                },
281                Value::BigIntArray(items) => match items.get(pos) {
282                    Some(Some(n)) => Ok(Value::BigInt(*n)),
283                    Some(None) | None => Ok(Value::Null),
284                },
285                other => Err(EvalError::TypeMismatch {
286                    detail: format!(
287                        "subscript target must be an array, got {:?}",
288                        other.data_type()
289                    ),
290                }),
291            }
292        }
293        // v7.10.12 — `x op ANY(arr)` / `x op ALL(arr)`. PG
294        // 3VL: ANY → true if any element compares-true; NULL if
295        // no true but some NULL; false otherwise. ALL: false if
296        // any compares-false; NULL if no false but some NULL;
297        // true otherwise.
298        Expr::AnyAll {
299            expr,
300            op,
301            array,
302            is_any,
303        } => {
304            let lhs = eval_expr(expr, row, ctx)?;
305            let arr = eval_expr(array, row, ctx)?;
306            if matches!(arr, Value::Null) {
307                return Ok(Value::Null);
308            }
309            let elems: Vec<Option<Value>> = match arr {
310                Value::TextArray(items) => items.into_iter().map(|o| o.map(Value::Text)).collect(),
311                Value::IntArray(items) => items.into_iter().map(|o| o.map(Value::Int)).collect(),
312                Value::BigIntArray(items) => {
313                    items.into_iter().map(|o| o.map(Value::BigInt)).collect()
314                }
315                other => {
316                    return Err(EvalError::TypeMismatch {
317                        detail: format!(
318                            "ANY/ALL right-hand side must be an array, got {:?}",
319                            other.data_type()
320                        ),
321                    });
322                }
323            };
324            let mut saw_null = matches!(lhs, Value::Null);
325            let mut saw_match = false;
326            let mut saw_mismatch = false;
327            for elem in elems {
328                let elem_v = match elem {
329                    Some(v) => v,
330                    None => {
331                        saw_null = true;
332                        continue;
333                    }
334                };
335                if matches!(lhs, Value::Null) {
336                    saw_null = true;
337                    continue;
338                }
339                match apply_binary(*op, lhs.clone(), elem_v) {
340                    Ok(Value::Bool(true)) => saw_match = true,
341                    Ok(Value::Bool(false)) => saw_mismatch = true,
342                    Ok(Value::Null) => saw_null = true,
343                    Ok(other) => {
344                        return Err(EvalError::TypeMismatch {
345                            detail: format!(
346                                "ANY/ALL comparison didn't return Bool: {:?}",
347                                other.data_type()
348                            ),
349                        });
350                    }
351                    Err(e) => return Err(e),
352                }
353            }
354            let result = if *is_any {
355                if saw_match {
356                    Value::Bool(true)
357                } else if saw_null {
358                    Value::Null
359                } else {
360                    Value::Bool(false)
361                }
362            } else if saw_mismatch {
363                Value::Bool(false)
364            } else if saw_null {
365                Value::Null
366            } else {
367                Value::Bool(true)
368            };
369            Ok(result)
370        }
371        // v7.13.0 — CASE WHEN … END (mailrs round-5 G9).
372        // Short-circuit on the first matching branch. Searched form
373        // (operand=None) treats each branch's WHEN as a Bool
374        // predicate. Simple form (operand=Some) compares with =.
375        // ELSE on no match; NULL if no ELSE.
376        Expr::Case {
377            operand,
378            branches,
379            else_branch,
380        } => {
381            let operand_value = match operand {
382                Some(o) => Some(eval_expr(o, row, ctx)?),
383                None => None,
384            };
385            for (when_expr, then_expr) in branches {
386                let when_value = eval_expr(when_expr, row, ctx)?;
387                let matched = match &operand_value {
388                    None => matches!(when_value, Value::Bool(true)),
389                    Some(op_v) => matches!(
390                        apply_binary(spg_sql::ast::BinOp::Eq, op_v.clone(), when_value)?,
391                        Value::Bool(true)
392                    ),
393                };
394                if matched {
395                    return eval_expr(then_expr, row, ctx);
396                }
397            }
398            match else_branch {
399                Some(e) => eval_expr(e, row, ctx),
400                None => Ok(Value::Null),
401            }
402        }
403    }
404}
405
406/// v7.10.10 — best-effort text rendering for non-TEXT array
407/// elements (numbers, bools, etc.). The PG rule is that
408/// `ARRAY[1, 2]` is `int[]`, but SPG's v7.10 only models TEXT[],
409/// so we widen by stringifying. NUMERIC formatting goes through
410/// the existing canonical helpers to stay consistent with
411/// `format_numeric` / `format_date` etc.
412fn value_to_text_for_array(v: &Value) -> String {
413    match v {
414        Value::Text(s) | Value::Json(s) => s.clone(),
415        Value::Int(n) => n.to_string(),
416        Value::BigInt(n) => n.to_string(),
417        Value::SmallInt(n) => n.to_string(),
418        Value::Bool(b) => {
419            if *b {
420                "true".into()
421            } else {
422                "false".into()
423            }
424        }
425        Value::Float(x) => format!("{x}"),
426        Value::Date(d) => format_date(*d),
427        Value::Timestamp(t) => format_timestamp(*t),
428        Value::Numeric { scaled, scale } => format_numeric(*scaled, *scale),
429        _ => format!("{v:?}"),
430    }
431}
432
433/// Pull an integer component (year / month / ... / microsecond) out
434/// of a `DATE` or `TIMESTAMP`. Returns NULL on a NULL source, errors
435/// when the source isn't a calendar type.
436fn extract_field(field: spg_sql::ast::ExtractField, v: &Value) -> Result<Value, EvalError> {
437    use spg_sql::ast::ExtractField as F;
438    if matches!(v, Value::Null) {
439        return Ok(Value::Null);
440    }
441    // INTERVAL has its own decomposition — `YEAR` / `MONTH` come from
442    // the months part, the rest from the microseconds part. PG matches
443    // this convention (months is normalised modulo 12 for MONTH).
444    if let Value::Interval { months, micros } = *v {
445        let years = months / 12;
446        let mons = months % 12;
447        let secs_total = micros / 1_000_000;
448        let frac = micros % 1_000_000;
449        let result = match field {
450            F::Year => i64::from(years),
451            F::Month => i64::from(mons),
452            F::Day => micros / 86_400_000_000,
453            F::Hour => (secs_total / 3600) % 24,
454            F::Minute => (secs_total / 60) % 60,
455            F::Second => secs_total % 60,
456            F::Microsecond => (secs_total % 60) * 1_000_000 + frac,
457        };
458        return Ok(Value::BigInt(result));
459    }
460    let (days, day_micros) = match *v {
461        Value::Date(d) => (d, 0_i64),
462        Value::Timestamp(t) => {
463            let days = t.div_euclid(86_400_000_000);
464            let day_micros = t.rem_euclid(86_400_000_000);
465            (i32::try_from(days).unwrap_or(i32::MAX), day_micros)
466        }
467        _ => {
468            return Err(EvalError::TypeMismatch {
469                detail: format!(
470                    "EXTRACT requires DATE / TIMESTAMP / INTERVAL, got {:?}",
471                    v.data_type()
472                ),
473            });
474        }
475    };
476    let (y, m, d) = civil_components(days);
477    let secs = day_micros / 1_000_000;
478    let hh = secs / 3600;
479    let mm = (secs / 60) % 60;
480    let ss = secs % 60;
481    let frac = day_micros % 1_000_000;
482    let result = match field {
483        F::Year => i64::from(y),
484        F::Month => i64::from(m),
485        F::Day => i64::from(d),
486        F::Hour => hh,
487        F::Minute => mm,
488        F::Second => ss,
489        F::Microsecond => ss * 1_000_000 + frac,
490    };
491    Ok(Value::BigInt(result))
492}
493
494/// Internal wrapper around the file-private `civil_from_days` so the
495/// public surface area doesn't change. Returns `(year, month, day)`.
496fn civil_components(days: i32) -> (i32, u32, u32) {
497    civil_from_days(days)
498}
499
500/// SQL `LIKE` matcher. Wildcards are `%` (any run, possibly empty) and `_`
501/// (exactly one char). `\` escapes the next pattern char so `\%` matches a
502/// literal `%`. Matches the whole input — no implicit anchoring needed
503/// since SQL `LIKE` is always full-string.
504fn like_match(text: &str, pattern: &str) -> bool {
505    let text: Vec<char> = text.chars().collect();
506    let pat: Vec<char> = pattern.chars().collect();
507    like_match_inner(&text, 0, &pat, 0)
508}
509
510fn like_match_inner(text: &[char], mut ti: usize, pat: &[char], mut pi: usize) -> bool {
511    while pi < pat.len() {
512        match pat[pi] {
513            '%' => {
514                // Collapse consecutive `%` and try every possible split.
515                while pi < pat.len() && pat[pi] == '%' {
516                    pi += 1;
517                }
518                if pi == pat.len() {
519                    return true;
520                }
521                for k in ti..=text.len() {
522                    if like_match_inner(text, k, pat, pi) {
523                        return true;
524                    }
525                }
526                return false;
527            }
528            '_' => {
529                if ti >= text.len() {
530                    return false;
531                }
532                ti += 1;
533                pi += 1;
534            }
535            '\\' if pi + 1 < pat.len() => {
536                let want = pat[pi + 1];
537                if ti >= text.len() || text[ti] != want {
538                    return false;
539                }
540                ti += 1;
541                pi += 2;
542            }
543            c => {
544                if ti >= text.len() || text[ti] != c {
545                    return false;
546                }
547                ti += 1;
548                pi += 1;
549            }
550        }
551    }
552    ti == text.len()
553}
554
555/// Dispatch on lowercased function name. v1.4 implements only a handful of
556/// scalar functions; aggregates land in v1.5 alongside GROUP BY.
557fn apply_function(name: &str, args: &[Value], ctx: &EvalContext<'_>) -> Result<Value, EvalError> {
558    match name.to_ascii_lowercase().as_str() {
559        "length" => {
560            if args.len() != 1 {
561                return Err(EvalError::TypeMismatch {
562                    detail: format!("length() takes 1 arg, got {}", args.len()),
563                });
564            }
565            match &args[0] {
566                Value::Null => Ok(Value::Null),
567                Value::Text(s) => {
568                    let n = i32::try_from(s.chars().count()).unwrap_or(i32::MAX);
569                    Ok(Value::Int(n))
570                }
571                // v7.10.4 — PG semantics: length(bytea) returns
572                // byte count (= octet_length). Without this branch
573                // mailrs's INSERT … SELECT length(body) … against a
574                // BYTEA column would type-mismatch.
575                Value::Bytes(b) => {
576                    let n = i32::try_from(b.len()).unwrap_or(i32::MAX);
577                    Ok(Value::Int(n))
578                }
579                other => Err(EvalError::TypeMismatch {
580                    detail: format!("length() needs text or bytea, got {:?}", other.data_type()),
581                }),
582            }
583        }
584        // v7.10.4 — `OCTET_LENGTH(x)` returns byte count for both
585        // TEXT (UTF-8 byte length) and BYTEA. PG-spec name; aliases
586        // to length() for bytea by design.
587        "octet_length" => {
588            if args.len() != 1 {
589                return Err(EvalError::TypeMismatch {
590                    detail: format!("octet_length() takes 1 arg, got {}", args.len()),
591                });
592            }
593            match &args[0] {
594                Value::Null => Ok(Value::Null),
595                Value::Text(s) => {
596                    let n = i32::try_from(s.len()).unwrap_or(i32::MAX);
597                    Ok(Value::Int(n))
598                }
599                Value::Bytes(b) => {
600                    let n = i32::try_from(b.len()).unwrap_or(i32::MAX);
601                    Ok(Value::Int(n))
602                }
603                other => Err(EvalError::TypeMismatch {
604                    detail: format!(
605                        "octet_length() needs text or bytea, got {:?}",
606                        other.data_type()
607                    ),
608                }),
609            }
610        }
611        // v7.11.6 — `array_length(arr, dim)` returns the element
612        // count of `arr` along dimension `dim`. v7.11 only models
613        // single-dimension arrays so dim must be 1 (otherwise NULL,
614        // matching PG semantics for unsupported dimensions). NULL
615        // array → NULL. v7.11 TEXT[] only; non-array operand is
616        // a type mismatch.
617        "array_length" => {
618            if args.len() != 2 {
619                return Err(EvalError::TypeMismatch {
620                    detail: format!("array_length() takes 2 args, got {}", args.len()),
621                });
622            }
623            if matches!(args[0], Value::Null) || matches!(args[1], Value::Null) {
624                return Ok(Value::Null);
625            }
626            let len = match &args[0] {
627                Value::TextArray(items) => items.len(),
628                Value::IntArray(items) => items.len(),
629                Value::BigIntArray(items) => items.len(),
630                _ => {
631                    return Err(EvalError::TypeMismatch {
632                        detail: format!(
633                            "array_length() first arg must be an array, got {:?}",
634                            args[0].data_type()
635                        ),
636                    });
637                }
638            };
639            let dim: i64 = match args[1] {
640                Value::Int(n) => i64::from(n),
641                Value::BigInt(n) => n,
642                Value::SmallInt(n) => i64::from(n),
643                _ => {
644                    return Err(EvalError::TypeMismatch {
645                        detail: format!(
646                            "array_length() second arg must be integer, got {:?}",
647                            args[1].data_type()
648                        ),
649                    });
650                }
651            };
652            if dim != 1 {
653                return Ok(Value::Null);
654            }
655            let n = i32::try_from(len).unwrap_or(i32::MAX);
656            Ok(Value::Int(n))
657        }
658        // v7.11.6 — `array_position(arr, val)` returns 1-based
659        // index of the first element of `arr` equal to `val`, or
660        // NULL if not found. PG NULL semantics: NULL array → NULL;
661        // NULL val never matches (returns NULL if absent).
662        "array_position" => {
663            if args.len() != 2 {
664                return Err(EvalError::TypeMismatch {
665                    detail: format!("array_position() takes 2 args, got {}", args.len()),
666                });
667            }
668            if matches!(args[0], Value::Null) {
669                return Ok(Value::Null);
670            }
671            if matches!(args[1], Value::Null) {
672                return Ok(Value::Null);
673            }
674            match (&args[0], &args[1]) {
675                (Value::TextArray(items), Value::Text(needle)) => {
676                    for (idx, item) in items.iter().enumerate() {
677                        if let Some(s) = item
678                            && s == needle
679                        {
680                            return Ok(Value::Int(i32::try_from(idx + 1).unwrap_or(i32::MAX)));
681                        }
682                    }
683                    Ok(Value::Null)
684                }
685                (Value::IntArray(items), needle_v)
686                    if matches!(
687                        needle_v,
688                        Value::Int(_) | Value::SmallInt(_) | Value::BigInt(_)
689                    ) =>
690                {
691                    let needle: i64 = match *needle_v {
692                        Value::Int(n) => i64::from(n),
693                        Value::SmallInt(n) => i64::from(n),
694                        Value::BigInt(n) => n,
695                        _ => unreachable!(),
696                    };
697                    for (idx, item) in items.iter().enumerate() {
698                        if let Some(n) = item
699                            && i64::from(*n) == needle
700                        {
701                            return Ok(Value::Int(i32::try_from(idx + 1).unwrap_or(i32::MAX)));
702                        }
703                    }
704                    Ok(Value::Null)
705                }
706                (Value::BigIntArray(items), needle_v)
707                    if matches!(
708                        needle_v,
709                        Value::Int(_) | Value::SmallInt(_) | Value::BigInt(_)
710                    ) =>
711                {
712                    let needle: i64 = match *needle_v {
713                        Value::Int(n) => i64::from(n),
714                        Value::SmallInt(n) => i64::from(n),
715                        Value::BigInt(n) => n,
716                        _ => unreachable!(),
717                    };
718                    for (idx, item) in items.iter().enumerate() {
719                        if let Some(n) = item
720                            && *n == needle
721                        {
722                            return Ok(Value::Int(i32::try_from(idx + 1).unwrap_or(i32::MAX)));
723                        }
724                    }
725                    Ok(Value::Null)
726                }
727                (
728                    arr @ (Value::TextArray(_) | Value::IntArray(_) | Value::BigIntArray(_)),
729                    other,
730                ) => Err(EvalError::TypeMismatch {
731                    detail: format!(
732                        "array_position() needle type {:?} doesn't match array {:?}",
733                        other.data_type(),
734                        arr.data_type()
735                    ),
736                }),
737                (other, _) => Err(EvalError::TypeMismatch {
738                    detail: format!(
739                        "array_position() first arg must be an array, got {:?}",
740                        other.data_type()
741                    ),
742                }),
743            }
744        }
745        // v7.11.15 — `substring(s, start)` / `substring(s, start, length)`
746        // for both TEXT and BYTEA. PG semantics: `start` is 1-based;
747        // values ≤ 0 clamp into the string (i.e. effective start is
748        // adjusted so the window still begins at index 1 — but
749        // `length` is reduced by the clipped prefix). A NULL arg
750        // makes the result NULL. Out-of-range windows return an
751        // empty value, not NULL.
752        "substring" => {
753            if !matches!(args.len(), 2 | 3) {
754                return Err(EvalError::TypeMismatch {
755                    detail: format!("substring() takes 2 or 3 args, got {}", args.len()),
756                });
757            }
758            if args.iter().any(|a| matches!(a, Value::Null)) {
759                return Ok(Value::Null);
760            }
761            let start: i64 = match args[1] {
762                Value::Int(n) => i64::from(n),
763                Value::BigInt(n) => n,
764                Value::SmallInt(n) => i64::from(n),
765                _ => {
766                    return Err(EvalError::TypeMismatch {
767                        detail: format!(
768                            "substring() start must be integer, got {:?}",
769                            args[1].data_type()
770                        ),
771                    });
772                }
773            };
774            let length: Option<i64> = if args.len() == 3 {
775                match args[2] {
776                    Value::Int(n) => Some(i64::from(n)),
777                    Value::BigInt(n) => Some(n),
778                    Value::SmallInt(n) => Some(i64::from(n)),
779                    _ => {
780                        return Err(EvalError::TypeMismatch {
781                            detail: format!(
782                                "substring() length must be integer, got {:?}",
783                                args[2].data_type()
784                            ),
785                        });
786                    }
787                }
788            } else {
789                None
790            };
791            // PG: when length is given, end = start + length; if
792            // end < start the result is empty. Clip start to 1.
793            let (effective_start, effective_length): (i64, Option<i64>) = match length {
794                Some(len) => {
795                    let end = start.saturating_add(len);
796                    if end <= 1 || len < 0 {
797                        return Ok(match &args[0] {
798                            Value::Text(_) => Value::Text(String::new()),
799                            Value::Bytes(_) => Value::Bytes(Vec::new()),
800                            other => {
801                                return Err(EvalError::TypeMismatch {
802                                    detail: format!(
803                                        "substring() needs text or bytea, got {:?}",
804                                        other.data_type()
805                                    ),
806                                });
807                            }
808                        });
809                    }
810                    let eff_start = start.max(1);
811                    let eff_len = end - eff_start;
812                    (eff_start, Some(eff_len.max(0)))
813                }
814                None => (start.max(1), None),
815            };
816            match &args[0] {
817                Value::Text(s) => {
818                    // PG counts in characters (codepoints) for TEXT.
819                    let chars: Vec<char> = s.chars().collect();
820                    let skip = (effective_start - 1) as usize;
821                    if skip >= chars.len() {
822                        return Ok(Value::Text(String::new()));
823                    }
824                    let take = match effective_length {
825                        Some(n) => (n as usize).min(chars.len() - skip),
826                        None => chars.len() - skip,
827                    };
828                    Ok(Value::Text(chars[skip..skip + take].iter().collect()))
829                }
830                Value::Bytes(b) => {
831                    let skip = (effective_start - 1) as usize;
832                    if skip >= b.len() {
833                        return Ok(Value::Bytes(Vec::new()));
834                    }
835                    let take = match effective_length {
836                        Some(n) => (n as usize).min(b.len() - skip),
837                        None => b.len() - skip,
838                    };
839                    Ok(Value::Bytes(b[skip..skip + take].to_vec()))
840                }
841                other => Err(EvalError::TypeMismatch {
842                    detail: format!(
843                        "substring() needs text or bytea, got {:?}",
844                        other.data_type()
845                    ),
846                }),
847            }
848        }
849        // v7.11.15 — `position(needle, haystack)`. PG semantics:
850        // 1-based byte/char index of first occurrence, or 0 if
851        // absent. NULL on either operand → NULL. Empty needle
852        // returns 1 (PG convention). Works on TEXT (char positions)
853        // and BYTEA (byte positions). (The PG-spec syntax `position(
854        // needle IN haystack)` is not parsed in v7.11; clients must
855        // call the function-call form.)
856        "position" => {
857            if args.len() != 2 {
858                return Err(EvalError::TypeMismatch {
859                    detail: format!("position() takes 2 args, got {}", args.len()),
860                });
861            }
862            if matches!(args[0], Value::Null) || matches!(args[1], Value::Null) {
863                return Ok(Value::Null);
864            }
865            match (&args[0], &args[1]) {
866                (Value::Text(needle), Value::Text(haystack)) => {
867                    if needle.is_empty() {
868                        return Ok(Value::Int(1));
869                    }
870                    // Char-based position (PG uses character count).
871                    let h_chars: Vec<char> = haystack.chars().collect();
872                    let n_chars: Vec<char> = needle.chars().collect();
873                    if n_chars.len() > h_chars.len() {
874                        return Ok(Value::Int(0));
875                    }
876                    for i in 0..=h_chars.len() - n_chars.len() {
877                        if h_chars[i..i + n_chars.len()] == n_chars[..] {
878                            return Ok(Value::Int(i32::try_from(i + 1).unwrap_or(i32::MAX)));
879                        }
880                    }
881                    Ok(Value::Int(0))
882                }
883                (Value::Bytes(needle), Value::Bytes(haystack)) => {
884                    if needle.is_empty() {
885                        return Ok(Value::Int(1));
886                    }
887                    if needle.len() > haystack.len() {
888                        return Ok(Value::Int(0));
889                    }
890                    for i in 0..=haystack.len() - needle.len() {
891                        if &haystack[i..i + needle.len()] == needle.as_slice() {
892                            return Ok(Value::Int(i32::try_from(i + 1).unwrap_or(i32::MAX)));
893                        }
894                    }
895                    Ok(Value::Int(0))
896                }
897                (a, b) => Err(EvalError::TypeMismatch {
898                    detail: format!(
899                        "position() operands must both be text or both bytea, got {:?} and {:?}",
900                        a.data_type(),
901                        b.data_type()
902                    ),
903                }),
904            }
905        }
906        "upper" => {
907            if args.len() != 1 {
908                return Err(EvalError::TypeMismatch {
909                    detail: format!("upper() takes 1 arg, got {}", args.len()),
910                });
911            }
912            match &args[0] {
913                Value::Null => Ok(Value::Null),
914                Value::Text(s) => Ok(Value::Text(s.to_uppercase())),
915                other => Err(EvalError::TypeMismatch {
916                    detail: format!("upper() needs text, got {:?}", other.data_type()),
917                }),
918            }
919        }
920        "lower" => {
921            if args.len() != 1 {
922                return Err(EvalError::TypeMismatch {
923                    detail: format!("lower() takes 1 arg, got {}", args.len()),
924                });
925            }
926            match &args[0] {
927                Value::Null => Ok(Value::Null),
928                Value::Text(s) => Ok(Value::Text(s.to_lowercase())),
929                other => Err(EvalError::TypeMismatch {
930                    detail: format!("lower() needs text, got {:?}", other.data_type()),
931                }),
932            }
933        }
934        "abs" => {
935            if args.len() != 1 {
936                return Err(EvalError::TypeMismatch {
937                    detail: format!("abs() takes 1 arg, got {}", args.len()),
938                });
939            }
940            match &args[0] {
941                Value::Null => Ok(Value::Null),
942                Value::Int(n) => Ok(Value::Int(n.wrapping_abs())),
943                Value::BigInt(n) => Ok(Value::BigInt(n.wrapping_abs())),
944                Value::Float(x) => Ok(Value::Float(x.abs())),
945                other => Err(EvalError::TypeMismatch {
946                    detail: format!("abs() needs numeric, got {:?}", other.data_type()),
947                }),
948            }
949        }
950        "coalesce" => {
951            for a in args {
952                if !matches!(a, Value::Null) {
953                    return Ok(a.clone());
954                }
955            }
956            Ok(Value::Null)
957        }
958        "date_trunc" => date_trunc(args),
959        "date_part" => date_part(args),
960        "age" => age(args),
961        "to_char" => to_char(args),
962        // v6.4.3 — encode/decode + error_on_null SQL function bundle.
963        "encode" => encode_text(args),
964        "decode" => decode_text(args),
965        "error_on_null" => error_on_null(args),
966        // v7.12.1 — PG full-text search lexer / tsquery builders.
967        // mailrs G-CRIT-3 acceptance path: `to_tsvector('english',
968        // … || ' ' || … || …)` runs end-to-end against a tsvector
969        // column with Porter stemming + standard english stopwords.
970        "to_tsvector" => fts_to_tsvector(args, ctx),
971        "plainto_tsquery" => fts_plainto_tsquery(args, ctx),
972        "phraseto_tsquery" => fts_phraseto_tsquery(args, ctx),
973        "websearch_to_tsquery" => fts_websearch_to_tsquery(args, ctx),
974        "to_tsquery" => fts_to_tsquery(args, ctx),
975        // v7.12.2 — ranking functions. mailrs's fallback search
976        // query ORDERs BY ts_rank(search_vector, q) DESC.
977        "ts_rank" => fts_ts_rank(args),
978        "ts_rank_cd" => fts_ts_rank_cd(args),
979        other => Err(EvalError::TypeMismatch {
980            detail: format!("unknown function `{other}`"),
981        }),
982    }
983}
984
985/// v7.12.2 — `ts_rank([weights,] vec, query [, norm])`. v7.12.2
986/// supports the canonical `(vec, query)` two-arg form mailrs uses;
987/// optional weight-array / normalisation arguments error with an
988/// "unsupported" message rather than silently changing semantics.
989fn fts_ts_rank(args: &[Value]) -> Result<Value, EvalError> {
990    let (vec, query) = parse_rank_args("ts_rank", args)?;
991    match (vec, query) {
992        (None, _) | (_, None) => Ok(Value::Null),
993        (Some(v), Some(q)) => Ok(Value::Float(f64::from(crate::fts::ts_rank(&v, &q)))),
994    }
995}
996
997fn fts_ts_rank_cd(args: &[Value]) -> Result<Value, EvalError> {
998    let (vec, query) = parse_rank_args("ts_rank_cd", args)?;
999    match (vec, query) {
1000        (None, _) | (_, None) => Ok(Value::Null),
1001        (Some(v), Some(q)) => Ok(Value::Float(f64::from(crate::fts::ts_rank_cd(&v, &q)))),
1002    }
1003}
1004
1005fn parse_rank_args(
1006    name: &str,
1007    args: &[Value],
1008) -> Result<
1009    (
1010        Option<Vec<spg_storage::TsLexeme>>,
1011        Option<spg_storage::TsQueryAst>,
1012    ),
1013    EvalError,
1014> {
1015    if args.len() != 2 {
1016        return Err(EvalError::TypeMismatch {
1017            detail: format!(
1018                "{name}() takes 2 args in v7.12.2 (weights array + normalisation flag are v7.12.x carve-out), got {}",
1019                args.len()
1020            ),
1021        });
1022    }
1023    let vec = match &args[0] {
1024        Value::Null => None,
1025        Value::TsVector(v) => Some(v.clone()),
1026        other => {
1027            return Err(EvalError::TypeMismatch {
1028                detail: format!(
1029                    "{name}() first arg must be tsvector, got {:?}",
1030                    other.data_type()
1031                ),
1032            });
1033        }
1034    };
1035    let query = match &args[1] {
1036        Value::Null => None,
1037        Value::TsQuery(q) => Some(q.clone()),
1038        other => {
1039            return Err(EvalError::TypeMismatch {
1040                detail: format!(
1041                    "{name}() second arg must be tsquery, got {:?}",
1042                    other.data_type()
1043                ),
1044            });
1045        }
1046    };
1047    Ok((vec, query))
1048}
1049
1050/// v7.12.2 — `tsvector @@ tsquery` match operator. Either
1051/// ordering accepted (PG semantics). NULL on either side → NULL.
1052/// Anything that isn't tsvector/tsquery on either side is a type
1053/// mismatch. Returns BOOL.
1054fn ts_match(l: Value, r: Value) -> Result<Value, EvalError> {
1055    let (vec, query) = match (l, r) {
1056        (Value::Null, _) | (_, Value::Null) => return Ok(Value::Null),
1057        (Value::TsVector(v), Value::TsQuery(q)) => (v, q),
1058        (Value::TsQuery(q), Value::TsVector(v)) => (v, q),
1059        (l, r) => {
1060            return Err(EvalError::TypeMismatch {
1061                detail: format!(
1062                    "@@ requires (tsvector, tsquery), got ({:?}, {:?})",
1063                    l.data_type(),
1064                    r.data_type()
1065                ),
1066            });
1067        }
1068    };
1069    Ok(Value::Bool(crate::fts::ts_query_matches(&vec, &query)))
1070}
1071
1072/// v7.12.1 — `to_tsvector([config,] text)`. With one arg the
1073/// session-resolved `default_text_search_config` is used (defaults
1074/// to `simple` when unset); with two args the first picks the
1075/// config. NULL text → NULL.
1076fn fts_to_tsvector(args: &[Value], ctx: &EvalContext<'_>) -> Result<Value, EvalError> {
1077    let (config, text) = parse_fts_args("to_tsvector", args, ctx)?;
1078    match text {
1079        None => Ok(Value::Null),
1080        Some(t) => Ok(Value::TsVector(crate::fts::to_tsvector(config, &t))),
1081    }
1082}
1083
1084fn fts_plainto_tsquery(args: &[Value], ctx: &EvalContext<'_>) -> Result<Value, EvalError> {
1085    let (config, text) = parse_fts_args("plainto_tsquery", args, ctx)?;
1086    match text {
1087        None => Ok(Value::Null),
1088        Some(t) => Ok(Value::TsQuery(crate::fts::plainto_tsquery(config, &t))),
1089    }
1090}
1091
1092fn fts_phraseto_tsquery(args: &[Value], ctx: &EvalContext<'_>) -> Result<Value, EvalError> {
1093    let (config, text) = parse_fts_args("phraseto_tsquery", args, ctx)?;
1094    match text {
1095        None => Ok(Value::Null),
1096        Some(t) => Ok(Value::TsQuery(crate::fts::phraseto_tsquery(config, &t))),
1097    }
1098}
1099
1100fn fts_websearch_to_tsquery(args: &[Value], ctx: &EvalContext<'_>) -> Result<Value, EvalError> {
1101    let (config, text) = parse_fts_args("websearch_to_tsquery", args, ctx)?;
1102    match text {
1103        None => Ok(Value::Null),
1104        Some(t) => Ok(Value::TsQuery(crate::fts::websearch_to_tsquery(config, &t))),
1105    }
1106}
1107
1108fn fts_to_tsquery(args: &[Value], ctx: &EvalContext<'_>) -> Result<Value, EvalError> {
1109    let (config, text) = parse_fts_args("to_tsquery", args, ctx)?;
1110    match text {
1111        None => Ok(Value::Null),
1112        Some(t) => Ok(Value::TsQuery(crate::fts::to_tsquery(config, &t)?)),
1113    }
1114}
1115
1116/// Parse the `(config, text)` / `(text)` argument pair shared by
1117/// all FTS builders. Returns the resolved config + the text
1118/// payload (None when text is NULL). The one-arg form pulls the
1119/// config from the session's `default_text_search_config`.
1120fn parse_fts_args(
1121    name: &str,
1122    args: &[Value],
1123    ctx: &EvalContext<'_>,
1124) -> Result<(crate::fts::TsConfig, Option<String>), EvalError> {
1125    let (config_arg, text_arg) = match args {
1126        [t] => (None, t),
1127        [c, t] => (Some(c), t),
1128        _ => {
1129            return Err(EvalError::TypeMismatch {
1130                detail: format!("{name}() takes 1 or 2 args, got {}", args.len()),
1131            });
1132        }
1133    };
1134    let config = match config_arg {
1135        None => match ctx.default_text_search_config {
1136            Some(name_str) => crate::fts::TsConfig::from_name(name_str).ok_or_else(|| {
1137                EvalError::TypeMismatch {
1138                    detail: format!(
1139                        "text search config not implemented: {name_str:?} (supported: simple, english)"
1140                    ),
1141                }
1142            })?,
1143            None => crate::fts::TsConfig::Simple,
1144        },
1145        Some(Value::Null) => return Ok((crate::fts::TsConfig::Simple, None)),
1146        Some(Value::Text(name_str)) => crate::fts::TsConfig::from_name(name_str).ok_or_else(|| {
1147            EvalError::TypeMismatch {
1148                detail: format!(
1149                    "text search config not implemented: {name_str:?} (supported: simple, english)"
1150                ),
1151            }
1152        })?,
1153        Some(other) => {
1154            return Err(EvalError::TypeMismatch {
1155                detail: format!(
1156                    "{name}() config arg must be text, got {:?}",
1157                    other.data_type()
1158                ),
1159            });
1160        }
1161    };
1162    let text = match text_arg {
1163        Value::Null => None,
1164        Value::Text(s) => Some(s.clone()),
1165        other => {
1166            return Err(EvalError::TypeMismatch {
1167                detail: format!(
1168                    "{name}() text arg must be text, got {:?}",
1169                    other.data_type()
1170                ),
1171            });
1172        }
1173    };
1174    Ok((config, text))
1175}
1176
1177/// v6.4.3 — `encode(bytes_as_text, format)`. PG works on bytea
1178/// arguments; SPG's value space treats Text as the byte container
1179/// (raw UTF-8 bytes). Supported formats: base64 (PG default),
1180/// base64url (RFC 4648 §5), base32hex (RFC 4648 §7 extended-hex),
1181/// hex.
1182fn encode_text(args: &[Value]) -> Result<Value, EvalError> {
1183    if args.len() != 2 {
1184        return Err(EvalError::TypeMismatch {
1185            detail: format!("encode() takes 2 args, got {}", args.len()),
1186        });
1187    }
1188    if matches!(args[0], Value::Null) || matches!(args[1], Value::Null) {
1189        return Ok(Value::Null);
1190    }
1191    let bytes: &[u8] = match &args[0] {
1192        Value::Text(s) => s.as_bytes(),
1193        other => {
1194            return Err(EvalError::TypeMismatch {
1195                detail: format!("encode() expects text bytes, got {:?}", other.data_type()),
1196            });
1197        }
1198    };
1199    let fmt = match &args[1] {
1200        Value::Text(s) => s.to_ascii_lowercase(),
1201        other => {
1202            return Err(EvalError::TypeMismatch {
1203                detail: format!("encode() format must be text, got {:?}", other.data_type()),
1204            });
1205        }
1206    };
1207    let out = match fmt.as_str() {
1208        "base64" => b64_encode(bytes, B64_STD),
1209        "base64url" => b64_encode(bytes, B64_URL),
1210        "base32hex" => b32hex_encode(bytes),
1211        "hex" => hex_encode(bytes),
1212        other => {
1213            return Err(EvalError::TypeMismatch {
1214                detail: format!("encode(): unknown format `{other}`"),
1215            });
1216        }
1217    };
1218    Ok(Value::Text(out))
1219}
1220
1221/// v6.4.3 — `decode(text, format)`. Inverse of `encode`; returns
1222/// Text containing the raw decoded bytes (caller may CAST to bytea
1223/// equivalent if SPG adds bytea later).
1224fn decode_text(args: &[Value]) -> Result<Value, EvalError> {
1225    if args.len() != 2 {
1226        return Err(EvalError::TypeMismatch {
1227            detail: format!("decode() takes 2 args, got {}", args.len()),
1228        });
1229    }
1230    if matches!(args[0], Value::Null) || matches!(args[1], Value::Null) {
1231        return Ok(Value::Null);
1232    }
1233    let text = match &args[0] {
1234        Value::Text(s) => s.as_str(),
1235        other => {
1236            return Err(EvalError::TypeMismatch {
1237                detail: format!("decode() expects text, got {:?}", other.data_type()),
1238            });
1239        }
1240    };
1241    let fmt = match &args[1] {
1242        Value::Text(s) => s.to_ascii_lowercase(),
1243        other => {
1244            return Err(EvalError::TypeMismatch {
1245                detail: format!("decode() format must be text, got {:?}", other.data_type()),
1246            });
1247        }
1248    };
1249    let bytes = match fmt.as_str() {
1250        "base64" => b64_decode(text, B64_STD)?,
1251        "base64url" => b64_decode(text, B64_URL)?,
1252        "base32hex" => b32hex_decode(text)?,
1253        "hex" => hex_decode(text)?,
1254        other => {
1255            return Err(EvalError::TypeMismatch {
1256                detail: format!("decode(): unknown format `{other}`"),
1257            });
1258        }
1259    };
1260    let s = String::from_utf8(bytes).map_err(|_| EvalError::TypeMismatch {
1261        detail: "decode(): result bytes are not valid UTF-8 (SPG stores raw bytes as Text)".into(),
1262    })?;
1263    Ok(Value::Text(s))
1264}
1265
1266/// v6.4.3 — `error_on_null(v)`. Returns `v` unchanged if non-NULL;
1267/// errors otherwise. Convenience to assert NOT NULL inside an
1268/// expression without wrapping it in COALESCE + raise hacks.
1269fn error_on_null(args: &[Value]) -> Result<Value, EvalError> {
1270    if args.len() != 1 {
1271        return Err(EvalError::TypeMismatch {
1272            detail: format!("error_on_null() takes 1 arg, got {}", args.len()),
1273        });
1274    }
1275    if matches!(args[0], Value::Null) {
1276        return Err(EvalError::TypeMismatch {
1277            detail: "error_on_null(): argument is NULL".into(),
1278        });
1279    }
1280    Ok(args[0].clone())
1281}
1282
1283// ── byte-level encoders ───────────────────────────────────────────
1284
1285const B64_STD: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
1286const B64_URL: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
1287const B32HEX_ALPHABET: &[u8; 32] = b"0123456789ABCDEFGHIJKLMNOPQRSTUV";
1288
1289fn b64_encode(bytes: &[u8], alpha: &[u8; 64]) -> String {
1290    let mut out = String::with_capacity((bytes.len() + 2) / 3 * 4);
1291    let mut i = 0;
1292    while i + 3 <= bytes.len() {
1293        let n = ((bytes[i] as u32) << 16) | ((bytes[i + 1] as u32) << 8) | (bytes[i + 2] as u32);
1294        out.push(alpha[((n >> 18) & 0x3f) as usize] as char);
1295        out.push(alpha[((n >> 12) & 0x3f) as usize] as char);
1296        out.push(alpha[((n >> 6) & 0x3f) as usize] as char);
1297        out.push(alpha[(n & 0x3f) as usize] as char);
1298        i += 3;
1299    }
1300    let rem = bytes.len() - i;
1301    if rem == 1 {
1302        let n = (bytes[i] as u32) << 16;
1303        out.push(alpha[((n >> 18) & 0x3f) as usize] as char);
1304        out.push(alpha[((n >> 12) & 0x3f) as usize] as char);
1305        out.push('=');
1306        out.push('=');
1307    } else if rem == 2 {
1308        let n = ((bytes[i] as u32) << 16) | ((bytes[i + 1] as u32) << 8);
1309        out.push(alpha[((n >> 18) & 0x3f) as usize] as char);
1310        out.push(alpha[((n >> 12) & 0x3f) as usize] as char);
1311        out.push(alpha[((n >> 6) & 0x3f) as usize] as char);
1312        out.push('=');
1313    }
1314    out
1315}
1316
1317fn b64_decode(text: &str, alpha: &[u8; 64]) -> Result<Vec<u8>, EvalError> {
1318    let mut lookup = [255u8; 256];
1319    for (i, &c) in alpha.iter().enumerate() {
1320        lookup[c as usize] = i as u8;
1321    }
1322    let mut out = Vec::with_capacity(text.len() * 3 / 4);
1323    let mut buf: u32 = 0;
1324    let mut bits: u32 = 0;
1325    for c in text.bytes() {
1326        if c == b'=' {
1327            break;
1328        }
1329        if c == b'\n' || c == b'\r' || c == b' ' {
1330            continue;
1331        }
1332        let v = lookup[c as usize];
1333        if v == 255 {
1334            return Err(EvalError::TypeMismatch {
1335                detail: format!("decode(base64): invalid char {:?}", c as char),
1336            });
1337        }
1338        buf = (buf << 6) | v as u32;
1339        bits += 6;
1340        if bits >= 8 {
1341            bits -= 8;
1342            out.push(((buf >> bits) & 0xff) as u8);
1343        }
1344    }
1345    Ok(out)
1346}
1347
1348fn b32hex_encode(bytes: &[u8]) -> String {
1349    let mut out = String::with_capacity((bytes.len() * 8 + 4) / 5);
1350    let mut buf: u64 = 0;
1351    let mut bits: u32 = 0;
1352    for &b in bytes {
1353        buf = (buf << 8) | b as u64;
1354        bits += 8;
1355        while bits >= 5 {
1356            bits -= 5;
1357            out.push(B32HEX_ALPHABET[((buf >> bits) & 0x1f) as usize] as char);
1358        }
1359    }
1360    if bits > 0 {
1361        out.push(B32HEX_ALPHABET[((buf << (5 - bits)) & 0x1f) as usize] as char);
1362    }
1363    // Pad to multiple of 8.
1364    while out.len() % 8 != 0 {
1365        out.push('=');
1366    }
1367    out
1368}
1369
1370fn b32hex_decode(text: &str) -> Result<Vec<u8>, EvalError> {
1371    let mut lookup = [255u8; 256];
1372    for (i, &c) in B32HEX_ALPHABET.iter().enumerate() {
1373        lookup[c as usize] = i as u8;
1374        // base32hex is case-insensitive — also map lowercase.
1375        let lower = (c as char).to_ascii_lowercase() as u8;
1376        lookup[lower as usize] = i as u8;
1377    }
1378    let mut out = Vec::with_capacity(text.len() * 5 / 8);
1379    let mut buf: u64 = 0;
1380    let mut bits: u32 = 0;
1381    for c in text.bytes() {
1382        if c == b'=' {
1383            break;
1384        }
1385        if c == b'\n' || c == b'\r' || c == b' ' {
1386            continue;
1387        }
1388        let v = lookup[c as usize];
1389        if v == 255 {
1390            return Err(EvalError::TypeMismatch {
1391                detail: format!("decode(base32hex): invalid char {:?}", c as char),
1392            });
1393        }
1394        buf = (buf << 5) | v as u64;
1395        bits += 5;
1396        if bits >= 8 {
1397            bits -= 8;
1398            out.push(((buf >> bits) & 0xff) as u8);
1399        }
1400    }
1401    Ok(out)
1402}
1403
1404fn hex_encode(bytes: &[u8]) -> String {
1405    const HEX: &[u8; 16] = b"0123456789abcdef";
1406    let mut out = String::with_capacity(bytes.len() * 2);
1407    for &b in bytes {
1408        out.push(HEX[(b >> 4) as usize] as char);
1409        out.push(HEX[(b & 0xf) as usize] as char);
1410    }
1411    out
1412}
1413
1414fn hex_decode(text: &str) -> Result<Vec<u8>, EvalError> {
1415    let trimmed = text.trim();
1416    if trimmed.len() % 2 != 0 {
1417        return Err(EvalError::TypeMismatch {
1418            detail: "decode(hex): input length must be even".into(),
1419        });
1420    }
1421    let mut out = Vec::with_capacity(trimmed.len() / 2);
1422    let mut hi: u8 = 0;
1423    for (i, c) in trimmed.bytes().enumerate() {
1424        let v = match c {
1425            b'0'..=b'9' => c - b'0',
1426            b'a'..=b'f' => c - b'a' + 10,
1427            b'A'..=b'F' => c - b'A' + 10,
1428            _ => {
1429                return Err(EvalError::TypeMismatch {
1430                    detail: format!("decode(hex): invalid char {:?}", c as char),
1431                });
1432            }
1433        };
1434        if i % 2 == 0 {
1435            hi = v;
1436        } else {
1437            out.push((hi << 4) | v);
1438        }
1439    }
1440    Ok(out)
1441}
1442
1443/// `date_part(field_text, source)` — function form of `EXTRACT(field FROM
1444/// source)`. Same component dispatch (DATE / TIMESTAMP / INTERVAL) and
1445/// same `BigInt` return shape; PG returns double precision but we keep the
1446/// integer convention so the runner's `query I` shape works unchanged.
1447fn date_part(args: &[Value]) -> Result<Value, EvalError> {
1448    use spg_sql::ast::ExtractField as F;
1449    if args.len() != 2 {
1450        return Err(EvalError::TypeMismatch {
1451            detail: format!("date_part() takes 2 args, got {}", args.len()),
1452        });
1453    }
1454    if matches!(&args[0], Value::Null) || matches!(&args[1], Value::Null) {
1455        return Ok(Value::Null);
1456    }
1457    let Value::Text(field_name) = &args[0] else {
1458        return Err(EvalError::TypeMismatch {
1459            detail: format!(
1460                "date_part() needs a text field, got {:?}",
1461                args[0].data_type()
1462            ),
1463        });
1464    };
1465    let field = match field_name.to_ascii_lowercase().as_str() {
1466        "year" => F::Year,
1467        "month" => F::Month,
1468        "day" => F::Day,
1469        "hour" => F::Hour,
1470        "minute" => F::Minute,
1471        "second" => F::Second,
1472        "microsecond" | "microseconds" => F::Microsecond,
1473        other => {
1474            return Err(EvalError::TypeMismatch {
1475                detail: format!(
1476                    "unknown date_part field {other:?}; \
1477                     supported: year, month, day, hour, minute, second, microsecond"
1478                ),
1479            });
1480        }
1481    };
1482    extract_field(field, &args[1])
1483}
1484
1485/// `age(t1, t2)` — return `t1 - t2` as an INTERVAL. v2.12 produces a
1486/// micros-only interval (no months normalisation) because PG's
1487/// month-justification rule is sensitive to the day-of-month walk and
1488/// adds material complexity for marginal corpus value.
1489///
1490/// `age(t)` (single-arg form) is intentionally unsupported in v2.12:
1491/// the dispatcher errors instead of guessing a clock source. Callers
1492/// who want PG's `age(t)` semantics should write `age(CURRENT_DATE, t)`
1493/// explicitly so the clock reference is visible at the SQL layer.
1494fn age(args: &[Value]) -> Result<Value, EvalError> {
1495    if args.is_empty() || args.len() > 2 {
1496        return Err(EvalError::TypeMismatch {
1497            detail: format!("age() takes 1 or 2 args, got {}", args.len()),
1498        });
1499    }
1500    if args.iter().any(|v| matches!(v, Value::Null)) {
1501        return Ok(Value::Null);
1502    }
1503    // Coerce to TIMESTAMP micros — DATE lifts to midnight; TIMESTAMP
1504    // stays as-is; anything else errors.
1505    let to_micros = |v: &Value| -> Result<i64, EvalError> {
1506        match v {
1507            Value::Timestamp(t) => Ok(*t),
1508            Value::Date(d) => Ok(i64::from(*d) * 86_400_000_000),
1509            other => Err(EvalError::TypeMismatch {
1510                detail: format!("age() needs DATE or TIMESTAMP, got {:?}", other.data_type()),
1511            }),
1512        }
1513    };
1514    if args.len() == 1 {
1515        return Err(EvalError::TypeMismatch {
1516            detail: "single-arg age() is unsupported in v2.12 \
1517                     (use age(CURRENT_DATE, t) explicitly)"
1518                .into(),
1519        });
1520    }
1521    let a = to_micros(&args[0])?;
1522    let b = to_micros(&args[1])?;
1523    let delta = a.checked_sub(b).ok_or(EvalError::TypeMismatch {
1524        detail: "age() subtraction overflows i64 microseconds".into(),
1525    })?;
1526    Ok(Value::Interval {
1527        months: 0,
1528        micros: delta,
1529    })
1530}
1531
1532/// `to_char(value, format)` — render a DATE / TIMESTAMP through a PG
1533/// format template. Supports the high-traffic placeholders:
1534///   YYYY YY MM Mon Month DD HH24 HH12 MI SS MS US AM PM
1535/// Unrecognised characters pass through literally so the template's
1536/// punctuation ('-', ':', ' ', '/') needs no escape mechanism.
1537fn to_char(args: &[Value]) -> Result<Value, EvalError> {
1538    use core::fmt::Write as _;
1539    if args.len() != 2 {
1540        return Err(EvalError::TypeMismatch {
1541            detail: format!("to_char() takes 2 args, got {}", args.len()),
1542        });
1543    }
1544    if matches!(&args[0], Value::Null) || matches!(&args[1], Value::Null) {
1545        return Ok(Value::Null);
1546    }
1547    let Value::Text(fmt) = &args[1] else {
1548        return Err(EvalError::TypeMismatch {
1549            detail: format!(
1550                "to_char() needs a text format, got {:?}",
1551                args[1].data_type()
1552            ),
1553        });
1554    };
1555    let (days, day_micros) = match &args[0] {
1556        Value::Date(d) => (*d, 0_i64),
1557        Value::Timestamp(t) => {
1558            let days = t.div_euclid(86_400_000_000);
1559            (
1560                i32::try_from(days).unwrap_or(i32::MAX),
1561                t.rem_euclid(86_400_000_000),
1562            )
1563        }
1564        other => {
1565            return Err(EvalError::TypeMismatch {
1566                detail: format!(
1567                    "to_char() needs DATE or TIMESTAMP, got {:?}",
1568                    other.data_type()
1569                ),
1570            });
1571        }
1572    };
1573    let (y, mo, d) = civil_from_days(days);
1574    let secs = day_micros / 1_000_000;
1575    let frac = day_micros % 1_000_000;
1576    // div_euclid keeps every value non-negative — the casts below are
1577    // sign-safe by construction. `secs ∈ [0, 86400)`, `frac ∈ [0,
1578    // 1_000_000)`, so all three quantities fit in u32.
1579    let hh24 = u32::try_from(secs / 3600).unwrap_or(0);
1580    let mi = u32::try_from((secs / 60) % 60).unwrap_or(0);
1581    let ss = u32::try_from(secs % 60).unwrap_or(0);
1582    let hh12 = match hh24 % 12 {
1583        0 => 12,
1584        x => x,
1585    };
1586    let ampm = if hh24 < 12 { "AM" } else { "PM" };
1587    let ms = u32::try_from(frac / 1_000).unwrap_or(0); // millisecond
1588    let us = u32::try_from(frac).unwrap_or(0); // microsecond (0..1_000_000)
1589
1590    let mut out = String::with_capacity(fmt.len() + 8);
1591    let bytes = fmt.as_bytes();
1592    let mut i = 0;
1593    // write! against a String never fails — discard the Result.
1594    while i < bytes.len() {
1595        // Try the longest prefixes first so "YYYY" wins over "YY".
1596        let rest = &bytes[i..];
1597        if rest.starts_with(b"YYYY") {
1598            let _ = write!(out, "{y:04}");
1599            i += 4;
1600        } else if rest.starts_with(b"YY") {
1601            #[allow(clippy::cast_sign_loss, clippy::cast_possible_truncation)]
1602            let yy = (y.rem_euclid(100)) as u32;
1603            let _ = write!(out, "{yy:02}");
1604            i += 2;
1605        } else if rest.starts_with(b"Month") {
1606            out.push_str(MONTH_FULL[(mo - 1) as usize]);
1607            i += 5;
1608        } else if rest.starts_with(b"Mon") {
1609            out.push_str(MONTH_ABBR[(mo - 1) as usize]);
1610            i += 3;
1611        } else if rest.starts_with(b"MM") {
1612            let _ = write!(out, "{mo:02}");
1613            i += 2;
1614        } else if rest.starts_with(b"DD") {
1615            let _ = write!(out, "{d:02}");
1616            i += 2;
1617        } else if rest.starts_with(b"HH24") {
1618            let _ = write!(out, "{hh24:02}");
1619            i += 4;
1620        } else if rest.starts_with(b"HH12") {
1621            let _ = write!(out, "{hh12:02}");
1622            i += 4;
1623        } else if rest.starts_with(b"MI") {
1624            let _ = write!(out, "{mi:02}");
1625            i += 2;
1626        } else if rest.starts_with(b"SS") {
1627            let _ = write!(out, "{ss:02}");
1628            i += 2;
1629        } else if rest.starts_with(b"MS") {
1630            let _ = write!(out, "{ms:03}");
1631            i += 2;
1632        } else if rest.starts_with(b"US") {
1633            let _ = write!(out, "{us:06}");
1634            i += 2;
1635        } else if rest.starts_with(b"AM") || rest.starts_with(b"PM") {
1636            out.push_str(ampm);
1637            i += 2;
1638        } else {
1639            // Pass any non-placeholder byte through verbatim.
1640            out.push(bytes[i] as char);
1641            i += 1;
1642        }
1643    }
1644    Ok(Value::Text(out))
1645}
1646
1647const MONTH_FULL: [&str; 12] = [
1648    "January",
1649    "February",
1650    "March",
1651    "April",
1652    "May",
1653    "June",
1654    "July",
1655    "August",
1656    "September",
1657    "October",
1658    "November",
1659    "December",
1660];
1661const MONTH_ABBR: [&str; 12] = [
1662    "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
1663];
1664
1665/// `date_trunc(unit, timestamp)` — round a `TIMESTAMP` down to the
1666/// requested calendar boundary (year / month / day / hour / minute /
1667/// second). Returns the truncated `TIMESTAMP`. NULL on either side
1668/// propagates to NULL.
1669fn date_trunc(args: &[Value]) -> Result<Value, EvalError> {
1670    if args.len() != 2 {
1671        return Err(EvalError::TypeMismatch {
1672            detail: format!("date_trunc() takes 2 args, got {}", args.len()),
1673        });
1674    }
1675    if matches!(&args[0], Value::Null) || matches!(&args[1], Value::Null) {
1676        return Ok(Value::Null);
1677    }
1678    let Value::Text(unit) = &args[0] else {
1679        return Err(EvalError::TypeMismatch {
1680            detail: format!(
1681                "date_trunc() needs a text unit, got {:?}",
1682                args[0].data_type()
1683            ),
1684        });
1685    };
1686    // Both DATE and TIMESTAMP sources are accepted. DATE lifts to
1687    // midnight first; the result is always TIMESTAMP.
1688    let micros = match &args[1] {
1689        Value::Timestamp(t) => *t,
1690        Value::Date(d) => i64::from(*d) * 86_400_000_000,
1691        other => {
1692            return Err(EvalError::TypeMismatch {
1693                detail: format!(
1694                    "date_trunc() needs DATE or TIMESTAMP, got {:?}",
1695                    other.data_type()
1696                ),
1697            });
1698        }
1699    };
1700    let unit_lc = unit.to_ascii_lowercase();
1701    let days = micros.div_euclid(86_400_000_000);
1702    let day_micros = micros.rem_euclid(86_400_000_000);
1703    let day_i32 = i32::try_from(days).unwrap_or(i32::MAX);
1704    let (y, m, _) = civil_from_days(day_i32);
1705    let truncated = match unit_lc.as_str() {
1706        "year" => i64::from(days_from_civil(y, 1, 1)) * 86_400_000_000,
1707        "month" => i64::from(days_from_civil(y, m, 1)) * 86_400_000_000,
1708        "day" => days * 86_400_000_000,
1709        "hour" => days * 86_400_000_000 + (day_micros / 3_600_000_000) * 3_600_000_000,
1710        "minute" => days * 86_400_000_000 + (day_micros / 60_000_000) * 60_000_000,
1711        "second" => days * 86_400_000_000 + (day_micros / 1_000_000) * 1_000_000,
1712        other => {
1713            return Err(EvalError::TypeMismatch {
1714                detail: format!(
1715                    "unknown date_trunc unit {other:?}; \
1716                     supported: year, month, day, hour, minute, second"
1717                ),
1718            });
1719        }
1720    };
1721    Ok(Value::Timestamp(truncated))
1722}
1723
1724/// PG-style `expr::TYPE` coercion. NULL always casts as NULL.
1725pub fn cast_value(v: Value, target: CastTarget) -> Result<Value, EvalError> {
1726    if matches!(v, Value::Null) {
1727        return Ok(Value::Null);
1728    }
1729    match target {
1730        CastTarget::Vector => cast_to_vector(v),
1731        CastTarget::Text => Ok(Value::Text(value_to_text(&v))),
1732        CastTarget::Int => cast_numeric_to_int(v),
1733        CastTarget::BigInt => cast_numeric_to_bigint(v),
1734        CastTarget::Float => cast_numeric_to_float(v),
1735        CastTarget::Bool => cast_to_bool(v),
1736        CastTarget::Date => cast_to_date(v),
1737        // TIMESTAMP and TIMESTAMPTZ have identical runtime
1738        // representation (i64 microseconds UTC).
1739        CastTarget::Timestamp | CastTarget::Timestamptz => cast_to_timestamp(v),
1740        // v7.9.25 — `expr::INTERVAL`. Currently only TEXT → Interval
1741        // is supported (the mailrs idiom: `$1::INTERVAL` where the
1742        // bound param is a string like `'7 days'`).
1743        CastTarget::Interval => cast_to_interval(v),
1744        // v7.9.25 — `::json` / `::jsonb`. Routes Text → Json
1745        // (validation is the producer's responsibility, same as
1746        // the column-INSERT path).
1747        CastTarget::Json | CastTarget::Jsonb => match v {
1748            Value::Json(s) => Ok(Value::Json(s)),
1749            Value::Text(s) => Ok(Value::Json(s)),
1750            other => Err(EvalError::TypeMismatch {
1751                detail: alloc::format!(
1752                    "::json / ::jsonb only accepts TEXT-shape inputs, got {:?}",
1753                    other.data_type()
1754                ),
1755            }),
1756        },
1757        // v7.9.26 — `::regtype` / `::regclass`. SPG has no
1758        // pg_catalog; surface a clear error.
1759        CastTarget::RegType | CastTarget::RegClass => Err(EvalError::TypeMismatch {
1760            detail: "::regtype / ::regclass not supported on SPG \
1761                 (no pg_catalog); use SHOW TABLES / spg_table_ddl instead"
1762                .into(),
1763        }),
1764        // v7.10.11 — `::TEXT[]`. Decode PG external array form
1765        // when input is Text; pass through unchanged when it is
1766        // already TextArray. Anything else is a type mismatch.
1767        CastTarget::TextArray => match v {
1768            Value::TextArray(items) => Ok(Value::TextArray(items)),
1769            Value::Text(s) => decode_text_array_external(&s).map(Value::TextArray),
1770            other => Err(EvalError::TypeMismatch {
1771                detail: alloc::format!(
1772                    "::TEXT[] only accepts TEXT / TEXT[] inputs, got {:?}",
1773                    other.data_type()
1774                ),
1775            }),
1776        },
1777        // v7.11.13 — `::INT[]` / `::BIGINT[]`. Decode PG external
1778        // form `{1,2,3}` when input is Text; widen TextArray /
1779        // IntArray as appropriate.
1780        CastTarget::IntArray => cast_to_int_array(v),
1781        CastTarget::BigIntArray => cast_to_bigint_array(v),
1782        // v7.12.0 — `::tsvector` / `::tsquery`. Decodes PG external
1783        // form when input is Text; passes through unchanged when the
1784        // input is already the target type. Other inputs are a type
1785        // mismatch. Lexer / Porter stemmer arrive in v7.12.1; the
1786        // external-form cast at v7.12.0 is the path pg_dump and
1787        // direct-literal callers use.
1788        CastTarget::TsVector => match v {
1789            Value::TsVector(items) => Ok(Value::TsVector(items)),
1790            Value::Text(s) => decode_tsvector_external(&s).map(Value::TsVector),
1791            other => Err(EvalError::TypeMismatch {
1792                detail: alloc::format!(
1793                    "::tsvector only accepts TEXT / tsvector inputs, got {:?}",
1794                    other.data_type()
1795                ),
1796            }),
1797        },
1798        CastTarget::TsQuery => match v {
1799            Value::TsQuery(ast) => Ok(Value::TsQuery(ast)),
1800            Value::Text(s) => decode_tsquery_external(&s).map(Value::TsQuery),
1801            other => Err(EvalError::TypeMismatch {
1802                detail: alloc::format!(
1803                    "::tsquery only accepts TEXT / tsquery inputs, got {:?}",
1804                    other.data_type()
1805                ),
1806            }),
1807        },
1808    }
1809}
1810
1811fn cast_to_int_array(v: Value) -> Result<Value, EvalError> {
1812    match v {
1813        Value::IntArray(items) => Ok(Value::IntArray(items)),
1814        Value::BigIntArray(items) => {
1815            let mut out: Vec<Option<i32>> = Vec::with_capacity(items.len());
1816            for item in items {
1817                match item {
1818                    None => out.push(None),
1819                    Some(n) => match i32::try_from(n) {
1820                        Ok(x) => out.push(Some(x)),
1821                        Err(_) => {
1822                            return Err(EvalError::TypeMismatch {
1823                                detail: alloc::format!("::INT[] element {n} overflows i32"),
1824                            });
1825                        }
1826                    },
1827                }
1828            }
1829            Ok(Value::IntArray(out))
1830        }
1831        Value::Text(s) => decode_int_array_external(&s).map(Value::IntArray),
1832        Value::TextArray(items) => {
1833            let mut out: Vec<Option<i32>> = Vec::with_capacity(items.len());
1834            for item in items {
1835                match item {
1836                    None => out.push(None),
1837                    Some(s) => match s.parse::<i32>() {
1838                        Ok(n) => out.push(Some(n)),
1839                        Err(_) => {
1840                            return Err(EvalError::TypeMismatch {
1841                                detail: alloc::format!("::INT[] cannot parse {s:?}"),
1842                            });
1843                        }
1844                    },
1845                }
1846            }
1847            Ok(Value::IntArray(out))
1848        }
1849        other => Err(EvalError::TypeMismatch {
1850            detail: alloc::format!("::INT[] does not accept {:?}", other.data_type()),
1851        }),
1852    }
1853}
1854
1855fn cast_to_bigint_array(v: Value) -> Result<Value, EvalError> {
1856    match v {
1857        Value::BigIntArray(items) => Ok(Value::BigIntArray(items)),
1858        Value::IntArray(items) => Ok(Value::BigIntArray(
1859            items.into_iter().map(|x| x.map(i64::from)).collect(),
1860        )),
1861        Value::Text(s) => decode_bigint_array_external(&s).map(Value::BigIntArray),
1862        Value::TextArray(items) => {
1863            let mut out: Vec<Option<i64>> = Vec::with_capacity(items.len());
1864            for item in items {
1865                match item {
1866                    None => out.push(None),
1867                    Some(s) => match s.parse::<i64>() {
1868                        Ok(n) => out.push(Some(n)),
1869                        Err(_) => {
1870                            return Err(EvalError::TypeMismatch {
1871                                detail: alloc::format!("::BIGINT[] cannot parse {s:?}"),
1872                            });
1873                        }
1874                    },
1875                }
1876            }
1877            Ok(Value::BigIntArray(out))
1878        }
1879        other => Err(EvalError::TypeMismatch {
1880            detail: alloc::format!("::BIGINT[] does not accept {:?}", other.data_type()),
1881        }),
1882    }
1883}
1884
1885fn decode_int_array_external(s: &str) -> Result<Vec<Option<i32>>, EvalError> {
1886    let trimmed = s.trim();
1887    let inner = trimmed
1888        .strip_prefix('{')
1889        .and_then(|x| x.strip_suffix('}'))
1890        .ok_or_else(|| EvalError::TypeMismatch {
1891            detail: alloc::format!("INT[] literal {s:?} must be enclosed in '{{...}}'"),
1892        })?;
1893    if inner.trim().is_empty() {
1894        return Ok(Vec::new());
1895    }
1896    inner
1897        .split(',')
1898        .map(|part| {
1899            let p = part.trim();
1900            if p.eq_ignore_ascii_case("NULL") {
1901                Ok(None)
1902            } else {
1903                p.parse::<i32>()
1904                    .map(Some)
1905                    .map_err(|_| EvalError::TypeMismatch {
1906                        detail: alloc::format!("INT[] element {p:?} is not an i32"),
1907                    })
1908            }
1909        })
1910        .collect()
1911}
1912
1913fn decode_bigint_array_external(s: &str) -> Result<Vec<Option<i64>>, EvalError> {
1914    let trimmed = s.trim();
1915    let inner = trimmed
1916        .strip_prefix('{')
1917        .and_then(|x| x.strip_suffix('}'))
1918        .ok_or_else(|| EvalError::TypeMismatch {
1919            detail: alloc::format!("BIGINT[] literal {s:?} must be enclosed in '{{...}}'"),
1920        })?;
1921    if inner.trim().is_empty() {
1922        return Ok(Vec::new());
1923    }
1924    inner
1925        .split(',')
1926        .map(|part| {
1927            let p = part.trim();
1928            if p.eq_ignore_ascii_case("NULL") {
1929                Ok(None)
1930            } else {
1931                p.parse::<i64>()
1932                    .map(Some)
1933                    .map_err(|_| EvalError::TypeMismatch {
1934                        detail: alloc::format!("BIGINT[] element {p:?} is not an i64"),
1935                    })
1936            }
1937        })
1938        .collect()
1939}
1940
1941/// v7.10.11 — same decoder as `decode_text_array_literal` in
1942/// `lib.rs`, but lives here so the eval-time cast path stays
1943/// inside `spg-engine::eval`. Kept in lock-step with the engine
1944/// `coerce_value` decoder by tests.
1945fn decode_text_array_external(s: &str) -> Result<Vec<Option<String>>, EvalError> {
1946    let trimmed = s.trim();
1947    let inner = trimmed
1948        .strip_prefix('{')
1949        .and_then(|x| x.strip_suffix('}'))
1950        .ok_or_else(|| EvalError::TypeMismatch {
1951            detail: alloc::format!("TEXT[] literal {s:?} must be enclosed in '{{...}}'"),
1952        })?;
1953    let mut out: Vec<Option<String>> = Vec::new();
1954    if inner.trim().is_empty() {
1955        return Ok(out);
1956    }
1957    let bytes = inner.as_bytes();
1958    let mut i = 0;
1959    while i <= bytes.len() {
1960        while i < bytes.len() && (bytes[i] == b' ' || bytes[i] == b'\t') {
1961            i += 1;
1962        }
1963        if i < bytes.len() && bytes[i] == b'"' {
1964            i += 1;
1965            let mut buf = String::new();
1966            while i < bytes.len() && bytes[i] != b'"' {
1967                if bytes[i] == b'\\' && i + 1 < bytes.len() {
1968                    buf.push(bytes[i + 1] as char);
1969                    i += 2;
1970                } else {
1971                    buf.push(bytes[i] as char);
1972                    i += 1;
1973                }
1974            }
1975            if i >= bytes.len() {
1976                return Err(EvalError::TypeMismatch {
1977                    detail: "unterminated quoted element in TEXT[] literal".into(),
1978                });
1979            }
1980            i += 1;
1981            out.push(Some(buf));
1982        } else {
1983            let start = i;
1984            while i < bytes.len() && bytes[i] != b',' {
1985                i += 1;
1986            }
1987            let raw = inner[start..i].trim();
1988            if raw.eq_ignore_ascii_case("NULL") {
1989                out.push(None);
1990            } else {
1991                out.push(Some(raw.to_string()));
1992            }
1993        }
1994        while i < bytes.len() && (bytes[i] == b' ' || bytes[i] == b'\t') {
1995            i += 1;
1996        }
1997        if i >= bytes.len() {
1998            break;
1999        }
2000        if bytes[i] != b',' {
2001            return Err(EvalError::TypeMismatch {
2002                detail: "expected ',' between TEXT[] elements".into(),
2003            });
2004        }
2005        i += 1;
2006    }
2007    Ok(out)
2008}
2009
2010fn cast_to_interval(v: Value) -> Result<Value, EvalError> {
2011    match v {
2012        Value::Interval { months, micros } => Ok(Value::Interval { months, micros }),
2013        Value::Text(s) => {
2014            let (months, micros) = spg_sql::parser::parse_interval_text(&s).ok_or_else(|| {
2015                EvalError::TypeMismatch {
2016                    detail: alloc::format!("cannot parse {s:?} as INTERVAL"),
2017                }
2018            })?;
2019            Ok(Value::Interval { months, micros })
2020        }
2021        other => Err(EvalError::TypeMismatch {
2022            detail: alloc::format!(
2023                "::INTERVAL only accepts TEXT-shape inputs, got {:?}",
2024                other.data_type()
2025            ),
2026        }),
2027    }
2028}
2029
2030fn cast_to_date(v: Value) -> Result<Value, EvalError> {
2031    match v {
2032        Value::Date(d) => Ok(Value::Date(d)),
2033        // Integer literals carry days since the Unix epoch — used by
2034        // the `CURRENT_DATE` AST rewrite to inject the wall clock.
2035        Value::Int(n) => Ok(Value::Date(n)),
2036        Value::BigInt(n) => {
2037            i32::try_from(n)
2038                .map(Value::Date)
2039                .map_err(|_| EvalError::TypeMismatch {
2040                    detail: "bigint days-since-epoch out of DATE range".into(),
2041                })
2042        }
2043        // Timestamp truncates to its day boundary.
2044        Value::Timestamp(t) => {
2045            let days = t.div_euclid(86_400_000_000);
2046            i32::try_from(days)
2047                .map(Value::Date)
2048                .map_err(|_| EvalError::TypeMismatch {
2049                    detail: "timestamp out of DATE range".into(),
2050                })
2051        }
2052        Value::Text(s) => parse_date_literal(&s)
2053            .map(Value::Date)
2054            .ok_or(EvalError::TypeMismatch {
2055                detail: format!("cannot parse {s:?} as DATE (expected YYYY-MM-DD)"),
2056            }),
2057        other => Err(EvalError::TypeMismatch {
2058            detail: format!("cannot cast {:?} to DATE", other.data_type()),
2059        }),
2060    }
2061}
2062
2063fn cast_to_timestamp(v: Value) -> Result<Value, EvalError> {
2064    match v {
2065        Value::Timestamp(t) => Ok(Value::Timestamp(t)),
2066        // Int / BigInt carry microseconds since the Unix epoch — used
2067        // by the `NOW()` / `CURRENT_TIMESTAMP` AST rewrite to inject
2068        // the wall clock as a plain integer literal.
2069        Value::Int(n) => Ok(Value::Timestamp(i64::from(n))),
2070        Value::BigInt(n) => Ok(Value::Timestamp(n)),
2071        // DATE → TIMESTAMP picks midnight on the date.
2072        Value::Date(d) => Ok(Value::Timestamp(i64::from(d) * 86_400_000_000)),
2073        Value::Text(s) => {
2074            parse_timestamp_literal(&s)
2075                .map(Value::Timestamp)
2076                .ok_or(EvalError::TypeMismatch {
2077                    detail: format!(
2078                        "cannot parse {s:?} as TIMESTAMP \
2079                     (expected YYYY-MM-DD[ HH:MM:SS[.ffffff]])"
2080                    ),
2081                })
2082        }
2083        other => Err(EvalError::TypeMismatch {
2084            detail: format!("cannot cast {:?} to TIMESTAMP", other.data_type()),
2085        }),
2086    }
2087}
2088
2089fn value_to_text(v: &Value) -> String {
2090    match v {
2091        // v7.5.0 — Value is #[non_exhaustive]; any future variant
2092        // without explicit text rendering hits the Debug fallback
2093        // at the end.
2094        Value::SmallInt(n) => format!("{n}"),
2095        Value::Int(n) => format!("{n}"),
2096        Value::BigInt(n) => format!("{n}"),
2097        Value::Float(x) => format!("{x}"),
2098        // v4.9: JSON renders identically to Text — both are raw UTF-8.
2099        Value::Text(s) | Value::Json(s) => s.clone(),
2100        Value::Bool(b) => (if *b { "true" } else { "false" }).into(),
2101        Value::Vector(v) => {
2102            let cells: Vec<String> = v.iter().map(|x| format!("{x}")).collect();
2103            format!("[{}]", cells.join(", "))
2104        }
2105        // v6.0.1: render SQ8 cells dequantised, so SELECT output
2106        // matches the pgvector wire shape clients expect. The
2107        // recall envelope already absorbs the ≤ (max-min)/255/2
2108        // dequantisation error.
2109        Value::Sq8Vector(q) => {
2110            let cells: Vec<String> = spg_storage::quantize::dequantize(q)
2111                .iter()
2112                .map(|x| format!("{x}"))
2113                .collect();
2114            format!("[{}]", cells.join(", "))
2115        }
2116        // v6.0.3: HalfVector cells dequantise bit-exactly to f32
2117        // for SELECT output.
2118        Value::HalfVector(h) => {
2119            let cells: Vec<String> = h.to_f32_vec().iter().map(|x| format!("{x}")).collect();
2120            format!("[{}]", cells.join(", "))
2121        }
2122        Value::Numeric { scaled, scale } => format_numeric(*scaled, *scale),
2123        Value::Date(d) => format_date(*d),
2124        Value::Timestamp(t) => format_timestamp(*t),
2125        Value::Interval { months, micros } => format_interval(*months, *micros),
2126        Value::Null => "NULL".into(),
2127        // v7.10.4 — BYTEA renders as PG hex form.
2128        Value::Bytes(b) => format_bytea_hex(b),
2129        // v7.10.9 — TEXT[] / INT[] / BIGINT[] render PG external form.
2130        Value::TextArray(items) => format_text_array(items),
2131        Value::IntArray(items) => format_int_array(items),
2132        Value::BigIntArray(items) => format_bigint_array(items),
2133        // v7.12.0 — tsvector / tsquery render PG external form.
2134        Value::TsVector(lexs) => format_tsvector(lexs),
2135        Value::TsQuery(ast) => format_tsquery(ast),
2136        // v7.5.0 — #[non_exhaustive] fallback for future Value variants.
2137        _ => format!("{v:?}"),
2138    }
2139}
2140
2141/// Render a `Date` (days since epoch) as `YYYY-MM-DD`. Negative values
2142/// for pre-1970 dates render with a leading `-` on the year.
2143pub fn format_date(days: i32) -> String {
2144    let (y, m, d) = civil_from_days(days);
2145    format!("{y:04}-{m:02}-{d:02}")
2146}
2147
2148/// Render a `Timestamp` (microseconds since epoch) as
2149/// `YYYY-MM-DD HH:MM:SS[.fff...]`. Trailing-zero fractional digits are
2150/// dropped; a whole-second value has no fractional part.
2151pub fn format_timestamp(micros: i64) -> String {
2152    const MICROS_PER_DAY: i64 = 86_400_000_000;
2153    // Split into day + intra-day part with proper floor division so
2154    // negative timestamps render right too.
2155    let days = micros.div_euclid(MICROS_PER_DAY);
2156    let day_micros = micros.rem_euclid(MICROS_PER_DAY);
2157    let day_i32 = i32::try_from(days).unwrap_or(i32::MAX);
2158    let (y, m, d) = civil_from_days(day_i32);
2159    let secs = day_micros / 1_000_000;
2160    let frac = day_micros % 1_000_000;
2161    let hh = secs / 3600;
2162    let mm = (secs / 60) % 60;
2163    let ss = secs % 60;
2164    if frac == 0 {
2165        format!("{y:04}-{m:02}-{d:02} {hh:02}:{mm:02}:{ss:02}")
2166    } else {
2167        // Strip trailing zeros from the 6-digit fractional component.
2168        let raw = format!("{frac:06}");
2169        let trimmed = raw.trim_end_matches('0');
2170        format!("{y:04}-{m:02}-{d:02} {hh:02}:{mm:02}:{ss:02}.{trimmed}")
2171    }
2172}
2173
2174/// Howard Hinnant's `civil_from_days` — converts days since the Unix
2175/// epoch back to a proleptic-Gregorian (year, month, day) triple. Both
2176/// directions of this calendar conversion live in `eval.rs` so the
2177/// engine never reaches for `std` time facilities.
2178#[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
2179fn civil_from_days(days: i32) -> (i32, u32, u32) {
2180    let z = i64::from(days) + 719_468;
2181    let era = z.div_euclid(146_097);
2182    // doe ∈ [0, 146_097); fits in u32 with room to spare. Same for
2183    // every other quantity below — `as u32` truncations are safe by
2184    // construction.
2185    let doe = (z - era * 146_097) as u32;
2186    let yoe = (doe.saturating_sub(doe / 1460) + doe / 36524 - doe / 146_096) / 365;
2187    let y_base = i64::from(yoe) + era * 400;
2188    let doy = doe.saturating_sub(365 * yoe + yoe / 4 - yoe / 100);
2189    let mp = (5 * doy + 2) / 153;
2190    let d = doy.saturating_sub((153 * mp + 2) / 5) + 1;
2191    let m = if mp < 10 { mp + 3 } else { mp - 9 };
2192    let y = if m <= 2 { y_base + 1 } else { y_base };
2193    (y as i32, m, d)
2194}
2195
2196/// Inverse of `civil_from_days` — converts (year, month, day) to days
2197/// since 1970-01-01. Out-of-range months / days saturate.
2198#[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
2199pub fn days_from_civil(y: i32, m: u32, d: u32) -> i32 {
2200    let y_adj = if m <= 2 {
2201        i64::from(y) - 1
2202    } else {
2203        i64::from(y)
2204    };
2205    let era = y_adj.div_euclid(400);
2206    let yoe = (y_adj - era * 400) as u32;
2207    let doy = (153 * (if m > 2 { m - 3 } else { m + 9 }) + 2) / 5 + d.saturating_sub(1);
2208    let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
2209    let total = era * 146_097 + i64::from(doe) - 719_468;
2210    i32::try_from(total).unwrap_or(i32::MAX)
2211}
2212
2213/// Parse `YYYY-MM-DD` into a `Date` (days since Unix epoch). Returns
2214/// `None` on shape / numeric failure; the engine surfaces that as a
2215/// `TypeMismatch` with the original text included.
2216pub fn parse_date_literal(s: &str) -> Option<i32> {
2217    let bytes = s.as_bytes();
2218    if bytes.len() != 10 || bytes[4] != b'-' || bytes[7] != b'-' {
2219        return None;
2220    }
2221    let y: i32 = s[0..4].parse().ok()?;
2222    let m: u32 = s[5..7].parse().ok()?;
2223    let d: u32 = s[8..10].parse().ok()?;
2224    if !(1..=12).contains(&m) || !(1..=31).contains(&d) {
2225        return None;
2226    }
2227    Some(days_from_civil(y, m, d))
2228}
2229
2230/// Parse `YYYY-MM-DD[ HH:MM:SS[.ffffff]]` into a `Timestamp`
2231/// (microseconds since Unix epoch). The time portion is optional;
2232/// missing → midnight. The fractional portion accepts 1–6 digits and
2233/// pads with zeros to microseconds.
2234pub fn parse_timestamp_literal(s: &str) -> Option<i64> {
2235    let trimmed = s.trim();
2236    let (date_part, time_part) = match trimmed.find([' ', 'T']) {
2237        Some(i) => (&trimmed[..i], Some(&trimmed[i + 1..])),
2238        None => (trimmed, None),
2239    };
2240    let days = parse_date_literal(date_part)?;
2241    let day_micros = match time_part {
2242        None => 0,
2243        Some(t) => parse_time_of_day_micros(t)?,
2244    };
2245    Some(i64::from(days) * 86_400_000_000 + day_micros)
2246}
2247
2248fn parse_time_of_day_micros(t: &str) -> Option<i64> {
2249    let (time, frac_str) = match t.split_once('.') {
2250        Some((a, b)) => (a, Some(b)),
2251        None => (t, None),
2252    };
2253    let bytes = time.as_bytes();
2254    if bytes.len() != 8 || bytes[2] != b':' || bytes[5] != b':' {
2255        return None;
2256    }
2257    let hh: i64 = time[0..2].parse().ok()?;
2258    let mm: i64 = time[3..5].parse().ok()?;
2259    let ss: i64 = time[6..8].parse().ok()?;
2260    if !(0..24).contains(&hh) || !(0..60).contains(&mm) || !(0..60).contains(&ss) {
2261        return None;
2262    }
2263    let frac_micros: i64 = match frac_str {
2264        None => 0,
2265        Some(f) => {
2266            // Pad right with zeros to 6 digits, then truncate extras.
2267            if f.is_empty() || f.len() > 9 {
2268                return None;
2269            }
2270            let mut padded = String::with_capacity(6);
2271            padded.push_str(&f[..f.len().min(6)]);
2272            while padded.len() < 6 {
2273                padded.push('0');
2274            }
2275            padded.parse().ok()?
2276        }
2277    };
2278    Some(((hh * 3600 + mm * 60 + ss) * 1_000_000) + frac_micros)
2279}
2280
2281/// Render an `Interval { months, micros }` in a PG-ish shape. The output
2282/// mirrors `psql`'s text format: years/months from the months part,
2283/// days/HH:MM:SS[.frac] from the microsecond part. Empty parts are
2284/// omitted; an all-zero interval renders as `0`.
2285pub fn format_interval(months: i32, micros: i64) -> String {
2286    const MICROS_PER_DAY: i64 = 86_400_000_000;
2287    let mut parts: Vec<String> = Vec::new();
2288    let years = months / 12;
2289    let mons = months % 12;
2290    // PG renders the unit in the singular only for `+1`; `-1` and any
2291    // other value pluralise. Helper closes over that rule.
2292    let unit = |n: i64, singular: &'static str, plural: &'static str| -> &'static str {
2293        if n == 1 { singular } else { plural }
2294    };
2295    if years != 0 {
2296        parts.push(format!(
2297            "{years} {}",
2298            unit(i64::from(years), "year", "years")
2299        ));
2300    }
2301    if mons != 0 {
2302        parts.push(format!("{mons} {}", unit(i64::from(mons), "mon", "mons")));
2303    }
2304    let days = micros / MICROS_PER_DAY;
2305    let mut rem = micros % MICROS_PER_DAY;
2306    if days != 0 {
2307        parts.push(format!("{days} {}", unit(days, "day", "days")));
2308    }
2309    if rem != 0 {
2310        let neg = rem < 0;
2311        if neg {
2312            rem = -rem;
2313        }
2314        let secs = rem / 1_000_000;
2315        let frac = rem % 1_000_000;
2316        let hh = secs / 3600;
2317        let mm = (secs / 60) % 60;
2318        let ss = secs % 60;
2319        let sign = if neg { "-" } else { "" };
2320        if frac == 0 {
2321            parts.push(format!("{sign}{hh:02}:{mm:02}:{ss:02}"));
2322        } else {
2323            let raw = format!("{frac:06}");
2324            let trimmed = raw.trim_end_matches('0');
2325            parts.push(format!("{sign}{hh:02}:{mm:02}:{ss:02}.{trimmed}"));
2326        }
2327    }
2328    if parts.is_empty() {
2329        "0".into()
2330    } else {
2331        parts.join(" ")
2332    }
2333}
2334
2335/// Add `months` (signed) to a `(year, month, day)` triple using PG's
2336/// clamp-to-last-day rule (so `'2024-01-31' + 1 month` → `'2024-02-29'`).
2337fn add_months_to_civil(y: i32, m: u32, d: u32, months: i32) -> (i32, u32, u32) {
2338    let total_months = i64::from(y) * 12 + i64::from(m) - 1 + i64::from(months);
2339    let new_year = i32::try_from(total_months.div_euclid(12)).unwrap_or(i32::MAX);
2340    let new_month_zero = total_months.rem_euclid(12);
2341    #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
2342    let new_month = (new_month_zero as u32) + 1;
2343    let max_day = days_in_month(new_year, new_month);
2344    (new_year, new_month, d.min(max_day))
2345}
2346
2347const fn days_in_month(y: i32, m: u32) -> u32 {
2348    match m {
2349        1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
2350        2 => {
2351            // Proleptic Gregorian leap rule.
2352            if y.rem_euclid(4) == 0 && (y.rem_euclid(100) != 0 || y.rem_euclid(400) == 0) {
2353                29
2354            } else {
2355                28
2356            }
2357        }
2358        // 4 / 6 / 9 / 11 plus any out-of-range month (callers normalise
2359        // first, but be defensive) get the 30-day fallback.
2360        _ => 30,
2361    }
2362}
2363
2364/// v7.10.9 — render a TEXT[] in PG's external array form
2365/// (`{a,b,NULL}`). Elements containing whitespace, commas,
2366/// quotes, or braces get double-quoted with `\\` / `\"` escapes.
2367/// NULL elements use the literal token `NULL`. Public so the
2368/// wire layer can produce the canonical text-mode encoding.
2369pub fn format_text_array(items: &[Option<String>]) -> String {
2370    let mut out = String::with_capacity(2 + items.len() * 8);
2371    out.push('{');
2372    for (i, item) in items.iter().enumerate() {
2373        if i > 0 {
2374            out.push(',');
2375        }
2376        match item {
2377            None => out.push_str("NULL"),
2378            Some(s) => {
2379                let needs_quote = s.is_empty()
2380                    || s.eq_ignore_ascii_case("NULL")
2381                    || s.chars()
2382                        .any(|c| matches!(c, ',' | '{' | '}' | '"' | '\\' | ' ' | '\t'));
2383                if needs_quote {
2384                    out.push('"');
2385                    for c in s.chars() {
2386                        if c == '"' || c == '\\' {
2387                            out.push('\\');
2388                        }
2389                        out.push(c);
2390                    }
2391                    out.push('"');
2392                } else {
2393                    out.push_str(s);
2394                }
2395            }
2396        }
2397    }
2398    out.push('}');
2399    out
2400}
2401
2402/// v7.11.14 — render an INT[] in PG's external array form
2403/// (`{1,2,NULL}`). Integer payloads never need quoting. NULL
2404/// elements use the literal token `NULL`.
2405pub fn format_int_array(items: &[Option<i32>]) -> String {
2406    let mut out = String::with_capacity(2 + items.len() * 4);
2407    out.push('{');
2408    for (i, item) in items.iter().enumerate() {
2409        if i > 0 {
2410            out.push(',');
2411        }
2412        match item {
2413            None => out.push_str("NULL"),
2414            Some(n) => out.push_str(&n.to_string()),
2415        }
2416    }
2417    out.push('}');
2418    out
2419}
2420
2421/// v7.11.14 — render a BIGINT[] in PG's external array form
2422/// (`{1,2,NULL}`).
2423pub fn format_bigint_array(items: &[Option<i64>]) -> String {
2424    let mut out = String::with_capacity(2 + items.len() * 6);
2425    out.push('{');
2426    for (i, item) in items.iter().enumerate() {
2427        if i > 0 {
2428            out.push(',');
2429        }
2430        match item {
2431            None => out.push_str("NULL"),
2432            Some(n) => out.push_str(&n.to_string()),
2433        }
2434    }
2435    out.push('}');
2436    out
2437}
2438
2439/// v7.12.0 — render a `tsvector` in PG's external form:
2440/// `'lex':1,2A 'word':3` (single-quoted lexemes, optional
2441/// `:positions`, optional weight letter `A/B/C/D` per position).
2442/// Lexemes already arrive sorted + deduped from the engine. Used
2443/// by the wire layer (OID 3614) and by SELECT-text output.
2444pub fn format_tsvector(lexs: &[TsLexeme]) -> String {
2445    let mut out = String::with_capacity(lexs.len() * 12);
2446    for (i, l) in lexs.iter().enumerate() {
2447        if i > 0 {
2448            out.push(' ');
2449        }
2450        out.push('\'');
2451        for c in l.word.chars() {
2452            if c == '\'' {
2453                out.push('\'');
2454            }
2455            out.push(c);
2456        }
2457        out.push('\'');
2458        if !l.positions.is_empty() {
2459            for (pi, p) in l.positions.iter().enumerate() {
2460                out.push(if pi == 0 { ':' } else { ',' });
2461                out.push_str(&p.to_string());
2462            }
2463            // v7.12.0 — weight is per-lexeme (the v7.12 design
2464            // collapses PG's per-position weight into one letter).
2465            // Emit once after the last position; default `D`
2466            // (weight=0) stays implicit.
2467            match l.weight {
2468                3 => out.push('A'),
2469                2 => out.push('B'),
2470                1 => out.push('C'),
2471                _ => {}
2472            }
2473        }
2474    }
2475    out
2476}
2477
2478/// v7.12.0 — render a `tsquery` in PG's external form. Operator
2479/// precedence: `!` > `&` > `|`. Phrase distance shown as `<N>`.
2480pub fn format_tsquery(ast: &TsQueryAst) -> String {
2481    fn go(ast: &TsQueryAst, parent_prec: u8, out: &mut String) {
2482        // 0 = top, 1 = OR, 2 = AND, 3 = NOT/Phrase, 4 = atom.
2483        let (own_prec, write_self): (u8, &dyn Fn(&mut String)) = match ast {
2484            TsQueryAst::Or(_, _) => (1, &|_| {}),
2485            TsQueryAst::And(_, _) | TsQueryAst::Phrase { .. } => (2, &|_| {}),
2486            TsQueryAst::Not(_) => (3, &|_| {}),
2487            TsQueryAst::Term { .. } => (4, &|_| {}),
2488        };
2489        let need_parens = own_prec < parent_prec;
2490        if need_parens {
2491            out.push('(');
2492        }
2493        match ast {
2494            TsQueryAst::Term { word, .. } => {
2495                out.push('\'');
2496                for c in word.chars() {
2497                    if c == '\'' {
2498                        out.push('\'');
2499                    }
2500                    out.push(c);
2501                }
2502                out.push('\'');
2503            }
2504            TsQueryAst::And(a, b) => {
2505                go(a, own_prec, out);
2506                out.push_str(" & ");
2507                go(b, own_prec, out);
2508            }
2509            TsQueryAst::Or(a, b) => {
2510                go(a, own_prec, out);
2511                out.push_str(" | ");
2512                go(b, own_prec, out);
2513            }
2514            TsQueryAst::Not(x) => {
2515                out.push('!');
2516                go(x, own_prec, out);
2517            }
2518            TsQueryAst::Phrase {
2519                left,
2520                right,
2521                distance,
2522            } => {
2523                go(left, own_prec, out);
2524                out.push_str(&alloc::format!(" <{distance}> "));
2525                go(right, own_prec, out);
2526            }
2527        }
2528        write_self(out);
2529        if need_parens {
2530            out.push(')');
2531        }
2532    }
2533    let mut out = String::new();
2534    go(ast, 0, &mut out);
2535    out
2536}
2537
2538/// v7.12.0 — decode PG external form `'word':1,2A 'other':3` into
2539/// a `Vec<TsLexeme>`. Lexemes are sorted ascending by `word` (with
2540/// duplicates merged on positions) so the output matches the
2541/// engine invariant. Empty input yields an empty vector.
2542///
2543/// v7.12.0 only ships the cast-literal entry. Full `to_tsvector`
2544/// (Unicode word-split + Porter stemming + stopwords) lands in
2545/// v7.12.1.
2546pub fn decode_tsvector_external(s: &str) -> Result<Vec<TsLexeme>, EvalError> {
2547    let mut out: Vec<TsLexeme> = Vec::new();
2548    let mut i = 0;
2549    let bytes = s.as_bytes();
2550    while i < bytes.len() {
2551        while i < bytes.len() && bytes[i].is_ascii_whitespace() {
2552            i += 1;
2553        }
2554        if i >= bytes.len() {
2555            break;
2556        }
2557        // Quoted form `'word'` (with embedded `''` for a literal
2558        // single quote, mirroring PG).
2559        let word = if bytes[i] == b'\'' {
2560            i += 1;
2561            let mut w = String::new();
2562            loop {
2563                if i >= bytes.len() {
2564                    return Err(EvalError::TypeMismatch {
2565                        detail: "tsvector literal: unterminated quoted lexeme".into(),
2566                    });
2567                }
2568                let b = bytes[i];
2569                if b == b'\'' {
2570                    if i + 1 < bytes.len() && bytes[i + 1] == b'\'' {
2571                        w.push('\'');
2572                        i += 2;
2573                    } else {
2574                        i += 1;
2575                        break;
2576                    }
2577                } else {
2578                    w.push(b as char);
2579                    i += 1;
2580                }
2581            }
2582            w
2583        } else {
2584            // Bare form — read until whitespace, ':' or end.
2585            let start = i;
2586            while i < bytes.len() && !bytes[i].is_ascii_whitespace() && bytes[i] != b':' {
2587                i += 1;
2588            }
2589            core::str::from_utf8(&bytes[start..i])
2590                .map_err(|_| EvalError::TypeMismatch {
2591                    detail: "tsvector literal: non-UTF-8 lexeme".into(),
2592                })?
2593                .to_string()
2594        };
2595        if word.is_empty() {
2596            return Err(EvalError::TypeMismatch {
2597                detail: "tsvector literal: empty lexeme".into(),
2598            });
2599        }
2600        // Optional `:pos[,pos][,pos]`. Each position is u16; each
2601        // may carry a trailing weight letter A/B/C/D.
2602        let mut positions: Vec<u16> = Vec::new();
2603        let mut weight: u8 = 0;
2604        if i < bytes.len() && bytes[i] == b':' {
2605            i += 1;
2606            loop {
2607                let start = i;
2608                while i < bytes.len() && bytes[i].is_ascii_digit() {
2609                    i += 1;
2610                }
2611                if start == i {
2612                    return Err(EvalError::TypeMismatch {
2613                        detail: "tsvector literal: expected digit after ':'".into(),
2614                    });
2615                }
2616                let num: u16 = core::str::from_utf8(&bytes[start..i])
2617                    .expect("ascii digits")
2618                    .parse()
2619                    .map_err(|_| EvalError::TypeMismatch {
2620                        detail: alloc::format!(
2621                            "tsvector literal: position {} overflows u16",
2622                            core::str::from_utf8(&bytes[start..i]).unwrap_or("?")
2623                        ),
2624                    })?;
2625                positions.push(num);
2626                if i < bytes.len() {
2627                    let w = bytes[i];
2628                    if matches!(w, b'A' | b'B' | b'C' | b'D') {
2629                        weight = match w {
2630                            b'A' => 3,
2631                            b'B' => 2,
2632                            b'C' => 1,
2633                            _ => 0,
2634                        };
2635                        i += 1;
2636                    }
2637                }
2638                if i < bytes.len() && bytes[i] == b',' {
2639                    i += 1;
2640                    continue;
2641                }
2642                break;
2643            }
2644        }
2645        positions.sort_unstable();
2646        positions.dedup();
2647        // Merge into the output vector — sorted insert by word,
2648        // duplicate words merge positions.
2649        match out.binary_search_by(|l| l.word.as_str().cmp(word.as_str())) {
2650            Ok(idx) => {
2651                for p in positions {
2652                    if !out[idx].positions.contains(&p) {
2653                        out[idx].positions.push(p);
2654                    }
2655                }
2656                out[idx].positions.sort_unstable();
2657                if weight != 0 {
2658                    out[idx].weight = weight;
2659                }
2660            }
2661            Err(idx) => {
2662                out.insert(
2663                    idx,
2664                    TsLexeme {
2665                        word,
2666                        positions,
2667                        weight,
2668                    },
2669                );
2670            }
2671        }
2672    }
2673    Ok(out)
2674}
2675
2676/// v7.12.0 — decode PG external form `'foo' & 'bar' | !'baz'`
2677/// into a `TsQueryAst`. v7.12.0 supports the canonical
2678/// `to_tsquery` surface: single-quoted lexemes, `&` / `|` / `!`,
2679/// parens, and phrase `<N>`. Bare lexemes are accepted too. Full
2680/// `plainto_tsquery` / `websearch_to_tsquery` arrive in v7.12.1.
2681pub fn decode_tsquery_external(s: &str) -> Result<TsQueryAst, EvalError> {
2682    let mut p = TsQueryParser {
2683        bytes: s.as_bytes(),
2684        pos: 0,
2685    };
2686    p.skip_ws();
2687    if p.pos >= p.bytes.len() {
2688        return Err(EvalError::TypeMismatch {
2689            detail: "tsquery literal: empty".into(),
2690        });
2691    }
2692    let ast = p.parse_or()?;
2693    p.skip_ws();
2694    if p.pos < p.bytes.len() {
2695        return Err(EvalError::TypeMismatch {
2696            detail: alloc::format!("tsquery literal: trailing garbage at offset {}", p.pos),
2697        });
2698    }
2699    Ok(ast)
2700}
2701
2702struct TsQueryParser<'a> {
2703    bytes: &'a [u8],
2704    pos: usize,
2705}
2706
2707impl<'a> TsQueryParser<'a> {
2708    fn skip_ws(&mut self) {
2709        while self.pos < self.bytes.len() && self.bytes[self.pos].is_ascii_whitespace() {
2710            self.pos += 1;
2711        }
2712    }
2713    fn peek(&self) -> Option<u8> {
2714        self.bytes.get(self.pos).copied()
2715    }
2716    fn parse_or(&mut self) -> Result<TsQueryAst, EvalError> {
2717        let mut lhs = self.parse_and()?;
2718        loop {
2719            self.skip_ws();
2720            if self.peek() != Some(b'|') {
2721                return Ok(lhs);
2722            }
2723            self.pos += 1;
2724            let rhs = self.parse_and()?;
2725            lhs = TsQueryAst::Or(Box::new(lhs), Box::new(rhs));
2726        }
2727    }
2728    fn parse_and(&mut self) -> Result<TsQueryAst, EvalError> {
2729        let mut lhs = self.parse_unary()?;
2730        loop {
2731            self.skip_ws();
2732            match self.peek() {
2733                Some(b'&') => {
2734                    self.pos += 1;
2735                    let rhs = self.parse_unary()?;
2736                    lhs = TsQueryAst::And(Box::new(lhs), Box::new(rhs));
2737                }
2738                Some(b'<') => {
2739                    // Phrase distance `<N>`.
2740                    self.pos += 1;
2741                    let start = self.pos;
2742                    while self.pos < self.bytes.len() && self.bytes[self.pos].is_ascii_digit() {
2743                        self.pos += 1;
2744                    }
2745                    if start == self.pos || self.peek() != Some(b'>') {
2746                        return Err(EvalError::TypeMismatch {
2747                            detail: "tsquery literal: malformed <N> phrase operator".into(),
2748                        });
2749                    }
2750                    let n: u16 = core::str::from_utf8(&self.bytes[start..self.pos])
2751                        .expect("ascii digits")
2752                        .parse()
2753                        .map_err(|_| EvalError::TypeMismatch {
2754                            detail: "tsquery literal: phrase distance overflows u16".into(),
2755                        })?;
2756                    self.pos += 1; // consume '>'
2757                    let rhs = self.parse_unary()?;
2758                    lhs = TsQueryAst::Phrase {
2759                        left: Box::new(lhs),
2760                        right: Box::new(rhs),
2761                        distance: n,
2762                    };
2763                }
2764                _ => return Ok(lhs),
2765            }
2766        }
2767    }
2768    fn parse_unary(&mut self) -> Result<TsQueryAst, EvalError> {
2769        self.skip_ws();
2770        if self.peek() == Some(b'!') {
2771            self.pos += 1;
2772            let inner = self.parse_unary()?;
2773            return Ok(TsQueryAst::Not(Box::new(inner)));
2774        }
2775        self.parse_atom()
2776    }
2777    fn parse_atom(&mut self) -> Result<TsQueryAst, EvalError> {
2778        self.skip_ws();
2779        match self.peek() {
2780            Some(b'(') => {
2781                self.pos += 1;
2782                let inner = self.parse_or()?;
2783                self.skip_ws();
2784                if self.peek() != Some(b')') {
2785                    return Err(EvalError::TypeMismatch {
2786                        detail: "tsquery literal: missing ')'".into(),
2787                    });
2788                }
2789                self.pos += 1;
2790                Ok(inner)
2791            }
2792            Some(b'\'') => {
2793                self.pos += 1;
2794                let mut w = String::new();
2795                loop {
2796                    match self.peek() {
2797                        None => {
2798                            return Err(EvalError::TypeMismatch {
2799                                detail: "tsquery literal: unterminated quoted lexeme".into(),
2800                            });
2801                        }
2802                        Some(b'\'') => {
2803                            if self.bytes.get(self.pos + 1) == Some(&b'\'') {
2804                                w.push('\'');
2805                                self.pos += 2;
2806                            } else {
2807                                self.pos += 1;
2808                                break;
2809                            }
2810                        }
2811                        Some(b) => {
2812                            w.push(b as char);
2813                            self.pos += 1;
2814                        }
2815                    }
2816                }
2817                // Optional `:WEIGHT_MASK` (digit-mask) — v7.12.0
2818                // accepts but always stores 0 (any).
2819                self.skip_weight_suffix();
2820                Ok(TsQueryAst::Term {
2821                    word: w,
2822                    weight_mask: 0,
2823                })
2824            }
2825            Some(b) if b.is_ascii_alphanumeric() || b == b'_' => {
2826                let start = self.pos;
2827                while self.pos < self.bytes.len() {
2828                    let c = self.bytes[self.pos];
2829                    if c.is_ascii_alphanumeric() || c == b'_' {
2830                        self.pos += 1;
2831                    } else {
2832                        break;
2833                    }
2834                }
2835                let w = core::str::from_utf8(&self.bytes[start..self.pos])
2836                    .map_err(|_| EvalError::TypeMismatch {
2837                        detail: "tsquery literal: non-UTF-8 lexeme".into(),
2838                    })?
2839                    .to_string();
2840                self.skip_weight_suffix();
2841                Ok(TsQueryAst::Term {
2842                    word: w,
2843                    weight_mask: 0,
2844                })
2845            }
2846            Some(b) => Err(EvalError::TypeMismatch {
2847                detail: alloc::format!(
2848                    "tsquery literal: unexpected byte {:?} at offset {}",
2849                    b as char,
2850                    self.pos
2851                ),
2852            }),
2853            None => Err(EvalError::TypeMismatch {
2854                detail: "tsquery literal: expected term".into(),
2855            }),
2856        }
2857    }
2858    fn skip_weight_suffix(&mut self) {
2859        if self.peek() != Some(b':') {
2860            return;
2861        }
2862        self.pos += 1;
2863        while let Some(b) = self.peek() {
2864            if matches!(
2865                b,
2866                b'A' | b'B' | b'C' | b'D' | b'a' | b'b' | b'c' | b'd' | b'*'
2867            ) || b.is_ascii_digit()
2868            {
2869                self.pos += 1;
2870            } else {
2871                break;
2872            }
2873        }
2874    }
2875}
2876
2877/// v7.10.4 — render a BYTEA payload in PG's hex output format
2878/// (`\x` prefix, lowercase hex pairs). Public so the wire layer
2879/// can emit the canonical bytea-as-text representation.
2880pub fn format_bytea_hex(b: &[u8]) -> String {
2881    let mut out = String::with_capacity(2 + 2 * b.len());
2882    out.push_str("\\x");
2883    const HEX: &[u8; 16] = b"0123456789abcdef";
2884    for byte in b {
2885        out.push(HEX[(byte >> 4) as usize] as char);
2886        out.push(HEX[(byte & 0x0F) as usize] as char);
2887    }
2888    out
2889}
2890
2891/// Render a `Numeric { scaled, scale }` as its decimal text form.
2892/// Negative `scaled` prepends `-` to the absolute value's digits; the
2893/// integer / fractional split is by character count, padding the
2894/// fractional side with leading zeros to exactly `scale` chars.
2895pub fn format_numeric(scaled: i128, scale: u8) -> String {
2896    if scale == 0 {
2897        return format!("{scaled}");
2898    }
2899    let negative = scaled < 0;
2900    let mag_str = scaled.unsigned_abs().to_string();
2901    let mag_bytes = mag_str.as_bytes();
2902    let scale_u = scale as usize;
2903    let mut out = String::with_capacity(mag_str.len() + 3);
2904    if negative {
2905        out.push('-');
2906    }
2907    if mag_bytes.len() <= scale_u {
2908        out.push('0');
2909        out.push('.');
2910        for _ in mag_bytes.len()..scale_u {
2911            out.push('0');
2912        }
2913        out.push_str(&mag_str);
2914    } else {
2915        let split = mag_bytes.len() - scale_u;
2916        out.push_str(&mag_str[..split]);
2917        out.push('.');
2918        out.push_str(&mag_str[split..]);
2919    }
2920    out
2921}
2922
2923fn cast_numeric_to_int(v: Value) -> Result<Value, EvalError> {
2924    match v {
2925        Value::Int(n) => Ok(Value::Int(n)),
2926        Value::BigInt(n) => i32::try_from(n)
2927            .map(Value::Int)
2928            .map_err(|_| EvalError::TypeMismatch {
2929                detail: format!("bigint {n} does not fit in int"),
2930            }),
2931        #[allow(clippy::cast_possible_truncation)]
2932        Value::Float(x) => Ok(Value::Int(x as i32)),
2933        Value::Text(s) => {
2934            s.trim()
2935                .parse::<i32>()
2936                .map(Value::Int)
2937                .map_err(|_| EvalError::TypeMismatch {
2938                    detail: format!("cannot parse {s:?} as int"),
2939                })
2940        }
2941        Value::Bool(b) => Ok(Value::Int(i32::from(b))),
2942        other => Err(EvalError::TypeMismatch {
2943            detail: format!("cannot cast {:?} to int", other.data_type()),
2944        }),
2945    }
2946}
2947
2948fn cast_numeric_to_bigint(v: Value) -> Result<Value, EvalError> {
2949    match v {
2950        Value::Int(n) => Ok(Value::BigInt(i64::from(n))),
2951        Value::BigInt(n) => Ok(Value::BigInt(n)),
2952        #[allow(clippy::cast_possible_truncation)]
2953        Value::Float(x) => Ok(Value::BigInt(x as i64)),
2954        Value::Text(s) => {
2955            s.trim()
2956                .parse::<i64>()
2957                .map(Value::BigInt)
2958                .map_err(|_| EvalError::TypeMismatch {
2959                    detail: format!("cannot parse {s:?} as bigint"),
2960                })
2961        }
2962        Value::Bool(b) => Ok(Value::BigInt(i64::from(b))),
2963        other => Err(EvalError::TypeMismatch {
2964            detail: format!("cannot cast {:?} to bigint", other.data_type()),
2965        }),
2966    }
2967}
2968
2969fn cast_numeric_to_float(v: Value) -> Result<Value, EvalError> {
2970    match v {
2971        Value::Int(n) => Ok(Value::Float(f64::from(n))),
2972        #[allow(clippy::cast_precision_loss)]
2973        Value::BigInt(n) => Ok(Value::Float(n as f64)),
2974        Value::Float(x) => Ok(Value::Float(x)),
2975        Value::Text(s) => {
2976            s.trim()
2977                .parse::<f64>()
2978                .map(Value::Float)
2979                .map_err(|_| EvalError::TypeMismatch {
2980                    detail: format!("cannot parse {s:?} as float"),
2981                })
2982        }
2983        other => Err(EvalError::TypeMismatch {
2984            detail: format!("cannot cast {:?} to float", other.data_type()),
2985        }),
2986    }
2987}
2988
2989fn cast_to_bool(v: Value) -> Result<Value, EvalError> {
2990    match v {
2991        Value::Bool(b) => Ok(Value::Bool(b)),
2992        Value::Int(n) => Ok(Value::Bool(n != 0)),
2993        Value::BigInt(n) => Ok(Value::Bool(n != 0)),
2994        Value::Text(s) => {
2995            let lo = s.trim().to_ascii_lowercase();
2996            match lo.as_str() {
2997                "true" | "t" | "yes" | "y" | "1" | "on" => Ok(Value::Bool(true)),
2998                "false" | "f" | "no" | "n" | "0" | "off" => Ok(Value::Bool(false)),
2999                _ => Err(EvalError::TypeMismatch {
3000                    detail: format!("cannot parse {s:?} as bool"),
3001                }),
3002            }
3003        }
3004        other => Err(EvalError::TypeMismatch {
3005            detail: format!("cannot cast {:?} to bool", other.data_type()),
3006        }),
3007    }
3008}
3009
3010/// Parse a `Value::Text("[1.0, 2.0, 3.0]")` into a `Value::Vector(..)`. Mirrors
3011/// pgvector's `'[..]'::vector` cast. NULL casts as NULL.
3012pub fn cast_to_vector(v: Value) -> Result<Value, EvalError> {
3013    match v {
3014        Value::Null => Ok(Value::Null),
3015        Value::Vector(v) => Ok(Value::Vector(v)),
3016        Value::Text(s) => parse_vector_text(&s)
3017            .map(Value::Vector)
3018            .ok_or(EvalError::TypeMismatch {
3019                detail: format!("cannot parse {s:?} as a vector literal"),
3020            }),
3021        other => Err(EvalError::TypeMismatch {
3022            detail: format!("::vector requires text input, got {:?}", other.data_type()),
3023        }),
3024    }
3025}
3026
3027/// Parse `"[1.0, 2.0, -3]"` into `Vec<f32>`. Returns `None` on malformed input.
3028fn parse_vector_text(s: &str) -> Option<Vec<f32>> {
3029    let trimmed = s.trim();
3030    let inner = trimmed.strip_prefix('[')?.strip_suffix(']')?;
3031    let trimmed_inner = inner.trim();
3032    if trimmed_inner.is_empty() {
3033        return Some(Vec::new());
3034    }
3035    let mut out = Vec::new();
3036    for part in trimmed_inner.split(',') {
3037        let f: f32 = part.trim().parse().ok()?;
3038        out.push(f);
3039    }
3040    Some(out)
3041}
3042
3043fn literal_to_value(l: &Literal) -> Value {
3044    match l {
3045        Literal::Integer(n) => {
3046            if let Ok(small) = i32::try_from(*n) {
3047                Value::Int(small)
3048            } else {
3049                Value::BigInt(*n)
3050            }
3051        }
3052        Literal::Float(x) => Value::Float(*x),
3053        Literal::String(s) => Value::Text(s.clone()),
3054        Literal::Vector(v) => Value::Vector(v.clone()),
3055        Literal::Bool(b) => Value::Bool(*b),
3056        Literal::Null => Value::Null,
3057        Literal::Interval { months, micros, .. } => Value::Interval {
3058            months: *months,
3059            micros: *micros,
3060        },
3061    }
3062}
3063
3064fn resolve_column(c: &ColumnName, row: &Row, ctx: &EvalContext<'_>) -> Result<Value, EvalError> {
3065    if let Some(q) = &c.qualifier {
3066        // Multi-table evaluation (joins): the synthesised schema uses
3067        // composite column names "alias.column" so we look that up
3068        // directly. Falls back to the single-table case below if the
3069        // composite isn't present.
3070        let composite = alloc::format!("{q}.{name}", name = c.name);
3071        if let Some(pos) = ctx.columns.iter().position(|s| s.name == composite) {
3072            return Ok(row.values[pos].clone());
3073        }
3074        let expected = ctx.table_alias.ok_or_else(|| EvalError::UnknownQualifier {
3075            qualifier: q.clone(),
3076        })?;
3077        if q != expected {
3078            return Err(EvalError::UnknownQualifier {
3079                qualifier: q.clone(),
3080            });
3081        }
3082    }
3083    if let Some(pos) = ctx.columns.iter().position(|s| s.name == c.name) {
3084        return Ok(row.values[pos].clone());
3085    }
3086    // Bare-name fallback for joined schemas: match any single composite
3087    // column ending in ".<name>"; ambiguity is an error.
3088    let suffix = alloc::format!(".{name}", name = c.name);
3089    let mut matches = ctx
3090        .columns
3091        .iter()
3092        .enumerate()
3093        .filter(|(_, s)| s.name.ends_with(&suffix));
3094    let first = matches.next();
3095    let extra = matches.next();
3096    match (first, extra) {
3097        (Some((pos, _)), None) => Ok(row.values[pos].clone()),
3098        (Some(_), Some(_)) => Err(EvalError::TypeMismatch {
3099            detail: alloc::format!("ambiguous column reference: {}", c.name),
3100        }),
3101        _ => Err(EvalError::ColumnNotFound {
3102            name: c.name.clone(),
3103        }),
3104    }
3105}
3106
3107fn apply_unary(op: UnOp, v: Value) -> Result<Value, EvalError> {
3108    match (op, v) {
3109        (_, Value::Null) => Ok(Value::Null),
3110        (UnOp::Neg, Value::Int(n)) => {
3111            n.checked_neg()
3112                .map(Value::Int)
3113                .ok_or(EvalError::TypeMismatch {
3114                    detail: "integer overflow on unary -".into(),
3115                })
3116        }
3117        (UnOp::Neg, Value::BigInt(n)) => {
3118            n.checked_neg()
3119                .map(Value::BigInt)
3120                .ok_or(EvalError::TypeMismatch {
3121                    detail: "bigint overflow on unary -".into(),
3122                })
3123        }
3124        (UnOp::Neg, Value::Float(x)) => Ok(Value::Float(-x)),
3125        (UnOp::Neg, other) => Err(EvalError::TypeMismatch {
3126            detail: format!("unary - applied to {:?}", other.data_type()),
3127        }),
3128        (UnOp::Not, Value::Bool(b)) => Ok(Value::Bool(!b)),
3129        (UnOp::Not, other) => Err(EvalError::TypeMismatch {
3130            detail: format!("NOT applied to {:?}", other.data_type()),
3131        }),
3132    }
3133}
3134
3135/// v7.9.27b — true when two values are "not distinct" per PG:
3136/// both NULL counts as equal; otherwise reduces to regular Eq.
3137fn values_not_distinct(l: &Value, r: &Value) -> bool {
3138    match (l, r) {
3139        (Value::Null, Value::Null) => true,
3140        (Value::Null, _) | (_, Value::Null) => false,
3141        _ => l == r,
3142    }
3143}
3144
3145fn apply_binary(op: BinOp, l: Value, r: Value) -> Result<Value, EvalError> {
3146    // SQL three-valued logic for AND / OR with NULL is special — handle before
3147    // the general NULL-propagation rule.
3148    if let BinOp::And = op {
3149        return and_3vl(l, r);
3150    }
3151    if let BinOp::Or = op {
3152        return or_3vl(l, r);
3153    }
3154    // v7.9.27b — IS [NOT] DISTINCT FROM. NULL-safe equality:
3155    // `NULL IS NOT DISTINCT FROM NULL` → true. mailrs pg_dump.
3156    if let BinOp::IsNotDistinctFrom = op {
3157        return Ok(Value::Bool(values_not_distinct(&l, &r)));
3158    }
3159    if let BinOp::IsDistinctFrom = op {
3160        return Ok(Value::Bool(!values_not_distinct(&l, &r)));
3161    }
3162    // Everything else: any NULL operand → NULL.
3163    if l.is_null() || r.is_null() {
3164        return Ok(Value::Null);
3165    }
3166    // NUMERIC arithmetic and comparisons run in fixed-point; promote
3167    // integers to a common NUMERIC scale and stay in i128 throughout.
3168    if matches!(l, Value::Numeric { .. }) || matches!(r, Value::Numeric { .. }) {
3169        return apply_binary_numeric(op, l, r);
3170    }
3171    // Date / Timestamp arithmetic. PG semantics:
3172    //   * date + int      → date  (int is days)
3173    //   * int + date      → date
3174    //   * date - int      → date
3175    //   * date - date     → int   (days, signed)
3176    //   * timestamp - timestamp → bigint (microseconds, signed)
3177    // Other date/time math (`timestamp + int`, INTERVAL) lands later.
3178    if let Some(result) = apply_binary_calendar(op, &l, &r)? {
3179        return Ok(result);
3180    }
3181    match op {
3182        BinOp::Add => arith(l, r, i64::checked_add, |a, b| a + b, "+"),
3183        BinOp::Sub => arith(l, r, i64::checked_sub, |a, b| a - b, "-"),
3184        BinOp::Mul => arith(l, r, i64::checked_mul, |a, b| a * b, "*"),
3185        BinOp::Div => div_op(l, r),
3186        BinOp::L2Distance => l2_distance(l, r),
3187        BinOp::InnerProduct => inner_product(l, r),
3188        BinOp::CosineDistance => cosine_distance(l, r),
3189        BinOp::Concat => Ok(text_concat(&l, &r)),
3190        BinOp::JsonGet => crate::json::path_get(&l, &r, false),
3191        BinOp::JsonGetText => crate::json::path_get(&l, &r, true),
3192        BinOp::JsonGetPath => crate::json::path_walk(&l, &r, false),
3193        BinOp::JsonGetPathText => crate::json::path_walk(&l, &r, true),
3194        BinOp::JsonContains => crate::json::contains(&l, &r),
3195        // v7.12.2 — `@@` match. NULL on either side → NULL; PG
3196        // accepts both orderings so we normalise.
3197        BinOp::TsMatch => ts_match(l, r),
3198        BinOp::Eq | BinOp::NotEq | BinOp::Lt | BinOp::LtEq | BinOp::Gt | BinOp::GtEq => {
3199            compare(op, &l, &r)
3200        }
3201        BinOp::And | BinOp::Or | BinOp::IsDistinctFrom | BinOp::IsNotDistinctFrom => {
3202            unreachable!("handled above")
3203        }
3204    }
3205}
3206
3207/// Calendar arithmetic. Returns `Some(value)` when the operand pair
3208/// is a date/time combo this function understands, `None` to let the
3209/// caller fall through to the regular numeric / text paths.
3210fn apply_binary_calendar(op: BinOp, l: &Value, r: &Value) -> Result<Option<Value>, EvalError> {
3211    let int_value = |v: &Value| -> Option<i64> {
3212        match v {
3213            Value::SmallInt(n) => Some(i64::from(*n)),
3214            Value::Int(n) => Some(i64::from(*n)),
3215            Value::BigInt(n) => Some(*n),
3216            _ => None,
3217        }
3218    };
3219    // Most-specific cases first — DATE-DATE / TS-TS subtraction before
3220    // DATE-integer subtraction, otherwise the latter swallows the
3221    // former with an `int_value(Date) = None` no-op fall-through.
3222    match (l, r) {
3223        (Value::Date(a), Value::Date(b)) if op == BinOp::Sub => {
3224            return Ok(Some(Value::BigInt(i64::from(*a) - i64::from(*b))));
3225        }
3226        (Value::Timestamp(a), Value::Timestamp(b)) if op == BinOp::Sub => {
3227            let delta = a.checked_sub(*b).ok_or(EvalError::TypeMismatch {
3228                detail: "TIMESTAMP - TIMESTAMP overflows i64 microseconds".into(),
3229            })?;
3230            return Ok(Some(Value::BigInt(delta)));
3231        }
3232        _ => {}
3233    }
3234    // INTERVAL arithmetic. PG: timestamp ± interval → timestamp,
3235    // date ± interval → date (if interval is pure days/months with no
3236    // sub-day component) else timestamp, interval ± interval → interval.
3237    if let Some(out) = apply_binary_interval(op, l, r)? {
3238        return Ok(Some(out));
3239    }
3240    match (l, r) {
3241        (Value::Date(d), other) if op == BinOp::Add => {
3242            if let Some(n) = int_value(other) {
3243                let days = i64::from(*d).saturating_add(n);
3244                let days32 = i32::try_from(days).map_err(|_| EvalError::TypeMismatch {
3245                    detail: "DATE + integer overflows DATE range".into(),
3246                })?;
3247                return Ok(Some(Value::Date(days32)));
3248            }
3249        }
3250        (other, Value::Date(d)) if op == BinOp::Add => {
3251            if let Some(n) = int_value(other) {
3252                let days = i64::from(*d).saturating_add(n);
3253                let days32 = i32::try_from(days).map_err(|_| EvalError::TypeMismatch {
3254                    detail: "integer + DATE overflows DATE range".into(),
3255                })?;
3256                return Ok(Some(Value::Date(days32)));
3257            }
3258        }
3259        (Value::Date(d), other) if op == BinOp::Sub => {
3260            if let Some(n) = int_value(other) {
3261                let days = i64::from(*d).saturating_sub(n);
3262                let days32 = i32::try_from(days).map_err(|_| EvalError::TypeMismatch {
3263                    detail: "DATE - integer overflows DATE range".into(),
3264                })?;
3265                return Ok(Some(Value::Date(days32)));
3266            }
3267        }
3268        _ => {}
3269    }
3270    Ok(None)
3271}
3272
3273/// INTERVAL-aware binary ops. Recognises:
3274///   timestamp ± interval → timestamp
3275///   date ± interval      → date (if interval is integral days/months only)
3276///                       → timestamp (if interval has sub-day micros)
3277///   interval ± interval  → interval
3278/// Commutative for `+`. Returns `None` for unrecognised operand pairs so
3279/// the caller can fall through.
3280fn apply_binary_interval(op: BinOp, l: &Value, r: &Value) -> Result<Option<Value>, EvalError> {
3281    // Normalise so the interval (if any) is always on the right for Add;
3282    // Sub stays left-handed because it isn't commutative.
3283    let (lhs, rhs, sign): (&Value, &Value, i64) = match (l, r, op) {
3284        (Value::Interval { .. }, _, BinOp::Add) => (r, l, 1),
3285        (_, Value::Interval { .. }, BinOp::Add) => (l, r, 1),
3286        (_, Value::Interval { .. }, BinOp::Sub) => (l, r, -1),
3287        _ => return Ok(None),
3288    };
3289    let Value::Interval {
3290        months: rhs_months,
3291        micros: rhs_us,
3292    } = rhs
3293    else {
3294        unreachable!("rhs guaranteed to be Interval by the match above");
3295    };
3296    let signed_months = i64::from(*rhs_months) * sign;
3297    let signed_micros = rhs_us.checked_mul(sign).ok_or(EvalError::TypeMismatch {
3298        detail: "INTERVAL micros overflows on negation".into(),
3299    })?;
3300    match lhs {
3301        Value::Timestamp(t) => Ok(Some(Value::Timestamp(add_interval_to_micros(
3302            *t,
3303            signed_months,
3304            signed_micros,
3305        )?))),
3306        Value::Date(d) => {
3307            // Date + interval stays a date when the interval has zero
3308            // sub-day microseconds; otherwise promote to TIMESTAMP at
3309            // midnight of the (months-shifted) date first.
3310            let day_aligned = signed_micros.rem_euclid(86_400_000_000) == 0;
3311            if day_aligned {
3312                let micros_per_day = 86_400_000_000_i64;
3313                let days_delta = signed_micros / micros_per_day;
3314                let shifted = shift_date_by_months(*d, signed_months)?;
3315                let new_days =
3316                    i64::from(shifted)
3317                        .checked_add(days_delta)
3318                        .ok_or(EvalError::TypeMismatch {
3319                            detail: "DATE ± INTERVAL overflows DATE range".into(),
3320                        })?;
3321                let days32 = i32::try_from(new_days).map_err(|_| EvalError::TypeMismatch {
3322                    detail: "DATE ± INTERVAL overflows DATE range".into(),
3323                })?;
3324                Ok(Some(Value::Date(days32)))
3325            } else {
3326                let base =
3327                    i64::from(*d)
3328                        .checked_mul(86_400_000_000)
3329                        .ok_or(EvalError::TypeMismatch {
3330                            detail: "DATE → TIMESTAMP lift overflows for INTERVAL math".into(),
3331                        })?;
3332                Ok(Some(Value::Timestamp(add_interval_to_micros(
3333                    base,
3334                    signed_months,
3335                    signed_micros,
3336                )?)))
3337            }
3338        }
3339        Value::Interval {
3340            months: lhs_months,
3341            micros: lhs_us,
3342        } => {
3343            let new_months = i64::from(*lhs_months)
3344                .checked_add(signed_months)
3345                .and_then(|n| i32::try_from(n).ok())
3346                .ok_or(EvalError::TypeMismatch {
3347                    detail: "INTERVAL ± INTERVAL months overflows i32".into(),
3348                })?;
3349            let new_micros = lhs_us
3350                .checked_add(signed_micros)
3351                .ok_or(EvalError::TypeMismatch {
3352                    detail: "INTERVAL ± INTERVAL micros overflows i64".into(),
3353                })?;
3354            Ok(Some(Value::Interval {
3355                months: new_months,
3356                micros: new_micros,
3357            }))
3358        }
3359        _ => Err(EvalError::TypeMismatch {
3360            detail: format!(
3361                "operator {op:?} not defined for {:?} and INTERVAL",
3362                lhs.data_type()
3363            ),
3364        }),
3365    }
3366}
3367
3368/// Shift a `Date` by a signed number of months using the PG clamp rule.
3369fn shift_date_by_months(d: i32, months: i64) -> Result<i32, EvalError> {
3370    let (y, m, day) = civil_from_days(d);
3371    let months_i32 = i32::try_from(months).map_err(|_| EvalError::TypeMismatch {
3372        detail: "INTERVAL months delta out of i32 range".into(),
3373    })?;
3374    let (ny, nm, nd) = add_months_to_civil(y, m, day, months_i32);
3375    Ok(days_from_civil(ny, nm, nd))
3376}
3377
3378/// Add (months, micros) to a `Timestamp` (microseconds since epoch).
3379/// Months part is applied through civil calendar with clamp-to-last-day;
3380/// micros part is plain i64 addition with overflow guard.
3381fn add_interval_to_micros(t: i64, months: i64, micros: i64) -> Result<i64, EvalError> {
3382    let mut out = t;
3383    if months != 0 {
3384        const MICROS_PER_DAY: i64 = 86_400_000_000;
3385        let days = out.div_euclid(MICROS_PER_DAY);
3386        let day_micros = out.rem_euclid(MICROS_PER_DAY);
3387        let day_i32 = i32::try_from(days).map_err(|_| EvalError::TypeMismatch {
3388            detail: "TIMESTAMP day component out of i32 range for INTERVAL months math".into(),
3389        })?;
3390        let shifted_days = shift_date_by_months(day_i32, months)?;
3391        out = i64::from(shifted_days)
3392            .checked_mul(MICROS_PER_DAY)
3393            .and_then(|n| n.checked_add(day_micros))
3394            .ok_or(EvalError::TypeMismatch {
3395                detail: "TIMESTAMP ± INTERVAL months overflows i64 microseconds".into(),
3396            })?;
3397    }
3398    out.checked_add(micros).ok_or(EvalError::TypeMismatch {
3399        detail: "TIMESTAMP ± INTERVAL micros overflows i64".into(),
3400    })
3401}
3402
3403/// Dispatch for any binary op when at least one operand is NUMERIC.
3404/// Other-side integers / floats are promoted to a NUMERIC at a common
3405/// scale; all add / sub / mul / div / compare paths stay in i128.
3406#[allow(clippy::needless_pass_by_value)] // mirrors `apply_binary`'s by-value calling convention
3407fn apply_binary_numeric(op: BinOp, l: Value, r: Value) -> Result<Value, EvalError> {
3408    // Float still wins — Numeric + Float coerces both to f64 and runs
3409    // through the float path. PG demotes Numeric to float in this mix
3410    // too (the documented behaviour for `numeric + double precision`).
3411    let float_path = matches!(l, Value::Float(_)) || matches!(r, Value::Float(_));
3412    if float_path {
3413        let af = as_f64(&l)?;
3414        let bf = as_f64(&r)?;
3415        return match op {
3416            BinOp::Add => Ok(Value::Float(af + bf)),
3417            BinOp::Sub => Ok(Value::Float(af - bf)),
3418            BinOp::Mul => Ok(Value::Float(af * bf)),
3419            BinOp::Div => {
3420                if bf == 0.0 {
3421                    Err(EvalError::DivisionByZero)
3422                } else {
3423                    Ok(Value::Float(af / bf))
3424                }
3425            }
3426            BinOp::Eq | BinOp::NotEq | BinOp::Lt | BinOp::LtEq | BinOp::Gt | BinOp::GtEq => {
3427                let ord = af.partial_cmp(&bf).ok_or(EvalError::TypeMismatch {
3428                    detail: "NaN in NUMERIC/Float comparison".into(),
3429                })?;
3430                Ok(Value::Bool(cmp_to_bool(op, ord)))
3431            }
3432            BinOp::Concat => Ok(text_concat(&l, &r)),
3433            other => Err(EvalError::TypeMismatch {
3434                detail: format!("operator {other:?} not defined for NUMERIC and Float"),
3435            }),
3436        };
3437    }
3438    // Promote integer ↔ numeric to a shared scale (max of both sides).
3439    let (a, sa) = numeric_or_widen(&l).ok_or_else(|| EvalError::TypeMismatch {
3440        detail: format!("NUMERIC op against non-numeric {:?}", l.data_type()),
3441    })?;
3442    let (b, sb) = numeric_or_widen(&r).ok_or_else(|| EvalError::TypeMismatch {
3443        detail: format!("NUMERIC op against non-numeric {:?}", r.data_type()),
3444    })?;
3445    match op {
3446        BinOp::Add | BinOp::Sub => {
3447            let target_scale = sa.max(sb);
3448            let lhs = rescale(a, sa, target_scale).ok_or(EvalError::TypeMismatch {
3449                detail: "NUMERIC overflow on rescale".into(),
3450            })?;
3451            let rhs = rescale(b, sb, target_scale).ok_or(EvalError::TypeMismatch {
3452                detail: "NUMERIC overflow on rescale".into(),
3453            })?;
3454            let r = match op {
3455                BinOp::Add => lhs.checked_add(rhs),
3456                BinOp::Sub => lhs.checked_sub(rhs),
3457                _ => unreachable!(),
3458            }
3459            .ok_or(EvalError::TypeMismatch {
3460                detail: "NUMERIC overflow on +/-".into(),
3461            })?;
3462            Ok(Value::Numeric {
3463                scaled: r,
3464                scale: target_scale,
3465            })
3466        }
3467        BinOp::Mul => {
3468            let scaled = a.checked_mul(b).ok_or(EvalError::TypeMismatch {
3469                detail: "NUMERIC overflow on *".into(),
3470            })?;
3471            Ok(Value::Numeric {
3472                scaled,
3473                scale: sa.saturating_add(sb),
3474            })
3475        }
3476        BinOp::Div => {
3477            if b == 0 {
3478                return Err(EvalError::DivisionByZero);
3479            }
3480            // Result scale: keep the wider operand's scale. Pre-scale
3481            // the numerator so the integer division retains that many
3482            // fractional digits. Round half-away-from-zero.
3483            let target_scale = sa.max(sb);
3484            // Numerator effective scale becomes sa + target_scale; we
3485            // bring it up to (target_scale + sb) so the divisor's scale
3486            // cancels cleanly.
3487            let bump = pow10_i128(target_scale.saturating_add(sb).saturating_sub(sa));
3488            let num = a.checked_mul(bump).ok_or(EvalError::TypeMismatch {
3489                detail: "NUMERIC overflow on / scaling".into(),
3490            })?;
3491            let half = if b >= 0 { b / 2 } else { -(b / 2) };
3492            let adj = if (num >= 0) == (b >= 0) {
3493                num + half
3494            } else {
3495                num - half
3496            };
3497            Ok(Value::Numeric {
3498                scaled: adj / b,
3499                scale: target_scale,
3500            })
3501        }
3502        BinOp::Eq | BinOp::NotEq | BinOp::Lt | BinOp::LtEq | BinOp::Gt | BinOp::GtEq => {
3503            let target_scale = sa.max(sb);
3504            let lhs = rescale(a, sa, target_scale).ok_or(EvalError::TypeMismatch {
3505                detail: "NUMERIC overflow on rescale".into(),
3506            })?;
3507            let rhs = rescale(b, sb, target_scale).ok_or(EvalError::TypeMismatch {
3508                detail: "NUMERIC overflow on rescale".into(),
3509            })?;
3510            Ok(Value::Bool(cmp_to_bool(op, lhs.cmp(&rhs))))
3511        }
3512        BinOp::Concat => Ok(text_concat(&l, &r)),
3513        other => Err(EvalError::TypeMismatch {
3514            detail: format!("operator {other:?} not defined for NUMERIC"),
3515        }),
3516    }
3517}
3518
3519/// Express `v` as a `(scaled_i128, scale)` pair. Plain integers come
3520/// back with `scale=0`; NUMERIC keeps its own scale. Anything else
3521/// returns `None` and the caller raises a type error.
3522fn numeric_or_widen(v: &Value) -> Option<(i128, u8)> {
3523    match v {
3524        Value::Numeric { scaled, scale } => Some((*scaled, *scale)),
3525        Value::Int(n) => Some((i128::from(*n), 0)),
3526        Value::SmallInt(n) => Some((i128::from(*n), 0)),
3527        Value::BigInt(n) => Some((i128::from(*n), 0)),
3528        _ => None,
3529    }
3530}
3531
3532fn rescale(scaled: i128, src: u8, dst: u8) -> Option<i128> {
3533    if src == dst {
3534        return Some(scaled);
3535    }
3536    if dst > src {
3537        scaled.checked_mul(pow10_i128(dst - src))
3538    } else {
3539        let drop = pow10_i128(src - dst);
3540        let half = drop / 2;
3541        let r = if scaled >= 0 {
3542            scaled + half
3543        } else {
3544            scaled - half
3545        };
3546        Some(r / drop)
3547    }
3548}
3549
3550const fn pow10_i128(p: u8) -> i128 {
3551    let mut acc: i128 = 1;
3552    let mut i = 0;
3553    while i < p {
3554        acc *= 10;
3555        i += 1;
3556    }
3557    acc
3558}
3559
3560const fn cmp_to_bool(op: BinOp, ord: core::cmp::Ordering) -> bool {
3561    use core::cmp::Ordering::{Equal, Greater, Less};
3562    match op {
3563        BinOp::Eq => matches!(ord, Equal),
3564        BinOp::NotEq => !matches!(ord, Equal),
3565        BinOp::Lt => matches!(ord, Less),
3566        BinOp::LtEq => matches!(ord, Less | Equal),
3567        BinOp::Gt => matches!(ord, Greater),
3568        BinOp::GtEq => matches!(ord, Greater | Equal),
3569        _ => false,
3570    }
3571}
3572
3573/// SQL `||` string concatenation. Operands are coerced to text via the same
3574/// rule as `::text` cast. NULL propagates (handled above; this function only
3575/// runs with non-NULL operands).
3576fn text_concat(l: &Value, r: &Value) -> Value {
3577    // v7.11.8 — PG `||` overloads: TEXT[] || TEXT[] = concatenated array;
3578    // TEXT[] || TEXT (or TEXT || TEXT[]) prepends/appends the single
3579    // element. NULL || anything = NULL (PG semantics for arrays;
3580    // text concat treats NULL the same way after value_to_text).
3581    match (l, r) {
3582        (Value::Null, _) | (_, Value::Null) => {
3583            // PG text concat: NULL || x = NULL. Array concat: NULL || x = NULL.
3584            // Keep the legacy text path (value_to_text handles Null as ""),
3585            // but for arrays we surface real NULL to match PG.
3586            if matches!(
3587                l,
3588                Value::TextArray(_) | Value::IntArray(_) | Value::BigIntArray(_) | Value::Bytes(_)
3589            ) || matches!(
3590                r,
3591                Value::TextArray(_) | Value::IntArray(_) | Value::BigIntArray(_) | Value::Bytes(_)
3592            ) {
3593                return Value::Null;
3594            }
3595        }
3596        (Value::TextArray(a), Value::TextArray(b)) => {
3597            let mut out = a.clone();
3598            out.extend(b.iter().cloned());
3599            return Value::TextArray(out);
3600        }
3601        (Value::TextArray(a), Value::Text(s)) => {
3602            let mut out = a.clone();
3603            out.push(Some(s.clone()));
3604            return Value::TextArray(out);
3605        }
3606        (Value::Text(s), Value::TextArray(b)) => {
3607            let mut out: alloc::vec::Vec<Option<alloc::string::String>> =
3608                alloc::vec::Vec::with_capacity(1 + b.len());
3609            out.push(Some(s.clone()));
3610            out.extend(b.iter().cloned());
3611            return Value::TextArray(out);
3612        }
3613        // v7.11.13 — IntArray / BigIntArray `||` overloads. Same
3614        // PG semantics as TEXT[]: array||array concatenates, and
3615        // array||scalar appends/prepends. Mixed Int/BigInt widens
3616        // to BigIntArray.
3617        (Value::IntArray(a), Value::IntArray(b)) => {
3618            let mut out = a.clone();
3619            out.extend(b.iter().copied());
3620            return Value::IntArray(out);
3621        }
3622        (Value::IntArray(a), Value::Int(n)) => {
3623            let mut out = a.clone();
3624            out.push(Some(*n));
3625            return Value::IntArray(out);
3626        }
3627        (Value::IntArray(a), Value::SmallInt(n)) => {
3628            let mut out = a.clone();
3629            out.push(Some(i32::from(*n)));
3630            return Value::IntArray(out);
3631        }
3632        (Value::Int(n), Value::IntArray(b)) => {
3633            let mut out: alloc::vec::Vec<Option<i32>> = alloc::vec::Vec::with_capacity(1 + b.len());
3634            out.push(Some(*n));
3635            out.extend(b.iter().copied());
3636            return Value::IntArray(out);
3637        }
3638        (Value::SmallInt(n), Value::IntArray(b)) => {
3639            let mut out: alloc::vec::Vec<Option<i32>> = alloc::vec::Vec::with_capacity(1 + b.len());
3640            out.push(Some(i32::from(*n)));
3641            out.extend(b.iter().copied());
3642            return Value::IntArray(out);
3643        }
3644        (Value::BigIntArray(a), Value::BigIntArray(b)) => {
3645            let mut out = a.clone();
3646            out.extend(b.iter().copied());
3647            return Value::BigIntArray(out);
3648        }
3649        (Value::BigIntArray(a), Value::IntArray(b)) => {
3650            let mut out = a.clone();
3651            out.extend(b.iter().map(|o| o.map(i64::from)));
3652            return Value::BigIntArray(out);
3653        }
3654        (Value::IntArray(a), Value::BigIntArray(b)) => {
3655            let mut out: alloc::vec::Vec<Option<i64>> =
3656                a.iter().map(|o| o.map(i64::from)).collect();
3657            out.extend(b.iter().copied());
3658            return Value::BigIntArray(out);
3659        }
3660        (Value::BigIntArray(a), Value::BigInt(n)) => {
3661            let mut out = a.clone();
3662            out.push(Some(*n));
3663            return Value::BigIntArray(out);
3664        }
3665        (Value::BigIntArray(a), Value::Int(n)) => {
3666            let mut out = a.clone();
3667            out.push(Some(i64::from(*n)));
3668            return Value::BigIntArray(out);
3669        }
3670        (Value::BigIntArray(a), Value::SmallInt(n)) => {
3671            let mut out = a.clone();
3672            out.push(Some(i64::from(*n)));
3673            return Value::BigIntArray(out);
3674        }
3675        (Value::BigInt(n), Value::BigIntArray(b)) => {
3676            let mut out: alloc::vec::Vec<Option<i64>> = alloc::vec::Vec::with_capacity(1 + b.len());
3677            out.push(Some(*n));
3678            out.extend(b.iter().copied());
3679            return Value::BigIntArray(out);
3680        }
3681        (Value::Int(n), Value::BigIntArray(b)) => {
3682            let mut out: alloc::vec::Vec<Option<i64>> = alloc::vec::Vec::with_capacity(1 + b.len());
3683            out.push(Some(i64::from(*n)));
3684            out.extend(b.iter().copied());
3685            return Value::BigIntArray(out);
3686        }
3687        (Value::SmallInt(n), Value::BigIntArray(b)) => {
3688            let mut out: alloc::vec::Vec<Option<i64>> = alloc::vec::Vec::with_capacity(1 + b.len());
3689            out.push(Some(i64::from(*n)));
3690            out.extend(b.iter().copied());
3691            return Value::BigIntArray(out);
3692        }
3693        // v7.11.15 — BYTEA `||` is byte concatenation.
3694        (Value::Bytes(a), Value::Bytes(b)) => {
3695            let mut out = a.clone();
3696            out.extend_from_slice(b);
3697            return Value::Bytes(out);
3698        }
3699        _ => {}
3700    }
3701    let a = value_to_text(l);
3702    let b = value_to_text(r);
3703    Value::Text(a + &b)
3704}
3705
3706/// pgvector inner-product `<#>`. Returns the *negative* dot product so
3707/// smaller still means more similar — same convention as pgvector.
3708fn inner_product(l: Value, r: Value) -> Result<Value, EvalError> {
3709    let (a, b) = unwrap_vec_pair(l, r, "<#>")?;
3710    let mut dot: f64 = 0.0;
3711    for (x, y) in a.iter().zip(b.iter()) {
3712        dot += f64::from(*x) * f64::from(*y);
3713    }
3714    Ok(Value::Float(-dot))
3715}
3716
3717/// pgvector cosine distance `<=>` — `1 - (a·b) / (‖a‖ ‖b‖)`. A zero-norm
3718/// operand produces NaN (matches pgvector).
3719fn cosine_distance(l: Value, r: Value) -> Result<Value, EvalError> {
3720    let (a, b) = unwrap_vec_pair(l, r, "<=>")?;
3721    let mut dot: f64 = 0.0;
3722    let mut na: f64 = 0.0;
3723    let mut nb: f64 = 0.0;
3724    for (x, y) in a.iter().zip(b.iter()) {
3725        let xf = f64::from(*x);
3726        let yf = f64::from(*y);
3727        dot += xf * yf;
3728        na += xf * xf;
3729        nb += yf * yf;
3730    }
3731    let denom = sqrt_newton(na) * sqrt_newton(nb);
3732    if denom == 0.0 {
3733        return Ok(Value::Float(f64::NAN));
3734    }
3735    Ok(Value::Float(1.0 - dot / denom))
3736}
3737
3738fn unwrap_vec_pair(l: Value, r: Value, op: &str) -> Result<(Vec<f32>, Vec<f32>), EvalError> {
3739    // v6.0.1: SQ8 cells coming through the SQL evaluator are
3740    // dequantised to f32 here so the existing scalar distance
3741    // arithmetic stays intact. HNSW kNN search continues to use
3742    // the asymmetric ADC variant inside `cell_to_query_metric_
3743    // distance` — this path only runs when a vector expression
3744    // lands in the evaluator (full-scan ORDER BY, SELECT
3745    // projection of `v <-> $1`, etc.).
3746    let to_f32 = |v: Value| -> Option<Vec<f32>> {
3747        match v {
3748            Value::Vector(a) => Some(a),
3749            Value::Sq8Vector(q) => Some(spg_storage::quantize::dequantize(&q)),
3750            // v6.0.3: bit-exact dequant for halfvec cells.
3751            Value::HalfVector(h) => Some(h.to_f32_vec()),
3752            _ => None,
3753        }
3754    };
3755    let l_ty = l.data_type();
3756    let r_ty = r.data_type();
3757    match (to_f32(l), to_f32(r)) {
3758        (Some(a), Some(b)) => {
3759            if a.len() != b.len() {
3760                return Err(EvalError::TypeMismatch {
3761                    detail: format!("vector dim mismatch in {op}: {} vs {}", a.len(), b.len()),
3762                });
3763            }
3764            Ok((a, b))
3765        }
3766        _ => Err(EvalError::TypeMismatch {
3767            detail: format!("{op} requires two vectors, got {l_ty:?} and {r_ty:?}"),
3768        }),
3769    }
3770}
3771
3772/// Numeric arithmetic with widening.
3773/// - both `Int` → `Int` (with overflow check)
3774/// - `Int` op `BigInt` (either side) → `BigInt`
3775/// - any `Float` involved → `Float`
3776fn arith(
3777    l: Value,
3778    r: Value,
3779    int_op: impl Fn(i64, i64) -> Option<i64>,
3780    float_op: impl Fn(f64, f64) -> f64,
3781    op_name: &str,
3782) -> Result<Value, EvalError> {
3783    // Widen SmallInt to Int up front so the rest of the arithmetic
3784    // table only deals with Int / BigInt / Float pairs.
3785    let widen = |v: Value| -> Value {
3786        match v {
3787            Value::SmallInt(n) => Value::Int(i32::from(n)),
3788            other => other,
3789        }
3790    };
3791    let l = widen(l);
3792    let r = widen(r);
3793    match (l, r) {
3794        (Value::Int(a), Value::Int(b)) => {
3795            let result = int_op(i64::from(a), i64::from(b)).ok_or(EvalError::TypeMismatch {
3796                detail: format!("integer overflow on {op_name}"),
3797            })?;
3798            if let Ok(small) = i32::try_from(result) {
3799                Ok(Value::Int(small))
3800            } else {
3801                Ok(Value::BigInt(result))
3802            }
3803        }
3804        (Value::Int(a), Value::BigInt(b)) | (Value::BigInt(b), Value::Int(a)) => {
3805            let result = int_op(i64::from(a), b).ok_or(EvalError::TypeMismatch {
3806                detail: format!("bigint overflow on {op_name}"),
3807            })?;
3808            Ok(Value::BigInt(result))
3809        }
3810        (Value::BigInt(a), Value::BigInt(b)) => {
3811            let result = int_op(a, b).ok_or(EvalError::TypeMismatch {
3812                detail: format!("bigint overflow on {op_name}"),
3813            })?;
3814            Ok(Value::BigInt(result))
3815        }
3816        (a, b)
3817            if a.data_type() == Some(DataType::Float) || b.data_type() == Some(DataType::Float) =>
3818        {
3819            let af = as_f64(&a)?;
3820            let bf = as_f64(&b)?;
3821            Ok(Value::Float(float_op(af, bf)))
3822        }
3823        (a, b) => Err(EvalError::TypeMismatch {
3824            detail: format!(
3825                "{op_name} applied to non-numeric: {:?} vs {:?}",
3826                a.data_type(),
3827                b.data_type()
3828            ),
3829        }),
3830    }
3831}
3832
3833/// L2 (Euclidean) distance between two vectors of equal dimension.
3834/// Returned as `Value::Float(d)` so it composes with the existing
3835/// comparison / sort plumbing. Mismatched dims or non-vector operands
3836/// raise `TypeMismatch`.
3837#[allow(clippy::many_single_char_names)] // l, r, a, b, d are the natural names
3838fn l2_distance(l: Value, r: Value) -> Result<Value, EvalError> {
3839    // v6.0.1: route both operands through `unwrap_vec_pair` so SQ8
3840    // cells dequantise on the way in. Sub-f64 precision loss is
3841    // negligible vs the dequantisation noise the SQ8 path already
3842    // ships with.
3843    let (a, b) = unwrap_vec_pair(l, r, "<->")?;
3844    let mut sum: f64 = 0.0;
3845    for (x, y) in a.iter().zip(b.iter()) {
3846        let d = f64::from(*x) - f64::from(*y);
3847        sum += d * d;
3848    }
3849    Ok(Value::Float(sqrt_newton(sum)))
3850}
3851
3852/// Self-built `sqrt` for `f64` — `std::f64::sqrt` lives in `std`, which the
3853/// engine's `no_std` constraint disallows. Newton-Raphson with a few rounds
3854/// reaches IEEE-754 precision for the inputs we'll see (sum of squares of
3855/// f32-derived distances, always non-negative, never NaN).
3856fn sqrt_newton(x: f64) -> f64 {
3857    if x <= 0.0 {
3858        return 0.0;
3859    }
3860    let mut g = x;
3861    // 10 iterations is conservative; 6 already converges to ulp for typical
3862    // distances.
3863    for _ in 0..10 {
3864        g = 0.5 * (g + x / g);
3865    }
3866    g
3867}
3868
3869fn div_op(l: Value, r: Value) -> Result<Value, EvalError> {
3870    let any_float = matches!(l.data_type(), Some(DataType::Float))
3871        || matches!(r.data_type(), Some(DataType::Float));
3872    if any_float {
3873        let a = as_f64(&l)?;
3874        let b = as_f64(&r)?;
3875        if b == 0.0 {
3876            return Err(EvalError::DivisionByZero);
3877        }
3878        return Ok(Value::Float(a / b));
3879    }
3880    arith(
3881        l,
3882        r,
3883        |a, b| {
3884            if b == 0 { None } else { Some(a / b) }
3885        },
3886        |a, b| a / b,
3887        "/",
3888    )
3889    .map_err(|e| match e {
3890        // The closure returns None on b == 0; translate that into the dedicated
3891        // DivisionByZero variant instead of "integer overflow on /".
3892        EvalError::TypeMismatch { detail } if detail.contains('/') => EvalError::DivisionByZero,
3893        other => other,
3894    })
3895}
3896
3897fn as_f64(v: &Value) -> Result<f64, EvalError> {
3898    match v {
3899        Value::SmallInt(n) => Ok(f64::from(*n)),
3900        Value::Int(n) => Ok(f64::from(*n)),
3901        #[allow(clippy::cast_precision_loss)]
3902        Value::BigInt(n) => Ok(*n as f64),
3903        Value::Float(x) => Ok(*x),
3904        #[allow(clippy::cast_precision_loss)]
3905        Value::Numeric { scaled, scale } => {
3906            let mut div = 1.0_f64;
3907            for _ in 0..*scale {
3908                div *= 10.0;
3909            }
3910            Ok((*scaled as f64) / div)
3911        }
3912        other => Err(EvalError::TypeMismatch {
3913            detail: format!("cannot convert {:?} to FLOAT", other.data_type()),
3914        }),
3915    }
3916}
3917
3918fn compare(op: BinOp, l: &Value, r: &Value) -> Result<Value, EvalError> {
3919    let ord = match (l, r) {
3920        (Value::Int(a), Value::Int(b)) => i64::from(*a).cmp(&i64::from(*b)),
3921        (Value::Int(a), Value::BigInt(b)) => i64::from(*a).cmp(b),
3922        (Value::BigInt(a), Value::Int(b)) => a.cmp(&i64::from(*b)),
3923        (Value::BigInt(a), Value::BigInt(b)) => a.cmp(b),
3924        (a, b)
3925            if matches!(a.data_type(), Some(DataType::Float))
3926                || matches!(b.data_type(), Some(DataType::Float)) =>
3927        {
3928            let af = as_f64(a)?;
3929            let bf = as_f64(b)?;
3930            af.partial_cmp(&bf).ok_or(EvalError::TypeMismatch {
3931                detail: "NaN in comparison".into(),
3932            })?
3933        }
3934        (Value::Text(a), Value::Text(b)) => a.cmp(b),
3935        (Value::Bool(a), Value::Bool(b)) => a.cmp(b),
3936        // Date / Timestamp compare on their integer storage repr.
3937        // Cross-domain (Date vs Timestamp) lifts the Date to the
3938        // matching midnight TIMESTAMP first.
3939        (Value::Date(a), Value::Date(b)) => a.cmp(b),
3940        (Value::Timestamp(a), Value::Timestamp(b)) => a.cmp(b),
3941        (Value::Date(a), Value::Timestamp(b)) => (i64::from(*a) * 86_400_000_000).cmp(b),
3942        (Value::Timestamp(a), Value::Date(b)) => a.cmp(&(i64::from(*b) * 86_400_000_000)),
3943        // PG-style implicit coercion: comparing a DATE / TIMESTAMP
3944        // column against a text literal lifts the literal into the
3945        // matching domain (e.g. `day >= '2024-01-01'`).
3946        (Value::Date(a), Value::Text(b)) => {
3947            let bd = parse_date_literal(b).ok_or_else(|| EvalError::TypeMismatch {
3948                detail: format!("cannot parse {b:?} as DATE for comparison"),
3949            })?;
3950            a.cmp(&bd)
3951        }
3952        (Value::Text(a), Value::Date(b)) => {
3953            let ad = parse_date_literal(a).ok_or_else(|| EvalError::TypeMismatch {
3954                detail: format!("cannot parse {a:?} as DATE for comparison"),
3955            })?;
3956            ad.cmp(b)
3957        }
3958        (Value::Timestamp(a), Value::Text(b)) => {
3959            let bt = parse_timestamp_literal(b).ok_or_else(|| EvalError::TypeMismatch {
3960                detail: format!("cannot parse {b:?} as TIMESTAMP for comparison"),
3961            })?;
3962            a.cmp(&bt)
3963        }
3964        (Value::Text(a), Value::Timestamp(b)) => {
3965            let at = parse_timestamp_literal(a).ok_or_else(|| EvalError::TypeMismatch {
3966                detail: format!("cannot parse {a:?} as TIMESTAMP for comparison"),
3967            })?;
3968            at.cmp(b)
3969        }
3970        (a, b) => {
3971            return Err(EvalError::TypeMismatch {
3972                detail: format!(
3973                    "comparison between {:?} and {:?}",
3974                    a.data_type(),
3975                    b.data_type()
3976                ),
3977            });
3978        }
3979    };
3980    let result = match op {
3981        BinOp::Eq => ord.is_eq(),
3982        BinOp::NotEq => !ord.is_eq(),
3983        BinOp::Lt => ord.is_lt(),
3984        BinOp::LtEq => ord.is_le(),
3985        BinOp::Gt => ord.is_gt(),
3986        BinOp::GtEq => ord.is_ge(),
3987        BinOp::And
3988        | BinOp::Or
3989        | BinOp::Add
3990        | BinOp::Sub
3991        | BinOp::Mul
3992        | BinOp::Div
3993        | BinOp::L2Distance
3994        | BinOp::InnerProduct
3995        | BinOp::CosineDistance
3996        | BinOp::Concat
3997        | BinOp::JsonGet
3998        | BinOp::JsonGetText
3999        | BinOp::JsonGetPath
4000        | BinOp::JsonGetPathText
4001        | BinOp::JsonContains
4002        | BinOp::TsMatch
4003        | BinOp::IsDistinctFrom
4004        | BinOp::IsNotDistinctFrom => {
4005            unreachable!("compare() only called with comparison ops")
4006        }
4007    };
4008    Ok(Value::Bool(result))
4009}
4010
4011// SQL three-valued AND / OR.
4012fn and_3vl(l: Value, r: Value) -> Result<Value, EvalError> {
4013    match (l, r) {
4014        (Value::Bool(false), _) | (_, Value::Bool(false)) => Ok(Value::Bool(false)),
4015        (Value::Bool(true), Value::Bool(true)) => Ok(Value::Bool(true)),
4016        (Value::Null, _) | (_, Value::Null) => Ok(Value::Null),
4017        (a, b) => Err(EvalError::TypeMismatch {
4018            detail: format!(
4019                "AND on non-boolean: {:?} and {:?}",
4020                a.data_type(),
4021                b.data_type()
4022            ),
4023        }),
4024    }
4025}
4026
4027fn or_3vl(l: Value, r: Value) -> Result<Value, EvalError> {
4028    match (l, r) {
4029        (Value::Bool(true), _) | (_, Value::Bool(true)) => Ok(Value::Bool(true)),
4030        (Value::Bool(false), Value::Bool(false)) => Ok(Value::Bool(false)),
4031        (Value::Null, _) | (_, Value::Null) => Ok(Value::Null),
4032        (a, b) => Err(EvalError::TypeMismatch {
4033            detail: format!(
4034                "OR on non-boolean: {:?} and {:?}",
4035                a.data_type(),
4036                b.data_type()
4037            ),
4038        }),
4039    }
4040}
4041
4042#[cfg(test)]
4043mod tests {
4044    use super::*;
4045    use alloc::vec;
4046    use spg_storage::{ColumnSchema, Row};
4047
4048    fn col(name: &str, ty: DataType) -> ColumnSchema {
4049        ColumnSchema::new(name, ty, true)
4050    }
4051
4052    fn ctx<'a>(cols: &'a [ColumnSchema], alias: Option<&'a str>) -> EvalContext<'a> {
4053        EvalContext::new(cols, alias)
4054    }
4055
4056    fn lit(n: i64) -> Expr {
4057        Expr::Literal(Literal::Integer(n))
4058    }
4059
4060    fn null() -> Expr {
4061        Expr::Literal(Literal::Null)
4062    }
4063
4064    fn col_ref(name: &str) -> Expr {
4065        Expr::Column(ColumnName {
4066            qualifier: None,
4067            name: name.into(),
4068        })
4069    }
4070
4071    #[test]
4072    fn literal_evaluates_to_value() {
4073        let r = Row::new(vec![]);
4074        let cs: [ColumnSchema; 0] = [];
4075        let c = ctx(&cs, None);
4076        assert_eq!(eval_expr(&lit(42), &r, &c).unwrap(), Value::Int(42));
4077        assert_eq!(
4078            eval_expr(&Expr::Literal(Literal::Float(1.5)), &r, &c).unwrap(),
4079            Value::Float(1.5)
4080        );
4081        assert_eq!(eval_expr(&null(), &r, &c).unwrap(), Value::Null);
4082    }
4083
4084    #[test]
4085    fn column_lookup_unqualified() {
4086        let cs = vec![col("a", DataType::Int), col("b", DataType::Text)];
4087        let r = Row::new(vec![Value::Int(7), Value::Text("hi".into())]);
4088        let c = ctx(&cs, None);
4089        assert_eq!(eval_expr(&col_ref("a"), &r, &c).unwrap(), Value::Int(7));
4090        assert_eq!(
4091            eval_expr(&col_ref("b"), &r, &c).unwrap(),
4092            Value::Text("hi".into())
4093        );
4094    }
4095
4096    #[test]
4097    fn column_not_found_errors() {
4098        let cs = vec![col("a", DataType::Int)];
4099        let r = Row::new(vec![Value::Int(0)]);
4100        let c = ctx(&cs, None);
4101        let err = eval_expr(&col_ref("ghost"), &r, &c).unwrap_err();
4102        assert!(matches!(err, EvalError::ColumnNotFound { ref name } if name == "ghost"));
4103    }
4104
4105    #[test]
4106    fn qualified_column_matches_alias() {
4107        let cs = vec![col("a", DataType::Int)];
4108        let r = Row::new(vec![Value::Int(5)]);
4109        let c = ctx(&cs, Some("u"));
4110        let qualified = Expr::Column(ColumnName {
4111            qualifier: Some("u".into()),
4112            name: "a".into(),
4113        });
4114        assert_eq!(eval_expr(&qualified, &r, &c).unwrap(), Value::Int(5));
4115    }
4116
4117    #[test]
4118    fn qualified_column_unknown_alias_errors() {
4119        let cs = vec![col("a", DataType::Int)];
4120        let r = Row::new(vec![Value::Int(5)]);
4121        let c = ctx(&cs, Some("u"));
4122        let wrong = Expr::Column(ColumnName {
4123            qualifier: Some("x".into()),
4124            name: "a".into(),
4125        });
4126        assert!(matches!(
4127            eval_expr(&wrong, &r, &c).unwrap_err(),
4128            EvalError::UnknownQualifier { .. }
4129        ));
4130    }
4131
4132    #[test]
4133    fn arithmetic_with_widening() {
4134        let r = Row::new(vec![]);
4135        let cs: [ColumnSchema; 0] = [];
4136        let c = ctx(&cs, None);
4137        let e = Expr::Binary {
4138            lhs: alloc::boxed::Box::new(lit(2)),
4139            op: BinOp::Add,
4140            rhs: alloc::boxed::Box::new(Expr::Literal(Literal::Float(0.5))),
4141        };
4142        assert_eq!(eval_expr(&e, &r, &c).unwrap(), Value::Float(2.5));
4143    }
4144
4145    #[test]
4146    fn division_by_zero_errors() {
4147        let r = Row::new(vec![]);
4148        let cs: [ColumnSchema; 0] = [];
4149        let c = ctx(&cs, None);
4150        let e = Expr::Binary {
4151            lhs: alloc::boxed::Box::new(lit(1)),
4152            op: BinOp::Div,
4153            rhs: alloc::boxed::Box::new(lit(0)),
4154        };
4155        assert_eq!(
4156            eval_expr(&e, &r, &c).unwrap_err(),
4157            EvalError::DivisionByZero
4158        );
4159    }
4160
4161    #[test]
4162    fn comparison_returns_bool() {
4163        let r = Row::new(vec![]);
4164        let cs: [ColumnSchema; 0] = [];
4165        let c = ctx(&cs, None);
4166        let e = Expr::Binary {
4167            lhs: alloc::boxed::Box::new(lit(1)),
4168            op: BinOp::Lt,
4169            rhs: alloc::boxed::Box::new(lit(2)),
4170        };
4171        assert_eq!(eval_expr(&e, &r, &c).unwrap(), Value::Bool(true));
4172    }
4173
4174    #[test]
4175    fn null_propagates_through_arithmetic() {
4176        let r = Row::new(vec![]);
4177        let cs: [ColumnSchema; 0] = [];
4178        let c = ctx(&cs, None);
4179        let e = Expr::Binary {
4180            lhs: alloc::boxed::Box::new(lit(1)),
4181            op: BinOp::Add,
4182            rhs: alloc::boxed::Box::new(null()),
4183        };
4184        assert_eq!(eval_expr(&e, &r, &c).unwrap(), Value::Null);
4185    }
4186
4187    #[test]
4188    fn and_three_valued_logic() {
4189        let r = Row::new(vec![]);
4190        let cs: [ColumnSchema; 0] = [];
4191        let c = ctx(&cs, None);
4192        let tt = |a: bool, b_null: bool| Expr::Binary {
4193            lhs: alloc::boxed::Box::new(Expr::Literal(Literal::Bool(a))),
4194            op: BinOp::And,
4195            rhs: alloc::boxed::Box::new(if b_null {
4196                null()
4197            } else {
4198                Expr::Literal(Literal::Bool(true))
4199            }),
4200        };
4201        // FALSE AND NULL → FALSE
4202        assert_eq!(
4203            eval_expr(&tt(false, true), &r, &c).unwrap(),
4204            Value::Bool(false)
4205        );
4206        // TRUE AND NULL → NULL
4207        assert_eq!(eval_expr(&tt(true, true), &r, &c).unwrap(), Value::Null);
4208        // TRUE AND TRUE → TRUE
4209        assert_eq!(
4210            eval_expr(&tt(true, false), &r, &c).unwrap(),
4211            Value::Bool(true)
4212        );
4213    }
4214
4215    #[test]
4216    fn or_three_valued_logic() {
4217        let r = Row::new(vec![]);
4218        let cs: [ColumnSchema; 0] = [];
4219        let c = ctx(&cs, None);
4220        let or_with_null = |a: bool| Expr::Binary {
4221            lhs: alloc::boxed::Box::new(Expr::Literal(Literal::Bool(a))),
4222            op: BinOp::Or,
4223            rhs: alloc::boxed::Box::new(null()),
4224        };
4225        // TRUE OR NULL → TRUE
4226        assert_eq!(
4227            eval_expr(&or_with_null(true), &r, &c).unwrap(),
4228            Value::Bool(true)
4229        );
4230        // FALSE OR NULL → NULL
4231        assert_eq!(
4232            eval_expr(&or_with_null(false), &r, &c).unwrap(),
4233            Value::Null
4234        );
4235    }
4236
4237    #[test]
4238    fn not_on_null_is_null() {
4239        let r = Row::new(vec![]);
4240        let cs: [ColumnSchema; 0] = [];
4241        let c = ctx(&cs, None);
4242        let e = Expr::Unary {
4243            op: UnOp::Not,
4244            expr: alloc::boxed::Box::new(null()),
4245        };
4246        assert_eq!(eval_expr(&e, &r, &c).unwrap(), Value::Null);
4247    }
4248
4249    #[test]
4250    fn text_comparison_lexicographic() {
4251        let r = Row::new(vec![]);
4252        let cs: [ColumnSchema; 0] = [];
4253        let c = ctx(&cs, None);
4254        let e = Expr::Binary {
4255            lhs: alloc::boxed::Box::new(Expr::Literal(Literal::String("apple".into()))),
4256            op: BinOp::Lt,
4257            rhs: alloc::boxed::Box::new(Expr::Literal(Literal::String("banana".into()))),
4258        };
4259        assert_eq!(eval_expr(&e, &r, &c).unwrap(), Value::Bool(true));
4260    }
4261
4262    #[test]
4263    fn interval_format_basics() {
4264        assert_eq!(format_interval(0, 0), "0");
4265        assert_eq!(format_interval(0, 86_400_000_000), "1 day");
4266        assert_eq!(format_interval(0, -86_400_000_000), "-1 days");
4267        assert_eq!(format_interval(0, 3_600_000_000), "01:00:00");
4268        assert_eq!(
4269            format_interval(0, 86_400_000_000 + 9_000_000),
4270            "1 day 00:00:09"
4271        );
4272        assert_eq!(format_interval(14, 0), "1 year 2 mons");
4273        assert_eq!(format_interval(-1, 0), "-1 mons");
4274    }
4275
4276    #[test]
4277    fn interval_add_to_timestamp_micros_part() {
4278        // 2024-01-01 00:00:00 + INTERVAL '1 hour' = 2024-01-01 01:00:00
4279        let ts = i64::from(days_from_civil(2024, 1, 1)) * 86_400_000_000;
4280        let r = add_interval_to_micros(ts, 0, 3_600_000_000).unwrap();
4281        let expected = ts + 3_600_000_000;
4282        assert_eq!(r, expected);
4283    }
4284
4285    #[test]
4286    fn interval_clamp_month_end() {
4287        // 2024-01-31 + 1 month = 2024-02-29 (leap year).
4288        let d = days_from_civil(2024, 1, 31);
4289        let shifted = shift_date_by_months(d, 1).unwrap();
4290        let (y, m, day) = civil_from_days(shifted);
4291        assert_eq!((y, m, day), (2024, 2, 29));
4292        // 2023-01-31 + 1 month = 2023-02-28 (non-leap).
4293        let d = days_from_civil(2023, 1, 31);
4294        let shifted = shift_date_by_months(d, 1).unwrap();
4295        let (y, m, day) = civil_from_days(shifted);
4296        assert_eq!((y, m, day), (2023, 2, 28));
4297        // 2024-03-31 - 1 month = 2024-02-29.
4298        let d = days_from_civil(2024, 3, 31);
4299        let shifted = shift_date_by_months(d, -1).unwrap();
4300        let (y, m, day) = civil_from_days(shifted);
4301        assert_eq!((y, m, day), (2024, 2, 29));
4302    }
4303
4304    #[test]
4305    fn interval_date_plus_pure_days_stays_date() {
4306        // DATE + INTERVAL '7 days' must stay DATE.
4307        let d = days_from_civil(2024, 6, 1);
4308        let lhs = Value::Date(d);
4309        let rhs = Value::Interval {
4310            months: 0,
4311            micros: 7 * 86_400_000_000,
4312        };
4313        let v = apply_binary_interval(BinOp::Add, &lhs, &rhs)
4314            .unwrap()
4315            .unwrap();
4316        let expected = days_from_civil(2024, 6, 8);
4317        assert_eq!(v, Value::Date(expected));
4318    }
4319
4320    #[test]
4321    fn interval_date_plus_sub_day_lifts_to_timestamp() {
4322        // DATE + INTERVAL '1 hour' must lift to TIMESTAMP.
4323        let d = days_from_civil(2024, 6, 1);
4324        let lhs = Value::Date(d);
4325        let rhs = Value::Interval {
4326            months: 0,
4327            micros: 3_600_000_000,
4328        };
4329        let v = apply_binary_interval(BinOp::Add, &lhs, &rhs)
4330            .unwrap()
4331            .unwrap();
4332        let expected = i64::from(d) * 86_400_000_000 + 3_600_000_000;
4333        assert_eq!(v, Value::Timestamp(expected));
4334    }
4335}