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::borrow::Cow;
19use alloc::format;
20use alloc::string::{String, ToString};
21use alloc::vec::Vec;
22
23use spg_sql::ast::{BinOp, CastTarget, ColumnName, Expr, Literal};
24use spg_storage::{ColumnSchema, Row, Value};
25
26pub(crate) mod binop;
27mod cast;
28pub mod compiled;
29mod datetime;
30mod encoding;
31mod encodings;
32mod format;
33pub(crate) mod functions;
34mod inet;
35pub(crate) mod math;
36mod regexp;
37mod resolve;
38mod strings;
39mod textsearch;
40pub(crate) mod values;
41
42pub use crate::conversions::format_money_array;
43pub(crate) use binop::{
44    add_interval_to_micros, and_3vl, apply_binary, apply_binary_by_ref, apply_binary_interval,
45};
46use binop::{apply_binary_in, apply_unary, compare, pow10_i128};
47pub use cast::{cast_to_vector, cast_value, parse_vector_text};
48pub(crate) use compiled::{
49    CompiledExpr, compile_column_pos, compile_expr, eval_compiled, eval_compiled_ref,
50    fully_compilable,
51};
52use datetime::{
53    age, date_format_mysql, date_part, date_trunc, extract_field, from_unixtime, unix_timestamp_of,
54};
55use encoding::{decode_text, encode_text};
56pub use format::{
57    days_from_civil, format_bigint_array, format_bool_array, format_bytea_array, format_bytea_hex,
58    format_date, format_date_array, format_float, format_float_array, format_int_array,
59    format_interval, format_interval_array, format_money, format_numeric, format_numeric_array,
60    format_numeric_kind, format_real, format_smallint_array, format_text_array, format_time,
61    format_timestamp, format_timestamp_array, format_timestamptz, format_timestamptz_at,
62    format_timetz, format_uuid_array, parse_date_literal, parse_timestamp_literal,
63};
64// v7.39 (GUC knife 3) — session render styles + styled formatters.
65pub use format::{
66    DateOrder, DateStyleKind, IntervalStyleKind, RenderStyle, format_date_array_styled,
67    format_date_styled, format_float_array_styled, format_float_styled,
68    format_interval_array_styled, format_interval_styled, format_real_styled,
69    format_timestamp_array_styled, format_timestamp_styled, format_timestamptz_styled,
70    format_timestamptz_tz, parse_date_literal_ordered, parse_timestamp_literal_ordered,
71    parse_timestamp_literal_tz_ordered,
72};
73use functions::apply_function;
74use inet::{inet_host, inet_masklen, inet_network, inet_op_bool_result};
75pub(crate) use math::{f64_ceil, f64_floor, f64_sqrt};
76use math::{
77    f64_exp, f64_ln, f64_powi, f64_round_half_away, f64_trunc, prng_next_f64, prng_next_u64,
78};
79pub(crate) use regexp::{
80    CompiledRe, compile_re, compiled_is_match, regex_is_match, regexp_matches_rows,
81};
82use regexp::{regexp_matches, regexp_replace, regexp_split_to_array};
83use resolve::{
84    collation_fold_for_compare, compare_is_case_insensitive, composite_eq, eval_expr_cow,
85    is_owned_compare_value, resolve_column, resolve_column_borrowed, text_prefix_chars,
86};
87pub(crate) use resolve::{
88    column_at, column_collation, find_column_pos, is_binary_coerced, locate_column,
89};
90use strings::{
91    TrimSide, format_string, pg_quote_ident, pg_quote_literal, pg_typeof_name, string_left_right,
92    string_pad, string_trim, to_char, value_to_format_text,
93};
94pub use textsearch::{
95    decode_tsquery_external, decode_tsvector_external, format_tsquery, format_tsvector,
96};
97use textsearch::{
98    fts_phraseto_tsquery, fts_plainto_tsquery, fts_setweight, fts_to_tsquery, fts_to_tsvector,
99    fts_ts_headline, fts_ts_rank, fts_ts_rank_cd, fts_ts_rewrite, fts_tsquery_bool,
100    fts_websearch_to_tsquery, ts_match, tsvector_concat,
101};
102pub use values::gen_random_uuid_bytes;
103/// v7.39 (tz epic) — fixed-offset / abbreviation resolution, exposed
104/// for `SET timezone` validation (named zones go through the host tzdb).
105pub(crate) fn datetime_resolve_zone_offset(z: &str) -> Option<i64> {
106    datetime::resolve_zone_offset(z)
107}
108
109pub use values::value_to_text;
110pub use values::value_to_text_styled;
111pub use values::value_to_text_typed;
112pub use values::value_to_text_typed_styled;
113pub use values::value_to_text_with_fsp;
114use values::{
115    array_2d_dims, array_element_at, array_len, array_rebuild, value_cmp_for_min_max, value_to_f64,
116    values_equal_for_nullif,
117};
118
119/// Resolution context for evaluating a single row. `table_alias` is the alias
120/// (or table name) callers should accept as the qualifier on a column ref —
121/// e.g. `FROM users AS u` makes `u.name` valid and rejects `other.name`.
122#[derive(Clone)]
123#[allow(missing_debug_implementations)] // sequence_resolver is a dyn Fn — no Debug
124pub struct EvalContext<'a> {
125    pub columns: &'a [ColumnSchema],
126    pub table_alias: Option<&'a str>,
127    /// v6.1.1 — bound parameters for `$N` placeholders inside the
128    /// expression tree. Empty for simple queries; populated by the
129    /// prepared-statement Execute path with Bind values converted
130    /// to `Value`. Index N (1-based per PG) hits `params[N-1]`.
131    pub params: &'a [Value<'static>],
132    /// v7.12.1 — session text-search config (from `SET
133    /// default_text_search_config = '<name>'`). Resolved when the
134    /// engine builds an `EvalContext` and consumed by the FTS
135    /// function dispatcher when `to_tsvector(text)` /
136    /// `plainto_tsquery(text)` etc are called without an explicit
137    /// config arg. `None` falls through to `simple`.
138    pub default_text_search_config: Option<&'a str>,
139    /// v7.17.0 Phase 1.1 — `nextval` / `currval` / `setval`
140    /// resolver. The engine builds this around a `&mut Catalog`
141    /// so apply_function can mutate sequence state without
142    /// eval owning a catalog reference. When `None`, sequence
143    /// functions return an error (read-only contexts).
144    pub sequence_resolver: Option<&'a SequenceResolver<'a>>,
145    /// v7.37.16 (16.12) — read-only catalog reference for
146    /// builtins that need catalog walks (e.g. `pg_partition_root`,
147    /// `pg_partition_ancestors`). `None` falls through to the
148    /// "no catalog available" branch which returns NULL — same
149    /// shape PG returns for a non-existent OID. Most evaluation
150    /// sites don't need catalog access (row scans, projections);
151    /// they construct contexts with `catalog: None` and the
152    /// engine populates `Some(&self.catalog)` only at the engine's
153    /// top-level entry points where the borrow is unambiguous.
154    pub catalog: Option<&'a spg_storage::Catalog>,
155    /// v7.39 (round 346, M1) — is this a MySQL-dialect session? The two
156    /// dialects disagree about what counts as a truth value: MariaDB
157    /// takes any non-zero number (and a string's leading number) as
158    /// true, PG refuses anything that is not boolean. Set from the
159    /// engine by [`EvalContext::with_engine`]; a context built without
160    /// one keeps PG's stricter reading.
161    pub mysql_dialect: bool,
162    /// Session GUCs set via `SET name = value` / `set_config`, keyed by
163    /// lowercased name. `current_setting('app.foo')` reads custom
164    /// (namespaced) settings from here — the mechanism apps use for
165    /// request context / RLS. `None` in read-only contexts that have no
166    /// session; unknown names then fall through to PG defaults.
167    pub session_gucs: Option<&'a alloc::collections::BTreeMap<String, String>>,
168    /// v7.39 (read01 round 58) — the engine's role store, so
169    /// `has_table_privilege('bob', …)` can expand bob's role MEMBERSHIPS (a
170    /// grant to a group role answers `true` for its inheriting members). `None`
171    /// in a context with no engine behind it — the role then stands alone.
172    pub users: Option<&'a crate::users::UserStore>,
173    /// v7.39 (read01 round 61) — how deep we are inside USER-DEFINED function
174    /// bodies. A function's body is evaluated with a child context, and a body
175    /// may call another function, so this bounds the recursion (a function that
176    /// calls itself would otherwise blow the stack, which an embed host cannot
177    /// catch).
178    pub fn_depth: u16,
179    /// v7.39 (read01 round 63) — the ENGINE, for a user-function body that has
180    /// its own FROM (`SELECT v FROM t WHERE id = k`). Such a body has to run
181    /// through the real executor: reading `catalog`'s rows straight from eval
182    /// would bypass the row-header visibility filter, so under in-place MVCC a
183    /// function would happily read DEAD rows. `None` in a context with no
184    /// engine behind it — a body with a FROM then errors, saying so.
185    pub engine: Option<&'a crate::Engine>,
186    /// v7.38 (read01 U15) — per-scan deterministic sampler state for
187    /// `TABLESAMPLE … REPEATABLE(seed)`. A fresh cell is created before a
188    /// scan whose predicate may draw `__tsm_fract(seed)`; the cell holds
189    /// `None` until the first draw seeds it from that literal, then a
190    /// scan-local xorshift sequence (isolated from the process-global
191    /// `random()` PRNG, so it's deterministic and rescan-stable). `None`
192    /// here means no sampler is attached.
193    pub sample_rng: Option<&'a core::cell::Cell<Option<u64>>>,
194    /// v7.38 (read01 P3.25) — native-stack-overflow guard. Lazily seeded
195    /// with the stack pointer of the outermost `eval_expr` call; deeper
196    /// calls compare their own pointer against it and bail with
197    /// [`EvalError::StackDepthExceeded`] once usage crosses a safe margin,
198    /// so a pathologically nested expression errors instead of aborting the
199    /// process. Owned (not a borrowed cell) so it stays stack-local and
200    /// never touches `Engine`'s `Sync` bound.
201    pub recursion_base: core::cell::Cell<usize>,
202    /// v7.39 (GUC knife 3) — session render style (DateStyle /
203    /// IntervalStyle / extra_float_digits) for text output produced
204    /// inside expression evaluation (`::text` casts). Contexts built
205    /// away from the session (per-shard scan filters, index probes)
206    /// keep the default — they don't render text output.
207    pub render_style: crate::eval::format::RenderStyle,
208    /// v7.39 (tz epic) — host IANA timezone lookups for named zones
209    /// (session rendering, AT TIME ZONE, literal zone suffixes).
210    pub tz_offset_fn: Option<crate::TzOffsetFn>,
211    pub tz_localize_fn: Option<crate::TzLocalizeFn>,
212    pub tz_abbrev_fn: Option<crate::TzAbbrevFn>,
213    /// v7.38 (read01 P5.24) — host-provided CSPRNG (the server injects
214    /// `/dev/urandom`). Cryptographic builtins (`gen_random_bytes`,
215    /// `gen_salt`) draw from this instead of the process-static xorshift
216    /// PRNG, so their output isn't predictable. `None` (no host CSPRNG)
217    /// falls back to the PRNG — fine for the non-cryptographic `random()`.
218    pub salt_fn: Option<crate::SaltFn>,
219    /// v7.39 (read01 pgstatfuncs.c) — calling-connection identity for
220    /// pg_backend_pid(); `None` (embedded / detached contexts) → 1.
221    pub backend_pid_fn: Option<crate::BackendPidFn>,
222    /// v7.39 (round 476) — the WAL byte position, for the LSN functions.
223    pub wal_lsn_fn: Option<crate::WalLsnFn>,
224    /// v7.39 (round 318, V51) — host connection-control hook for
225    /// `pg_cancel_backend` / `pg_terminate_backend`. `None` (embedded /
226    /// detached contexts) ⇒ there is nothing to signal, so they answer
227    /// false rather than pretending the signal landed.
228    pub backend_signal_fn: Option<crate::BackendSignalFn>,
229    /// v7.38 (read01 P6.08) — host wall clock (µs since Unix epoch). `uuidv7`
230    /// uses it for the real time-ordered 48-bit millisecond prefix; `None`
231    /// (no host clock) falls back to the deterministic anchor.
232    pub clock: Option<crate::ClockFn>,
233    /// v7.38 (T24) — read-only view of the engine's transaction-version state,
234    /// so the `txid_*` / `pg_*_xact_id` / `pg_xact_status` builtins report the
235    /// real transaction ids instead of a constant stub. `None` on the scan /
236    /// join / aggregate contexts that never evaluate them.
237    pub xact: Option<XactView<'a>>,
238    /// v7.38 (T24) — PG's `txid_current()` ASSIGNS an id to a transaction that
239    /// has none. In autocommit a read-only statement has no writer version, so
240    /// the first call allocates one here and later calls in the same statement
241    /// reuse it — `SELECT txid_current(), txid_current()` must agree, as in PG.
242    pub assigned_xid: core::cell::Cell<Option<u64>>,
243}
244
245/// v7.38 (T24) — the transaction-id surface PG's `txid_*` family exposes.
246/// SPG's writer versions ARE its transaction ids (`row_header::next_version`),
247/// so no separate xid counter is needed — this is the bridge U22 was waiting
248/// on.
249#[derive(Clone, Copy, Debug)]
250pub struct XactView<'a> {
251    /// The id assigned to the current transaction (allocated at BEGIN) or, in
252    /// autocommit, to the current statement once it has written. `None` when
253    /// nothing has been assigned — `*_if_assigned` returns NULL there, as PG does.
254    pub current: Option<u64>,
255    /// Ids allocated by transactions that have neither committed nor aborted.
256    pub active: &'a alloc::collections::BTreeSet<u64>,
257    /// Ids of rolled-back transactions.
258    pub aborted: &'a alloc::collections::BTreeSet<u64>,
259}
260
261/// v7.17.0 — sequence-mutating callback used by `apply_function`
262/// for `nextval` / `currval` / `setval`. Implemented by the
263/// engine to thread `&mut Catalog` access through an immutable
264/// `&EvalContext`.
265pub type SequenceResolver<'a> = dyn Fn(SequenceOp) -> Result<i64, EvalError> + 'a;
266
267/// v7.17.0 — sequence operation requested by an Expr eval.
268#[derive(Debug, Clone)]
269pub enum SequenceOp {
270    Next(String),
271    Curr(String),
272    Set {
273        name: String,
274        value: i64,
275        is_called: bool,
276    },
277}
278
279impl<'a> EvalContext<'a> {
280    pub const fn new(columns: &'a [ColumnSchema], table_alias: Option<&'a str>) -> Self {
281        Self {
282            columns,
283            table_alias,
284            params: &[],
285            default_text_search_config: None,
286            sequence_resolver: None,
287            catalog: None,
288            mysql_dialect: false,
289            session_gucs: None,
290            users: None,
291            fn_depth: 0,
292            engine: None,
293            sample_rng: None,
294            recursion_base: core::cell::Cell::new(0),
295            render_style: crate::eval::format::RenderStyle {
296                date_style: crate::eval::format::DateStyleKind::Iso,
297                date_order: crate::eval::format::DateOrder::Mdy,
298                interval_style: crate::eval::format::IntervalStyleKind::Postgres,
299                extra_float_digits: 1,
300                bytea_escape: false,
301                mysql: false,
302            },
303            tz_offset_fn: None,
304            tz_localize_fn: None,
305            tz_abbrev_fn: None,
306            salt_fn: None,
307            backend_pid_fn: None,
308            wal_lsn_fn: None,
309            backend_signal_fn: None,
310            clock: None,
311            xact: None,
312            assigned_xid: core::cell::Cell::new(None),
313        }
314    }
315
316    /// v7.39 (GUC knife 3) — attach the session render style.
317    #[must_use]
318    pub const fn with_render_style(mut self, style: crate::eval::format::RenderStyle) -> Self {
319        self.render_style = style;
320        self
321    }
322
323    /// v7.39 (round 318, V51) — attach the host connection-control hook.
324    #[must_use]
325    pub const fn with_backend_signal_fn(mut self, f: Option<crate::BackendSignalFn>) -> Self {
326        self.backend_signal_fn = f;
327        self
328    }
329
330    /// v7.39 (round 476) — attach the WAL byte-position provider.
331    #[must_use]
332    pub const fn with_wal_lsn_fn(mut self, f: Option<crate::WalLsnFn>) -> Self {
333        self.wal_lsn_fn = f;
334        self
335    }
336
337    /// v7.39 (read01 pgstatfuncs.c) — attach the calling-connection id.
338    #[must_use]
339    pub const fn with_backend_pid_fn(mut self, f: Option<crate::BackendPidFn>) -> Self {
340        self.backend_pid_fn = f;
341        self
342    }
343
344    /// v7.39 (tz epic) — attach the host timezone lookups.
345    #[must_use]
346    pub const fn with_tz_fns(
347        mut self,
348        offset: Option<crate::TzOffsetFn>,
349        localize: Option<crate::TzLocalizeFn>,
350        abbrev: Option<crate::TzAbbrevFn>,
351    ) -> Self {
352        self.tz_offset_fn = offset;
353        self.tz_localize_fn = localize;
354        self.tz_abbrev_fn = abbrev;
355        self
356    }
357
358    /// v7.39 (tz epic) — offset (µs east) of an arbitrary zone spec at
359    /// a UTC instant: fixed forms resolve statically, named zones
360    /// through the host tzdb. None = unknown zone.
361    #[must_use]
362    pub fn zone_offset_at(&self, zone: &str, utc_micros: i64) -> Option<i64> {
363        if let Some(off) = datetime::resolve_zone_offset(zone) {
364            return Some(off);
365        }
366        self.tz_offset_fn.and_then(|f| f(zone, utc_micros))
367    }
368
369    /// v7.39 (tz epic) — the SESSION zone's offset at a UTC instant
370    /// (per-value: DST zones vary within one statement).
371    #[must_use]
372    pub fn session_tz_offset_at(&self, utc_micros: i64) -> i64 {
373        let Some(zone) = self.session_gucs.and_then(|g| g.get("timezone")) else {
374            return 0;
375        };
376        self.zone_offset_at(zone, utc_micros).unwrap_or(0)
377    }
378
379    /// v7.39 (tz epic) — the session zone's designation at an instant
380    /// (named zones only; None lets renderers spell UTC / +HH).
381    #[must_use]
382    pub fn session_tz_abbrev_at(&self, utc_micros: i64) -> Option<alloc::string::String> {
383        let zone = self.session_gucs.and_then(|g| g.get("timezone"))?;
384        if datetime::resolve_zone_offset(zone).is_some()
385            || zone.eq_ignore_ascii_case("utc")
386            || zone.eq_ignore_ascii_case("gmt")
387        {
388            return None;
389        }
390        self.tz_abbrev_fn.and_then(|f| f(zone, utc_micros))
391    }
392
393    /// v7.39 (tz epic) — local wall micros in `zone` -> UTC micros
394    /// (PG's DST disambiguation for named zones).
395    #[must_use]
396    pub fn zone_local_to_utc(&self, zone: &str, local_micros: i64) -> Option<i64> {
397        zone_local_to_utc_with(zone, local_micros, self.tz_localize_fn)
398    }
399
400    /// v7.38 (read01 P5.24) — attach the host CSPRNG so cryptographic
401    /// builtins don't fall back to the predictable PRNG.
402    #[must_use]
403    pub const fn with_salt_fn(mut self, f: Option<crate::SaltFn>) -> Self {
404        self.salt_fn = f;
405        self
406    }
407
408    /// v7.38 (read01 P6.08) — attach the host wall clock so `uuidv7` gets a
409    /// real time-ordered prefix instead of the deterministic anchor.
410    #[must_use]
411    pub const fn with_clock(mut self, f: Option<crate::ClockFn>) -> Self {
412        self.clock = f;
413        self
414    }
415
416    /// v7.38 (read01 U15) — attach a per-scan `TABLESAMPLE REPEATABLE`
417    /// sampler cell. The cell (seeded lazily on first `__tsm_fract` draw)
418    /// must outlive the context and be created fresh per scan so a rescan
419    /// re-seeds and reproduces the same sample.
420    #[must_use]
421    pub const fn with_sample_rng(mut self, cell: &'a core::cell::Cell<Option<u64>>) -> Self {
422        self.sample_rng = Some(cell);
423        self
424    }
425
426    /// Attach the session's GUC map so `current_setting` can resolve
427    /// custom (namespaced) settings written with `SET` / `set_config`.
428    #[must_use]
429    /// v7.39 (read01 round 63) — thread the engine (see `engine`).
430    pub const fn with_engine(mut self, engine: &'a crate::Engine) -> Self {
431        self.mysql_dialect = engine.backslash_escapes;
432        // v7.39 (round 368, M20 P3) — the dialect also decides how a binary
433        // string renders in a string context (latin-1 bytes vs PG `\x…`).
434        self.render_style.mysql = engine.backslash_escapes;
435        self.engine = Some(engine);
436        self
437    }
438
439    /// v7.39 (read01 round 58) — thread the role store (see `users`).
440    pub const fn with_users(mut self, users: &'a crate::users::UserStore) -> Self {
441        self.users = Some(users);
442        self
443    }
444
445    /// v7.39 (round 524) — attach a whole session bag at once. Every
446    /// write path needs the same four, and taking them one at a time is
447    /// how three of them ended up with none.
448    #[must_use]
449    pub(crate) fn with_session<'b: 'a>(mut self, s: &'b DmlSession) -> Self {
450        self.session_gucs = Some(&s.gucs);
451        self.users = Some(&s.users);
452        self.render_style = s.render_style;
453        self.tz_offset_fn = s.tz_offset_fn;
454        self.tz_localize_fn = s.tz_localize_fn;
455        self.tz_abbrev_fn = s.tz_abbrev_fn;
456        self
457    }
458
459    pub const fn with_session_gucs(
460        mut self,
461        gucs: &'a alloc::collections::BTreeMap<String, String>,
462    ) -> Self {
463        self.session_gucs = Some(gucs);
464        self
465    }
466
467    /// v7.37.16 (16.12) — attach a read-only catalog reference
468    /// so builtins like `pg_partition_root` can walk partition
469    /// roles. Defaults to None (NULL semantics).
470    #[must_use]
471    pub const fn with_catalog(mut self, catalog: &'a spg_storage::Catalog) -> Self {
472        self.catalog = Some(catalog);
473        self
474    }
475
476    /// v7.38 (T-tstz Phase 2) — the micro-offset of the session `TimeZone` GUC
477    /// (`SET TimeZone = '+09'` → +9h). A fixed offset / abbreviation resolves;
478    /// UTC and an unset GUC give 0; a named IANA zone (no tzdata) also gives 0
479    /// so a timestamptz still renders — as `+00` — rather than erroring on
480    /// every display. Timestamptz rendering / cast is the only consumer.
481    #[must_use]
482    pub fn session_tz_offset(&self) -> i64 {
483        self.session_gucs
484            .and_then(|g| g.get("timezone"))
485            .and_then(|z| datetime::resolve_zone_offset(z))
486            .unwrap_or(0)
487    }
488
489    /// v7.38 (T24) — attach the transaction-version view the `txid_*` builtins
490    /// read. Defaults to None, where they fall back to the process-wide cursor.
491    #[must_use]
492    pub const fn with_xact(mut self, xact: XactView<'a>) -> Self {
493        self.xact = Some(xact);
494        self
495    }
496
497    /// v7.17.0 — attach a sequence resolver. The engine wraps a
498    /// `&mut Catalog` in a closure that performs the requested
499    /// SequenceOp.
500    #[must_use]
501    pub const fn with_sequence_resolver(mut self, resolver: &'a SequenceResolver<'a>) -> Self {
502        self.sequence_resolver = Some(resolver);
503        self
504    }
505
506    /// v6.1.1 — attach a parameter buffer for `$N` placeholder
507    /// resolution. The slice must outlive the context; callers
508    /// construct it from the prepared statement's Bind values.
509    #[must_use]
510    pub const fn with_params(mut self, params: &'a [Value<'static>]) -> Self {
511        self.params = params;
512        self
513    }
514
515    /// v7.12.1 — attach the session's
516    /// `default_text_search_config`. Used by the FTS function
517    /// dispatcher when no explicit config arg is given.
518    #[must_use]
519    pub const fn with_default_text_search_config(mut self, cfg: Option<&'a str>) -> Self {
520        self.default_text_search_config = cfg;
521        self
522    }
523}
524
525/// v7.39 (round 523) — read a timestamp literal, reporting whether it
526/// carried an offset. Re-exported for the INSERT path, which decides
527/// there whether a value already names an instant.
528pub(crate) fn parse_timestamp_literal_tz_ordered_pub(
529    s: &str,
530    order: DateOrder,
531) -> Option<(i64, bool)> {
532    format::parse_timestamp_literal_tz_ordered(s, order)
533}
534
535/// v7.39 (round 523) — a FIXED zone's offset, when the name is one
536/// (`+09`, `UTC-5`). Named zones go through the host's tzdb instead.
537#[must_use]
538pub(crate) fn resolve_zone_offset_pub(zone: &str) -> Option<i64> {
539    datetime::resolve_zone_offset(zone)
540}
541
542/// v7.39 (round 523) — a wall-clock reading in `zone` as a UTC instant.
543///
544/// A free function because the INSERT path needs it too, and that path
545/// carries no `EvalContext`: it evaluates VALUES through a context-free
546/// literal walker. `EvalContext::zone_local_to_utc` delegates here so the
547/// two cannot drift.
548#[must_use]
549pub(crate) fn zone_local_to_utc_with(
550    zone: &str,
551    local_micros: i64,
552    localize: Option<crate::TzLocalizeFn>,
553) -> Option<i64> {
554    if let Some(off) = datetime::resolve_zone_offset(zone) {
555        return Some(local_micros - off);
556    }
557    localize.and_then(|f| f(zone, local_micros))
558}
559
560/// v7.39 (round 523) — the session zone an assignment to a timestamptz
561/// column is read in, or `None` when the session is on UTC and no shift
562/// applies.
563#[derive(Debug, Clone)]
564pub(crate) struct SessionCoercion {
565    /// The session zone, when it is not UTC. `None` leaves an instant
566    /// where it was.
567    pub zone: Option<alloc::string::String>,
568    pub localize: Option<crate::TzLocalizeFn>,
569    /// The session's date order. A written date is ambiguous
570    /// (`01/02/2020`), and this is what resolves it.
571    pub order: DateOrder,
572}
573
574impl SessionCoercion {
575    /// The UTC instant a naive wall-clock reading names in the session
576    /// zone, or `None` when the session is on UTC.
577    #[must_use]
578    pub(crate) fn wall_to_utc(&self, wall: i64) -> Option<i64> {
579        let zone = self.zone.as_ref()?;
580        zone_local_to_utc_with(zone, wall, self.localize)
581    }
582
583    /// v7.39 (round 524) — the session facts an ASSIGNMENT is read
584    /// under, from an evaluation context. `None` when both are the
585    /// defaults and nothing needs re-reading.
586    #[must_use]
587    pub(crate) fn from_ctx(ctx: &EvalContext<'_>) -> Option<Self> {
588        let zone = ctx
589            .session_gucs
590            .and_then(|g| g.get("timezone"))
591            .filter(|z| !z.eq_ignore_ascii_case("utc") && !z.eq_ignore_ascii_case("gmt"))
592            .cloned();
593        let order = ctx.render_style.date_order;
594        if zone.is_none() && order == DateOrder::Mdy {
595            return None;
596        }
597        Some(Self {
598            zone,
599            localize: ctx.tz_localize_fn,
600            order,
601        })
602    }
603}
604
605/// v7.39 (round 524) — the session facts a DML evaluation context needs,
606/// cloned so the row loop can still borrow the engine mutably.
607///
608/// Every write path built a BARE `EvalContext`, so an expression in an
609/// UPDATE's SET or a DELETE's WHERE was evaluated by an engine that knew
610/// nothing about the connection. One value, built once per statement,
611/// and a grep for `dml_session` finds every path that has it.
612pub(crate) struct DmlSession {
613    pub gucs: alloc::collections::BTreeMap<String, String>,
614    pub users: crate::users::UserStore,
615    pub render_style: RenderStyle,
616    pub tz_offset_fn: Option<crate::TzOffsetFn>,
617    pub tz_localize_fn: Option<crate::TzLocalizeFn>,
618    pub tz_abbrev_fn: Option<crate::TzAbbrevFn>,
619}
620
621/// v7.39 (round 524) — read a TEXT value bound for a temporal column
622/// under the session's date order.
623///
624/// `01/02/2020` is February 1st in a DMY session and January 2nd in an
625/// MDY one, and the write path was reading every one of them as MDY: a
626/// `SELECT '01/02/2020'::date` answered PG's value while the same
627/// literal INSERTed stored the day and month swapped. Nothing errors,
628/// and once stored the two readings are indistinguishable.
629#[must_use]
630pub(crate) fn session_read_temporal_text(
631    v: Value<'static>,
632    target: spg_storage::DataType,
633    coercion: Option<&SessionCoercion>,
634) -> Value<'static> {
635    use spg_storage::DataType as D;
636    let Some(c) = coercion else { return v };
637    if c.order == DateOrder::Mdy {
638        return v;
639    }
640    let Value::Text(s) = &v else { return v };
641    match target {
642        D::Date => format::parse_date_literal_ordered(s, c.order).map_or(v, Value::Date),
643        D::Timestamp | D::Timestamptz => format::parse_timestamp_literal_tz_ordered(s, c.order)
644            .map_or(v, |(t, _)| Value::Timestamp(t)),
645        _ => v,
646    }
647}
648
649#[derive(Debug, Clone, PartialEq)]
650pub enum EvalError {
651    ColumnNotFound {
652        name: String,
653    },
654    UnknownQualifier {
655        qualifier: String,
656    },
657    DivisionByZero,
658    TypeMismatch {
659        detail: String,
660    },
661    /// v6.1.1 — `$N` reference past the number of bound parameters.
662    /// Either the client sent too few in Bind, or the SQL has a
663    /// placeholder the prepared statement didn't account for.
664    PlaceholderOutOfRange {
665        n: u16,
666        bound: u16,
667    },
668    /// v7.38 (read01 P3.25) — the expression tree recursed deep enough to
669    /// threaten a native stack overflow; we bail out with an error the way
670    /// PG's `check_stack_depth()` does instead of aborting the process.
671    StackDepthExceeded,
672}
673
674impl core::fmt::Display for EvalError {
675    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
676        match self {
677            // v7.39 (read01 round 81) — PG's wording (and SQLSTATE trigger):
678            // `column "x" does not exist`, 42703. The old "column not found: x"
679            // matched none of the wire layer's `does not exist` patterns, so a
680            // missing column reached the client as the generic error class.
681            Self::ColumnNotFound { name } => write!(f, "column \"{name}\" does not exist"),
682            // v7.39 (round 241) — PG's wording (and 42P01 trigger): a
683            // qualifier that names no table in scope is "missing
684            // FROM-clause entry for table \"x\"". The old "unknown table
685            // qualifier" matched nothing a driver branches on.
686            Self::UnknownQualifier { qualifier } => {
687                write!(f, "missing FROM-clause entry for table \"{qualifier}\"")
688            }
689            Self::DivisionByZero => f.write_str("division by zero"),
690            Self::TypeMismatch { detail } => write!(f, "type mismatch: {detail}"),
691            Self::PlaceholderOutOfRange { n, bound } => write!(
692                f,
693                "parameter ${n} referenced but only {bound} bound by client"
694            ),
695            Self::StackDepthExceeded => {
696                f.write_str("stack depth limit exceeded (expression nested too deeply)")
697            }
698        }
699    }
700}
701
702/// v7.38 (read01 P3.25) — native-stack budget below the outermost
703/// `eval_expr` frame. Native stacks are typically 2–8 MB; 768 KiB leaves
704/// generous headroom while still permitting PG-class nesting depth (in a
705/// release build ~hundreds-to-thousands of frames fit under this).
706const MAX_EVAL_STACK_BYTES: usize = 768 * 1024;
707
708/// Address of a local in the current frame — a portable stand-in for the
709/// stack pointer (stacks grow downward on all supported targets).
710#[inline(never)]
711fn eval_stack_ptr() -> usize {
712    let probe = 0u8;
713    core::ptr::addr_of!(probe) as usize
714}
715
716/// v7.38 (read01 P6.40) — enforce a user DOMAIN's NOT NULL + CHECK constraints
717/// on a value being cast to it (`x::domain`). NULL fails a NOT NULL domain;
718/// otherwise every CHECK (which references the pseudo-column `VALUE`) must not
719/// evaluate to false. Returns the value unchanged when all constraints pass.
720fn apply_domain_constraints<'a>(
721    v: Value<'a>,
722    dom: &spg_storage::DomainDef,
723    name: &str,
724    cat: &spg_storage::Catalog,
725) -> Result<Value<'a>, EvalError> {
726    if matches!(v, Value::Null) {
727        // A NOT NULL anywhere in the chain rejects a NULL.
728        let mut cur = Some(dom);
729        while let Some(d) = cur {
730            if !d.nullable {
731                return Err(EvalError::TypeMismatch {
732                    detail: alloc::format!("domain {name} does not allow null values"),
733                });
734            }
735            cur = d
736                .base_domain
737                .as_ref()
738                .and_then(|p| cat.domain_types().get(p.as_str()));
739        }
740        return Ok(v);
741    }
742    // v7.39 (round 259) — walk the domain chain BASE-FIRST (probed: a
743    // value violating both a parent's and the child's constraint reports
744    // the PARENT's). The message names the domain being cast TO, but the
745    // constraint that actually failed — `value for domain pchild violates
746    // check constraint "pbase_check"`.
747    let mut chain: alloc::vec::Vec<&spg_storage::DomainDef> = alloc::vec![dom];
748    let mut cur = dom;
749    while let Some(parent) = cur
750        .base_domain
751        .as_ref()
752        .and_then(|p| cat.domain_types().get(p.as_str()))
753    {
754        // A cycle cannot be created through CREATE DOMAIN (the parent must
755        // already exist), but stop defensively rather than loop forever.
756        if chain.iter().any(|d| core::ptr::eq(*d, parent)) {
757            break;
758        }
759        chain.push(parent);
760        cur = parent;
761    }
762    chain.reverse();
763    for owner in chain {
764        apply_domain_checks_of(&v, owner, name)?;
765    }
766    Ok(v)
767}
768
769/// v7.39 (round 259) — run ONE domain's own CHECK list against `v`. The
770/// error names `target` (the domain the value is being cast to) and
771/// `owner` (whose constraint failed); for a single-level domain they are
772/// the same, which is the pre-259 wording.
773fn apply_domain_checks_of(
774    v: &Value<'_>,
775    dom: &spg_storage::DomainDef,
776    target: &str,
777) -> Result<(), EvalError> {
778    let name = target;
779    for chk in &dom.checks {
780        let src = &chk.expr;
781        // v7.39 (round 260) — report the constraint that failed by NAME.
782        let owner = chk.name.as_str();
783        let expr = spg_sql::parser::parse_expression(src).map_err(|e| EvalError::TypeMismatch {
784            detail: alloc::format!("domain {name} CHECK ({src:?}) failed to re-parse: {e:?}"),
785        })?;
786        let synth_cols = alloc::vec![spg_storage::ColumnSchema::new(
787            "value",
788            dom.base_type,
789            dom.nullable,
790        )];
791        let synth_ctx = EvalContext::new(&synth_cols, None);
792        // Owned copy so the temporary row doesn't borrow `v`'s lifetime.
793        let synth_row = spg_storage::Row {
794            values: alloc::vec![v.clone().into_owned()],
795        };
796        let r = eval_expr(&expr, &synth_row, &synth_ctx)?;
797        if matches!(r, Value::Bool(false)) {
798            return Err(EvalError::TypeMismatch {
799                detail: alloc::format!(
800                    "value for domain {name} violates check constraint \"{owner}\""
801                ),
802            });
803        }
804    }
805    Ok(())
806}
807
808/// v7.38 (read01 P6.67) — validate a value cast to a user ENUM: a text label
809/// must be one of the enum's members (else error, as PG does); a NULL is a
810/// valid typed null. The stored representation stays the text label.
811/// v7.39 (read01 rowtypes.c) — cast into a user composite type: parse the
812/// `(v1,"v 2",)` record text (double-quote wrapping with doubled quotes,
813/// empty field = NULL) and coerce each field to the declared type; a ROW
814/// value re-labels positionally.
815/// v7.39 (round 350/351, M7 + M11) — how MySQL reads a TEXT operand of
816/// an arithmetic or comparison operator. The identity in the PG dialect,
817/// and out-of-line so it costs the recursive `eval_expr` frame nothing.
818///
819/// Measured on MariaDB 11: `'2024-01-15' + INTERVAL 1 DAY` shifts the
820/// date; `'1abc'+0` is 1, `'abc'+0` is 0, `'2024-01-15'+0` is 2024; two
821/// strings compare as STRINGS (`'10' > '9'` is 0) while a mixed pair
822/// compares numerically (`'10' > 9` is 1).
823#[inline(never)]
824pub(crate) fn mysql_operand_reading_pair(
825    op: BinOp,
826    l: Value<'static>,
827    r: Value<'static>,
828) -> (Value<'static>, Value<'static>) {
829    if !mysql_coerces(op) {
830        return (l, r);
831    }
832    match (&l, &r) {
833        (Value::Text(t), Value::Interval { .. }) => (text_as_temporal(t).unwrap_or(l.clone()), r),
834        (Value::Interval { .. }, Value::Text(t)) => {
835            let rr = text_as_temporal(t).unwrap_or(r.clone());
836            (l, rr)
837        }
838        // v7.39 (round 353, M10) — a boolean IS an integer in MySQL, so
839        // `!1 + 1` is 1 (measured). It was `operator does not exist:
840        // boolean + integer`.
841        (Value::Bool(b), other)
842            if mysql_arith(op) && other.data_type().is_some_and(is_numeric_type) =>
843        {
844            (Value::BigInt(i64::from(*b)), r)
845        }
846        (other, Value::Bool(b))
847            if mysql_arith(op) && other.data_type().is_some_and(is_numeric_type) =>
848        {
849            let rr = Value::BigInt(i64::from(*b));
850            (l, rr)
851        }
852        (Value::Text(t), other) if other.data_type().is_some_and(is_numeric_type) => {
853            (mysql_number_of(t), r)
854        }
855        (other, Value::Text(t)) if other.data_type().is_some_and(is_numeric_type) => {
856            let rr = mysql_number_of(t);
857            (l, rr)
858        }
859        // v7.39 (round 367, M20 P2) — a binary string beside a number
860        // reads as its big-endian integer value (`0x10 + 0` = 16,
861        // `0x10 = 16` is true). Beside a Text operand it stays bytes so
862        // the byte-wise string compare (`0x61 = 'a'`) still fires.
863        (Value::Bytes(b), other) if other.data_type().is_some_and(is_numeric_type) => {
864            (mysql_bytes_as_number(b), r)
865        }
866        (other, Value::Bytes(b)) if other.data_type().is_some_and(is_numeric_type) => {
867            let rr = mysql_bytes_as_number(b);
868            (l, rr)
869        }
870        // Arithmetic between two strings is numeric; comparison is not.
871        (Value::Text(a), Value::Text(b)) if mysql_arith(op) => {
872            (mysql_number_of(a), mysql_number_of(b))
873        }
874        _ => (l, r),
875    }
876}
877
878/// Is this a mixed string/number pair, which MySQL compares numerically?
879fn mysql_mixed_pair(l: &Value<'_>, r: &Value<'_>) -> bool {
880    matches!((l, r), (Value::Text(_), o) | (o, Value::Text(_))
881        if o.data_type().is_some_and(is_numeric_type))
882}
883
884const fn mysql_arith(op: BinOp) -> bool {
885    matches!(
886        op,
887        BinOp::Add | BinOp::Sub | BinOp::Mul | BinOp::Div | BinOp::Mod
888    )
889}
890
891/// Does this comparison need the owned path — because a value's type
892/// wants it, because a CI collation folds it, or (MySQL) because a mixed
893/// string/number pair compares NUMERICALLY there while two strings
894/// compare as strings.
895#[inline(never)]
896fn needs_owned_compare(
897    lc: &Value<'_>,
898    rc: &Value<'_>,
899    lhs: &Expr,
900    rhs: &Expr,
901    ctx: &EvalContext<'_>,
902) -> bool {
903    is_owned_compare_value(lc)
904        || is_owned_compare_value(rc)
905        || compare_is_case_insensitive(lhs, rhs, ctx)
906        || (ctx.mysql_dialect && mysql_mixed_pair(lc, rc))
907}
908
909/// Which operators take MySQL's string→number reading.
910const fn mysql_coerces(op: BinOp) -> bool {
911    matches!(
912        op,
913        BinOp::Add
914            | BinOp::Sub
915            | BinOp::Mul
916            | BinOp::Div
917            | BinOp::Mod
918            | BinOp::Eq
919            | BinOp::NotEq
920            | BinOp::Lt
921            | BinOp::LtEq
922            | BinOp::Gt
923            | BinOp::GtEq
924    )
925}
926
927/// Does this type take part in MySQL's numeric coercion?
928fn is_numeric_type(t: spg_storage::DataType) -> bool {
929    use spg_storage::DataType as D;
930    matches!(
931        t,
932        D::SmallInt | D::Int | D::BigInt | D::Float | D::Real | D::Numeric { .. }
933    )
934}
935
936/// v7.39 (round 364, M4 P2) — a value as it participates in a MySQL
937/// session's default-collation comparison: text folds (accent- and
938/// case-insensitive), everything else is itself. Used by IN and LIKE,
939/// whose comparisons do not pass through `collation_fold_for_compare`.
940fn mysql_collation_key(v: Value<'static>, mysql: bool) -> Value<'static> {
941    match v {
942        Value::Text(s) if mysql => Value::text(spg_storage::mysql_compare_fold(&s)),
943        other => other,
944    }
945}
946
947/// A string as MySQL reads it in numeric position: an exact integer when
948/// the leading number is one, otherwise a double.
949#[inline(never)]
950fn mysql_number_of(s: &str) -> Value<'static> {
951    let n = mysql_leading_number(s);
952    if n.fract() == 0.0 && n.abs() < 9.007_199_254_740_992e15 {
953        #[allow(clippy::cast_possible_truncation)]
954        Value::BigInt(n as i64)
955    } else {
956        Value::Float(n)
957    }
958}
959
960/// v7.39 (round 367, M20 P2) — a MySQL binary string (a `0x…` / `X'…'` /
961/// `b'…'` literal, backed by `Value::Bytes`) reads as its bytes'
962/// BIG-ENDIAN unsigned integer in a numeric context: `0x4142 + 0` is
963/// 16706, `0x10 = 16` is true (measured on MariaDB 11). Only the low 16
964/// bytes participate — a hex literal used in arithmetic is at most an
965/// 8-byte BIGINT in practice — and a value past `i64::MAX` becomes a
966/// NUMERIC so nothing wraps negative.
967fn mysql_bytes_as_number(b: &[u8]) -> Value<'static> {
968    let start = b.len().saturating_sub(16);
969    let acc = b[start..]
970        .iter()
971        .fold(0u128, |a, &x| (a << 8) | u128::from(x));
972    if acc <= i64::MAX as u128 {
973        #[allow(clippy::cast_possible_truncation)]
974        Value::BigInt(acc as i64)
975    } else {
976        crate::conversions::big_literal_to_value(&alloc::format!("{acc}"))
977    }
978}
979
980/// MySQL's `/`: a real division, and NULL on a zero divisor. `None`
981/// when this pairing is not the integer/integer case PG and MySQL
982/// disagree about.
983#[inline(never)]
984pub(crate) fn mysql_true_division(
985    op: BinOp,
986    l: &Value<'_>,
987    r: &Value<'_>,
988    text_operand: bool,
989) -> Option<Value<'static>> {
990    // v7.39 (round 372) — MySQL's `x % 0` / `x MOD 0` is NULL, not the PG
991    // "division by zero" error (measured on MariaDB 11: `10%0`, `10 MOD
992    // 0`, `10.5%0` are all NULL, matching `1/0`). A non-zero divisor takes
993    // the normal modulo path.
994    if matches!(op, BinOp::Mod) {
995        return if value_is_zero(r) {
996            Some(Value::Null)
997        } else {
998            None
999        };
1000    }
1001    if !matches!(op, BinOp::Div) {
1002        return None;
1003    }
1004    // v7.39 (round 393) — MariaDB `/` on exact (int / decimal) operands is a
1005    // DECIMAL whose scale is the LEFT operand's scale + 4 (`7/2` is 3.5000,
1006    // `10.0/3` is 3.33333, `7.00/2` is 3.500000), NOT a float. A float /
1007    // double operand — or a STRING one, `'10'/'4'` is 2.5 (double) — makes
1008    // the result a float; a zero divisor is NULL.
1009    if text_operand
1010        || matches!(l, Value::Float(_) | Value::Real(_))
1011        || matches!(r, Value::Float(_) | Value::Real(_))
1012    {
1013        let f = |v: &Value<'_>| -> Option<f64> {
1014            match v {
1015                Value::Float(x) => Some(*x),
1016                Value::Real(x) => Some(f64::from(*x)),
1017                Value::SmallInt(n) => Some(f64::from(*n)),
1018                Value::Int(n) => Some(f64::from(*n)),
1019                #[allow(clippy::cast_precision_loss)]
1020                Value::BigInt(n) => Some(*n as f64),
1021                _ => None,
1022            }
1023        };
1024        let (a, b) = (f(l)?, f(r)?);
1025        return Some(if b == 0.0 {
1026            Value::Null
1027        } else {
1028            Value::Float(a / b)
1029        });
1030    }
1031    let (ls, lsc) = exact_decimal_parts(l)?;
1032    let (rs, rsc) = exact_decimal_parts(r)?;
1033    if rs == 0 {
1034        return Some(Value::Null);
1035    }
1036    let result_scale = u32::from(lsc) + 4;
1037    // result_scaled = round( ls * 10^(rsc + 4) / rs ), half away from zero.
1038    let pow = 10i128.checked_pow(u32::from(rsc) + 4)?;
1039    let num = ls.checked_mul(pow)?;
1040    let q = num / rs;
1041    let rem = num % rs;
1042    let bump = if rem.unsigned_abs() * 2 >= rs.unsigned_abs() {
1043        if (num < 0) == (rs < 0) { 1 } else { -1 }
1044    } else {
1045        0
1046    };
1047    Some(Value::numeric(q + bump, u16::try_from(result_scale).ok()?))
1048}
1049
1050/// The `(scaled, scale)` of an exact integer / NUMERIC value: an integer
1051/// has scale 0. None for a float / non-numeric (they take the float path).
1052fn exact_decimal_parts(v: &Value<'_>) -> Option<(i128, u16)> {
1053    match v {
1054        Value::SmallInt(n) => Some((i128::from(*n), 0)),
1055        Value::Int(n) => Some((i128::from(*n), 0)),
1056        Value::BigInt(n) => Some((i128::from(*n), 0)),
1057        Value::Numeric {
1058            scaled,
1059            scale,
1060            kind: spg_storage::NumericKind::Finite,
1061        } => Some((*scaled, *scale)),
1062        _ => None,
1063    }
1064}
1065
1066/// v7.39 (round 383) — the UNSIGNED 64-bit value a MySQL bitwise operand
1067/// reads as. MySQL's `& | ^ ~ << >>` all work on `BIGINT UNSIGNED`, so an
1068/// operand is its 64-bit two's-complement pattern (a negative integer:
1069/// `-5` is `0xFFFF…FB`), rounded to the nearest integer (a float / numeric:
1070/// `2.9` is 3), its big-endian value (a `0x…` binary string), or its
1071/// leading number (a string). Anything else (an inet, a range, a
1072/// bit-string) returns None so the operator keeps its own meaning.
1073#[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
1074fn mysql_bit_u64(v: &Value<'_>) -> Option<u64> {
1075    match v {
1076        Value::SmallInt(n) => Some(i64::from(*n) as u64),
1077        Value::Int(n) => Some(i64::from(*n) as u64),
1078        Value::BigInt(n) => Some(*n as u64),
1079        Value::Bool(b) => Some(u64::from(*b)),
1080        Value::Float(x) => Some(x.round() as i64 as u64),
1081        Value::Real(x) => Some(f64::from(*x).round() as i64 as u64),
1082        Value::Numeric {
1083            scaled,
1084            scale,
1085            kind: spg_storage::NumericKind::Finite,
1086        } => {
1087            // Round half away from zero to an integer, then take the low
1088            // 64 bits (two's complement) — `~2.9` is `~3`.
1089            if *scale > 38 {
1090                return None;
1091            }
1092            let div = 10i128.pow(u32::from(*scale));
1093            let q = scaled / div;
1094            let rem = scaled % div;
1095            let rounded = if rem.unsigned_abs() * 2 >= div.unsigned_abs() {
1096                q + scaled.signum()
1097            } else {
1098                q
1099            };
1100            Some(rounded as u64)
1101        }
1102        Value::Bytes(b) => mysql_bit_u64(&mysql_bytes_as_number(b)),
1103        Value::Text(s) => mysql_bit_u64(&mysql_number_of(s)),
1104        _ => None,
1105    }
1106}
1107
1108/// A MySQL bitwise result — a `BIGINT UNSIGNED`. It stays a signed
1109/// `BigInt` while it fits (so an integer-context consumer — MAKE_SET
1110/// bits, ELT / SUBSTRING / REPEAT counts — still takes it); a value past
1111/// `i64::MAX` (a set bit 63, e.g. `~5`) has no signed integer type, so it
1112/// becomes a scale-0 NUMERIC, which holds the whole `0..=2^64-1` range and
1113/// renders as the plain integer MySQL prints.
1114fn u64_as_value(n: u64) -> Value<'static> {
1115    match i64::try_from(n) {
1116        Ok(v) => Value::BigInt(v),
1117        Err(_) => Value::numeric(i128::from(n), 0),
1118    }
1119}
1120
1121/// v7.39 (round 383) — the MySQL bitwise operators on UNSIGNED 64-bit
1122/// integers. Returns None when either operand is not number-like (so an
1123/// `inet << int` / `bit(n) & bit(n)` / geometric `#` keeps its own path)
1124/// or the operator is not bitwise. A shift of 64 or more is 0 (MySQL does
1125/// not mask the shift count).
1126pub(crate) fn mysql_bitwise(op: BinOp, l: &Value<'_>, r: &Value<'_>) -> Option<Value<'static>> {
1127    let out = match op {
1128        BinOp::BitAnd => mysql_bit_u64(l)? & mysql_bit_u64(r)?,
1129        BinOp::BitOr => mysql_bit_u64(l)? | mysql_bit_u64(r)?,
1130        BinOp::BitXor => mysql_bit_u64(l)? ^ mysql_bit_u64(r)?,
1131        // `<<` / `>>` share the inet-containment BinOps; a numeric pair is a
1132        // shift, anything else stays inet / range / bit-string.
1133        BinOp::InetContainedBy => {
1134            let (a, n) = (mysql_bit_u64(l)?, mysql_bit_u64(r)?);
1135            if n >= 64 { 0 } else { a << n }
1136        }
1137        BinOp::InetContains => {
1138            let (a, n) = (mysql_bit_u64(l)?, mysql_bit_u64(r)?);
1139            if n >= 64 { 0 } else { a >> n }
1140        }
1141        _ => return None,
1142    };
1143    Some(u64_as_value(out))
1144}
1145
1146/// v7.39 (round 383) — MySQL unary `~x`: the UNSIGNED 64-bit complement
1147/// (`~5` is 18446744073709551610). None for a non-number operand (a
1148/// bit-string / inet / macaddr keeps PG's typed complement).
1149pub(crate) fn mysql_bit_not(v: &Value<'_>) -> Option<Value<'static>> {
1150    Some(u64_as_value(!mysql_bit_u64(v)?))
1151}
1152
1153/// v7.39 (round 390, type-fidelity epic P5) — the inline `SET('a','b',…)`
1154/// variant list an expression's column is declared with, or None. Mirrors
1155/// `expr_enum_type_name` — a bare `Expr::Column` looked up by name.
1156pub(crate) fn expr_set_variants<'e>(
1157    e: &'e Expr,
1158    columns: &'e [ColumnSchema],
1159) -> Option<&'e [String]> {
1160    match e {
1161        Expr::Column(c) => columns
1162            .iter()
1163            .find(|col| col.name == c.name)
1164            .and_then(|col| col.inline_set_variants.as_deref()),
1165        _ => None,
1166    }
1167}
1168
1169/// v7.39 (round 402) — the inline `ENUM('a','b',…)` variant list an
1170/// expression's column is declared with, or None. Like `expr_set_variants`.
1171pub(crate) fn expr_inline_enum_variants<'e>(
1172    e: &'e Expr,
1173    columns: &'e [ColumnSchema],
1174) -> Option<&'e [String]> {
1175    match e {
1176        Expr::Column(c) => columns
1177            .iter()
1178            .find(|col| col.name == c.name)
1179            .and_then(|col| col.inline_enum_variants.as_deref()),
1180        _ => None,
1181    }
1182}
1183
1184/// The 1-based ordinal a stored inline-ENUM text carries in a numeric
1185/// context (`e + 0` is 1 for the first member); the empty string / an
1186/// unknown member is 0 (MySQL's implicit `''` enum error value).
1187pub(crate) fn enum_text_to_ordinal(text: &str, variants: &[String]) -> i64 {
1188    variants
1189        .iter()
1190        .position(|v| v == text)
1191        .map_or(0, |p| p as i64 + 1)
1192}
1193
1194/// The bitmask a stored SET text carries in a numeric context: each
1195/// comma-separated member contributes `1 << its position` in the declared
1196/// variant list (`'a,c'` over `('a','b','c','d')` is 1 | 4 = 5). An empty
1197/// string is 0; an unknown member (should not occur — the write path
1198/// validates) contributes nothing.
1199pub(crate) fn set_text_to_bitmask(text: &str, variants: &[String]) -> i64 {
1200    if text.is_empty() {
1201        return 0;
1202    }
1203    let mut bits = 0i64;
1204    for member in text.split(',') {
1205        if let Some(pos) = variants.iter().position(|v| v == member) {
1206            bits |= 1i64 << pos;
1207        }
1208    }
1209    bits
1210}
1211
1212/// Is this an arithmetic / bitwise operator MySQL evaluates a SET column
1213/// numerically under? (`s + 0`, `s & flag`, …). The comparison operators
1214/// are NOT here — `s = 'a,c'` stays a text compare.
1215pub(crate) const fn is_mysql_numeric_binop(op: BinOp) -> bool {
1216    matches!(
1217        op,
1218        BinOp::Add
1219            | BinOp::Sub
1220            | BinOp::Mul
1221            | BinOp::Div
1222            | BinOp::Mod
1223            | BinOp::BitAnd
1224            | BinOp::BitOr
1225            | BinOp::BitXor
1226            | BinOp::InetContainedBy
1227            | BinOp::InetContains
1228    )
1229}
1230
1231/// v7.39 (round 372) — is `v` a numeric zero (any width / kind)? Used to
1232/// route `x % 0` / `MOD(x, 0)` to NULL under the MySQL dialect.
1233pub(crate) fn value_is_zero(v: &Value<'_>) -> bool {
1234    match v {
1235        Value::SmallInt(n) => *n == 0,
1236        Value::Int(n) => *n == 0,
1237        Value::BigInt(n) => *n == 0,
1238        Value::Float(x) => *x == 0.0,
1239        Value::Real(x) => *x == 0.0,
1240        Value::Numeric { scaled, .. } => *scaled == 0,
1241        _ => false,
1242    }
1243}
1244
1245/// `-'5'` in the MySQL dialect. Out-of-line for the same frame reason.
1246#[inline(never)]
1247fn mysql_negate_text(
1248    op: spg_sql::ast::UnOp,
1249    v: &Value<'static>,
1250) -> Option<Result<Value<'static>, EvalError>> {
1251    match v {
1252        Value::Text(t) => Some(apply_unary(op, mysql_number_of(t))),
1253        _ => None,
1254    }
1255}
1256
1257/// The MySQL reading of a unary operator, or None to let `apply_unary` (the
1258/// PG path) run. Kept out of `eval_expr`'s recursive frame — see the
1259/// round-383 frame cliff. Covers `NOT` on any truth value (round 346),
1260/// `-'str'` numeric negation (round 351), and the unsigned `~` complement
1261/// (round 383).
1262#[inline(never)]
1263fn mysql_unary_arm(
1264    op: spg_sql::ast::UnOp,
1265    v: &Value<'static>,
1266) -> Option<Result<Value<'static>, EvalError>> {
1267    use spg_sql::ast::UnOp;
1268    match op {
1269        // `NOT 5` is 0 — read any non-bool as a truth value; a bool / NULL
1270        // keeps the PG path (still refused there for non-bool).
1271        UnOp::Not if !matches!(v, Value::Bool(_) | Value::Null) => Some(mysql_not(v)),
1272        // `-'5'` is -5, `-'abc'` is 0.
1273        UnOp::Neg => mysql_negate_text(op, v),
1274        // `+ anything` is that thing: measured on MariaDB 11, `+'x'` is
1275        // 'x', `+TRUE` is 1, `+NULL` is NULL. No type check at all, unlike
1276        // PG, which refuses every non-numeric operand.
1277        UnOp::Plus => Some(Ok(v.clone())),
1278        // `~5` is the unsigned 64-bit complement; NULL stays NULL (PG path).
1279        UnOp::BitNot if !matches!(v, Value::Null) => mysql_bit_not(v).map(Ok),
1280        _ => None,
1281    }
1282}
1283
1284/// A date / timestamp string as its temporal value, or `None` when it is
1285/// not one (in which case the operand is left exactly as it was).
1286#[inline(never)]
1287fn text_as_temporal(t: &str) -> Option<Value<'static>> {
1288    parse_timestamp_literal(t)
1289        .map(Value::Timestamp)
1290        .or_else(|| parse_date_literal(t).map(Value::Date))
1291}
1292
1293/// v7.39 (round 620) — an unadorned string literal, which is what PG calls
1294/// `unknown`: a value whose type the context gets to choose. `''::TEXT` is
1295/// not one, and neither is a text column.
1296fn is_unknown_string_literal(e: &Expr) -> bool {
1297    matches!(e, Expr::Literal(spg_sql::ast::Literal::String(_)))
1298}
1299
1300/// v7.39 (round 620) — resolve such a literal to boolean, which is what a
1301/// boolean connective asks of it. An unparseable one is PG's input-syntax
1302/// error (22P02), not a type complaint: `'a' AND true` says
1303/// `invalid input syntax for type boolean: "a"`, exactly as `'a'::BOOLEAN`
1304/// does — same failure, same words, because it is the same coercion.
1305#[inline(never)]
1306fn coerce_unknown_literal_to_bool(e: &Expr) -> Result<Value<'static>, EvalError> {
1307    let Expr::Literal(spg_sql::ast::Literal::String(s)) = e else {
1308        unreachable!("guarded by is_unknown_string_literal")
1309    };
1310    cast::cast_value_in(
1311        Value::Text(s.clone().into()),
1312        spg_sql::ast::CastTarget::Bool,
1313        false,
1314    )
1315}
1316
1317/// v7.39 (round 621) — a literal that is plainly not a boolean, and the PG
1318/// type name for it. `NULL` and a bare string literal are deliberately absent:
1319/// neither carries a type of its own, and a boolean connective is a context
1320/// that gives them one.
1321fn non_boolean_literal_type(e: &Expr) -> Option<&'static str> {
1322    use spg_sql::ast::Literal as L;
1323    match e {
1324        Expr::Literal(L::Integer(_)) => Some("integer"),
1325        Expr::Literal(L::Float(_)) => Some("double precision"),
1326        Expr::Literal(L::Numeric { .. } | L::NumericBig(_)) => Some("numeric"),
1327        _ => None,
1328    }
1329}
1330
1331/// v7.39 (round 621) — `AND` / `OR`, evaluated the way PG evaluates them.
1332///
1333/// Round 620 handled the unknown literal here; round 621 adds the part that
1334/// makes `WHERE x <> 0 AND 1/x > 0` work at all. SPG evaluated both sides
1335/// always, so the guard idiom — the whole reason that predicate is written
1336/// that way — raised on the very rows the guard exists to exclude. Measured
1337/// against PG: `false AND (1/0 = 0)` answers `f`, `true OR (1/0 = 0)` answers
1338/// `t`, and a filter guarded that way returns its rows.
1339///
1340/// PG affords that AND still refuses `false AND 1`, because the two happen at
1341/// different times: the operand types are checked during ANALYSIS, before any
1342/// evaluation, and the short circuit is a RUN-TIME decision. Both parts are
1343/// here — the right-hand operand's type is read statically (it is the side
1344/// that may go unevaluated), and only a type that is definitively known and
1345/// definitively not boolean is refused. An unknown type is left alone, so a
1346/// shape the describer cannot type keeps the old behaviour rather than
1347/// earning a spurious error.
1348///
1349/// Order is PG's too, and it is strictly left-first: `(1/0 = 0) AND false`
1350/// raises on both, because the left is evaluated before anything can decide
1351/// that it did not need to be.
1352///
1353/// Out-of-line so it costs `eval_expr` no frame (the round-305 frame cliff).
1354#[inline(never)]
1355fn eval_connective(
1356    lhs: &Expr,
1357    op: BinOp,
1358    rhs: &Expr,
1359    row: &Row<'static>,
1360    ctx: &EvalContext<'_>,
1361) -> Result<Value<'static>, EvalError> {
1362    let side = |e: &Expr| -> Result<Value<'static>, EvalError> {
1363        if is_unknown_string_literal(e) {
1364            coerce_unknown_literal_to_bool(e)
1365        } else {
1366            eval_expr(e, row, ctx)
1367        }
1368    };
1369    let l = side(lhs)?;
1370    // The analysis-time half: refuse a right-hand operand that is plainly not
1371    // boolean, whether or not the short circuit would reach it.
1372    //
1373    // Only a LITERAL is read this way. The first cut asked
1374    // `describe_expr_type` for any expression's type, and it answers
1375    // confidently and wrongly for shapes that matter here — `NULL` comes back
1376    // as text, so `true AND NULL` earned a type error; and a MATCH … AGAINST
1377    // folds internally into an OR over tsvector operands, so full-text search
1378    // stopped working. Three existing pins caught all of it. A literal cannot
1379    // be misread, and it is what PG's own refusals in this area are about.
1380    if let Some(ty) = non_boolean_literal_type(rhs) {
1381        return Err(EvalError::TypeMismatch {
1382            detail: alloc::format!(
1383                "argument of {} must be type boolean, not type {ty}",
1384                if matches!(op, BinOp::And) {
1385                    "AND"
1386                } else {
1387                    "OR"
1388                },
1389            ),
1390        });
1391    }
1392    // Resolving an unknown literal belongs to the same half — it is a
1393    // coercion PG performs while analysing, so `false AND 'a'` says
1394    // `invalid input syntax for type boolean: "a"` rather than answering `f`.
1395    let rhs_resolved = if is_unknown_string_literal(rhs) {
1396        Some(coerce_unknown_literal_to_bool(rhs)?)
1397    } else {
1398        None
1399    };
1400    // The run-time half.
1401    match (op, &l) {
1402        (BinOp::And, Value::Bool(false)) => return Ok(Value::Bool(false)),
1403        (BinOp::Or, Value::Bool(true)) => return Ok(Value::Bool(true)),
1404        _ => {}
1405    }
1406    let r = match rhs_resolved {
1407        Some(v) => v,
1408        None => side(rhs)?,
1409    };
1410    if matches!(op, BinOp::And) {
1411        and_3vl(l, r)
1412    } else {
1413        apply_binary(op, l, r)
1414    }
1415}
1416
1417/// v7.39 (round 346, M1) — the MySQL reading of `AND` / `OR`, out-of-line
1418/// so it costs `eval_expr` no frame (see the round-305 frame cliff).
1419#[inline(never)]
1420fn eval_mysql_connective(
1421    lhs: &Expr,
1422    op: BinOp,
1423    rhs: &Expr,
1424    row: &Row<'static>,
1425    ctx: &EvalContext<'_>,
1426) -> Result<Value<'static>, EvalError> {
1427    let l = as_mysql_truth(eval_expr(lhs, row, ctx)?)?;
1428    let r = as_mysql_truth(eval_expr(rhs, row, ctx)?)?;
1429    apply_mysql_connective(op, l, r)
1430}
1431
1432/// v7.39 (round 407) — apply a MySQL logical connective (`AND` / `OR` /
1433/// `XOR`) to two operands already reduced to truth values (`Bool` or
1434/// `Null`). AND / OR reuse the dialect-blind `apply_binary`; `XOR` is
1435/// MySQL-only (no `apply_binary` arm) and computed here: NULL on either
1436/// side yields NULL, otherwise the exclusive-or of the two truth values.
1437pub(crate) fn apply_mysql_connective(
1438    op: BinOp,
1439    l: Value<'static>,
1440    r: Value<'static>,
1441) -> Result<Value<'static>, EvalError> {
1442    if op == BinOp::LogicalXor {
1443        return Ok(match (&l, &r) {
1444            (Value::Bool(a), Value::Bool(b)) => Value::Bool(a != b),
1445            _ => Value::Null,
1446        });
1447    }
1448    apply_binary(op, l, r)
1449}
1450
1451#[inline(never)]
1452pub(crate) fn as_mysql_truth(v: Value<'static>) -> Result<Value<'static>, EvalError> {
1453    Ok(match v {
1454        Value::Null => Value::Null,
1455        other => Value::Bool(predicate_is_true(&other, "AND", true)?),
1456    })
1457}
1458
1459/// The MySQL reading of `NOT`, likewise out-of-line.
1460#[inline(never)]
1461fn mysql_not(v: &Value<'_>) -> Result<Value<'static>, EvalError> {
1462    Ok(Value::Bool(!predicate_is_true(v, "NOT", true)?))
1463}
1464
1465/// v7.39 (round 346, M1) — is this value TRUE, in a position that wants a
1466/// truth value (WHERE / CASE WHEN / NOT / AND / OR / HAVING / ON)?
1467///
1468/// The engine used to write `matches!(v, Value::Bool(true))` at every such
1469/// position, so anything that was not already a boolean silently read as
1470/// FALSE. `SELECT CASE WHEN 1 THEN 'a' END` answered NULL and — far worse —
1471/// `SELECT … WHERE 1` returned **no rows at all**. Neither dialect does
1472/// that: MariaDB 11 takes any non-zero number as true, and PG 18.4 raises
1473/// `argument of WHERE must be type boolean, not type integer`.
1474///
1475/// NULL is not true (three-valued logic) and is not an error in either.
1476pub(crate) fn predicate_is_true(v: &Value<'_>, kw: &str, mysql: bool) -> Result<bool, EvalError> {
1477    match v {
1478        Value::Bool(b) => Ok(*b),
1479        Value::Null => Ok(false),
1480        _ if mysql => Ok(mysql_truthy(v)),
1481        // PG resolves a bare literal in this position through boolean
1482        // INPUT, so `CASE WHEN 'true'` is legal and `'abc'` is not.
1483        Value::Text(t) => match crate::eval::cast::cast_value(
1484            Value::text(t.to_string()),
1485            spg_sql::ast::CastTarget::Bool,
1486        )? {
1487            Value::Bool(b) => Ok(b),
1488            _ => Ok(false),
1489        },
1490        other => Err(EvalError::TypeMismatch {
1491            detail: alloc::format!(
1492                "argument of {kw} must be type boolean, not type {}",
1493                crate::eval::strings::pg_typeof_name(other)
1494            ),
1495        }),
1496    }
1497}
1498
1499/// MariaDB 11's reading, measured: a number is true when it is not zero
1500/// (`-1` and `0.5` are both true); a string contributes its LEADING
1501/// number, so `'1abc'` is true while `'abc'` and `''` are false.
1502fn mysql_truthy(v: &Value<'_>) -> bool {
1503    match v {
1504        Value::Bool(b) => *b,
1505        Value::Null => false,
1506        Value::SmallInt(n) => *n != 0,
1507        Value::Int(n) => *n != 0,
1508        Value::BigInt(n) => *n != 0,
1509        Value::Float(f) => *f != 0.0,
1510        Value::Real(f) => *f != 0.0,
1511        Value::Numeric { scaled, .. } => *scaled != 0,
1512        Value::Text(t) => mysql_leading_number(t) != 0.0,
1513        Value::BpChar(t) => mysql_leading_number(t) != 0.0,
1514        // Everything else converts to a non-zero number in MariaDB (a
1515        // DATE reads as its YYYYMMDD digits, for one).
1516        _ => true,
1517    }
1518}
1519
1520/// The leading numeric prefix of a string, MySQL-style: `'1abc'` is 1,
1521/// `'abc'` and `''` are 0.
1522#[inline(never)]
1523pub(crate) fn mysql_leading_number(s: &str) -> f64 {
1524    let t = s.trim_start();
1525    let mut end = 0usize;
1526    let mut seen_dot = false;
1527    let mut seen_digit = false;
1528    // v7.39 (round 351, M11) — the exponent form counts: MariaDB reads
1529    // `'1e3'` as 1000 and `'1.5e2'` as 150 (measured). A trailing `e`
1530    // with no digits after it is not part of the number (`'1e'` is 1).
1531    let mut seen_exp = false;
1532    let mut exp_at = 0usize;
1533    for (i, c) in t.char_indices() {
1534        match c {
1535            '-' | '+' if i == 0 => {}
1536            '-' | '+' if seen_exp && i == exp_at + 1 => {}
1537            '0'..='9' => seen_digit = true,
1538            '.' if !seen_dot && !seen_exp => seen_dot = true,
1539            'e' | 'E' if seen_digit && !seen_exp => {
1540                seen_exp = true;
1541                exp_at = i;
1542            }
1543            _ => break,
1544        }
1545        end = i + c.len_utf8();
1546    }
1547    if !seen_digit {
1548        return 0.0;
1549    }
1550    // Trim an exponent that never got its digits.
1551    let mut text = &t[..end];
1552    while !text.is_empty() && text.parse::<f64>().is_err() {
1553        text = &text[..text.len() - 1];
1554    }
1555    text.parse::<f64>().unwrap_or(0.0)
1556}
1557
1558/// v7.39 (read01 ruleutils.c) — resolve a relation name to its synthetic
1559/// oid: user tables in the 16384+ band (table_names order), views at
1560/// 32768+, and the synthesised system catalogs at their REAL PG oids.
1561/// `None` when the name is unknown (the caller keeps the legacy text
1562/// behaviour so `'anything'::regclass::text` still round-trips).
1563pub(crate) fn regclass_name_to_oid(cat: &spg_storage::Catalog, bare: &str) -> Option<i64> {
1564    // v7.39 (round 337, V62) — an INDEX and a SEQUENCE are relations too:
1565    // both have a `pg_class` row, so both answer to `::regclass` in PG.
1566    // v7.39 (round 338, V64) — and the bands live in ONE allocator now,
1567    // shared with the catalog synths, so `pg_class.oid = 'x'::regclass`
1568    // holds for every kind rather than only for tables.
1569    if let Some(oid) = crate::system_catalog::relation_oid(cat, bare) {
1570        return Some(oid);
1571    }
1572    Some(match bare {
1573        "pg_type" => 1247,
1574        "pg_attribute" => 1249,
1575        "pg_proc" => 1255,
1576        "pg_class" => 1259,
1577        "pg_database" => 1262,
1578        "pg_constraint" => 2606,
1579        "pg_index" => 2610,
1580        "pg_namespace" => 2615,
1581        // v7.39 (round 650) — the text-search catalogs. This list is a
1582        // hand-kept subset of `CATALOG_RELATIONS`, which is why adding a
1583        // catalog there was not enough for `'pg_ts_config'::regclass`.
1584        "pg_ts_config" => 3602,
1585        "pg_ts_config_map" => 3603,
1586        "pg_ts_dict" => 3600,
1587        "pg_ts_parser" => 3601,
1588        "pg_ts_template" => 3764,
1589        // 7.38.1 S5.1 — stop hand-copying: anything CATALOG_RELATIONS
1590        // publishes resolves here too (pg_dump's dependency pass casts
1591        // 'pg_extension' / 'pg_amop' / 'pg_opfamily'::regclass).
1592        other => {
1593            return crate::system_catalog::CATALOG_RELATIONS
1594                .iter()
1595                .find(|(n, _)| other.eq_ignore_ascii_case(n))
1596                .map(|(_, oid)| *oid);
1597        }
1598    })
1599}
1600
1601/// v7.39 (round 263) — crate-visible wrapper so the write path can
1602/// relabel + coerce a value into a composite column's declared type.
1603pub(crate) fn apply_composite_cast_pub(
1604    v: Value<'static>,
1605    comp: &spg_storage::CompositeDef,
1606    cat: Option<&spg_storage::Catalog>,
1607) -> Result<Value<'static>, EvalError> {
1608    apply_composite_cast_in(v, comp, cat)
1609}
1610
1611/// v7.39 (round 264) — resolve one field's value, recursing when the
1612/// field is itself a COMPOSITE. Without this a nested field kept the
1613/// inner record's TEXT rendering, so `(x).inner.street` errored and
1614/// `row_to_json` nested a string rather than an object.
1615fn coerce_composite_field(
1616    val: Value<'static>,
1617    fname: &str,
1618    fty: spg_storage::DataType,
1619    user_ty: Option<&str>,
1620    cat: Option<&spg_storage::Catalog>,
1621) -> Result<Value<'static>, EvalError> {
1622    if matches!(val, Value::Null) {
1623        return Ok(val);
1624    }
1625    if let Some(tn) = user_ty
1626        && let Some(inner) = cat.and_then(|c| c.composite_types().get(tn))
1627    {
1628        return apply_composite_cast_in(val, inner, cat);
1629    }
1630    crate::conversions::coerce_value(val, fty, fname, 0).map_err(|e| EvalError::TypeMismatch {
1631        detail: alloc::format!("{e}"),
1632    })
1633}
1634
1635fn apply_composite_cast(
1636    v: Value<'static>,
1637    comp: &spg_storage::CompositeDef,
1638) -> Result<Value<'static>, EvalError> {
1639    apply_composite_cast_in(v, comp, None)
1640}
1641
1642fn apply_composite_cast_in(
1643    v: Value<'static>,
1644    comp: &spg_storage::CompositeDef,
1645    cat: Option<&spg_storage::Catalog>,
1646) -> Result<Value<'static>, EvalError> {
1647    match v {
1648        Value::Null => Ok(Value::Null),
1649        Value::Composite(fields) => {
1650            if fields.len() != comp.fields.len() {
1651                // PG reports the SHAPE mismatch as a plain cast refusal.
1652                return Err(EvalError::TypeMismatch {
1653                    detail: alloc::format!("cannot cast type record to {}", comp.name),
1654                });
1655            }
1656            // v7.39 (round 263) — relabel AND coerce: this branch only
1657            // renamed the fields, so `ROW('x','notanint')::addr` kept the
1658            // text in an int field and PG's input error never fired.
1659            let mut out: alloc::vec::Vec<(alloc::string::String, Value<'static>)> =
1660                alloc::vec::Vec::with_capacity(comp.fields.len());
1661            for (i, ((name, fty), (_, val))) in comp.fields.iter().zip(fields).enumerate() {
1662                let ut = comp.field_user_types.get(i).and_then(Option::as_deref);
1663                let coerced = coerce_composite_field(val, name, *fty, ut, cat)?;
1664                out.push((name.clone(), coerced));
1665            }
1666            Ok(Value::Composite(out))
1667        }
1668        Value::Text(s) => {
1669            let raw = parse_record_text(s.as_ref()).ok_or_else(|| EvalError::TypeMismatch {
1670                detail: alloc::format!("malformed record literal: \"{s}\""),
1671            })?;
1672            if raw.len() != comp.fields.len() {
1673                return Err(EvalError::TypeMismatch {
1674                    detail: alloc::format!("malformed record literal: \"{s}\""),
1675                });
1676            }
1677            let mut out: alloc::vec::Vec<(alloc::string::String, Value<'static>)> =
1678                alloc::vec::Vec::with_capacity(raw.len());
1679            for (i, ((fname, fty), field_text)) in comp.fields.iter().zip(raw).enumerate() {
1680                let ut = comp.field_user_types.get(i).and_then(Option::as_deref);
1681                let val = match field_text {
1682                    None => Value::Null,
1683                    Some(t) => coerce_composite_field(Value::text(t), fname, *fty, ut, cat)?,
1684                };
1685                out.push((fname.clone(), val));
1686            }
1687            Ok(Value::Composite(out))
1688        }
1689        other => Err(EvalError::TypeMismatch {
1690            detail: alloc::format!(
1691                "cannot cast {} to composite type \"{}\"",
1692                crate::conversions::pg_type_name_for_error_opt(other.data_type()),
1693                comp.name
1694            ),
1695        }),
1696    }
1697}
1698
1699/// Split PG's record text `(f1,f2,...)` into per-field raw strings
1700/// (None = empty field = NULL). Double quotes wrap fields containing
1701/// metacharacters; `""` inside is a literal quote; a backslash escapes
1702/// the next character.
1703fn parse_record_text(s: &str) -> Option<alloc::vec::Vec<Option<alloc::string::String>>> {
1704    let t = s.trim();
1705    let inner = t.strip_prefix('(')?.strip_suffix(')')?;
1706    let mut out: alloc::vec::Vec<Option<alloc::string::String>> = alloc::vec::Vec::new();
1707    let chars: alloc::vec::Vec<char> = inner.chars().collect();
1708    let mut field = alloc::string::String::new();
1709    let mut quoted_seen = false;
1710    let mut i = 0usize;
1711    let mut in_quotes = false;
1712    loop {
1713        if i >= chars.len() {
1714            if in_quotes {
1715                return None;
1716            }
1717            out.push(if field.is_empty() && !quoted_seen {
1718                None
1719            } else {
1720                Some(field.clone())
1721            });
1722            break;
1723        }
1724        let c = chars[i];
1725        if in_quotes {
1726            match c {
1727                '"' if chars.get(i + 1) == Some(&'"') => {
1728                    field.push('"');
1729                    i += 2;
1730                }
1731                '"' => {
1732                    in_quotes = false;
1733                    i += 1;
1734                }
1735                '\\' => {
1736                    field.push(*chars.get(i + 1)?);
1737                    i += 2;
1738                }
1739                _ => {
1740                    field.push(c);
1741                    i += 1;
1742                }
1743            }
1744        } else {
1745            match c {
1746                '"' => {
1747                    in_quotes = true;
1748                    quoted_seen = true;
1749                    i += 1;
1750                }
1751                ',' => {
1752                    out.push(if field.is_empty() && !quoted_seen {
1753                        None
1754                    } else {
1755                        Some(core::mem::take(&mut field))
1756                    });
1757                    quoted_seen = false;
1758                    i += 1;
1759                }
1760                '\\' => {
1761                    field.push(*chars.get(i + 1)?);
1762                    i += 2;
1763                }
1764                _ => {
1765                    field.push(c);
1766                    i += 1;
1767                }
1768            }
1769        }
1770    }
1771    Some(out)
1772}
1773
1774fn apply_enum_cast<'a>(
1775    v: Value<'a>,
1776    en: &spg_storage::EnumDef,
1777    name: &str,
1778) -> Result<Value<'a>, EvalError> {
1779    match &v {
1780        Value::Null => Ok(v),
1781        Value::Text(s) => {
1782            if en.labels.iter().any(|l| l.as_str() == s.as_ref()) {
1783                Ok(v)
1784            } else {
1785                Err(EvalError::TypeMismatch {
1786                    detail: alloc::format!("invalid input value for enum {name}: {s:?}"),
1787                })
1788            }
1789        }
1790        other => Err(EvalError::TypeMismatch {
1791            detail: alloc::format!(
1792                "cannot cast {} to enum {name}",
1793                crate::conversions::pg_type_name_for_error_opt(other.data_type())
1794            ),
1795        }),
1796    }
1797}
1798
1799/// v7.39 (read01 utils/adt, enum.c) — enum_first / enum_last /
1800/// enum_range resolved from the argument's STATIC enum type (an explicit
1801/// `::enumtype` cast or a column's `ColumnSchema.user_enum_type`) over the
1802/// catalog's member order. Returns None when no argument names a known
1803/// enum, letting the generic function path produce its usual error.
1804/// Out-of-line (`inline(never)`) so the sizable locals don't land in
1805/// `eval_expr`'s recursion frame.
1806/// Enum-ness lives outside the DataType lattice: the witness for "this
1807/// expression is enum-typed" is an explicit `::enumtype` cast or a column
1808/// whose `ColumnSchema.user_enum_type` is set.
1809/// v7.39 (round 258) — crate-visible wrapper so the projection builder
1810/// can keep an expression's enum identity (see `select.rs`).
1811pub(crate) fn expr_enum_type_name_pub<'e>(
1812    e: &'e Expr,
1813    columns: &'e [ColumnSchema],
1814) -> Option<&'e str> {
1815    expr_enum_type_name(e, columns)
1816}
1817
1818/// v7.39 (round 425) — the fractional-seconds precision a projected
1819/// expression should RENDER with: the widest declared precision among the
1820/// MySQL temporal columns it reads. `MAX(d3)` and `d3 + INTERVAL 1 SECOND`
1821/// both keep `d3`'s three digits, as MariaDB does. `None` when the
1822/// expression touches no such column, which leaves PG rendering untouched.
1823///
1824/// Residual (recorded, not modelled): MariaDB also WIDENS the precision from
1825/// some operands — `DATE_ADD(d3, INTERVAL 1 MICROSECOND)` prints six digits
1826/// there. Taking the max over referenced columns covers the common shapes
1827/// and never narrows below the source column.
1828pub(crate) fn expr_mysql_fsp(e: &Expr, columns: &[ColumnSchema]) -> Option<u8> {
1829    fn walk(e: &Expr, columns: &[ColumnSchema], best: &mut Option<u8>) {
1830        match e {
1831            Expr::Column(c) => {
1832                if let Some(f) = columns
1833                    .iter()
1834                    .find(|col| col.name == c.name)
1835                    .and_then(|col| col.mysql_fsp)
1836                {
1837                    *best = Some(best.map_or(f, |b: u8| b.max(f)));
1838                }
1839            }
1840            Expr::Binary { lhs, rhs, .. } => {
1841                walk(lhs, columns, best);
1842                walk(rhs, columns, best);
1843            }
1844            Expr::Unary { expr, .. } | Expr::Cast { expr, .. } => walk(expr, columns, best),
1845            Expr::FunctionCall { args, .. } => {
1846                for a in args {
1847                    walk(a, columns, best);
1848                }
1849            }
1850            Expr::Case {
1851                operand,
1852                branches,
1853                else_branch,
1854            } => {
1855                if let Some(o) = operand.as_deref() {
1856                    walk(o, columns, best);
1857                }
1858                for (w, t) in branches {
1859                    walk(w, columns, best);
1860                    walk(t, columns, best);
1861                }
1862                if let Some(el) = else_branch.as_deref() {
1863                    walk(el, columns, best);
1864                }
1865            }
1866            _ => {}
1867        }
1868    }
1869    let mut best = None;
1870    walk(e, columns, &mut best);
1871    best
1872}
1873
1874/// v7.39 (round 467) — is this expression MySQL-UNSIGNED?
1875///
1876/// MySQL decides unsignedness statically, from the expression's type, not
1877/// from the value it happens to produce. Measured on MariaDB 11: `SUM(a) -
1878/// 100` answers -99 even though `a` is `INT UNSIGNED`, because SUM's result
1879/// type is not unsigned; `a - 5` on the same column raises 1690. So this
1880/// walks the expression the way MySQL's type resolution does.
1881///
1882/// A cast names its target `unsigned` (the parser lowercases MySQL's
1883/// `CAST(x AS UNSIGNED)` into `CastTarget::Named`). Arithmetic is unsigned
1884/// when EITHER operand is — that is MySQL's rule, and it is why `1 - b`
1885/// raises while `5 - a` does not: both are unsigned expressions, but only
1886/// the first has a negative result.
1887///
1888/// Deliberately NOT unsigned: unary minus (MariaDB answers -1 for
1889/// `-CAST(1 AS UNSIGNED)`), and every function result including the
1890/// aggregates. Both measured.
1891pub(crate) fn expr_is_mysql_unsigned(e: &Expr, columns: &[ColumnSchema]) -> bool {
1892    match e {
1893        Expr::Column(c) => columns
1894            .iter()
1895            .find(|col| col.name == c.name)
1896            .is_some_and(|col| col.is_unsigned),
1897        Expr::Cast {
1898            target: CastTarget::Named(n),
1899            ..
1900        } => n.eq_ignore_ascii_case("unsigned"),
1901        Expr::Binary {
1902            lhs,
1903            op: BinOp::Add | BinOp::Sub | BinOp::Mul,
1904            rhs,
1905        } => expr_is_mysql_unsigned(lhs, columns) || expr_is_mysql_unsigned(rhs, columns),
1906        _ => false,
1907    }
1908}
1909
1910/// v7.39 (round 467) — MySQL arithmetic over an UNSIGNED operand, with
1911/// MySQL's range check.
1912///
1913/// `INT UNSIGNED` columns holding 1 and 5 made `a - b` answer **-4** in a
1914/// MySQL session. MariaDB raises `ERROR 1690 (22003): BIGINT UNSIGNED value
1915/// is out of range`. A negative answer where the server promises a
1916/// non-negative one is the kind of thing an application stores back into
1917/// the same column, so it was silent and wrong in the worst direction.
1918///
1919/// The check runs in i128 so the subtraction that underflows is observed
1920/// rather than wrapped, and it only fires when the expression is unsigned
1921/// AND both operands are integers — a NUMERIC or float operand takes the
1922/// ordinary path, as it does in MySQL.
1923///
1924/// `#[inline(never)]`: this is called from the recursive evaluator's
1925/// hottest frame, which already sits against the stack guard.
1926#[inline(never)]
1927fn apply_binary_mysql_unsigned(
1928    op: BinOp,
1929    lhs: &Expr,
1930    rhs: &Expr,
1931    l: Value<'static>,
1932    r: Value<'static>,
1933    ctx: &EvalContext,
1934) -> Result<Value<'static>, EvalError> {
1935    if ctx.mysql_dialect
1936        && matches!(op, BinOp::Add | BinOp::Sub | BinOp::Mul)
1937        && let Some(a) = mysql_int_operand(&l)
1938        && let Some(b) = mysql_int_operand(&r)
1939        && (expr_is_mysql_unsigned(lhs, ctx.columns) || expr_is_mysql_unsigned(rhs, ctx.columns))
1940    {
1941        let out = match op {
1942            BinOp::Add => a.checked_add(b),
1943            BinOp::Sub => a.checked_sub(b),
1944            _ => a.checked_mul(b),
1945        };
1946        let in_range = out.is_some_and(|v| (0..=i128::from(u64::MAX)).contains(&v));
1947        if !in_range {
1948            // MariaDB names the offending expression in the message, with
1949            // minimal parentheses — `a * 0 - 1`, not `((a * 0) - 1)`.
1950            // `pretty_expr` is the deparser that already produces that
1951            // shape. Residual, recorded rather than faked: MariaDB writes
1952            // its columns fully qualified in backticks
1953            // (`db`.`tbl`.`col`), and the database name is not something
1954            // the evaluation context carries.
1955            return Err(EvalError::TypeMismatch {
1956                detail: alloc::format!(
1957                    "BIGINT UNSIGNED value is out of range in '{}'",
1958                    spg_sql::ast::pretty_expr_mysql(&Expr::Binary {
1959                        lhs: alloc::boxed::Box::new(lhs.clone()),
1960                        op,
1961                        rhs: alloc::boxed::Box::new(rhs.clone()),
1962                    })
1963                ),
1964            });
1965        }
1966    }
1967    let out = apply_binary_in(op, l, r, ctx.mysql_dialect);
1968    // v7.39 (round 503) — MariaDB answers NULL for division / modulo by
1969    // zero; SPG raised.
1970    //
1971    // Measured against MariaDB 11: `SELECT 1/0`, `SELECT 5 DIV 0` and
1972    // `SELECT 5 % 0` are all NULL — and they are NULL under the DEFAULT
1973    // sql_mode too, which contains `ERROR_FOR_DIVISION_BY_ZERO`. That flag
1974    // governs WRITES, not the expression: the division evaluates to NULL,
1975    // and a strict-mode INSERT of that result is what raises 1365.
1976    //
1977    // The rule is therefore the DIALECT's, not the mode's: in a MySQL
1978    // session the expression is NULL. It is deliberately not gated on
1979    // `mysql_strict` — an earlier cut of this was, and the gate fired only
1980    // because the probe's context happens to carry no engine, which a
1981    // later round attaching one would have silently reversed.
1982    //
1983    // RESIDUAL, recorded rather than faked: MariaDB's strict-mode INSERT
1984    // of a division by zero raises 1365 and its non-strict INSERT stores
1985    // NULL. SPG's INSERT path evaluates elsewhere and still raises, so it
1986    // matches strict and diverges from non-strict. Closing that needs the
1987    // expression to know it is in a write, which nothing here carries.
1988    if ctx.mysql_dialect && matches!(out, Err(EvalError::DivisionByZero)) {
1989        return Ok(Value::Null);
1990    }
1991    out
1992}
1993
1994/// The integer an operand contributes to the unsigned range check, or
1995/// `None` when it is not an integer at all (NULL, text, NUMERIC, float).
1996fn mysql_int_operand(v: &Value<'_>) -> Option<i128> {
1997    match v {
1998        Value::SmallInt(n) => Some(i128::from(*n)),
1999        Value::Int(n) => Some(i128::from(*n)),
2000        Value::BigInt(n) => Some(i128::from(*n)),
2001        // v7.39 (round 471) — a BIGINT UNSIGNED cell is stored as Numeric
2002        // with scale 0, so the range check has to see it as the integer it
2003        // is. Without this arm the column's own type moved it out of reach
2004        // of round 467's guard and `c - 5` went back to answering -4.
2005        Value::Numeric { scaled, scale, .. } if *scale == 0 => Some(*scaled),
2006        _ => None,
2007    }
2008}
2009
2010fn expr_enum_type_name<'e>(e: &'e Expr, columns: &'e [ColumnSchema]) -> Option<&'e str> {
2011    match e {
2012        Expr::Cast {
2013            target: CastTarget::Named(n),
2014            ..
2015        } => Some(n.as_str()),
2016        Expr::Column(c) => columns
2017            .iter()
2018            .find(|col| col.name == c.name)
2019            // v7.39 (round 259) — a DOMAIN column carries its name in its
2020            // own field; both are "the user type this column is declared
2021            // as", which is what the callers (enum-order comparison,
2022            // pg_typeof) want. Callers gate on the catalog, so a name that
2023            // is one kind never resolves as the other.
2024            .and_then(|col| {
2025                col.user_enum_type
2026                    .as_deref()
2027                    .or(col.user_domain_type.as_deref())
2028            }),
2029        _ => None,
2030    }
2031}
2032
2033/// v7.39 (enum order knife) — the member-label list for an enum-typed
2034/// expression, or None when the expression carries no enum witness or the
2035/// name is not a known enum. The returned slice borrows the catalog.
2036pub(crate) fn expr_enum_labels<'c>(
2037    e: &Expr,
2038    columns: &[ColumnSchema],
2039    catalog: Option<&'c spg_storage::Catalog>,
2040) -> Option<&'c [String]> {
2041    let name = expr_enum_type_name(e, columns)?;
2042    catalog
2043        .and_then(|cat| cat.enum_types().get(name))
2044        .map(|en| en.labels.as_slice())
2045}
2046
2047/// v7.39 (enum order knife) — compare two enum labels by member order.
2048/// None when either side is not Text or not a member (caller falls back to
2049/// the generic comparison, so a stray value never panics or misorders
2050/// silently differently from before).
2051pub(crate) fn enum_ord_cmp(
2052    labels: &[String],
2053    a: &Value<'_>,
2054    b: &Value<'_>,
2055) -> Option<core::cmp::Ordering> {
2056    let pos = |v: &Value<'_>| -> Option<usize> {
2057        match v {
2058            Value::Text(s) => labels.iter().position(|l| l.as_str() == s.as_ref()),
2059            _ => None,
2060        }
2061    };
2062    Some(pos(a)?.cmp(&pos(b)?))
2063}
2064
2065/// v7.39 (enum order knife) — Binary-comparison hook: when either side's
2066/// static type witnesses an enum and both runtime values are member labels,
2067/// compare by member order (PG's enumsortorder semantics). Out-of-line to
2068/// keep `eval_expr`'s recursion frame small.
2069#[inline(never)]
2070fn enum_compare_hook(
2071    op: BinOp,
2072    lhs: &Expr,
2073    rhs: &Expr,
2074    l: &Value<'_>,
2075    r: &Value<'_>,
2076    ctx: &EvalContext<'_>,
2077) -> Option<Result<Value<'static>, EvalError>> {
2078    let cat = ctx.catalog?;
2079    if cat.enum_types().is_empty() {
2080        return None;
2081    }
2082    let labels = expr_enum_labels(lhs, ctx.columns, ctx.catalog)
2083        .or_else(|| expr_enum_labels(rhs, ctx.columns, ctx.catalog))?;
2084    let ord = enum_ord_cmp(labels, l, r)?;
2085    let b = match op {
2086        BinOp::Eq => ord == core::cmp::Ordering::Equal,
2087        BinOp::NotEq => ord != core::cmp::Ordering::Equal,
2088        BinOp::Lt => ord == core::cmp::Ordering::Less,
2089        BinOp::LtEq => ord != core::cmp::Ordering::Greater,
2090        BinOp::Gt => ord == core::cmp::Ordering::Greater,
2091        BinOp::GtEq => ord != core::cmp::Ordering::Less,
2092        _ => return None,
2093    };
2094    Some(Ok(Value::Bool(b)))
2095}
2096
2097/// v7.39 (round 693) — Binary-comparison hook for a declared collation, the
2098/// last shape F36 left open: `loc BETWEEN 'a' AND 'd'` returns a different
2099/// ROW SET under `en_US.utf8` than under byte order, not merely a different
2100/// order.
2101///
2102/// It sits beside [`enum_compare_hook`] because it is the same kind of fact
2103/// — something about the operand COLUMNS that `compare` cannot look up from
2104/// two values — and takes the same two protections: `#[inline(never)]`, so
2105/// `eval_expr`'s recursion frame does not grow (the comment at the call site
2106/// records a fourth `||` there tipping the 768 KiB guard on its own), and
2107/// the caller's Text/Text gate, so no integer comparison reaches it.
2108///
2109/// EQUALITY is deliberately not handled. PG18's `en_US.utf8` is
2110/// deterministic, so `=`, `<>`, `LIKE`, `IN` and `count(DISTINCT …)` give
2111/// byte-equality's answer — measured, all five. Only the ordering operators
2112/// change, and `least`/`greatest` follow them through their own comparator.
2113#[inline(never)]
2114fn collate_compare_hook(
2115    op: BinOp,
2116    lhs: &Expr,
2117    rhs: &Expr,
2118    l: &Value<'_>,
2119    r: &Value<'_>,
2120    ctx: &EvalContext<'_>,
2121) -> Option<Result<Value<'static>, EvalError>> {
2122    if !matches!(op, BinOp::Lt | BinOp::LtEq | BinOp::Gt | BinOp::GtEq) {
2123        return None;
2124    }
2125    let (Value::Text(a), Value::Text(b)) = (l, r) else {
2126        return None;
2127    };
2128    let resolve = |c: &spg_sql::ast::ColumnName| -> Option<alloc::string::String> {
2129        let pos = find_column_pos(c, ctx)?;
2130        ctx.columns.get(pos)?.collation_name.clone()
2131    };
2132    let derived = crate::collate_derive::derive(lhs, &resolve)
2133        .combine_pub(crate::collate_derive::derive(rhs, &resolve));
2134    if let Some((x, y)) = derived.conflict() {
2135        return Some(Err(EvalError::TypeMismatch {
2136            detail: alloc::format!(
2137                "collation mismatch between implicit collations \"{x}\" and \"{y}\""
2138            ),
2139        }));
2140    }
2141    let ord = crate::collate::compare(derived.name()?, a, b)?;
2142    let b = match op {
2143        BinOp::Lt => ord == core::cmp::Ordering::Less,
2144        BinOp::LtEq => ord != core::cmp::Ordering::Greater,
2145        BinOp::Gt => ord == core::cmp::Ordering::Greater,
2146        BinOp::GtEq => ord != core::cmp::Ordering::Less,
2147        _ => return None,
2148    };
2149    Some(Ok(Value::Bool(b)))
2150}
2151
2152/// v7.39 (round 693) — the collation `least`/`greatest` should compare by,
2153/// derived across every argument the same way a comparison's two operands
2154/// are. `None` keeps byte order, which is right for arguments that declare
2155/// nothing.
2156#[inline(never)]
2157fn greatest_least_collation(args: &[Expr], ctx: &EvalContext<'_>) -> Option<alloc::string::String> {
2158    let resolve = |c: &spg_sql::ast::ColumnName| -> Option<alloc::string::String> {
2159        let pos = find_column_pos(c, ctx)?;
2160        ctx.columns.get(pos)?.collation_name.clone()
2161    };
2162    let derived = args
2163        .iter()
2164        .fold(crate::collate_derive::Derived::None, |acc, a| {
2165            acc.combine_pub(crate::collate_derive::derive(a, &resolve))
2166        });
2167    derived
2168        .name()
2169        .filter(|n| crate::collate::is_supported(n))
2170        .map(alloc::string::ToString::to_string)
2171}
2172
2173/// v7.39 (round 704) — rewrite a comparison's operator-not-found error when
2174/// the operand at fault is an UNKNOWN string literal against a numeric-family
2175/// value. PG commits such a literal to the other side's type before comparing,
2176/// so its error is the input function's — `invalid input syntax for type
2177/// integer: "abc"` — not `operator does not exist: integer = text`. An
2178/// explicit `::text` operand keeps the operator error (`1 IS DISTINCT FROM
2179/// 'a'::text`, measured on PG18), which is precisely the distinction two
2180/// `Value`s cannot carry: the first cut of this round rewrote inside
2181/// `binop::compare` and the r238 pin plus corpus 19 caught it the same day.
2182///
2183/// Error-path only — a comparison that succeeds never calls this — so the
2184/// 35.6 %-of-self-time note on `compare` is untouched.
2185#[cold]
2186#[inline(never)]
2187fn unknown_literal_cmp_error(
2188    err: EvalError,
2189    lhs: &Expr,
2190    rhs: &Expr,
2191    lv: &Value<'_>,
2192    rv: &Value<'_>,
2193) -> EvalError {
2194    let EvalError::TypeMismatch { detail } = &err else {
2195        return err;
2196    };
2197    // Two spellings of the same fall-through: `compare`'s operator error,
2198    // and the owned numeric path's conversion error (`f = 'y'` reaches
2199    // "cannot convert text to FLOAT"). Both mean the literal failed to
2200    // lift; neither is what PG says about an unknown literal.
2201    if !detail.starts_with("operator does not exist")
2202        && !detail.starts_with("cannot convert text to")
2203    {
2204        return err;
2205    }
2206    let numeric = |v: &Value<'_>| {
2207        matches!(
2208            v.data_type(),
2209            Some(
2210                spg_storage::DataType::SmallInt
2211                    | spg_storage::DataType::Int
2212                    | spg_storage::DataType::BigInt
2213                    | spg_storage::DataType::Float
2214                    | spg_storage::DataType::Real
2215                    | spg_storage::DataType::Numeric { .. }
2216            )
2217        )
2218    };
2219    let rewrite = |s: &Value<'_>, other: &Value<'_>| -> Option<EvalError> {
2220        let Value::Text(text) = s else { return None };
2221        let dt = other.data_type()?;
2222        Some(EvalError::TypeMismatch {
2223            detail: alloc::format!(
2224                "invalid input syntax for type {}: \"{text}\"",
2225                crate::conversions::pg_type_name_for_error(dt)
2226            ),
2227        })
2228    };
2229    if is_unknown_string_literal(lhs)
2230        && numeric(rv)
2231        && let Some(e) = rewrite(lv, rv)
2232    {
2233        return e;
2234    }
2235    if is_unknown_string_literal(rhs)
2236        && numeric(lv)
2237        && let Some(e) = rewrite(rv, lv)
2238    {
2239        return e;
2240    }
2241    err
2242}
2243
2244fn enum_arg_type_name<'e>(args: &'e [Expr], ctx: &EvalContext<'e>) -> Option<&'e str> {
2245    args.iter()
2246        .find_map(|a| expr_enum_type_name(a, ctx.columns))
2247        .filter(|n| {
2248            ctx.catalog
2249                .is_some_and(|cat| cat.enum_types().contains_key(*n))
2250        })
2251}
2252
2253/// Cheap value-free precheck so `eval_expr`'s recursion frame carries no
2254/// binding for the enum path (stack-depth guard budget).
2255#[inline(never)]
2256fn enum_introspection_applies(args: &[Expr], ctx: &EvalContext<'_>) -> bool {
2257    enum_arg_type_name(args, ctx).is_some()
2258}
2259
2260#[inline(never)]
2261fn eval_enum_introspection(
2262    name: &str,
2263    args: &[Expr],
2264    row: &Row<'static>,
2265    ctx: &EvalContext<'_>,
2266) -> Result<Value<'static>, EvalError> {
2267    let Some(en) = enum_arg_type_name(args, ctx)
2268        .and_then(|n| ctx.catalog.and_then(|cat| cat.enum_types().get(n)))
2269    else {
2270        // The precheck guarantees this arm is unreachable; keep a typed
2271        // error rather than a panic if the two ever drift.
2272        return Err(EvalError::TypeMismatch {
2273            detail: "could not determine polymorphic type".into(),
2274        });
2275    };
2276    let labels = &en.labels;
2277    if labels.is_empty() {
2278        return Ok(Value::Null);
2279    }
2280    if name.eq_ignore_ascii_case("enum_first") {
2281        return Ok(Value::text(labels[0].clone()));
2282    }
2283    if name.eq_ignore_ascii_case("enum_last") {
2284        return Ok(Value::text(labels[labels.len() - 1].clone()));
2285    }
2286    // enum_range(NULL) = all; enum_range(lo, hi) slices inclusively,
2287    // NULL bound = open end (PG).
2288    let pos_of = |v: &Value<'_>| -> Option<usize> {
2289        match v {
2290            Value::Text(s) => labels.iter().position(|l| l == s.as_ref()),
2291            _ => None,
2292        }
2293    };
2294    let (lo, hi) = if args.len() == 2 {
2295        let a = eval_expr(&args[0], row, ctx)?;
2296        let b = eval_expr(&args[1], row, ctx)?;
2297        (
2298            pos_of(&a).unwrap_or(0),
2299            pos_of(&b).unwrap_or(labels.len() - 1),
2300        )
2301    } else {
2302        (0, labels.len() - 1)
2303    };
2304    let out: alloc::vec::Vec<Option<String>> = labels
2305        .get(lo..=hi)
2306        .unwrap_or(&[])
2307        .iter()
2308        .map(|l| Some(l.clone()))
2309        .collect();
2310    Ok(Value::TextArray(out))
2311}
2312
2313/// Apply one `[index]` subscript to a value — the single-step semantics shared
2314/// by 1-D array elements and JSON path access (`j['a']`, `j[0]`). NULL target
2315/// or index → NULL; a 1-based integer indexes a 1-D array (out of range → NULL,
2316/// non-array → error); JSON delegates to `path_get`.
2317fn apply_one_subscript(
2318    target_v: Value<'static>,
2319    index: &Expr,
2320    row: &Row<'static>,
2321    ctx: &EvalContext<'_>,
2322) -> Result<Value<'static>, EvalError> {
2323    let idx_v = eval_expr(index, row, ctx)?;
2324    if matches!(target_v, Value::Null) || matches!(idx_v, Value::Null) {
2325        return Ok(Value::Null);
2326    }
2327    // v7.38 (read01) — JSON/JSONB subscripting (`j['a']`, `j[0]`, chained
2328    // `j['a']['b']`) is object/array access, identical to the `->` operator
2329    // (text key → object field, integer → 0-based array element). PG 14+.
2330    if matches!(target_v, Value::Json(_)) {
2331        return crate::json::path_get(&target_v, &idx_v, false);
2332    }
2333    let i: i64 = match idx_v {
2334        Value::Int(n) => i64::from(n),
2335        Value::BigInt(n) => n,
2336        Value::SmallInt(n) => i64::from(n),
2337        other => {
2338            return Err(EvalError::TypeMismatch {
2339                detail: format!(
2340                    "array subscript must be integer, got {}",
2341                    crate::conversions::pg_type_name_for_error_opt(other.data_type())
2342                ),
2343            });
2344        }
2345    };
2346    if i < 1 {
2347        return Ok(Value::Null);
2348    }
2349    let pos = (i - 1) as usize;
2350    match array_element_at(&target_v, pos) {
2351        Some(v) => Ok(v),
2352        None if array_len(&target_v).is_some() => Ok(Value::Null),
2353        None => Err(EvalError::TypeMismatch {
2354            detail: format!(
2355                "subscript target must be an array, got {}",
2356                crate::conversions::pg_type_name_for_error_opt(target_v.data_type())
2357            ),
2358        }),
2359    }
2360}
2361
2362/// v7.38 (read01, 2D-subscript) — index a 2-D array (`arr[i][j]`). PG needs
2363/// exactly two subscripts to reach an element; a single subscript on a 2-D
2364/// array yields NULL (not the row), and any out-of-range index → NULL. Both
2365/// subscripts are 1-based.
2366fn eval_matrix_subscript(
2367    base: &Value<'static>,
2368    idx_exprs: &[&Expr],
2369    row: &Row<'static>,
2370    ctx: &EvalContext<'_>,
2371) -> Result<Value<'static>, EvalError> {
2372    if idx_exprs.len() != 2 {
2373        return Ok(Value::Null);
2374    }
2375    let mut idx = [0i64; 2];
2376    for (k, ix) in idx_exprs.iter().enumerate() {
2377        idx[k] = match eval_expr(ix, row, ctx)? {
2378            Value::Null => return Ok(Value::Null),
2379            Value::Int(n) => i64::from(n),
2380            Value::BigInt(n) => n,
2381            Value::SmallInt(n) => i64::from(n),
2382            other => {
2383                return Err(EvalError::TypeMismatch {
2384                    detail: format!(
2385                        "array subscript must be integer, got {}",
2386                        crate::conversions::pg_type_name_for_error_opt(other.data_type())
2387                    ),
2388                });
2389            }
2390        };
2391    }
2392    let (r, c) = (idx[0], idx[1]);
2393    if r < 1 || c < 1 {
2394        return Ok(Value::Null);
2395    }
2396    let (ri, ci) = ((r - 1) as usize, (c - 1) as usize);
2397    macro_rules! elem {
2398        ($rows:expr, $map:expr) => {
2399            Ok($rows
2400                .get(ri)
2401                .and_then(|inner| inner.get(ci))
2402                .map_or(Value::Null, |cell| cell.as_ref().map_or(Value::Null, $map)))
2403        };
2404    }
2405    match base {
2406        Value::IntArray2D(rows) => elem!(rows, |n| Value::Int(*n)),
2407        Value::BigIntArray2D(rows) => elem!(rows, |n| Value::BigInt(*n)),
2408        Value::BoolArray2D(rows) => elem!(rows, |b| Value::Bool(*b)),
2409        Value::TextArray2D(rows) => {
2410            elem!(rows, |s| Value::Text(alloc::borrow::Cow::Owned(s.clone())))
2411        }
2412        _ => Ok(Value::Null),
2413    }
2414}
2415
2416/// Out-of-lined `eval_expr` arm — keeps the recursive frame small
2417/// (stack-depth guard budget); body unchanged.
2418#[inline(never)]
2419fn eval_cast_arm(
2420    expr: &Expr,
2421    target: &CastTarget,
2422    row: &Row<'static>,
2423    ctx: &EvalContext<'_>,
2424) -> Result<Value<'static>, EvalError> {
2425    let v = eval_expr(expr, row, ctx)?;
2426    // v7.39 (round 473) — `<oid>::regclass` names the relation.
2427    //
2428    // The cast itself has no catalog, so it answered the bare number:
2429    // `indexrelid::regclass` printed `100001` where PG prints `ix1`, and
2430    // pg_class / pg_index rows are read by joining on oids and rendering
2431    // them — a tool cannot match the two up. `relation_name_for_oid`
2432    // mirrors `relation_oid`'s walks so the two directions agree; an oid
2433    // that names nothing keeps rendering as the number, which is what PG
2434    // does for a dropped relation's oid too.
2435    if matches!(target, CastTarget::RegClass)
2436        && let Some(cat) = ctx.catalog
2437    {
2438        let oid = match &v {
2439            Value::Int(n) => Some(i64::from(*n)),
2440            Value::BigInt(n) => Some(*n),
2441            _ => None,
2442        };
2443        if let Some(oid) = oid
2444            && let Some(name) = crate::system_catalog::relation_name_for_oid(cat, oid)
2445        {
2446            return Ok(Value::text(name));
2447        }
2448    }
2449    // v7.38 (read01 P6.40) — a cast to a user DOMAIN (`x::posint`)
2450    // enforces the domain's NOT NULL + CHECK constraints, matching PG.
2451    // The base-type coercion already happened when `v` was produced
2452    // (the domain is a constrained alias of its base type); here we
2453    // only run the constraints.
2454    if let CastTarget::Named(name) = target
2455        && let Some(cat) = ctx.catalog
2456    {
2457        if let Some(dom) = cat.domain_types().get(name.as_str()) {
2458            return apply_domain_constraints(v, dom, name, cat);
2459        }
2460        // v7.38 (read01 P6.67) — `'label'::<user enum>` validates the
2461        // label against the enum's members (a non-member errors like
2462        // PG). A typed NULL passes through carrying the enum type.
2463        if let Some(en) = cat.enum_types().get(name.as_str()) {
2464            return apply_enum_cast(v, en, name);
2465        }
2466        // v7.39 (read01 rowtypes.c) — `'(1,x)'::<composite>` parses PG's
2467        // record text form against the type's field list; a ROW value
2468        // re-labels its fields.
2469        if let Some(comp) = cat.composite_types().get(name.as_str()) {
2470            // v7.39 (round 264) — pass the catalog so a NESTED composite
2471            // field resolves into a record rather than staying text.
2472            return apply_composite_cast_in(v, comp, ctx.catalog);
2473        }
2474        // v7.39 (round 509) — every TABLE also names a row type, and
2475        // `jsonb_populate_record(NULL::mytable, …)` is PG's canonical
2476        // spelling for "shaped like this table". PG accepts `NULL::mytable`
2477        // and refuses `1::mytable` with "cannot cast type integer to
2478        // mytable" — the type exists, the conversion does not. This only
2479        // ever worked here because a NULL skipped cast resolution entirely;
2480        // now that it does not, the row type has to be named explicitly.
2481        if cat.get(name.as_str()).is_some() {
2482            return if matches!(v, Value::Null) {
2483                Ok(Value::Null)
2484            } else {
2485                Err(EvalError::TypeMismatch {
2486                    detail: alloc::format!(
2487                        "cannot cast type {} to {name}",
2488                        crate::eval::strings::pg_typeof_name(&v),
2489                    ),
2490                })
2491            };
2492        }
2493        // v7.39 (round 513) — `regnamespace` and `regrole` resolve against
2494        // things that live outside the type table: schemas on the catalog,
2495        // roles on the engine. They belong here for the same reason the
2496        // relation check above does — this is the arm that can see them.
2497        // v7.39 (round 526) — the NUMERIC direction, which is the one a
2498        // catalog join uses: `relnamespace::regnamespace` names the
2499        // schema a relation lives in, and it errored with "unsupported
2500        // cast target" while `'public'::regnamespace` worked. Round 513
2501        // added the name direction only, so the half that reads a
2502        // catalog was the half missing.
2503        if (name.eq_ignore_ascii_case("regnamespace") || name.eq_ignore_ascii_case("regrole"))
2504            && let Some(oid) = match &v {
2505                Value::Int(n) => Some(i64::from(*n)),
2506                Value::BigInt(n) => Some(*n),
2507                _ => None,
2508            }
2509        {
2510            let named = if name.eq_ignore_ascii_case("regnamespace") {
2511                crate::system_catalog::schema_name_for_oid(oid)
2512            } else {
2513                ctx.engine.and_then(|e| e.role_name_for_oid(oid))
2514            };
2515            // PG prints the bare number for an oid that names nothing,
2516            // exactly as `regclass` does.
2517            return Ok(Value::text(
2518                named.unwrap_or_else(|| alloc::format!("{oid}")),
2519            ));
2520        }
2521        if name.eq_ignore_ascii_case("regnamespace")
2522            && let Value::Text(t) = &v
2523        {
2524            let want = t.trim().trim_matches('"');
2525            // 7.38.1 S5.1 — the name direction answers the DUAL
2526            // (oid, name) value for the schemas with a published oid:
2527            // regnamespace IS an oid in PG, and pg_dump compares it
2528            // against numeric namespace columns (`opcnamespace =
2529            // 'pg_catalog'::regnamespace`) — while the wire render
2530            // stays the NAME, as PG's does (the round-513 contract).
2531            // The RegClass dual carries exactly that pair. A user
2532            // schema without a published oid keeps plain text.
2533            return if spg_storage::is_builtin_schema(want) || cat.schema_exists(want) {
2534                Ok(match want {
2535                    "pg_catalog" => Value::RegClass(11, "pg_catalog".into()),
2536                    "public" => Value::RegClass(2200, "public".into()),
2537                    "information_schema" => Value::RegClass(13000, "information_schema".into()),
2538                    _ => Value::text(want.to_string()),
2539                })
2540            } else {
2541                Err(EvalError::TypeMismatch {
2542                    detail: alloc::format!("schema \"{want}\" does not exist"),
2543                })
2544            };
2545        }
2546        if name.eq_ignore_ascii_case("regrole")
2547            && let Value::Text(t) = &v
2548        {
2549            let want = t.trim().trim_matches('"').to_string();
2550            // PG ships predefined roles that exist whether or not anybody
2551            // created them; SPG carries the rest on the engine.
2552            const PREDEFINED: &[&str] = &[
2553                "pg_read_all_data",
2554                "pg_write_all_data",
2555                "pg_monitor",
2556                "pg_read_all_settings",
2557                "pg_read_all_stats",
2558                "pg_stat_scan_tables",
2559                "pg_signal_backend",
2560                "pg_checkpoint",
2561                "pg_maintain",
2562                "pg_use_reserved_connections",
2563                "pg_create_subscription",
2564            ];
2565            let known = PREDEFINED.iter().any(|r| r.eq_ignore_ascii_case(&want))
2566                || ctx.engine.is_some_and(|e| e.role_exists(&want));
2567            return if known {
2568                Ok(Value::text(want))
2569            } else {
2570                Err(EvalError::TypeMismatch {
2571                    detail: alloc::format!("role \"{want}\" does not exist"),
2572                })
2573            };
2574        }
2575        // v7.39 (round 509) — the cast target is checked even when the
2576        // operand is NULL. `cast_value_in` short-circuits a NULL before it
2577        // looks at the target, so `NULL::nosuchtype` silently answered NULL
2578        // and `pg_typeof(NULL::nosuchtype)` answered `unknown`, while
2579        // `1::nosuchtype` errored — the gap was exactly the NULL case, in
2580        // both spellings. Everything a catalog can name has been tried by
2581        // now; what is left is the builtin table.
2582        if matches!(v, Value::Null)
2583            && !crate::eval::cast::builtin_target_resolves(name, ctx.mysql_dialect)
2584        {
2585            return Err(EvalError::TypeMismatch {
2586                detail: cast::unknown_type_error_text(name),
2587            });
2588        }
2589    }
2590    // v7.39 (round 285) — `::record`, the anonymous composite type. PG
2591    // treats it as an IDENTITY cast on anything already composite: the
2592    // value keeps its fields and their names, so `(ROW(1,2)::record).f1`
2593    // and `(r).x` still resolve. Only a non-composite is refused, with
2594    // PG's wording. `record` is not a catalog type, so this cannot live
2595    // in the lookups above.
2596    if let CastTarget::Named(name) = target
2597        && name.eq_ignore_ascii_case("record")
2598    {
2599        return match v {
2600            Value::Composite(_) | Value::Null => Ok(v),
2601            other => Err(EvalError::TypeMismatch {
2602                detail: alloc::format!(
2603                    "cannot cast type {} to record",
2604                    crate::eval::strings::pg_typeof_name(&other),
2605                ),
2606            }),
2607        };
2608    }
2609    // v7.38 (read01, T22) — a numeric OID cast to regclass reverse-looks
2610    // up the user relation name (PG's 16384+ band, assigned in
2611    // table_names() order). System OIDs / non-matches fall through to
2612    // the integer-rendering path in cast_value.
2613    if matches!(target, CastTarget::RegClass) {
2614        // v7.39 (read01 ruleutils.c) — regclass is DUAL-shape: oid for
2615        // catalog joins (conrelid = 't'::regclass), name for display.
2616        let oid_in = match &v {
2617            Value::SmallInt(n) => Some(i64::from(*n)),
2618            Value::Int(n) => Some(i64::from(*n)),
2619            Value::BigInt(n) => Some(*n),
2620            _ => None,
2621        };
2622        if let (Some(oid), Some(cat)) = (oid_in, ctx.catalog) {
2623            if oid >= 16384 {
2624                if let Some(name) = cat.table_names().into_iter().nth((oid - 16384) as usize) {
2625                    return Ok(Value::RegClass(oid, name.into()));
2626                }
2627            }
2628        }
2629        if let (Value::Text(s), Some(cat)) = (&v, ctx.catalog) {
2630            let bare = s
2631                .rsplit('.')
2632                .next()
2633                .unwrap_or(s)
2634                .trim_matches('"')
2635                .to_string();
2636            if let Some(oid) = regclass_name_to_oid(cat, &bare) {
2637                return Ok(Value::RegClass(oid, bare.into()));
2638            }
2639            // v7.39 (round 337, V62) — a name that is no relation at all is
2640            // PG's error, not a silent pass-through. `'nope'::regclass`
2641            // used to answer the TEXT `nope`, so a downstream
2642            // `pg_get_viewdef('nope'::regclass)` reported "no such view"
2643            // when the truth is there is no such relation — and a
2644            // catalog join on it quietly matched nothing. PG 18.4:
2645            // `ERROR: relation "nope" does not exist`. (`to_regclass` is
2646            // the spelling that answers NULL instead, and still does.)
2647            //
2648            // The system views SPG synthesises have no oid space, so they
2649            // keep the textual form rather than erroring.
2650            const SYSTEM_RELS: &[&str] = &[
2651                "pg_roles",
2652                "pg_user",
2653                "pg_tables",
2654                "pg_views",
2655                "pg_settings",
2656                "pg_stat_activity",
2657                "pg_stat_database",
2658                "pg_stat_user_tables",
2659                "pg_class",
2660                "pg_attribute",
2661                "pg_type",
2662                "pg_proc",
2663                "pg_namespace",
2664                "pg_constraint",
2665                "pg_index",
2666                "pg_rewrite",
2667            ];
2668            if !SYSTEM_RELS.contains(&bare.as_str()) {
2669                return Err(EvalError::TypeMismatch {
2670                    detail: alloc::format!("relation \"{bare}\" does not exist"),
2671                });
2672            }
2673        }
2674    }
2675    // v7.39 (round 339, V63) — `::regproc` / `::regprocedure` resolve
2676    // against the USER function catalog too. Name resolution ran against
2677    // the static pg_proc table alone, so `'my_fn'::regproc` — the form
2678    // every catalog query and pg_dump uses to name a function — raised
2679    // `function "my_fn" does not exist` for a function that plainly did.
2680    // The cast layer has no catalog handle; this is the same interception
2681    // point the `::regclass` block above uses.
2682    if let (CastTarget::Named(tname), Some(cat), Value::Text(s)) = (target, ctx.catalog, &v) {
2683        let lower = tname.to_ascii_lowercase();
2684        if matches!(lower.as_str(), "regproc" | "regprocedure") {
2685            let raw = s.trim();
2686            // regprocedure carries the argument list: `f(int,text)`.
2687            let (name_part, args_part) = match raw.split_once('(') {
2688                Some((n, rest)) => (n.trim(), Some(rest.trim_end_matches(')'))),
2689                None => (raw, None),
2690            };
2691            let bare = name_part
2692                .strip_prefix("public.")
2693                .unwrap_or(name_part)
2694                .trim_matches('"');
2695            let cands = cat.functions_named(bare);
2696            if let Some(args_txt) = args_part {
2697                // An overload IS distinguishable here — the argument list
2698                // is what regprocedure exists to carry.
2699                let want =
2700                    crate::system_catalog::canonical_arg_types(&alloc::format!("({args_txt})"));
2701                if let Some(f) = cands
2702                    .iter()
2703                    .find(|f| crate::system_catalog::canonical_arg_types(&f.args_repr) == want)
2704                {
2705                    let rendered = alloc::format!(
2706                        "{bare}({})",
2707                        crate::system_catalog::canonical_arg_types(&f.args_repr)
2708                    );
2709                    // v7.39 (round 342, V65) — dual shape: the oid for
2710                    // catalog joins, the rendering for display.
2711                    let oid = crate::system_catalog::function_oid_by_signature(cat, bare, &want)
2712                        .unwrap_or(0);
2713                    return Ok(Value::RegProc(oid, rendered.into()));
2714                }
2715            } else {
2716                match cands.len() {
2717                    0 => {}
2718                    1 => {
2719                        let oid = crate::system_catalog::function_oid(cat, bare).unwrap_or(0);
2720                        return Ok(Value::RegProc(oid, bare.into()));
2721                    }
2722                    _ => {
2723                        return Err(EvalError::TypeMismatch {
2724                            detail: alloc::format!("more than one function named \"{bare}\""),
2725                        });
2726                    }
2727                }
2728            }
2729        }
2730    }
2731    // v7.38 (T-tstz Phase 1) — `<timestamptz>::text` renders the offset
2732    // (`2024-01-15 10:30:00+00`); plain timestamp does not. The runtime
2733    // value is the same tz-less `Value::Timestamp`, so consult the
2734    // inner expression's static type. Falls through to the ordinary
2735    // cast on any shape the static typer can't resolve — worst case is
2736    // today's no-offset rendering, never a wrong instant.
2737    if matches!(target, CastTarget::Text)
2738        && let Value::Timestamp(t) = &v
2739        && crate::describe::describe_expr(expr, ctx.columns)
2740            .is_some_and(|s| matches!(s.ty, spg_storage::DataType::Timestamptz))
2741    {
2742        // v7.39 (tz epic) — per-VALUE session offset (DST zones
2743        // vary within a statement); non-ISO DateStyles carry the
2744        // zone designation instead of the numeric offset.
2745        let off = ctx.session_tz_offset_at(*t);
2746        let abbr = ctx.session_tz_abbrev_at(*t);
2747        return Ok(Value::text(format::format_timestamptz_tz(
2748            *t,
2749            &ctx.render_style,
2750            off,
2751            abbr.as_deref(),
2752        )));
2753    }
2754    // v7.39 (read01 utils/adt, datetime.c) — the relative
2755    // reserved words resolve against the transaction clock:
2756    // 'today'/'tomorrow'/'yesterday' are midnight dates, 'now'
2757    // is the current instant ('now'::date = today). Clockless
2758    // engines fall through to the parser (which rejects them).
2759    if matches!(
2760        target,
2761        CastTarget::Date | CastTarget::Timestamp | CastTarget::Timestamptz
2762    ) && let Value::Text(word) = &v
2763        && let Some(clock) = ctx.clock
2764    {
2765        let w = word.trim().to_ascii_lowercase();
2766        if matches!(w.as_str(), "today" | "tomorrow" | "yesterday" | "now") {
2767            let now_us = clock();
2768            let today = i32::try_from(now_us.div_euclid(86_400_000_000)).ok();
2769            if let Some(today) = today {
2770                let day = match w.as_str() {
2771                    "tomorrow" => today + 1,
2772                    "yesterday" => today - 1,
2773                    _ => today,
2774                };
2775                return Ok(match (&target, w.as_str()) {
2776                    (CastTarget::Date, _) => Value::Date(day),
2777                    (_, "now") => Value::Timestamp(now_us),
2778                    _ => Value::Timestamp(crate::conversions::date_days_to_micros(day)),
2779                });
2780            }
2781        }
2782    }
2783    // v7.39 (GUC knife 5) — text INPUT to date/timestamp under a
2784    // non-MDY DateOrder disambiguates by the session order
2785    // (`'01/02/2024'::date` is Feb 1 under DMY). The default MDY
2786    // order flows through cast_value's parse_date_literal.
2787    if ctx.render_style.date_order != format::DateOrder::Mdy {
2788        match (&target, &v) {
2789            (CastTarget::Date, Value::Text(s)) => {
2790                if let Some(d) = format::parse_date_literal_ordered(s, ctx.render_style.date_order)
2791                {
2792                    return Ok(Value::Date(d));
2793                }
2794            }
2795            (CastTarget::Timestamp, Value::Text(s)) => {
2796                if let Some(t) =
2797                    format::parse_timestamp_literal_ordered(s, ctx.render_style.date_order)
2798                {
2799                    return Ok(Value::Timestamp(t));
2800                }
2801            }
2802            _ => {}
2803        }
2804    }
2805    // v7.39 (round 309, V30) — the mirror of the timestamptz arm
2806    // below. A literal carrying a zone NAME is legal input to the
2807    // zone-less types, and PG throws the zone away rather than
2808    // converting: `'2020-01-01 10:00:00 America/New_York'::timestamp`
2809    // is 10:00, not 15:00. Round 289 did this for a numeric `+02`
2810    // offset; a named zone still failed to parse at all.
2811    //
2812    // The name is not simply stripped — PG validates it, and says so
2813    // (`time zone "bogus/zone" not recognized`, lowercased) rather than
2814    // reporting a malformed literal. That check is why this belongs
2815    // here and not in `cast_value`: resolving a zone needs the host
2816    // functions, which only the context carries.
2817    let zoneless_target = match &target {
2818        CastTarget::Timestamp => Some("timestamp"),
2819        CastTarget::Date => Some("date"),
2820        // `::time` has no CastTarget of its own; it arrives named.
2821        CastTarget::Named(n) if n.eq_ignore_ascii_case("time") => Some("time"),
2822        _ => None,
2823    };
2824    if let Some(kind) = zoneless_target
2825        && let Value::Text(txt) = &v
2826        && let Some((wall, zone)) = split_trailing_zone_name(txt, ctx.render_style.date_order)
2827    {
2828        if ctx.zone_local_to_utc(zone, wall).is_none() {
2829            // Measured boundary: PG calls the token a ZONE NAME — and
2830            // so reports a misspelling as such — only when it is
2831            // path-shaped. A bare word it does not know (`ABCD`, `QQQ`,
2832            // `UTC_X`) makes the whole literal invalid syntax instead,
2833            // because nothing marks it as having meant a zone at all.
2834            if zone.contains('/') {
2835                return Err(EvalError::TypeMismatch {
2836                    detail: alloc::format!(
2837                        "time zone \"{}\" not recognized",
2838                        zone.to_ascii_lowercase()
2839                    ),
2840                });
2841            }
2842        } else {
2843            return Ok(match kind {
2844                "date" => {
2845                    Value::Date(i32::try_from(wall.div_euclid(86_400_000_000)).map_err(|_| {
2846                        EvalError::TypeMismatch {
2847                            detail: "timestamp out of DATE range".into(),
2848                        }
2849                    })?)
2850                }
2851                "time" => Value::Time(wall.rem_euclid(86_400_000_000)),
2852                _ => Value::Timestamp(wall),
2853            });
2854        }
2855    }
2856    // v7.39 (tz epic) — timestamptz INPUT: an offset-less
2857    // literal is a wall-clock reading in the session zone
2858    // (PG); a trailing IANA zone name localises there. Both
2859    // fall through to cast_value when nothing matches (its
2860    // parse treats naive input as UTC — correct for a UTC
2861    // session).
2862    if matches!(target, CastTarget::Timestamptz)
2863        && let Value::Text(txt) = &v
2864    {
2865        let order = ctx.render_style.date_order;
2866        let sess_zone = ctx
2867            .session_gucs
2868            .and_then(|g| g.get("timezone"))
2869            .map(String::as_str);
2870        // Trailing zone name: the last space-separated token,
2871        // when it names a resolvable zone (contains a letter
2872        // and isn't consumed by the plain parse).
2873        if let Some(idx) = txt.trim_end().rfind(' ') {
2874            let (head, tail) = (txt[..idx].trim(), txt[idx + 1..].trim());
2875            let tail_is_zoneish = tail.len() > 1
2876                && tail.bytes().any(|b| b.is_ascii_alphabetic())
2877                && !tail.eq_ignore_ascii_case("bc")
2878                && !tail.eq_ignore_ascii_case("ad");
2879            if tail_is_zoneish
2880                && format::parse_timestamp_literal_tz_ordered(txt, order).is_none()
2881                && let Some((wall, false)) = format::parse_timestamp_literal_tz_ordered(head, order)
2882                && let Some(utc) = ctx.zone_local_to_utc(tail, wall)
2883            {
2884                return Ok(Value::Timestamp(utc));
2885            }
2886        }
2887        if let Some((wall, had_tz)) = format::parse_timestamp_literal_tz_ordered(txt, order) {
2888            if had_tz {
2889                return Ok(Value::Timestamp(wall));
2890            }
2891            if let Some(zone) = sess_zone
2892                && !zone.eq_ignore_ascii_case("utc")
2893                && !zone.eq_ignore_ascii_case("gmt")
2894                && let Some(utc) = ctx.zone_local_to_utc(zone, wall)
2895            {
2896                return Ok(Value::Timestamp(utc));
2897            }
2898            return Ok(Value::Timestamp(wall));
2899        }
2900    }
2901    // v7.39 (round 523) — a NAIVE timestamp cast to timestamptz is a
2902    // wall-clock reading in the session zone, exactly as the text form
2903    // above already is. This was a no-op, so under `SET TimeZone =
2904    // 'Asia/Tokyo'` a `TIMESTAMP '2020-01-01 00:00:00'::timestamptz`
2905    // named 09:00 JST — a different INSTANT, nine hours from the one PG
2906    // stores, not a different rendering of the same one.
2907    //
2908    // The source's static type is the witness: SPG keeps timestamptz in
2909    // the same `Value::Timestamp`, so only an expression that is not
2910    // ALREADY timestamptz may be shifted, or a tstz-to-tstz cast would
2911    // move the instant twice.
2912    if matches!(target, CastTarget::Timestamptz)
2913        && let Value::Timestamp(wall) = &v
2914        && !matches!(
2915            crate::describe::describe_expr(expr, ctx.columns).map(|s| s.ty),
2916            Some(spg_storage::DataType::Timestamptz)
2917        )
2918        && let Some(zone) = ctx.session_gucs.and_then(|g| g.get("timezone"))
2919        && !zone.eq_ignore_ascii_case("utc")
2920        && !zone.eq_ignore_ascii_case("gmt")
2921        && let Some(utc) = ctx.zone_local_to_utc(zone, *wall)
2922    {
2923        return Ok(Value::Timestamp(utc));
2924    }
2925    // v7.39 (round 523) — and the other direction: a timestamptz cast
2926    // DOWN to a zone-free type reads the local clock in the session
2927    // zone. `(TIMESTAMPTZ '2020-01-01 15:00:00Z')::date` answered
2928    // 2020-01-01 in Tokyo where PG answers 2020-01-02 — a whole day out
2929    // for every instant in the last nine hours of a UTC day, which is
2930    // exactly the shape a daily report groups on. `now()::timestamp`
2931    // likewise disagreed with `now() AT TIME ZONE <session zone>`, which
2932    // PG defines to be the same value.
2933    if matches!(target, CastTarget::Timestamp | CastTarget::Date)
2934        && let Value::Timestamp(t) = &v
2935        && crate::describe::describe_expr(expr, ctx.columns)
2936            .is_some_and(|s| matches!(s.ty, spg_storage::DataType::Timestamptz))
2937    {
2938        let local = t.saturating_add(ctx.session_tz_offset_at(*t));
2939        return Ok(match target {
2940            CastTarget::Date => i32::try_from(local.div_euclid(86_400_000_000))
2941                .map_or(Value::Timestamp(local), Value::Date),
2942            _ => Value::Timestamp(local),
2943        });
2944    }
2945    // v7.39 (GUC knife 3) — the out-function casts honour the
2946    // session render style, like PG's date_out/interval_out/
2947    // float8out under DateStyle/IntervalStyle/extra_float_digits.
2948    if matches!(target, CastTarget::Text) {
2949        match &v {
2950            // v7.39 (round 524) — `bytea_out` is a render GUC too.
2951            Value::Bytes(b) if ctx.render_style.bytea_escape => {
2952                return Ok(Value::text(format::format_bytea_escape(b)));
2953            }
2954            Value::Date(d) => {
2955                return Ok(Value::text(format::format_date_styled(
2956                    *d,
2957                    &ctx.render_style,
2958                )));
2959            }
2960            Value::Timestamp(t) => {
2961                return Ok(Value::text(format::format_timestamp_styled(
2962                    *t,
2963                    &ctx.render_style,
2964                )));
2965            }
2966            Value::Interval {
2967                months,
2968                days,
2969                micros,
2970            } => {
2971                return Ok(Value::text(format::format_interval_styled(
2972                    *months,
2973                    *days,
2974                    *micros,
2975                    &ctx.render_style,
2976                )));
2977            }
2978            Value::Float(x) => {
2979                return Ok(Value::text(format::format_float_styled(
2980                    *x,
2981                    &ctx.render_style,
2982                )));
2983            }
2984            Value::Real(x) => {
2985                return Ok(Value::text(format::format_real_styled(
2986                    *x,
2987                    &ctx.render_style,
2988                )));
2989            }
2990            _ => {}
2991        }
2992    }
2993    crate::eval::cast::cast_value_ref_in(v, target, ctx.mysql_dialect)
2994}
2995
2996/// Out-of-lined `eval_expr` arm — keeps the recursive frame small
2997/// (stack-depth guard budget); body unchanged.
2998#[inline(never)]
2999fn eval_array_arm(
3000    items: &[Expr],
3001    row: &Row<'static>,
3002    ctx: &EvalContext<'_>,
3003) -> Result<Value<'static>, EvalError> {
3004    let mut materialised: Vec<Value<'static>> = Vec::with_capacity(items.len());
3005    for elem in items {
3006        materialised.push(eval_expr(elem, row, ctx)?);
3007    }
3008    // v7.38 (read01, T10) — a constructor whose elements are all 1-D
3009    // arrays builds a 2-D array (`ARRAY[[1,2],[3,4]]`). All rows must
3010    // share a length (PG: "multidimensional arrays must have array
3011    // expressions with matching dimensions"). Int rows promote to
3012    // bigint if any row is bigint; a text row makes the whole thing text.
3013    // v7.39 (read01 round 73) — a row of ANY array kind counts. Round 72 gave
3014    // `ARRAY[true,false]` its real `bool[]` type, and this detector only knew
3015    // Int / BigInt / Text rows — so `ARRAY[ARRAY[true,false]]` stopped being a
3016    // 2-D array at all and collapsed into a 1-D text[] of rendered rows, with
3017    // `[1][2]` failing outright. A regression THIS campaign introduced, caught by
3018    // the very sweep that was chasing its own residual. Rows that are not
3019    // int/bigint arrays render into the text 2-D form below (SPG has no bool 2-D
3020    // storage variant — a recorded residual), but they stay 2-D.
3021    let all_arrays = !materialised.is_empty()
3022        && materialised.iter().all(|v| {
3023            values::array_len(v).is_some()
3024                && !matches!(
3025                    v,
3026                    Value::TextArray2D(_)
3027                        | Value::IntArray2D(_)
3028                        | Value::BigIntArray2D(_)
3029                        | Value::BoolArray2D(_)
3030                )
3031        });
3032    if all_arrays {
3033        let row_len = values::array_len(&materialised[0]).unwrap_or(0);
3034        let same_len = materialised
3035            .iter()
3036            .all(|v| values::array_len(v) == Some(row_len));
3037        if !same_len {
3038            return Err(EvalError::TypeMismatch {
3039                detail: "multidimensional arrays must have array expressions \
3040                         with matching dimensions"
3041                    .into(),
3042            });
3043        }
3044        // v7.39 (read01 round 75) — all-BOOL rows build a real `bool[][]`. BOOL is
3045        // the one element type whose ARRAY rendering (`t`) differs from its
3046        // scalar one (`true`), so the text-backed 2-D could not be right for it:
3047        // `ARRAY[ARRAY[true,false]]::text` wants `{{t,f}}` while `[1][2]::text`
3048        // wants `false`. Every other type renders the same either way — which is
3049        // why this is the only typed 2-D SPG needs.
3050        if materialised
3051            .iter()
3052            .all(|v| matches!(v, Value::BoolArray(_)))
3053        {
3054            let rows: Vec<Vec<Option<bool>>> = materialised
3055                .into_iter()
3056                .map(|v| match v {
3057                    Value::BoolArray(r) => r,
3058                    _ => unreachable!("checked above"),
3059                })
3060                .collect();
3061            return Ok(Value::BoolArray2D(rows));
3062        }
3063        let any_text = materialised
3064            .iter()
3065            .any(|v| !matches!(v, Value::IntArray(_) | Value::BigIntArray(_)));
3066        let any_big = materialised
3067            .iter()
3068            .any(|v| matches!(v, Value::BigIntArray(_)));
3069        if any_text {
3070            let rows: Vec<Vec<Option<String>>> = materialised
3071                .into_iter()
3072                .map(|v| match v {
3073                    Value::TextArray(r) => r,
3074                    // Any other element type renders into the text 2-D form,
3075                    // element by element. SPG has no typed 2-D storage beyond
3076                    // int / bigint / text, so a bool 2-D array IS text — and the
3077                    // SCALAR rendering is the one to use: `(arr)[1][2]::text`
3078                    // must read `false`, as in PG. (`pg_typeof` reporting
3079                    // `text[]` rather than `boolean[]` is the recorded residual;
3080                    // a typed 2-D needs new storage variants.)
3081                    other => {
3082                        let n = values::array_len(&other).unwrap_or(0);
3083                        (0..n)
3084                            .map(|i| match values::array_element_at(&other, i) {
3085                                None | Some(Value::Null) => None,
3086                                Some(v) => Some(value_to_text(&v)),
3087                            })
3088                            .collect()
3089                    }
3090                })
3091                .collect();
3092            return Ok(Value::TextArray2D(rows));
3093        }
3094        if any_big {
3095            let rows: Vec<Vec<Option<i64>>> = materialised
3096                .into_iter()
3097                .map(|v| match v {
3098                    Value::BigIntArray(r) => r,
3099                    Value::IntArray(r) => r.into_iter().map(|c| c.map(i64::from)).collect(),
3100                    _ => unreachable!(),
3101                })
3102                .collect();
3103            return Ok(Value::BigIntArray2D(rows));
3104        }
3105        let rows: Vec<Vec<Option<i32>>> = materialised
3106            .into_iter()
3107            .map(|v| match v {
3108                Value::IntArray(r) => r,
3109                _ => unreachable!(),
3110            })
3111            .collect();
3112        return Ok(Value::IntArray2D(rows));
3113    }
3114    // v7.39 (read01 round 72) — a HOMOGENEOUS array of a non-numeric, non-text
3115    // type keeps that type, and is unambiguous, so it is decided BEFORE the
3116    // numeric/text unification below. Everything outside the numeric ladder and
3117    // text used to fall into that loop's `_ => has_text = true` — a silent
3118    // degradation, not a decision: `ARRAY[true, false]` came back as `text[]`.
3119    // It usually LOOKED right (array_to_string renders `t` either way), which is
3120    // exactly what let it sit; the array FUNCTIONS are what tripped over it.
3121    if let Some(v) = values::homogeneous_typed_array(&materialised) {
3122        return Ok(crate::describe::upgrade_timestamptz_array(
3123            v,
3124            items,
3125            ctx.columns,
3126        ));
3127    }
3128    // v7.39 (round 236) — PG resolves an ARRAY constructor's elements to ONE
3129    // element type and refuses the constructor when they have no common one:
3130    // `ARRAY[1, 'a'::text]` is "ARRAY types integer and text cannot be
3131    // matched". SPG degraded to `text[]` instead, so `ARRAY[1, true]` came
3132    // back as `{1,t}` — a column of rendered strings that then behaved like
3133    // text everywhere downstream. Same rule (and the same untyped-literal
3134    // subtlety) as the set-operation resolution in round 233: a bare string
3135    // literal is PG's `unknown` and takes the other elements' type, so it is
3136    // identified from the SYNTAX, not from the value's runtime type.
3137    unify_array_elements(items, &mut materialised)?;
3138    // Coercing the untyped elements can make the array homogeneous
3139    // (`ARRAY[true,'t']` becomes two booleans), so re-try the typed-array
3140    // path before falling into the numeric/text ladder below — otherwise
3141    // the now-uniform boolean array would still degrade to text[].
3142    if let Some(v) = values::homogeneous_typed_array(&materialised) {
3143        return Ok(crate::describe::upgrade_timestamptz_array(
3144            v,
3145            items,
3146            ctx.columns,
3147        ));
3148    }
3149    let mut has_text = false;
3150    let mut has_float = false;
3151    let mut has_numeric = false;
3152    let mut has_bigint = false;
3153    let mut has_int = false;
3154    // A NumericBig or non-finite (NaN/Inf) numeric can't be held in
3155    // NumericArray's `(i128, scale)` cells, so it forces the text[]
3156    // fallback rather than a lossy/panicking conversion.
3157    let mut numeric_representable = true;
3158    for v in &materialised {
3159        match v {
3160            Value::Null => {}
3161            Value::Int(_) | Value::SmallInt(_) => has_int = true,
3162            Value::BigInt(_) => has_bigint = true,
3163            Value::Numeric {
3164                kind: spg_storage::NumericKind::Finite,
3165                ..
3166            } => {
3167                has_numeric = true;
3168            }
3169            Value::Numeric { .. } => {
3170                has_numeric = true;
3171                numeric_representable = false;
3172            }
3173            Value::NumericBig(_) => {
3174                has_numeric = true;
3175                numeric_representable = false;
3176            }
3177            Value::Float(_) => has_float = true,
3178            Value::Text(_) | Value::Json(_) => has_text = true,
3179            // v7.39 (round 652) — a reg value belongs to the array by
3180            // its OID half. Falling into the catch-all made
3181            // `ARRAY['pg_class'::regclass]` a text array, so
3182            // `oid = ANY(…)` compared bigint against text and was
3183            // refused — while the identical `oid = 'pg_class'::regclass`
3184            // worked. Same defect the IN-list gate had, one layer down.
3185            Value::RegClass(..) | Value::RegProc(..) | Value::RegType(..) => has_bigint = true,
3186            _ => has_text = true,
3187        }
3188    }
3189    let any_numlike = has_int || has_bigint || has_numeric || has_float;
3190    if has_text || !any_numlike || (has_numeric && !numeric_representable) {
3191        let out: Vec<Option<String>> = materialised
3192            .into_iter()
3193            .map(|v| match v {
3194                Value::Null => None,
3195                Value::Text(s) | Value::Json(s) => Some(s.into_owned()),
3196                other => Some(value_to_text_for_array(&other, &ctx.render_style)),
3197            })
3198            .collect();
3199        return Ok(Value::TextArray(out));
3200    }
3201    // v7.38 (read01) — PG array-element unification across the numeric
3202    // ladder: any float → double precision[]; else any numeric →
3203    // numeric[] (each element keeps its own scale, PG's behaviour);
3204    // else the integer widths. Matches `pg_typeof(ARRAY[1, 2.5])` =
3205    // numeric[] and keeps downstream `[i]` arithmetic numeric.
3206    if has_float {
3207        let out: Vec<Option<f64>> = materialised
3208            .into_iter()
3209            .map(|v| match v {
3210                Value::Null => None,
3211                Value::Float(f) => Some(f),
3212                Value::Int(n) => Some(f64::from(n)),
3213                Value::SmallInt(n) => Some(f64::from(n)),
3214                #[allow(clippy::cast_precision_loss)]
3215                Value::BigInt(n) => Some(n as f64),
3216                #[allow(clippy::cast_precision_loss)]
3217                Value::Numeric { scaled, scale, .. } => {
3218                    Some(scaled as f64 / libm::pow(10.0, f64::from(scale)))
3219                }
3220                _ => None,
3221            })
3222            .collect();
3223        return Ok(Value::FloatArray(out));
3224    }
3225    if has_numeric {
3226        let out: Vec<Option<(i128, u16)>> = materialised
3227            .into_iter()
3228            .map(|v| match v {
3229                Value::Null => None,
3230                Value::SmallInt(n) => Some((i128::from(n), 0)),
3231                Value::Int(n) => Some((i128::from(n), 0)),
3232                Value::BigInt(n) => Some((i128::from(n), 0)),
3233                Value::Numeric { scaled, scale, .. } => Some((scaled, scale)),
3234                _ => None,
3235            })
3236            .collect();
3237        return Ok(Value::NumericArray(out));
3238    }
3239    if has_bigint {
3240        let out: Vec<Option<i64>> = materialised
3241            .into_iter()
3242            .map(|v| match v {
3243                Value::Null => None,
3244                Value::Int(n) => Some(i64::from(n)),
3245                Value::SmallInt(n) => Some(i64::from(n)),
3246                Value::BigInt(n) => Some(n),
3247                // Keep in step with the `has_bigint` classification above:
3248                // whatever is counted there has to be convertible here, and
3249                // the arm below panics rather than errors. Round 652 added
3250                // the reg family to the classifier and this materialiser
3251                // took a wire-visible panic until it learned them too.
3252                Value::RegClass(oid, _) | Value::RegProc(oid, _) | Value::RegType(oid, _) => {
3253                    Some(oid)
3254                }
3255                _ => unreachable!(),
3256            })
3257            .collect();
3258        return Ok(Value::BigIntArray(out));
3259    }
3260    let out: Vec<Option<i32>> = materialised
3261        .into_iter()
3262        .map(|v| match v {
3263            Value::Null => None,
3264            Value::Int(n) => Some(n),
3265            Value::SmallInt(n) => Some(i32::from(n)),
3266            _ => unreachable!(),
3267        })
3268        .collect();
3269    Ok(Value::IntArray(out))
3270}
3271
3272/// Out-of-lined `eval_expr` arm — keeps the recursive frame small
3273/// (stack-depth guard budget); body unchanged.
3274#[inline(never)]
3275fn eval_function_call_arm(
3276    name: &str,
3277    args: &[Expr],
3278    row: &Row<'static>,
3279    ctx: &EvalContext<'_>,
3280) -> Result<Value<'static>, EvalError> {
3281    // v7.39 (read01 round 77) — named arguments (`f(x := 1)` / `f(x => 1)`).
3282    // The parser leaves them in the tree because only the catalog knows a user
3283    // function's parameter names; here they become positional, once, for
3284    // builtins and user functions alike.
3285    // v7.39 (read01 round 100) — `VARIADIC <array>` splices the array's
3286    // elements in as individual trailing arguments before dispatch, so a
3287    // variadic builtin (concat / concat_ws / format / …) sees them exactly as
3288    // if they had been written out. Done before the named-arg pass and the
3289    // positional dispatch.
3290    if args.iter().any(|a| matches!(a, Expr::Variadic(_))) {
3291        let expanded = expand_variadic_args(args, row, ctx)?;
3292        return eval_function_call_arm(name, &expanded, row, ctx);
3293    }
3294    // v7.39 (round 276) — `date_part('timezone'|…, <timestamp>)` must be
3295    // REJECTED the way EXTRACT already rejects it, and the judgement
3296    // needs the argument's STATIC declared type: SPG stores timestamptz
3297    // in the same `Value::Timestamp`, so a timestamptz legitimately
3298    // answers 0 while a plain timestamp must error. The dispatch below
3299    // receives values, not expressions, so the check belongs here —
3300    // the same place, and the same r237 trust rule (only a cast or a
3301    // column is believed), that the EXTRACT arm uses.
3302    if name.eq_ignore_ascii_case("date_part")
3303        && args.len() == 2
3304        && let Expr::Literal(spg_sql::ast::Literal::String(unit)) = &args[0]
3305        && matches!(
3306            unit.to_ascii_lowercase().as_str(),
3307            "timezone" | "timezone_hour" | "timezone_minute"
3308        )
3309        && matches!(&args[1], Expr::Cast { .. } | Expr::Column(_))
3310        && let Some(sch) = crate::describe::describe_expr(&args[1], ctx.columns)
3311        && matches!(sch.ty, spg_storage::DataType::Timestamp)
3312    {
3313        return Err(EvalError::TypeMismatch {
3314            detail: alloc::format!(
3315                "unit \"{}\" not supported for type timestamp without time zone",
3316                unit.to_ascii_lowercase()
3317            ),
3318        });
3319    }
3320    // v7.39 (round 258) — `pg_typeof` over an ENUM. An enum value travels
3321    // as `Value::Text` (its label), so the value-driven namer answered
3322    // `text`; the type lives in the EXPRESSION, which this arm still has.
3323    // `expr_enum_type_name` resolves a column or a cast statically — the
3324    // same static-only discipline round 253 used for EXTRACT's type name.
3325    if name.eq_ignore_ascii_case("pg_typeof")
3326        && let [arg] = args
3327    {
3328        // The name must be a REAL enum in the catalog. `expr_enum_type_name`
3329        // returns any named cast's target verbatim — it is only a
3330        // pre-filter for `expr_enum_labels`, which does the catalog
3331        // lookup — so using it alone hijacked every `x::float8` /
3332        // `x::int2` and reported SPG's internal spelling instead of PG's.
3333        // v7.39 (round 259) — domains report their own name too; like an
3334        // enum, a domain value travels as its BASE type's value, so the
3335        // name has to come from the expression. Both lookups are gated on
3336        // the catalog: `expr_enum_type_name` returns ANY named cast's
3337        // target verbatim, so an ungated use hijacks `x::float8`.
3338        let is_user_type = |e: &Expr| {
3339            expr_enum_type_name(e, ctx.columns)
3340                .filter(|n| {
3341                    // v7.39 (round 330, V48) — the information_schema
3342                    // domains are built into the server rather than
3343                    // catalog objects (a catalog domain is user data and
3344                    // would be dumped), so they are recognised here too.
3345                    crate::system_catalog::is_information_schema_domain(n)
3346                        || ctx.catalog.is_some_and(|cat| {
3347                            cat.enum_types().contains_key(*n)
3348                                || cat.domain_types().contains_key(*n)
3349                                // v7.39 (round 263) — composites too: a cast
3350                                // to one reported the generic `record`.
3351                                || cat.composite_types().contains_key(*n)
3352                        })
3353                })
3354                .map(alloc::string::String::from)
3355        };
3356        let is_enum = is_user_type;
3357        if let Some(en) = is_enum(arg) {
3358            return Ok(Value::text(en));
3359        }
3360        // `ARRAY[<enum>, …]` reports the array form.
3361        if let Expr::Array(items) = arg
3362            && let Some(first) = items.first()
3363            && let Some(en) = is_enum(first)
3364        {
3365            return Ok(Value::text(alloc::format!("{en}[]")));
3366        }
3367    }
3368    if args.iter().any(|a| matches!(a, Expr::NamedArg { .. })) {
3369        let positional = resolve_named_args(name, args, ctx)?;
3370        return eval_function_call_arm(name, &positional, row, ctx);
3371    }
3372    eval_function_call_positional(name, args, row, ctx)
3373}
3374
3375/// v7.39 (read01 round 100) — rewrite a call's argument list, replacing each
3376/// `VARIADIC <array>` with the array's elements as literal arguments. A NULL
3377/// array contributes no elements (PG treats `VARIADIC NULL` as empty). Regular
3378/// arguments are carried through untouched so they still evaluate against the
3379/// row in the recursive call.
3380fn expand_variadic_args(
3381    args: &[Expr],
3382    row: &Row<'static>,
3383    ctx: &EvalContext<'_>,
3384) -> Result<alloc::vec::Vec<Expr>, EvalError> {
3385    let mut out = alloc::vec::Vec::with_capacity(args.len());
3386    for a in args {
3387        if let Expr::Variadic(inner) = a {
3388            let v = eval_expr(inner, row, ctx)?;
3389            let elems = crate::select::array_value_to_elements(&v).map_err(|_| {
3390                EvalError::TypeMismatch {
3391                    detail: "VARIADIC argument must be an array".into(),
3392                }
3393            })?;
3394            for e in elems {
3395                out.push(Expr::Literal(crate::value_to_literal(e)));
3396            }
3397        } else {
3398            out.push(a.clone());
3399        }
3400    }
3401    Ok(out)
3402}
3403
3404/// The declared parameter names of `fname`, or `None` when it takes none.
3405/// Builtins whose parameters PG names live in the table; everything else asks
3406/// the catalog, where a user function's `args_repr` has carried its parameter
3407/// names since the day CREATE FUNCTION stored them.
3408fn declared_param_names(fname: &str, ctx: &EvalContext<'_>) -> Option<alloc::vec::Vec<String>> {
3409    let lower = fname.to_ascii_lowercase();
3410    let builtin: &[&str] = match lower.as_str() {
3411        "make_date" => &["year", "month", "day"],
3412        "make_time" => &["hour", "min", "sec"],
3413        "make_timestamp" | "make_timestamptz" => &["year", "month", "mday", "hour", "min", "sec"],
3414        "make_interval" => &["years", "months", "weeks", "days", "hours", "mins", "secs"],
3415        _ => &[],
3416    };
3417    if !builtin.is_empty() {
3418        return Some(builtin.iter().map(|s| (*s).to_string()).collect());
3419    }
3420    let cat = ctx.catalog?;
3421    let def = cat
3422        .functions()
3423        .values()
3424        .find(|f| f.name.eq_ignore_ascii_case(&lower))?;
3425    let names = spg_storage::function_arg_names(&def.args_repr);
3426    if names.iter().all(alloc::string::String::is_empty) {
3427        return None;
3428    }
3429    Some(names)
3430}
3431
3432/// Rewrite a call's arguments into positional order. Positional arguments fill
3433/// slots left to right; a named one goes to its declared slot. Slots nobody
3434/// filled stay absent for a user function (arity is checked at the call) and
3435/// become integer 0 for the `make_*` builtins, whose trailing fields PG
3436/// defaults that way.
3437fn resolve_named_args(
3438    fname: &str,
3439    args: &[Expr],
3440    ctx: &EvalContext<'_>,
3441) -> Result<alloc::vec::Vec<Expr>, EvalError> {
3442    let Some(params) = declared_param_names(fname, ctx) else {
3443        return Err(EvalError::TypeMismatch {
3444            detail: alloc::format!("function {fname}(...) does not support named arguments"),
3445        });
3446    };
3447    let mut slots: alloc::vec::Vec<Option<Expr>> = (0..params.len()).map(|_| None).collect();
3448    let mut next_positional = 0usize;
3449    for a in args {
3450        let (idx, val) = match a {
3451            Expr::NamedArg { name, expr } => {
3452                let i = params
3453                    .iter()
3454                    .position(|p| p.eq_ignore_ascii_case(name))
3455                    .ok_or_else(|| EvalError::TypeMismatch {
3456                        detail: alloc::format!("{fname}(...) has no argument named \"{name}\""),
3457                    })?;
3458                (i, (**expr).clone())
3459            }
3460            other => {
3461                let i = next_positional;
3462                next_positional += 1;
3463                (i, other.clone())
3464            }
3465        };
3466        if idx >= slots.len() {
3467            return Err(EvalError::TypeMismatch {
3468                detail: alloc::format!("{fname}(...) got too many arguments"),
3469            });
3470        }
3471        if slots[idx].is_some() {
3472            return Err(EvalError::TypeMismatch {
3473                detail: alloc::format!("{fname}(...) got multiple values for one argument"),
3474            });
3475        }
3476        slots[idx] = Some(val);
3477    }
3478    let make_family = fname.to_ascii_lowercase().starts_with("make_");
3479    let mut out = alloc::vec::Vec::with_capacity(slots.len());
3480    for slot in slots {
3481        match slot {
3482            Some(e) => out.push(e),
3483            None if make_family => {
3484                out.push(Expr::Literal(spg_sql::ast::Literal::Integer(0)));
3485            }
3486            // A user function's unfilled slot is simply not passed; the call's
3487            // own arity check phrases the error.
3488            None => {}
3489        }
3490    }
3491    Ok(out)
3492}
3493
3494fn eval_function_call_positional(
3495    name: &str,
3496    args: &[Expr],
3497    row: &Row<'static>,
3498    ctx: &EvalContext<'_>,
3499) -> Result<Value<'static>, EvalError> {
3500    // v7.39 (round 237) — COALESCE / GREATEST / LEAST resolve their
3501    // arguments to one type the way CASE and ARRAY do. Checked statically:
3502    // an argument may have side effects (`COALESCE(nextval('s'), 1)`), so
3503    // its declared type is read rather than its value.
3504    if matches!(args.len(), 2..) {
3505        let construct = if name.eq_ignore_ascii_case("coalesce") {
3506            Some("COALESCE")
3507        } else if name.eq_ignore_ascii_case("greatest") {
3508            Some("GREATEST")
3509        } else if name.eq_ignore_ascii_case("least") {
3510            Some("LEAST")
3511        } else {
3512            None
3513        };
3514        if let Some(construct) = construct {
3515            unify_branch_types_static(construct, args.iter(), ctx)?;
3516        }
3517    }
3518    // v7.39 (read01 utils/adt, enum.c) — the enum introspection
3519    // v7.39 (read01 utils/adt, enum.c) — the enum introspection
3520    // family needs the ARGUMENT'S STATIC TYPE (the value is
3521    // usually NULL::enumtype): first/last/range over the
3522    // catalog's member order. Out-of-line so eval_expr's
3523    // recursion frame stays small (stack-depth guard budget).
3524    if (name.eq_ignore_ascii_case("enum_first")
3525        || name.eq_ignore_ascii_case("enum_last")
3526        || name.eq_ignore_ascii_case("enum_range"))
3527        && enum_introspection_applies(args, ctx)
3528    {
3529        return eval_enum_introspection(name, args, row, ctx);
3530    }
3531    // v7.39 (tz epic) — AT TIME ZONE (fn form: timezone(zone, ts))
3532    // with a NAMED zone needs the host tzdb and the argument's
3533    // static type for its two directions:
3534    //   naive AT ZONE  -> that zone's wall clock -> UTC instant
3535    //   tstz  AT ZONE  -> UTC instant -> that zone's wall clock
3536    // Fixed offsets / abbreviations keep the legacy path below.
3537    // v7.39 (round 523) — `to_char(tstz, fmt)` renders the LOCAL clock
3538    // in the session zone, and its zone tokens name that zone. It was
3539    // rendering the UTC reading and spelling it `UTC`, so a formatted
3540    // stamp disagreed with the same value's own `::text`.
3541    if args.len() == 2
3542        && name.eq_ignore_ascii_case("to_char")
3543        && let Some(zone) = ctx.session_gucs.and_then(|g| g.get("timezone"))
3544        && !zone.eq_ignore_ascii_case("utc")
3545        && !zone.eq_ignore_ascii_case("gmt")
3546        && crate::describe::describe_expr(&args[0], ctx.columns)
3547            .is_some_and(|s| matches!(s.ty, spg_storage::DataType::Timestamptz))
3548        && let Value::Timestamp(t) = eval_expr(&args[0], row, ctx)?
3549    {
3550        let off = ctx.session_tz_offset_at(t);
3551        let abbrev = ctx
3552            .session_tz_abbrev_at(t)
3553            .unwrap_or_else(|| zone.to_uppercase());
3554        let vals = [
3555            Value::Timestamp(t.saturating_add(off)),
3556            eval_expr(&args[1], row, ctx)?,
3557        ];
3558        return crate::eval::strings::to_char_in_zone(&vals, Some((&abbrev, off)));
3559    }
3560    // v7.39 (round 523) — `date_trunc(unit, tstz)` truncates on the
3561    // LOCAL calendar in the session zone. It was truncating in UTC and
3562    // rendering the result in the session zone, so under `SET TimeZone =
3563    // 'Asia/Tokyo'` a day truncation answered `2020-01-01 09:00:00+09` —
3564    // not a day boundary at all, and the wrong day for anything before
3565    // 09:00. Every report grouped by day was cut nine hours late.
3566    //
3567    // The three-argument form already does exactly this, DST reverse
3568    // lookup and all, so the session zone is passed to THAT rather than
3569    // written a second time. Only a statically-known timestamptz shifts:
3570    // a naive timestamp has no zone to be read in.
3571    if args.len() == 2
3572        && (name.eq_ignore_ascii_case("date_trunc") || name.eq_ignore_ascii_case("date_bin"))
3573        && let Some(zone) = ctx.session_gucs.and_then(|g| g.get("timezone"))
3574        && !zone.eq_ignore_ascii_case("utc")
3575        && !zone.eq_ignore_ascii_case("gmt")
3576        && crate::describe::describe_expr(&args[1], ctx.columns)
3577            .is_some_and(|s| matches!(s.ty, spg_storage::DataType::Timestamptz))
3578    {
3579        let vals = [
3580            eval_expr(&args[0], row, ctx)?,
3581            eval_expr(&args[1], row, ctx)?,
3582            Value::text(zone.clone()),
3583        ];
3584        return datetime::date_trunc(&vals, ctx);
3585    }
3586    if args.len() == 2
3587        && name.eq_ignore_ascii_case("timezone")
3588        && let zone_v = eval_expr(&args[0], row, ctx)?
3589        && let Value::Text(zone) = &zone_v
3590        && datetime::resolve_zone_offset(zone.as_ref()).is_none()
3591        && !zone.trim().eq_ignore_ascii_case("utc")
3592        && !zone.trim().eq_ignore_ascii_case("gmt")
3593        && zone.parse::<i64>().is_err()
3594        && ctx.tz_offset_fn.is_some()
3595    {
3596        let zone = zone.trim();
3597        let src_is_tstz = crate::describe::describe_expr(&args[1], ctx.columns)
3598            .is_some_and(|s| matches!(s.ty, spg_storage::DataType::Timestamptz));
3599        let inner = eval_expr(&args[1], row, ctx)?;
3600        if let Value::Timestamp(t) = inner {
3601            if src_is_tstz {
3602                if let Some(off) = ctx.zone_offset_at(zone, t) {
3603                    return Ok(Value::Timestamp(t + off));
3604                }
3605            } else if let Some(utc) = ctx.zone_local_to_utc(zone, t) {
3606                return Ok(Value::Timestamp(utc));
3607            }
3608            return Err(EvalError::TypeMismatch {
3609                detail: alloc::format!("time zone \"{zone}\" not recognized"),
3610            });
3611        }
3612    }
3613    // v7.29 (round-22 phase 3) - prefix fast path: LEFT(col, n)
3614    // on a TEXT column borrows the cell and clones only the
3615    // prefix. The generic path clones the WHOLE cell first -
3616    // a LEFT(body, 120) over 24k x 30 KB rows spent 383 ms
3617    // copying bytes it then threw away (7 ms without LEFT).
3618    if args.len() == 2
3619        && name.eq_ignore_ascii_case("left")
3620        && let Expr::Column(c) = &args[0]
3621        && let Some(cell) = resolve_column_borrowed(c, row, ctx)?
3622    {
3623        {
3624            match cell {
3625                Value::Null => return Ok(Value::Null),
3626                Value::Text(t) => {
3627                    let n_v = eval_expr(&args[1], row, ctx)?;
3628                    if let Value::SmallInt(_) | Value::Int(_) | Value::BigInt(_) = n_v {
3629                        let n = match n_v {
3630                            Value::SmallInt(x) => i64::from(x),
3631                            Value::Int(x) => i64::from(x),
3632                            Value::BigInt(x) => x,
3633                            _ => 0,
3634                        };
3635                        return Ok(Value::text(text_prefix_chars(t, n)));
3636                    }
3637                }
3638                _ => {}
3639            }
3640        }
3641    }
3642    // v7.38 (T-tstz Phase 1) — the ONE case where pg_typeof needs the
3643    // static type: timestamptz. The runtime value is a tz-less
3644    // Value::Timestamp, so the value-driven answer below can only ever
3645    // say "without time zone". For every other type the value-driven
3646    // path is strictly better (it distinguishes json vs jsonb, keeps
3647    // NULL as "unknown", and is not fooled by describe_expr's lossy
3648    // heuristics), so we consult the static typer ONLY when it says
3649    // Timestamptz and otherwise fall through untouched.
3650    if args.len() == 1
3651        && name.eq_ignore_ascii_case("pg_typeof")
3652        && crate::describe::describe_expr(&args[0], ctx.columns)
3653            .is_some_and(|s| matches!(s.ty, spg_storage::DataType::Timestamptz))
3654    {
3655        return Ok(Value::text::<alloc::string::String>(
3656            "timestamp with time zone".into(),
3657        ));
3658    }
3659    // v7.39 (round 694) — `oid[]`. Its VALUE is a BigIntArray, so the
3660    // value-driven namer answers `bigint[]`; the declared type lives in the
3661    // expression, exactly as it does for the Timestamptz arm above and for
3662    // the enum / domain / composite arms further down. The scalar `oid`
3663    // needed the same treatment in round 667.
3664    if args.len() == 1
3665        && name.eq_ignore_ascii_case("pg_typeof")
3666        && crate::describe::describe_expr(&args[0], ctx.columns)
3667            .is_some_and(|s| matches!(s.ty, spg_storage::DataType::OidArray))
3668    {
3669        return Ok(Value::text::<alloc::string::String>("oid[]".into()));
3670    }
3671    // v7.39 (read01 round 56) — a COMPOSITE column reports its type NAME, not
3672    // the generic `record` the runtime value would give. Composite-ness lives
3673    // outside the DataType lattice (the stored form is JSON), so the witness is
3674    // the column's `user_composite_type` — the same shape as the enum witness.
3675    if args.len() == 1
3676        && name.eq_ignore_ascii_case("pg_typeof")
3677        && let Expr::Column(c) = &args[0]
3678        && let Some(cname) = ctx
3679            .columns
3680            .iter()
3681            .find(|sc| sc.name.eq_ignore_ascii_case(&c.name))
3682            .and_then(|sc| sc.user_composite_type.as_deref())
3683    {
3684        return Ok(Value::text::<alloc::string::String>(cname.into()));
3685    }
3686    // v7.39 (round 291) — `name` is a DECLARED type over a Value::Text,
3687    // so the value can never witness it; the schema is the only witness,
3688    // exactly as for a composite column above.
3689    if args.len() == 1
3690        && name.eq_ignore_ascii_case("pg_typeof")
3691        && let Expr::Column(c) = &args[0]
3692        && ctx
3693            .columns
3694            .iter()
3695            .any(|sc| sc.name.eq_ignore_ascii_case(&c.name) && sc.ty == spg_storage::DataType::Name)
3696    {
3697        return Ok(Value::text::<alloc::string::String>("name".into()));
3698    }
3699    // …and the same for a bare `'abc'::name`, where the cast TARGET is
3700    // the witness. PG computes pg_typeof statically; SPG reads the
3701    // value, which by then is an ordinary text.
3702    if args.len() == 1
3703        && name.eq_ignore_ascii_case("pg_typeof")
3704        && let Expr::Cast {
3705            target: spg_sql::ast::CastTarget::Named(n),
3706            ..
3707        } = &args[0]
3708        && n.eq_ignore_ascii_case("name")
3709    {
3710        return Ok(Value::text::<alloc::string::String>("name".into()));
3711    }
3712    // v7.39 (read01 round 116) — a bare, uncoerced string literal is PG's
3713    // `unknown` type, not text: `pg_typeof('x')` / `pg_typeof('123')` /
3714    // `pg_typeof('2024-01-01')` all report `unknown`. The literal only becomes
3715    // text once context coerces it — a cast (`'x'::text`), a concatenation, or
3716    // a function argument — each of which is a different Expr node that falls
3717    // through to the value-driven path below (which correctly says text).
3718    if args.len() == 1
3719        && name.eq_ignore_ascii_case("pg_typeof")
3720        && matches!(&args[0], Expr::Literal(spg_sql::ast::Literal::String(_)))
3721    {
3722        return Ok(Value::text::<alloc::string::String>("unknown".into()));
3723    }
3724    // v7.37.16 — pg_typeof of a NULL cell reports the COLUMN's
3725    // static type when it has one (PG: `VALUES (NULL),(1.5)`
3726    // types the column numeric and its NULL row's pg_typeof says
3727    // numeric, not unknown).
3728    //
3729    // A BARE `NULL` stays "unknown", as PG has it. That used to fall
3730    // out of TEXT being absent from the name table — a NULL literal
3731    // describes as TEXT, so the lookup returned None and the caller
3732    // reported unknown. Round 871 filled that table in, which silently
3733    // took the bare-NULL behaviour with it and broke
3734    // `pg_typeof_null_returns_unknown`. The rule is now stated rather
3735    // than emergent: an untyped NULL literal is unknown, a NULL that
3736    // was cast reports what it was cast to.
3737    if args.len() == 1 && name.eq_ignore_ascii_case("pg_typeof") {
3738        if matches!(&args[0], Expr::Literal(spg_sql::ast::Literal::Null)) {
3739            return Ok(Value::text::<alloc::string::String>("unknown".into()));
3740        }
3741        let v = eval_expr(&args[0], row, ctx)?;
3742        if matches!(v, Value::Null)
3743            && let Some(shape) = crate::describe::describe_expr(&args[0], ctx.columns)
3744            && let Some(n) = pg_typeof_name_for_datatype(shape.ty)
3745        {
3746            return Ok(Value::text(n));
3747        }
3748        // v7.39 (round 640) — a NON-null cell normally answers from the
3749        // value, which is right for every type whose identity the value
3750        // carries. `xid8` has no value of its own — a cell is a
3751        // `Value::BigInt` — so it can only ever say "bigint" unless the
3752        // schema is asked. `xid` is listed with it because a cell that
3753        // reached here as a plain integer (a synthesised catalog row
3754        // that has not been converted) should still name its column's
3755        // type rather than the storage it arrived in.
3756        //
3757        // v7.39 (round 667) — `oid` joins them for the same reason and no
3758        // other: its cell is a `Value::BigInt` too, so `pg_typeof(1::oid)`
3759        // answered `bigint`. Still not a general switch — where the value
3760        // knows its own identity it is the better witness, because an
3761        // expression's static shape is an approximation and its result is
3762        // the fact.
3763        if !matches!(v, Value::Null)
3764            && let Some(shape) = crate::describe::describe_expr(&args[0], ctx.columns)
3765            && matches!(
3766                shape.ty,
3767                spg_storage::DataType::Xid
3768                    | spg_storage::DataType::Xid8
3769                    | spg_storage::DataType::Oid
3770            )
3771            && let Some(n) = pg_typeof_name_for_datatype(shape.ty)
3772        {
3773            return Ok(Value::text(n));
3774        }
3775        return apply_function(name, &[v], ctx);
3776    }
3777    // v7.37 D.1 — COALESCE result-type coercion. PG gives COALESCE the
3778    // common type of its branches, so a typed sibling (`NULL::time`,
3779    // `col::time`) makes the whole expression that type and an untyped
3780    // string-literal branch is coerced to it. Without this,
3781    // `COALESCE(NULL::time, '12:00')::text` rendered the raw `12:00`
3782    // instead of `12:00:00`. Only kicks in when the picked value is a
3783    // bare Text and a non-text cast-target sibling exists.
3784    if name.eq_ignore_ascii_case("coalesce") && !args.is_empty() {
3785        // v7.39 (round 609) — PG's COALESCE does not evaluate a branch past
3786        // the first non-NULL one. This evaluated every branch into a `Vec`
3787        // and so RAISED errors PG never raises: `coalesce(1, 1/0)`,
3788        // `coalesce(NULL, 2, 1/0)` and `coalesce(1, NULL, 1/0)` all failed
3789        // with "division by zero" where PG answers 1, 2 and 1.
3790        //
3791        // A branch after the pick is still READ for its type — that is what
3792        // decides the result's, and `COALESCE(1, 2.5)` is numeric in both
3793        // engines — but its error is discarded, because PG never runs it and
3794        // so never reports it. A branch that fails contributes no type,
3795        // which is the same as SPG having no declared type to widen to.
3796        //
3797        // The two `Vec`s this replaces cost two allocations a row even for
3798        // `coalesce(id, 0)` over a plain INTEGER column, where the answer
3799        // needs none.
3800        let mut result: Option<Value<'static>> = None;
3801        let mut tbuf = [spg_storage::DataType::Int; 8];
3802        let mut ntypes = 0usize;
3803        let mut spill: Vec<spg_storage::DataType> = Vec::new();
3804        for a in args {
3805            let v = if result.is_none() {
3806                eval_expr(a, row, ctx)?
3807            } else {
3808                match eval_expr(a, row, ctx) {
3809                    Ok(v) => v,
3810                    Err(_) => continue,
3811                }
3812            };
3813            // v7.39 (round 649) — a NULL branch still has a TYPE, and PG
3814            // resolves COALESCE's result from the branches' declared
3815            // types, not from the values that survive. `Value::Null` has
3816            // no `data_type()`, so `coalesce(1::int, NULL::float8)`
3817            // collected only `integer` and answered integer where PG
3818            // answers double precision. Ask the expression when the
3819            // value cannot say — inside the arm that already runs, and
3820            // only on the NULL that would otherwise contribute nothing.
3821            let branch_ty = match v.data_type() {
3822                Some(t) => Some(t),
3823                None => crate::describe::describe_expr(a, ctx.columns).map(|sh| sh.ty),
3824            };
3825            if let Some(t) = branch_ty {
3826                if ntypes < tbuf.len() {
3827                    tbuf[ntypes] = t;
3828                    ntypes += 1;
3829                } else {
3830                    spill.push(t);
3831                }
3832            }
3833            if result.is_none() && !matches!(v, Value::Null) {
3834                result = Some(v);
3835            }
3836        }
3837        let result = result.unwrap_or(Value::Null);
3838        if matches!(result, Value::Text(_)) {
3839            if let Some(target) = args.iter().find_map(coalesce_type_hint) {
3840                return crate::eval::cast::cast_value(result, target);
3841            }
3842        }
3843        // v7.38 (read01) — otherwise widen the picked value to the PG
3844        // common type of all branches (COALESCE(1, 2.5) → numeric).
3845        if spill.is_empty() {
3846            return Ok(widen_to_common(result, &tbuf[..ntypes]));
3847        }
3848        let mut types: Vec<spg_storage::DataType> = tbuf[..ntypes].to_vec();
3849        types.append(&mut spill);
3850        return Ok(widen_to_common(result, &types));
3851    }
3852    let evaluated: Result<Vec<Value<'static>>, _> =
3853        args.iter().map(|a| eval_expr(a, row, ctx)).collect();
3854    let evaluated = evaluated?;
3855    // v7.39 (read01 json.c) — to_json(timestamptz) spells the instant in
3856    // ISO 8601 WITH the session-zone offset ("2024-03-09T14:05:06+00:00"),
3857    // unlike plain timestamp. The runtime value carries no tz tag, so the
3858    // argument's static type is the witness.
3859    if (name.eq_ignore_ascii_case("to_json") || name.eq_ignore_ascii_case("to_jsonb"))
3860        && evaluated.len() == 1
3861        && let Some(Value::Timestamp(t)) = evaluated.first()
3862        && args.first().is_some_and(|a| {
3863            crate::describe::describe_expr(a, ctx.columns)
3864                .is_some_and(|sh| matches!(sh.ty, spg_storage::DataType::Timestamptz))
3865        })
3866    {
3867        let off = ctx.session_tz_offset_at(*t);
3868        let local = t + off;
3869        let days = local.div_euclid(86_400_000_000);
3870        let day_us = local.rem_euclid(86_400_000_000);
3871        let (y, mo, d) = civil_from_days(i32::try_from(days).unwrap_or(0));
3872        let secs = day_us / 1_000_000;
3873        let frac = day_us % 1_000_000;
3874        let (hh, mi, ss) = (secs / 3600, (secs / 60) % 60, secs % 60);
3875        let mut txt = alloc::format!("{y:04}-{mo:02}-{d:02}T{hh:02}:{mi:02}:{ss:02}");
3876        if frac != 0 {
3877            let f = alloc::format!("{frac:06}");
3878            txt.push('.');
3879            txt.push_str(f.trim_end_matches('0'));
3880        }
3881        let (sign, omag) = if off < 0 { ('-', -off) } else { ('+', off) };
3882        let (oh, om) = (omag / 3_600_000_000, (omag / 60_000_000) % 60);
3883        let _ = core::fmt::Write::write_fmt(&mut txt, format_args!("{sign}{oh:02}:{om:02}"));
3884        return Ok(Value::json(alloc::format!("\"{txt}\"")));
3885    }
3886    // v7.39 (enum order knife) — greatest/least over enum-typed arguments
3887    // pick by member order, not label text (PG). The witness needs the arg
3888    // ASTs, so this can't live in the value-level function dispatch.
3889    if (name.eq_ignore_ascii_case("greatest") || name.eq_ignore_ascii_case("least"))
3890        && let Some(labels) = args
3891            .iter()
3892            .find_map(|a| expr_enum_labels(a, ctx.columns, ctx.catalog))
3893        && evaluated
3894            .iter()
3895            .all(|v| matches!(v, Value::Text(_) | Value::Null))
3896    {
3897        let is_greatest = name.eq_ignore_ascii_case("greatest");
3898        let mut best: Option<&Value<'static>> = None;
3899        for v in evaluated.iter().filter(|v| !matches!(v, Value::Null)) {
3900            best = Some(match best {
3901                None => v,
3902                Some(b) => match enum_ord_cmp(labels, v, b) {
3903                    Some(core::cmp::Ordering::Greater) if is_greatest => v,
3904                    Some(core::cmp::Ordering::Less) if !is_greatest => v,
3905                    Some(_) => b,
3906                    // A non-member snuck in — fall out to the generic path.
3907                    None => return apply_function(name, &evaluated, ctx),
3908                },
3909            });
3910        }
3911        return Ok(best.cloned().unwrap_or(Value::Null));
3912    }
3913    // v7.39 (round 693) — and the same for a declared COLLATION, which
3914    // `least`/`greatest` need for the same structural reason: the witness
3915    // is the argument's column, so it cannot live in the value-level
3916    // dispatch either. Measured on PG18 over a column declaring
3917    // en_US.utf8: `least(a,'d')` is `d` and `greatest(a,'d')` is `Zebra`,
3918    // where byte order gives the pair reversed.
3919    if (name.eq_ignore_ascii_case("greatest") || name.eq_ignore_ascii_case("least"))
3920        && evaluated
3921            .iter()
3922            .all(|v| matches!(v, Value::Text(_) | Value::Null))
3923        && let Some(coll) = greatest_least_collation(args, ctx)
3924    {
3925        let is_greatest = name.eq_ignore_ascii_case("greatest");
3926        let mut best: Option<&Value<'static>> = None;
3927        for v in evaluated.iter().filter(|v| !matches!(v, Value::Null)) {
3928            best = Some(match (best, v) {
3929                (None, _) => v,
3930                (Some(Value::Text(y)), Value::Text(x)) => {
3931                    match crate::collate::compare(&coll, x, y) {
3932                        Some(core::cmp::Ordering::Greater) if is_greatest => v,
3933                        Some(core::cmp::Ordering::Less) if !is_greatest => v,
3934                        Some(_) => best.unwrap_or(v),
3935                        // Not a collation this build performs after all —
3936                        // one answer, from the generic path.
3937                        None => return apply_function(name, &evaluated, ctx),
3938                    }
3939                }
3940                (Some(b), _) => b,
3941            });
3942        }
3943        return Ok(best.cloned().unwrap_or(Value::Null));
3944    }
3945    // v7.39 (round 621) — an unadorned string literal takes the type the
3946    // function's parameter asks for. `justify_interval('36 hours')` is answered
3947    // by PG and was refused here, and so were `justify_days('35 days')` and
3948    // `justify_hours('27 hours')` — the spelling everyone writes, since typing
3949    // `INTERVAL` in front of the literal is exactly what PG saves you from.
3950    //
3951    // Only a LITERAL is resolved, which is the same boundary round 620 drew for
3952    // the boolean connectives: `justify_interval(t)` over a TEXT column stays
3953    // refused, because PG refuses it too (no such overload). The arg ASTs are
3954    // needed to tell those apart, so this cannot live in the value-level
3955    // dispatch — the same reason the enum witness above sits here.
3956    if let Some(want) = unknown_literal_param_type(name) {
3957        let mut coerced = evaluated;
3958        for (i, a) in args.iter().enumerate() {
3959            if is_unknown_string_literal(a)
3960                && let Some(slot) = coerced.get_mut(i)
3961            {
3962                *slot = cast::cast_value_in(
3963                    core::mem::replace(slot, Value::Null),
3964                    want.clone(),
3965                    false,
3966                )?;
3967            }
3968        }
3969        return apply_function(name, &coerced, ctx);
3970    }
3971    apply_function(name, &evaluated, ctx)
3972}
3973
3974/// v7.39 (round 621) — the parameter type a bare string literal resolves to.
3975///
3976/// PG resolves an `unknown` literal to whatever the chosen overload declares.
3977/// SPG has no overload resolution to hang that on, so the functions whose only
3978/// parameter is unambiguous are listed. `None` leaves the argument alone.
3979fn unknown_literal_param_type(name: &str) -> Option<spg_sql::ast::CastTarget> {
3980    match name.to_ascii_lowercase().as_str() {
3981        "justify_days" | "justify_hours" | "justify_interval" => {
3982            Some(spg_sql::ast::CastTarget::Interval)
3983        }
3984        _ => None,
3985    }
3986}
3987
3988/// Out-of-lined `eval_expr` arm — keeps the recursive frame small
3989/// (stack-depth guard budget); body unchanged.
3990#[inline(never)]
3991fn eval_any_all_arm(
3992    expr: &Expr,
3993    op: &BinOp,
3994    array: &Expr,
3995    is_any: bool,
3996    row: &Row<'static>,
3997    ctx: &EvalContext<'_>,
3998) -> Result<Value<'static>, EvalError> {
3999    let lhs = eval_expr(expr, row, ctx)?;
4000    let arr = eval_expr(array, row, ctx)?;
4001    any_all_over(lhs, arr, op, is_any)
4002}
4003
4004/// v7.39 (round 597) — the ANY/ALL comparison with both sides already in
4005/// hand. Split out so a CONSTANT right-hand array can be built once at
4006/// compile time instead of once per row: `WHERE id = ANY (ARRAY[1..10])`
4007/// rebuilt the array for all 500k rows and cost 268 ms against PG18's 8.3,
4008/// rising to 494 ms at twenty elements, while the equivalent
4009/// `id IN (1..10)` took 2.3. The body below is unchanged; it never touched
4010/// `row`.
4011pub(crate) fn any_all_over(
4012    lhs: Value<'static>,
4013    arr: Value<'static>,
4014    op: &BinOp,
4015    is_any: bool,
4016) -> Result<Value<'static>, EvalError> {
4017    if matches!(arr, Value::Null) {
4018        return Ok(Value::Null);
4019    }
4020    // v7.38 (read01) — an unknown-string RHS (`x = ANY('{1,2,3}')`)
4021    // takes the LHS's type: coerce the external array text to the array
4022    // type matching the LHS's element type, like PG.
4023    let arr = match &arr {
4024        Value::Text(_) => {
4025            // The LHS's element type, or TEXT when the LHS is an
4026            // untyped NULL (PG's unknown → text default).
4027            let arr_ty = match lhs.data_type() {
4028                Some(spg_storage::DataType::SmallInt) => spg_storage::DataType::SmallIntArray,
4029                Some(spg_storage::DataType::Int) => spg_storage::DataType::IntArray,
4030                Some(spg_storage::DataType::BigInt) => spg_storage::DataType::BigIntArray,
4031                Some(spg_storage::DataType::Numeric { .. }) => spg_storage::DataType::NumericArray,
4032                Some(spg_storage::DataType::Float) => spg_storage::DataType::FloatArray,
4033                Some(spg_storage::DataType::Bool) => spg_storage::DataType::BoolArray,
4034                Some(spg_storage::DataType::Date) => spg_storage::DataType::DateArray,
4035                _ => spg_storage::DataType::TextArray,
4036            };
4037            crate::conversions::coerce_value(arr.clone(), arr_ty, "", 0).unwrap_or(arr)
4038        }
4039        _ => arr,
4040    };
4041    // Build the element list generically so every scalar array type
4042    // (numeric[], float8[], bool[], date[], …) is accepted, not just
4043    // int/bigint/text.
4044    let Some(len) = array_len(&arr) else {
4045        return Err(EvalError::TypeMismatch {
4046            detail: format!(
4047                "ANY/ALL right-hand side must be an array, got {}",
4048                crate::conversions::pg_type_name_for_error_opt(arr.data_type())
4049            ),
4050        });
4051    };
4052    let elems: Vec<Option<Value>> = (0..len)
4053        .map(|i| match array_element_at(&arr, i) {
4054            Some(Value::Null) | None => None,
4055            Some(v) => Some(v),
4056        })
4057        .collect();
4058    // PG: `x op ANY (empty)` → false and `x op ALL (empty)` →
4059    // true, decided purely by emptiness — the comparison is
4060    // never evaluated, so a NULL LHS is irrelevant. This must
4061    // short-circuit before `saw_null` is seeded from the LHS,
4062    // otherwise `NULL op ANY/ALL (empty)` wrongly yields NULL.
4063    if elems.is_empty() {
4064        return Ok(Value::Bool(!is_any));
4065    }
4066    let mut saw_null = matches!(lhs, Value::Null);
4067    let mut saw_match = false;
4068    let mut saw_mismatch = false;
4069    for elem in elems {
4070        let elem_v = match elem {
4071            Some(v) => v,
4072            None => {
4073                saw_null = true;
4074                continue;
4075            }
4076        };
4077        if matches!(lhs, Value::Null) {
4078            saw_null = true;
4079            continue;
4080        }
4081        match apply_binary(*op, lhs.clone(), elem_v) {
4082            Ok(Value::Bool(true)) => saw_match = true,
4083            Ok(Value::Bool(false)) => saw_mismatch = true,
4084            Ok(Value::Null) => saw_null = true,
4085            Ok(other) => {
4086                return Err(EvalError::TypeMismatch {
4087                    detail: format!(
4088                        "ANY/ALL comparison didn't return Bool: {}",
4089                        crate::conversions::pg_type_name_for_error_opt(other.data_type())
4090                    ),
4091                });
4092            }
4093            Err(e) => return Err(e),
4094        }
4095    }
4096    let result = if is_any {
4097        if saw_match {
4098            Value::Bool(true)
4099        } else if saw_null {
4100            Value::Null
4101        } else {
4102            Value::Bool(false)
4103        }
4104    } else if saw_mismatch {
4105        Value::Bool(false)
4106    } else if saw_null {
4107        Value::Null
4108    } else {
4109        Value::Bool(true)
4110    };
4111    Ok(result)
4112}
4113
4114/// Out-of-lined `eval_expr` arm — keeps the recursive frame small
4115/// (stack-depth guard budget); body unchanged.
4116#[inline(never)]
4117fn eval_case_arm(
4118    operand: &Option<alloc::boxed::Box<Expr>>,
4119    branches: &[(Expr, Expr)],
4120    else_branch: &Option<alloc::boxed::Box<Expr>>,
4121    row: &Row<'static>,
4122    ctx: &EvalContext<'_>,
4123) -> Result<Value<'static>, EvalError> {
4124    // v7.39 (round 237) — PG resolves the RESULT branches to one type and
4125    // refuses the CASE when they have no common one, before running
4126    // anything. SPG returned whichever branch fired, so
4127    // `CASE WHEN true THEN 1 ELSE 'a'::text END` answered `1` and the same
4128    // expression answered text on another row.
4129    {
4130        // PG resolves the ELSE branch FIRST and then the WHEN results, and
4131        // its message names the running type before the conflicting one —
4132        // which is why `THEN 1 ELSE 'a'::text` reports "text and integer"
4133        // while a two-WHEN `THEN 1 ... THEN true` reports "integer and
4134        // boolean". Probed against 18.4; the order is observable.
4135        let mut results: Vec<&Expr> = Vec::with_capacity(branches.len() + 1);
4136        if let Some(e) = else_branch {
4137            results.push(e);
4138        }
4139        results.extend(branches.iter().map(|(_, r)| r));
4140        unify_branch_types_static("CASE", results, ctx)?;
4141    }
4142    let operand_value = match operand {
4143        Some(o) => Some(eval_expr(o, row, ctx)?),
4144        None => None,
4145    };
4146    // v7.37 D.1 — CASE result-type coercion (same rule as COALESCE): a
4147    // typed result branch (`... THEN '10:00'::time`) makes the whole
4148    // CASE that type, so an untyped string-literal branch is coerced to
4149    // it. Compute the hint once from every THEN/ELSE branch.
4150    let case_hint = branches
4151        .iter()
4152        .map(|(_, t)| t)
4153        .chain(else_branch.iter().map(|b| b.as_ref()))
4154        .find_map(coalesce_type_hint);
4155    // v7.38 (read01) — the CASE result is PG's common type of every
4156    // THEN/ELSE branch, so a taken integer branch is widened to
4157    // numeric when a sibling branch is numeric (and `pg_typeof` /
4158    // downstream division match PG). Only one branch is evaluated, so
4159    // the type must come from the branch expressions statically.
4160    let branch_types: Vec<spg_storage::DataType> = branches
4161        .iter()
4162        .map(|(_, t)| t)
4163        .chain(else_branch.iter().map(|b| b.as_ref()))
4164        .filter_map(|e| crate::describe::describe_expr(e, ctx.columns).map(|s| s.ty))
4165        .collect();
4166    let coerce = |v: Value<'static>| -> Result<Value<'static>, EvalError> {
4167        let v = match (&v, &case_hint) {
4168            (Value::Text(_), Some(target)) => cast::cast_value(v, target.clone())?,
4169            _ => v,
4170        };
4171        Ok(widen_to_common(v, &branch_types))
4172    };
4173    for (when_expr, then_expr) in branches {
4174        let when_value = eval_expr(when_expr, row, ctx)?;
4175        let matched = match &operand_value {
4176            // v7.39 (round 346, M1) — the WHEN condition is a truth value,
4177            // not a boolean-shaped one: `CASE WHEN 1 THEN 'a' END` used to
4178            // answer NULL in BOTH dialects, where MariaDB answers `a` and
4179            // PG raises `argument of CASE/WHEN must be type boolean`.
4180            None => predicate_is_true(&when_value, "CASE/WHEN", ctx.mysql_dialect)?,
4181            // v7.39 (round 412) — under the MySQL default collation the
4182            // `CASE op WHEN v` equality folds Text/BpChar operands (CI +
4183            // accent + PAD SPACE), matching `op = v` outside CASE.
4184            Some(op_v) => {
4185                let (l, r) = if ctx.mysql_dialect {
4186                    match (op_v, &when_value) {
4187                        (Value::Text(x), Value::Text(y)) | (Value::BpChar(x), Value::BpChar(y)) => {
4188                            (
4189                                Value::text(spg_storage::mysql_compare_fold(x)),
4190                                Value::text(spg_storage::mysql_compare_fold(y)),
4191                            )
4192                        }
4193                        _ => (op_v.clone(), when_value),
4194                    }
4195                } else {
4196                    (op_v.clone(), when_value)
4197                };
4198                matches!(
4199                    apply_binary(spg_sql::ast::BinOp::Eq, l, r)?,
4200                    Value::Bool(true)
4201                )
4202            }
4203        };
4204        if matched {
4205            return coerce(eval_expr(then_expr, row, ctx)?);
4206        }
4207    }
4208    match else_branch {
4209        Some(e) => coerce(eval_expr(e, row, ctx)?),
4210        None => Ok(Value::Null),
4211    }
4212}
4213
4214/// Out-of-lined `eval_expr` arm — keeps the recursive frame small
4215/// (stack-depth guard budget); body unchanged.
4216#[inline(never)]
4217fn eval_array_slice_arm(
4218    target: &Expr,
4219    lo: &Option<alloc::boxed::Box<Expr>>,
4220    hi: &Option<alloc::boxed::Box<Expr>>,
4221    row: &Row<'static>,
4222    ctx: &EvalContext<'_>,
4223) -> Result<Value<'static>, EvalError> {
4224    let target_v = eval_expr(target, row, ctx)?;
4225    if matches!(target_v, Value::Null) {
4226        return Ok(Value::Null);
4227    }
4228    let bound = |e: Option<&Expr>| -> Result<Option<i64>, EvalError> {
4229        match e {
4230            None => Ok(None),
4231            Some(b) => match eval_expr(b, row, ctx)? {
4232                Value::Null => Ok(None),
4233                Value::Int(n) => Ok(Some(i64::from(n))),
4234                Value::BigInt(n) => Ok(Some(n)),
4235                Value::SmallInt(n) => Ok(Some(i64::from(n))),
4236                other => Err(EvalError::TypeMismatch {
4237                    detail: format!(
4238                        "array slice bound must be integer, got {}",
4239                        crate::conversions::pg_type_name_for_error_opt(other.data_type())
4240                    ),
4241                }),
4242            },
4243        }
4244    };
4245    let lo_b = bound(lo.as_deref())?;
4246    let hi_b = bound(hi.as_deref())?;
4247    fn window(len: usize, lo: Option<i64>, hi: Option<i64>) -> (usize, usize) {
4248        let start = lo.map_or(0, |l| (l.max(1) - 1) as usize).min(len);
4249        let end = hi.map_or(len, |h| h.max(0) as usize).min(len);
4250        (start, end.max(start))
4251    }
4252    match target_v {
4253        Value::TextArray(items) => {
4254            let (s, e) = window(items.len(), lo_b, hi_b);
4255            Ok(Value::TextArray(items[s..e].to_vec()))
4256        }
4257        Value::IntArray(items) => {
4258            let (s, e) = window(items.len(), lo_b, hi_b);
4259            Ok(Value::IntArray(items[s..e].to_vec()))
4260        }
4261        Value::BigIntArray(items) => {
4262            let (s, e) = window(items.len(), lo_b, hi_b);
4263            Ok(Value::BigIntArray(items[s..e].to_vec()))
4264        }
4265        other => Err(EvalError::TypeMismatch {
4266            detail: format!(
4267                "slice target must be an array, got {}",
4268                crate::conversions::pg_type_name_for_error_opt(other.data_type())
4269            ),
4270        }),
4271    }
4272}
4273
4274/// Out-of-lined `eval_expr` arm — keeps the recursive frame small
4275/// (stack-depth guard budget); body unchanged.
4276#[inline(never)]
4277fn eval_in_list_arm(
4278    expr: &Expr,
4279    list: &[Expr],
4280    negated: bool,
4281    row: &Row<'static>,
4282    ctx: &EvalContext<'_>,
4283) -> Result<Value<'static>, EvalError> {
4284    // v7.39 (round 238) — PG resolves the whole list's type BEFORE comparing
4285    // anything, so `1 IN (1, 'a'::text)` is refused. SPG compared item by
4286    // item and broke on the first match, so the offending element was never
4287    // reached and the predicate quietly answered true. Checked statically,
4288    // like round 237: evaluating the rest of the list to inspect it would
4289    // change when side effects fire.
4290    require_in_list_comparable(expr, list, ctx)?;
4291    // v7.39 (round 364, M4 P2) — a MySQL session folds text before the
4292    // membership test, so `t IN ('FOO')` matches 'Foo'. `BINARY` is not
4293    // reachable through a bare column needle here; the fold is text-only.
4294    // v7.39 (round 370, M4 P4a) — an explicit `COLLATE utf8mb4_bin` needle
4295    // column is byte-wise, so it does not fold. v7.39 (round 371, M4 P4b) —
4296    // a per-expression `… COLLATE utf8mb4_bin` / `BINARY …` on the needle
4297    // OR any list item forces the whole membership test byte-wise.
4298    let in_fold = ctx.mysql_dialect
4299        && !resolve::operand_is_binary_column(expr, ctx)
4300        && !resolve::is_binary_coerced(expr)
4301        && !list.iter().any(|i| resolve::is_binary_coerced(i));
4302    let needle = mysql_collation_key(eval_expr(expr, row, ctx)?, in_fold);
4303    let needle_null = matches!(needle, Value::Null);
4304    let mut saw_null = needle_null && !list.is_empty();
4305    let mut matched = false;
4306    if !needle_null {
4307        for item in list {
4308            let v = mysql_collation_key(eval_expr(item, row, ctx)?, in_fold);
4309            if matches!(v, Value::Null) {
4310                saw_null = true;
4311                continue;
4312            }
4313            match apply_binary(BinOp::Eq, needle.clone(), v)? {
4314                Value::Bool(true) => {
4315                    matched = true;
4316                    break;
4317                }
4318                Value::Bool(false) => {}
4319                Value::Null => saw_null = true,
4320                other => {
4321                    return Err(EvalError::TypeMismatch {
4322                        detail: format!(
4323                            "IN comparison didn't return Bool: {}",
4324                            crate::conversions::pg_type_name_for_error_opt(other.data_type())
4325                        ),
4326                    });
4327                }
4328            }
4329        }
4330    }
4331    let inner = if matched {
4332        Value::Bool(true)
4333    } else if saw_null {
4334        Value::Null
4335    } else {
4336        Value::Bool(false)
4337    };
4338    Ok(match (negated, inner) {
4339        (true, Value::Bool(b)) => Value::Bool(!b),
4340        (_, v) => v,
4341    })
4342}
4343
4344/// Out-of-lined `eval_expr` arm — keeps the recursive frame small
4345/// (stack-depth guard budget); body unchanged.
4346#[inline(never)]
4347fn eval_like_arm(
4348    expr: &Expr,
4349    pattern: &Expr,
4350    negated: bool,
4351    case_insensitive: bool,
4352    row: &Row<'static>,
4353    ctx: &EvalContext<'_>,
4354) -> Result<Value<'static>, EvalError> {
4355    let v = eval_expr(expr, row, ctx)?;
4356    let p = eval_expr(pattern, row, ctx)?;
4357    // NULL on either side propagates to NULL — same as PG.
4358    // v7.39 (bpchar epic) — LIKE matches bpchar on its PADDED
4359    // stored form, per PG's bpchar pattern operators.
4360    let (text, pat) = match (v, p) {
4361        (Value::Null, _) | (_, Value::Null) => return Ok(Value::Null),
4362        (Value::Text(a) | Value::BpChar(a), Value::Text(b) | Value::BpChar(b)) => (a, b),
4363        (Value::Text(_) | Value::BpChar(_), other) | (other, _) => {
4364            return Err(EvalError::TypeMismatch {
4365                detail: format!(
4366                    "LIKE requires text operands, got {}",
4367                    crate::conversions::pg_type_name_for_error_opt(other.data_type())
4368                ),
4369            });
4370        }
4371    };
4372    // v7.25 (round-17) — ILIKE folds both operands (PG
4373    // lowercases per the default collation).
4374    // v7.39 (round 364, M4 P2) — a MySQL session's default collation is
4375    // accent- and case-insensitive, so `LIKE` folds both sides the way
4376    // `ILIKE` does; the wildcards `%` / `_` are not Latin letters so the
4377    // fold leaves them alone.
4378    // v7.39 (round 370, M4 P4a) — an explicit `COLLATE utf8mb4_bin` column
4379    // matches byte-wise, so it does not fold. v7.39 (round 371, M4 P4b) —
4380    // a per-expression `… COLLATE utf8mb4_bin` / `BINARY …` on either the
4381    // value or the pattern forces byte-wise too.
4382    let mysql = ctx.mysql_dialect
4383        && !resolve::operand_is_binary_column(expr, ctx)
4384        && !resolve::operand_is_binary_column(pattern, ctx)
4385        && !resolve::is_binary_coerced(expr)
4386        && !resolve::is_binary_coerced(pattern);
4387    let m = if case_insensitive {
4388        like_match(&text.to_lowercase(), &pat.to_lowercase())?
4389    } else if mysql {
4390        like_match(
4391            &spg_storage::mysql_ci_fold(&text),
4392            &spg_storage::mysql_ci_fold(&pat),
4393        )?
4394    } else {
4395        like_match(&text, &pat)?
4396    };
4397    Ok(Value::Bool(if negated { !m } else { m }))
4398}
4399
4400/// Out-of-lined `eval_expr` arm — keeps the recursive frame small
4401/// (stack-depth guard budget); body unchanged.
4402#[inline(never)]
4403fn eval_extract_arm(
4404    field: &spg_sql::ast::ExtractField,
4405    source: &Expr,
4406    row: &Row<'static>,
4407    ctx: &EvalContext<'_>,
4408) -> Result<Value<'static>, EvalError> {
4409    let v = eval_expr(source, row, ctx)?;
4410    extract_from_value(field, v, source, ctx)
4411}
4412
4413/// v7.39 (round 595) — the field extraction, with the source value already
4414/// in hand. Split out so the compiled-predicate program can pop the source
4415/// off its stack instead of handing the whole node back to the interpreter:
4416/// one non-compilable node used to disqualify the entire WHERE, and
4417/// `WHERE extract(year FROM t) = 2020` was interpreting the column read and
4418/// the comparison too. The body below is unchanged; it never touched `row`.
4419pub(crate) fn extract_from_value(
4420    field: &spg_sql::ast::ExtractField,
4421    v: Value<'static>,
4422    source: &Expr,
4423    ctx: &EvalContext<'_>,
4424) -> Result<Value<'static>, EvalError> {
4425    // v7.39 (round 382) — MySQL coerces a date/time STRING to its temporal
4426    // value for EXTRACT (`EXTRACT(YEAR FROM '2020-05-15')` is 2020, and the
4427    // time fields read a `'... HH:MM:SS'` string); PG needs a typed source.
4428    let v = match &v {
4429        Value::Text(s) if ctx.mysql_dialect => text_as_temporal(s).unwrap_or(v),
4430        _ => v,
4431    };
4432    // v7.39 (tz epic) — timezone[_hour|_minute] of a timestamptz
4433    // reports the SESSION offset at that instant (PG: 32400 for
4434    // Tokyo; -14400 for New York in July).
4435    if matches!(
4436        field,
4437        spg_sql::ast::ExtractField::Timezone
4438            | spg_sql::ast::ExtractField::TimezoneHour
4439            | spg_sql::ast::ExtractField::TimezoneMinute
4440    ) && let Value::Timestamp(t) = &v
4441        && crate::describe::describe_expr(source, ctx.columns)
4442            .is_some_and(|s| matches!(s.ty, spg_storage::DataType::Timestamptz))
4443    {
4444        let off_secs = ctx.session_tz_offset_at(*t) / 1_000_000;
4445        let n = match field {
4446            spg_sql::ast::ExtractField::Timezone => off_secs,
4447            spg_sql::ast::ExtractField::TimezoneHour => off_secs / 3600,
4448            _ => (off_secs / 60) % 60,
4449        };
4450        // v7.39 (round 253) — numeric, like every other EXTRACT result.
4451        return Ok(Value::Numeric {
4452            scaled: i128::from(n),
4453            scale: 0,
4454            kind: spg_storage::NumericKind::Finite,
4455        });
4456    }
4457    // v7.39 (round 523) — and every OTHER field of a timestamptz reads
4458    // the local clock in the session zone, which is the whole reason PG
4459    // has the type. `extract(hour from …)` answered the UTC hour under
4460    // `SET TimeZone = 'Asia/Tokyo'` — 0 where PG says 9 — and
4461    // `extract(dow …)` therefore named the wrong DAY, so a report
4462    // grouped by weekday put nine hours of every Sunday under Saturday.
4463    // Only fields of the local clock shift; epoch and julian are
4464    // absolute, and the timezone fields answered above.
4465    let v = match &v {
4466        Value::Timestamp(t)
4467            if !matches!(
4468                field,
4469                spg_sql::ast::ExtractField::Epoch
4470                    | spg_sql::ast::ExtractField::Julian
4471                    | spg_sql::ast::ExtractField::Timezone
4472                    | spg_sql::ast::ExtractField::TimezoneHour
4473                    | spg_sql::ast::ExtractField::TimezoneMinute
4474            ) && crate::describe::describe_expr(source, ctx.columns)
4475                .is_some_and(|s| matches!(s.ty, spg_storage::DataType::Timestamptz)) =>
4476        {
4477            Value::Timestamp(t.saturating_add(ctx.session_tz_offset_at(*t)))
4478        }
4479        _ => v,
4480    };
4481    // v7.39 (round 253) — the source's PG type name for error wording,
4482    // upgraded from the declared type when statically known (a tstz
4483    // VALUE is indistinguishable from a timestamp). Only a cast /
4484    // column is trusted (the r237 lesson: describe_expr reports a
4485    // binary operator as its left operand's type).
4486    let static_declared = matches!(source, Expr::Cast { .. } | Expr::Column(_))
4487        .then(|| crate::describe::describe_expr(source, ctx.columns))
4488        .flatten()
4489        .map(|sch| sch.ty);
4490    let src_name = match static_declared {
4491        Some(spg_storage::DataType::Timestamptz) => "timestamp with time zone",
4492        _ => datetime::value_src_type_name(&v),
4493    };
4494    // PG rejects the timezone family on a plain timestamp (0A000);
4495    // only reject when the declared type is STATICALLY timestamp — a
4496    // dynamic value stays lenient (the pre-r253 zero answer).
4497    if matches!(
4498        field,
4499        spg_sql::ast::ExtractField::Timezone
4500            | spg_sql::ast::ExtractField::TimezoneHour
4501            | spg_sql::ast::ExtractField::TimezoneMinute
4502    ) && matches!(static_declared, Some(spg_storage::DataType::Timestamp))
4503    {
4504        return Err(EvalError::TypeMismatch {
4505            detail: alloc::format!(
4506                "unit \"{}\" not supported for type timestamp without time zone",
4507                alloc::format!("{field}").to_lowercase()
4508            ),
4509        });
4510    }
4511    // v7.39 (round 418) — MySQL's compound units (`DAY_SECOND`, `YEAR_MONTH`,
4512    // …) reach here as `ExtractField::Other`, which PG rejects. Under the
4513    // MySQL dialect they pack several components into one integer instead.
4514    if ctx.mysql_dialect
4515        && let spg_sql::ast::ExtractField::Other(name) = field
4516        && let Some(packed) = crate::eval::datetime::mysql_compound_extract(name, &v)
4517    {
4518        return Ok(packed);
4519    }
4520    extract_field(field, &v, src_name)
4521}
4522
4523/// Out-of-lined `eval_expr` arm — keeps the recursive frame small
4524/// (stack-depth guard budget); body unchanged.
4525#[inline(never)]
4526fn eval_array_subscript_arm(
4527    expr: &Expr,
4528    row: &Row<'static>,
4529    ctx: &EvalContext<'_>,
4530) -> Result<Value<'static>, EvalError> {
4531    // Collect the whole subscript chain so PG's multi-dimensional
4532    // access (`arr[i][j]` is ONE N-subscript op) is distinguishable
4533    // from chained 1-D indexing. `arr[1][2]` parses as
4534    // `(arr[1])[2]`; PG indexes the matrix directly and returns NULL
4535    // for a partial subscript (`arr[1]` on a 2-D array is NULL).
4536    let mut idx_exprs: Vec<&Expr> = Vec::new();
4537    let mut base = expr;
4538    while let Expr::ArraySubscript { target, index } = base {
4539        idx_exprs.push(index);
4540        base = target;
4541    }
4542    idx_exprs.reverse();
4543    let base_v = eval_expr(base, row, ctx)?;
4544    if matches!(
4545        base_v,
4546        Value::IntArray2D(_)
4547            | Value::BigIntArray2D(_)
4548            | Value::TextArray2D(_)
4549            | Value::BoolArray2D(_)
4550    ) {
4551        return eval_matrix_subscript(&base_v, &idx_exprs, row, ctx);
4552    }
4553    // 1-D array / JSON: apply each subscript left-to-right. This
4554    // reproduces the prior single-subscript semantics exactly, and
4555    // chained JSON (`j['a']['b']`) still resolves step by step.
4556    let mut cur = base_v;
4557    for ix in idx_exprs {
4558        cur = apply_one_subscript(cur, ix, row, ctx)?;
4559    }
4560    Ok(cur)
4561}
4562
4563/// Out-of-lined `eval_expr` arm — keeps the recursive frame small
4564/// (stack-depth guard budget); body unchanged.
4565#[inline(never)]
4566fn eval_field_access_arm(
4567    base: &Expr,
4568    field: &str,
4569    row: &Row<'static>,
4570    ctx: &EvalContext<'_>,
4571) -> Result<Value<'static>, EvalError> {
4572    // v7.38 (read01, T9) — composite field access `(expr).field`.
4573    // The base evaluates to a record; look the member up by name
4574    // (`f1`..`fN` for an anonymous ROW, base column names for a
4575    // whole-row). A NULL record yields NULL (PG semantics).
4576    let v = eval_expr(base, row, ctx)?;
4577    match v {
4578        Value::Null => Ok(Value::Null),
4579        Value::Composite(fields) => fields
4580            .into_iter()
4581            .find(|(name, _)| name == field)
4582            .map(|(_, val)| val)
4583            .ok_or_else(|| missing_field_error(base, field, ctx)),
4584        _ => Err(not_a_composite_error(base, field, ctx)),
4585    }
4586}
4587
4588/// v7.39 (round 285) — PG words a missing composite field three ways, and
4589/// which one you get depends on the base expression's STATIC type, not on
4590/// the value:
4591///
4592///   * a named composite — `column "nosuch" not found in data type rc9`
4593///   * a whole-row table reference — `column rt8.nosuch does not exist`
4594///     (unquoted, and qualified — the odd one out)
4595///   * an anonymous ROW or `::record` — `could not identify column
4596///     "nosuch" in record data type`
4597///
4598/// All three read off live PG 18.4. A `Value::Composite` carries its field
4599/// names but not its type name, so the base expression is what decides.
4600fn missing_field_error(base: &Expr, field: &str, ctx: &EvalContext<'_>) -> EvalError {
4601    // v7.39 (round 307, V25) — the named type may arrive by cast OR from
4602    // the schema of a column that a projection produced, so ask once and
4603    // let the catalog say whether it is a composite. Before this only
4604    // the cast spelling was recognised, which is why a composite that
4605    // came through a derived table or a CTE — where the base is a plain
4606    // column — fell through to the anonymous-record wording.
4607    if let Some(name) = base_named_type(base, ctx)
4608        && ctx
4609            .catalog
4610            .is_some_and(|c| c.composite_types().contains_key(name))
4611    {
4612        return EvalError::TypeMismatch {
4613            detail: alloc::format!("column \"{field}\" not found in data type {name}"),
4614        };
4615    }
4616    if let Expr::Column(c) = base
4617        && c.qualifier.is_none()
4618    {
4619        // A column DECLARED as a named composite reports that type — the
4620        // schema records it in `user_composite_type`, which is the only
4621        // place the name survives (a `Value::Composite` does not carry it).
4622        if let Some(name) = ctx
4623            .columns
4624            .iter()
4625            .find(|col| col.name.eq_ignore_ascii_case(&c.name))
4626            .and_then(|col| col.user_composite_type.as_ref())
4627        {
4628            return EvalError::TypeMismatch {
4629                detail: alloc::format!("column \"{field}\" not found in data type {name}"),
4630            };
4631        }
4632        // A whole-row reference to a real table is the odd wording out:
4633        // qualified, and unquoted.
4634        if ctx.catalog.is_some_and(|cat| cat.get(&c.name).is_some()) {
4635            return EvalError::TypeMismatch {
4636                detail: alloc::format!("column {}.{field} does not exist", c.name),
4637            };
4638        }
4639    }
4640    EvalError::TypeMismatch {
4641        detail: alloc::format!("could not identify column \"{field}\" in record data type"),
4642    }
4643}
4644
4645/// v7.39 (round 307, V25) — the user-declared type name behind a field
4646/// access, if any: either written as a cast (`ROW(…)::rc9`) or carried on
4647/// the column's schema.
4648///
4649/// All three schema slots are consulted rather than just the composite
4650/// one. A projection currently files the name of a `::rc9` cast under
4651/// `user_enum_type` — `expr_enum_type_name` answers for ANY named cast,
4652/// without asking whether the name is an enum — so keying off one slot
4653/// would answer for some shapes and not others. The caller decides what
4654/// the name MEANS by asking the catalog, which is the only thing that
4655/// actually knows; this function just finds it.
4656fn base_named_type<'c>(base: &'c Expr, ctx: &'c EvalContext<'_>) -> Option<&'c str> {
4657    match base {
4658        Expr::Cast {
4659            target: CastTarget::Named(name),
4660            ..
4661        } => Some(name.as_str()),
4662        Expr::Column(c) => ctx
4663            .columns
4664            .iter()
4665            .find(|sc| sc.name.eq_ignore_ascii_case(&c.name))
4666            .and_then(|sc| {
4667                sc.user_composite_type
4668                    .as_deref()
4669                    .or(sc.user_domain_type.as_deref())
4670                    .or(sc.user_enum_type.as_deref())
4671            }),
4672        _ => None,
4673    }
4674}
4675
4676/// v7.39 (round 307, V25) — PG's wording when field notation is applied
4677/// to something that is not a composite at all. It names the type:
4678/// `column notation .f applied to type pos9, which is not a composite
4679/// type` — for a domain and an enum alike. Only when the base has no
4680/// user-declared type at all does the generic message stand.
4681fn not_a_composite_error(base: &Expr, field: &str, ctx: &EvalContext<'_>) -> EvalError {
4682    if let Some(name) = base_named_type(base, ctx)
4683        && ctx.catalog.is_some_and(|c| {
4684            c.enum_types().contains_key(name) || c.domain_types().contains_key(name)
4685        })
4686    {
4687        return EvalError::TypeMismatch {
4688            detail: alloc::format!(
4689                "column notation .{field} applied to type {name}, which is not a composite type"
4690            ),
4691        };
4692    }
4693    EvalError::TypeMismatch {
4694        detail: alloc::format!("field access `.{field}` requires a composite (record) value"),
4695    }
4696}
4697
4698/// Out-of-lined `eval_expr` arm — keeps the recursive frame small
4699/// (stack-depth guard budget); body unchanged.
4700#[inline(never)]
4701/// v7.39 (round 328, V45) — the three-valued boolean tests. None of them
4702/// ever answers NULL: a NULL input is "not true" and "not false", and IS
4703/// UNKNOWN is precisely the NULL case. Verified against PG 18.4 —
4704/// `NULL::bool IS TRUE` is false, `IS NOT TRUE` true, `IS UNKNOWN` true,
4705/// and `false IS NOT FALSE` false.
4706fn eval_bool_test_arm(
4707    expr: &Expr,
4708    value: Option<bool>,
4709    negated: bool,
4710    row: &Row<'static>,
4711    ctx: &EvalContext<'_>,
4712) -> Result<Value<'static>, EvalError> {
4713    let v = eval_expr(expr, row, ctx)?;
4714    let hit = match (value, &v) {
4715        // IS UNKNOWN — the input is NULL.
4716        (None, Value::Null) => true,
4717        // v7.39 (round 625) — and PG rejects a non-boolean here too:
4718        // `argument of IS UNKNOWN must be type boolean`. MySQL has no
4719        // IS UNKNOWN, so there is no dialect branch.
4720        (None, Value::Bool(_)) => false,
4721        (None, other) => {
4722            return Err(EvalError::TypeMismatch {
4723                detail: alloc::format!(
4724                    "argument of IS {}UNKNOWN must be type boolean, not type {}",
4725                    if negated { "NOT " } else { "" },
4726                    crate::conversions::pg_type_name_for_error_opt(other.data_type())
4727                ),
4728            });
4729        }
4730        (Some(_), Value::Null) => false,
4731        (Some(want), Value::Bool(b)) => *b == want,
4732        // v7.39 (round 397) — MySQL reads a non-boolean as a truth value
4733        // for `IS TRUE` / `IS FALSE` (`5 IS TRUE` is 1, `0 IS FALSE` is 1,
4734        // `'abc' IS TRUE` is 0). PG rejects a non-boolean at parse time, so
4735        // this only fires under the dialect; a NULL is already handled.
4736        (Some(want), other) if ctx.mysql_dialect => mysql_truthy(other) == want,
4737        // v7.39 (round 625, S05b/F29) — on PG a non-boolean is REJECTED, and
4738        // the comment above said so while the arm below answered `false`
4739        // anyway. `1 IS TRUE` came back false, which reads as "the test was
4740        // run and did not hold" rather than "you cannot ask this of an
4741        // integer" — the wrong answer for every non-boolean type, eight of
4742        // them measured. PG's own sentence, which names the operator and the
4743        // type it got.
4744        (Some(_), other) => {
4745            return Err(EvalError::TypeMismatch {
4746                detail: alloc::format!(
4747                    "argument of IS {}{} must be type boolean, not type {}",
4748                    if negated { "NOT " } else { "" },
4749                    if value == Some(true) { "TRUE" } else { "FALSE" },
4750                    crate::conversions::pg_type_name_for_error_opt(other.data_type())
4751                ),
4752            });
4753        }
4754    };
4755    Ok(Value::Bool(hit != negated))
4756}
4757
4758fn eval_is_null_arm(
4759    expr: &Expr,
4760    negated: bool,
4761    row: &Row<'static>,
4762    ctx: &EvalContext<'_>,
4763) -> Result<Value<'static>, EvalError> {
4764    // v7.38 (read01 P4.11) — `ROW(...) IS [NOT] NULL` is evaluated
4765    // field-wise, not as a whole-value null test: a row IS NULL when
4766    // every field is null, and IS NOT NULL when every field is
4767    // non-null — so the two are NOT simple negations (ROW(1,NULL) is
4768    // neither). A field that is itself a row is a non-null value, so
4769    // the check does not recurse. The `(a, b) IS NULL` tuple spelling
4770    // is already desugared to `a IS NULL AND b IS NULL` in the parser;
4771    // this covers the explicit `ROW(...)` constructor.
4772    if let Expr::FunctionCall { name, args } = expr
4773        && name.eq_ignore_ascii_case("row")
4774    {
4775        let mut all_null = true;
4776        let mut all_non_null = true;
4777        for a in args {
4778            if matches!(eval_expr(a, row, ctx)?, Value::Null) {
4779                all_non_null = false;
4780            } else {
4781                all_null = false;
4782            }
4783        }
4784        return Ok(Value::Bool(if negated { all_non_null } else { all_null }));
4785    }
4786    // v7.39 (round 962) — the same field-wise rule for a row-valued
4787    // EXPRESSION, not just the `ROW(...)` spelling. P4.11 keyed on the
4788    // syntax, so every other way to hold a row got the whole-value test:
4789    // measured against PG18.4, `SELECT an IS NULL FROM an` on a row whose
4790    // every column is NULL answered `t` there and `f` here, and a column
4791    // declared with a composite type behaved the same way. Round 961 made
4792    // whole-row references reachable through a projection, which is what
4793    // surfaced it.
4794    //
4795    // Fields are tested exactly as the `ROW(...)` arm tests its
4796    // arguments, without recursing — a field that is itself a row is a
4797    // non-null value.
4798    let v = eval_expr(expr, row, ctx)?;
4799    if let Value::Composite(fields) = &v {
4800        let mut all_null = true;
4801        let mut all_non_null = true;
4802        for (_, f) in fields {
4803            if matches!(f, Value::Null) {
4804                all_non_null = false;
4805            } else {
4806                all_null = false;
4807            }
4808        }
4809        return Ok(Value::Bool(if negated { all_non_null } else { all_null }));
4810    }
4811    let is_null = matches!(v, Value::Null);
4812    Ok(Value::Bool(if negated { !is_null } else { is_null }))
4813}
4814
4815pub fn eval_expr(
4816    expr: &Expr,
4817    row: &Row<'static>,
4818    ctx: &EvalContext<'_>,
4819) -> Result<Value<'static>, EvalError> {
4820    // v7.38 (read01 P3.25) — guard against a native stack overflow on a
4821    // pathologically nested expression (`a AND a AND … ` × thousands): the
4822    // recursion base is seeded on the outermost call, and once a deeper
4823    // call has consumed more than the budget we return an error the way
4824    // PG's check_stack_depth() does, rather than aborting the process.
4825    let sp = eval_stack_ptr();
4826    let base = ctx.recursion_base.get();
4827    if base == 0 {
4828        ctx.recursion_base.set(sp);
4829    } else if base.saturating_sub(sp) > MAX_EVAL_STACK_BYTES {
4830        return Err(EvalError::StackDepthExceeded);
4831    }
4832    match expr {
4833        Expr::AggregateOrdered { .. } => Err(EvalError::TypeMismatch {
4834            detail: "aggregate ORDER BY is only valid inside an aggregating SELECT".into(),
4835        }),
4836        // A named argument is only meaningful inside a call, where the callee's
4837        // parameter names give it a slot. Anywhere else it is a syntax error,
4838        // and saying so beats silently evaluating it as if the name were absent.
4839        Expr::NamedArg { name, .. } => Err(EvalError::TypeMismatch {
4840            detail: alloc::format!("named argument \"{name}\" is only valid in a function call"),
4841        }),
4842        Expr::Literal(l) => Ok(literal_to_value(l)),
4843        Expr::Column(c) => resolve_column(c, row, ctx),
4844        Expr::Placeholder(n) => {
4845            let idx = usize::from(*n).saturating_sub(1);
4846            ctx.params
4847                .get(idx)
4848                .cloned()
4849                .ok_or_else(|| EvalError::PlaceholderOutOfRange {
4850                    n: *n,
4851                    bound: u16::try_from(ctx.params.len()).unwrap_or(u16::MAX),
4852                })
4853        }
4854        // v7.39 (round 620) — an unadorned string literal carries PG's
4855        // `unknown` type, and a boolean connective is a context that resolves
4856        // it TO boolean. `'true' AND true`, `'f' OR false` and `NOT 'a'` are
4857        // answered by PG (`t`, `f`, and the input-syntax error respectively)
4858        // and were all refused here with `argument of … must be type boolean,
4859        // not type text` — the message PG reserves for an operand that really
4860        // IS text (`''::TEXT AND true`), which stays refused. Out-of-line and
4861        // behind a literal-shaped guard: this is the recursive frame the
4862        // 768 KiB stack budget is tuned against.
4863        Expr::Unary {
4864            op: spg_sql::ast::UnOp::Not,
4865            expr,
4866        } if !ctx.mysql_dialect && is_unknown_string_literal(expr) => apply_unary(
4867            spg_sql::ast::UnOp::Not,
4868            coerce_unknown_literal_to_bool(expr)?,
4869        ),
4870        Expr::Unary { op, expr } => {
4871            let v = eval_expr(expr, row, ctx)?;
4872            // The MySQL-specific unary readings (NOT any truth value, `-`/`~`
4873            // on a string, `~` unsigned) live out-of-line: `eval_expr` is the
4874            // recursive frame the 768 KiB stack-depth budget is tuned
4875            // against, and locals added here cost one nesting level each (the
4876            // round-305 / round-383 frame cliff).
4877            if ctx.mysql_dialect {
4878                if let Some(r) = mysql_unary_arm(*op, &v) {
4879                    return r;
4880                }
4881            }
4882            apply_unary(*op, v)
4883        }
4884        // v7.39 (round 346, M1) — MariaDB reads both sides of AND / OR as
4885        // truth values (`1 AND 2` is 1, measured). apply_binary has no
4886        // dialect, so the coercion happens here, where it does. The body
4887        // is out-of-line: `eval_expr` is the recursive frame the 768 KiB
4888        // stack-depth budget is tuned against, and locals added here cost
4889        // one nesting level each (the round-305 frame cliff).
4890        Expr::Binary { lhs, op, rhs }
4891            if ctx.mysql_dialect && matches!(op, BinOp::And | BinOp::Or | BinOp::LogicalXor) =>
4892        {
4893            eval_mysql_connective(lhs, *op, rhs, row, ctx)
4894        }
4895        // v7.39 (round 620/621) — the unknown-literal resolution and the
4896        // short circuit, both out of line. Placed AFTER the MySQL arm so the
4897        // dialect keeps its own reading of these connectives.
4898        Expr::Binary { lhs, op, rhs } if matches!(op, BinOp::And | BinOp::Or) => {
4899            eval_connective(lhs, *op, rhs, row, ctx)
4900        }
4901        Expr::Binary { lhs, op, rhs } => {
4902            // v7.32 (P4 borrow channel) — comparison fast path. A pure
4903            // comparison op only reads its operands and returns Bool,
4904            // and for non-NUMERIC / non-INTERVAL / non-CI-collation
4905            // operands `apply_binary` IS just the NULL-3VL check plus
4906            // the ref-based `compare` (NUMERIC routes through fixed-
4907            // point `apply_binary_numeric`; INTERVAL through
4908            // `apply_binary_interval`; CI columns fold). So read the
4909            // operands borrowed — a column cell is no longer cloned
4910            // just to compare it (`WHERE thread_id != ''` alone cloned
4911            // one Text cell per scanned row). Anything that needs the
4912            // owned path falls through unchanged.
4913            if matches!(
4914                op,
4915                BinOp::Eq | BinOp::NotEq | BinOp::Lt | BinOp::LtEq | BinOp::Gt | BinOp::GtEq
4916            ) {
4917                let lc = eval_expr_cow(lhs, row, ctx)?;
4918                let rc = eval_expr_cow(rhs, row, ctx)?;
4919                // v7.39 (enum order knife) — enum-typed operands compare by
4920                // member order, not label text. Cold unless both sides are
4921                // Text and the catalog has enum types at all.
4922                if matches!(lc.as_ref(), Value::Text(_)) && matches!(rc.as_ref(), Value::Text(_)) {
4923                    if let Some(r) = enum_compare_hook(*op, lhs, rhs, lc.as_ref(), rc.as_ref(), ctx)
4924                    {
4925                        return r;
4926                    }
4927                    // v7.39 (round 693) — and the collation hook, under the
4928                    // same Text/Text gate for the same reason.
4929                    if let Some(r) =
4930                        collate_compare_hook(*op, lhs, rhs, lc.as_ref(), rc.as_ref(), ctx)
4931                    {
4932                        return r;
4933                    }
4934                }
4935                // v7.39 (round 351, M11) — the three conditions fold into
4936                // ONE call. Adding a fourth as another `||` here tipped the
4937                // 768 KiB stack guard on its own (measured — this is the
4938                // hottest recursive frame there is); one call is cheaper
4939                // than the three it replaces.
4940                let owned_path = needs_owned_compare(lc.as_ref(), rc.as_ref(), lhs, rhs, ctx);
4941                if !owned_path {
4942                    if lc.as_ref().is_null() || rc.as_ref().is_null() {
4943                        return Ok(Value::Null);
4944                    }
4945                    return compare(*op, lc.as_ref(), rc.as_ref()).map_err(|e| {
4946                        unknown_literal_cmp_error(e, lhs, rhs, lc.as_ref(), rc.as_ref())
4947                    });
4948                }
4949                let (l, r) = collation_fold_for_compare(
4950                    *op,
4951                    lhs,
4952                    rhs,
4953                    lc.into_owned(),
4954                    rc.into_owned(),
4955                    ctx,
4956                );
4957                // The owned call consumes the values; the rewrite needs the
4958                // literal's text and the other side's type only on the ERROR
4959                // path, so capture those two up front — the capture itself is
4960                // gated on the cheap expr test, so a comparison with no
4961                // unknown literal pays one branch.
4962                let probe = (is_unknown_string_literal(lhs) || is_unknown_string_literal(rhs))
4963                    .then(|| (l.clone(), r.clone()));
4964                return apply_binary_in(*op, l, r, ctx.mysql_dialect).map_err(|e| match &probe {
4965                    Some((pl, pr)) => unknown_literal_cmp_error(e, lhs, rhs, pl, pr),
4966                    None => e,
4967                });
4968            }
4969            let l = eval_expr(lhs, row, ctx)?;
4970            let r = eval_expr(rhs, row, ctx)?;
4971            // v7.17.0 Phase 2.5 — collation-aware text comparison.
4972            // When either operand of a comparison op references a
4973            // column declared `COLLATE "case_insensitive"` (or any
4974            // MySQL `_ci` collation), case-fold both sides before
4975            // the byte-wise compare so `WHERE name = 'foo'` matches
4976            // stored `'Foo'`. Non-Text values fall straight through
4977            // — the helper is a no-op outside Text-Text equality
4978            // and inequality.
4979            let (l, r) = collation_fold_for_compare(*op, lhs, rhs, l, r, ctx);
4980            // v7.39 (GUC knife 4) — `date/interval/float || text` textifies
4981            // through the out-functions, which honour the session render
4982            // style. Pre-render the style-sensitive operand here (the
4983            // orthodox home is an implicit-cast node at type resolution;
4984            // until then this keeps apply_binary style-free). Default
4985            // style short-circuits — text_concat's own value_to_text
4986            // produces the identical bytes.
4987            if matches!(op, spg_sql::ast::BinOp::Concat)
4988                && ctx.render_style != format::RenderStyle::default()
4989            {
4990                let styled = |v: Value<'static>| -> Value<'static> {
4991                    match &v {
4992                        Value::Date(_)
4993                        | Value::Timestamp(_)
4994                        | Value::Interval { .. }
4995                        | Value::Float(_)
4996                        | Value::Real(_) => {
4997                            Value::text(values::value_to_text_styled(&v, &ctx.render_style))
4998                        }
4999                        _ => v,
5000                    }
5001                };
5002                let (sl, sr) = (styled(l), styled(r));
5003                return apply_binary(*op, sl, sr);
5004            }
5005            apply_binary_mysql_unsigned(*op, lhs, rhs, l, r, ctx)
5006        }
5007        Expr::Cast { expr, target } => eval_cast_arm(expr, target, row, ctx),
5008        Expr::FieldAccess { base, field } => eval_field_access_arm(base, field, row, ctx),
5009        Expr::IsNull { expr, negated } => eval_is_null_arm(expr, *negated, row, ctx),
5010        // v7.39 (round 328, V45) — `x IS [NOT] TRUE | FALSE | UNKNOWN`.
5011        // Out-of-line like its IS NULL neighbour: an inline body here
5012        // grows every frame of the recursive evaluator, which is what
5013        // tipped the 512KB depth guard in round 305.
5014        Expr::BoolTest {
5015            expr,
5016            value,
5017            negated,
5018        } => eval_bool_test_arm(expr, *value, *negated, row, ctx),
5019        Expr::FunctionCall { name, args } => eval_function_call_arm(name, args, row, ctx),
5020        // v7.39 (read01 round 100) — VARIADIC is spliced into its enclosing
5021        // call before the args are evaluated (see eval_function_call_arm); a
5022        // bare one reaching here was written outside a function call.
5023        Expr::Variadic(_) => Err(EvalError::TypeMismatch {
5024            detail: "VARIADIC is only valid as a function-call argument".into(),
5025        }),
5026        Expr::Like {
5027            expr,
5028            pattern,
5029            negated,
5030            case_insensitive,
5031        } => eval_like_arm(expr, pattern, *negated, *case_insensitive, row, ctx),
5032        Expr::Extract { field, source } => eval_extract_arm(field, source, row, ctx),
5033        // v4.10: subquery nodes should have been resolved into
5034        // Literal / InList nodes by Engine::resolve_select_subqueries
5035        // before the row loop. Anything reaching here is a bug.
5036        Expr::ScalarSubquery(_)
5037        | Expr::Exists { .. }
5038        | Expr::InSubquery { .. }
5039        | Expr::RowInSubquery { .. }
5040        | Expr::RowCmpSubquery { .. } => Err(EvalError::TypeMismatch {
5041            detail: "subquery reached row eval — engine resolver bug".into(),
5042        }),
5043        // v7.30.2 (mailrs round-25) — flat `expr [NOT] IN (a, b, …)`.
5044        // Iterative scan with PG three-valued logic: TRUE on the first
5045        // Eq match; if nothing matched, NULL when the needle is NULL or
5046        // any comparison was NULL; FALSE otherwise. Empty list (only
5047        // reachable via an empty subquery result) is FALSE / TRUE even
5048        // for a NULL needle — no comparison ever happens.
5049        Expr::InList {
5050            expr,
5051            list,
5052            negated,
5053        } => eval_in_list_arm(expr, list, *negated, row, ctx),
5054        // v4.12: window functions should have been rewritten into
5055        // synthetic __win_N column references by
5056        // exec_select_with_window before row eval. Anything
5057        // reaching here is similarly a bug.
5058        Expr::WindowFunction { .. } => Err(EvalError::TypeMismatch {
5059            detail: "window function reached row eval — engine rewrite bug".into(),
5060        }),
5061        // v7.10.10 — `ARRAY[expr, expr, …]` constructor.
5062        // v7.11.13 — element-type detection: all integers →
5063        // IntArray (or BigIntArray when widening), any Text →
5064        // TextArray. Non-TEXT non-integer elements (Bool, Float)
5065        // stringify into TextArray as the safe default.
5066        Expr::Array(items) => eval_array_arm(items, row, ctx),
5067        // v7.10.12 — `arr[i]` PG-style 1-based indexing.
5068        // Out-of-range indices (including i ≤ 0) return NULL.
5069        Expr::ArraySubscript { .. } => eval_array_subscript_arm(expr, row, ctx),
5070        // Array slice `arr[lo:hi]` — PG 1-based, both ends
5071        // inclusive, out-of-range bounds clamp, missing bounds
5072        // extend to the array's ends. Result keeps the element
5073        // type; an empty window yields an empty array.
5074        Expr::ArraySlice { target, lo, hi } => eval_array_slice_arm(target, lo, hi, row, ctx),
5075        // v7.10.12 — `x op ANY(arr)` / `x op ALL(arr)`. PG
5076        // 3VL: ANY → true if any element compares-true; NULL if
5077        // no true but some NULL; false otherwise. ALL: false if
5078        // any compares-false; NULL if no false but some NULL;
5079        // true otherwise.
5080        Expr::AnyAll {
5081            expr,
5082            op,
5083            array,
5084            is_any,
5085        } => eval_any_all_arm(expr, op, array, *is_any, row, ctx),
5086        // v7.13.0 — CASE WHEN … END (mailrs round-5 G9).
5087        // Short-circuit on the first matching branch. Searched form
5088        // (operand=None) treats each branch's WHEN as a Bool
5089        // predicate. Simple form (operand=Some) compares with =.
5090        // ELSE on no match; NULL if no ELSE.
5091        Expr::Case {
5092            operand,
5093            branches,
5094            else_branch,
5095        } => eval_case_arm(operand, branches, else_branch, row, ctx),
5096    }
5097}
5098
5099/// v7.10.10 — best-effort text rendering for non-TEXT array
5100/// elements (numbers, bools, etc.). The PG rule is that
5101/// `ARRAY[1, 2]` is `int[]`, but SPG's v7.10 only models TEXT[],
5102/// so we widen by stringifying. NUMERIC formatting goes through
5103/// the existing canonical helpers to stay consistent with
5104/// `format_numeric` / `format_date` etc.
5105/// v7.37 D.1 — the COALESCE result-type hint: a sibling branch's explicit
5106/// cast target (`NULL::time`, `col::time`), unless it is Text (Text carries no
5107/// coercion). Returns the first non-Text `CastTarget` found, mirroring PG's
5108/// left-to-right common-type resolution for the common single-typed-branch case.
5109fn coalesce_type_hint(e: &Expr) -> Option<CastTarget> {
5110    match e {
5111        Expr::Cast { target, .. } if !matches!(target, CastTarget::Text) => Some(target.clone()),
5112        _ => None,
5113    }
5114}
5115
5116/// v7.38 (read01) — widen `v` to the already-resolved common type `common`
5117/// of a `CASE`/`COALESCE`/`GREATEST`/`LEAST`/`NULLIF` result, so the value's
5118/// type matches the one PG reports and downstream operators (e.g. `/`) see
5119/// the widened type (integer division vs numeric division). Only widens;
5120/// anything already at the common type, or that fails to coerce, is returned
5121/// untouched (this must never turn a working expression into an error).
5122/// NUMERIC is scale-preserving: an existing exact-numeric keeps its own scale
5123/// (PG renders `COALESCE(1.50, 2)` as `1.50`); only integers promote, to
5124/// scale 0.
5125pub(crate) fn widen_value_to(v: Value<'static>, common: spg_storage::DataType) -> Value<'static> {
5126    use spg_storage::DataType as DT;
5127    // Only widen numeric- and temporal-category results: these are the ones
5128    // whose type actually changes a downstream value (integer vs numeric
5129    // division, date vs timestamp). Widening a string result (varchar ∪ text)
5130    // would only relabel the type while risking a spurious length-limit error
5131    // when coercing into a modelled-length varchar/char, so leave it as-is.
5132    if !matches!(
5133        common,
5134        DT::SmallInt
5135            | DT::Int
5136            | DT::BigInt
5137            | DT::Numeric { .. }
5138            // v7.39 (round 649) — `real` was absent here too, so even once
5139            // `common_type` learned to rank it, the value was handed back
5140            // unwidened: `coalesce(1::int, 1::real)` stayed integer where
5141            // PG says real. Two lists, one ladder — the gap had to be
5142            // closed in both.
5143            | DT::Real
5144            | DT::Float
5145            | DT::Date
5146            | DT::Time
5147            | DT::Timestamp
5148            | DT::Timestamptz
5149    ) {
5150        return v;
5151    }
5152    if matches!(v, Value::Null) {
5153        return v;
5154    }
5155    if v.data_type() == Some(common) {
5156        return v;
5157    }
5158    if matches!(common, spg_storage::DataType::Numeric { .. })
5159        && matches!(v, Value::Numeric { .. } | Value::NumericBig(_))
5160    {
5161        return v;
5162    }
5163    let target = if matches!(common, spg_storage::DataType::Numeric { .. }) {
5164        spg_storage::DataType::Numeric {
5165            precision: 0,
5166            scale: 0,
5167        }
5168    } else {
5169        common
5170    };
5171    match crate::conversions::coerce_value(v.clone(), target, "", 0) {
5172        Ok(cv) => cv,
5173        Err(_) => v,
5174    }
5175}
5176
5177/// Widen `v` to the PG common type of the sibling `types`, or leave it as-is
5178/// when the types don't resolve to a single widening type. See
5179/// [`widen_value_to`] and [`crate::describe::common_type`].
5180pub(crate) fn widen_to_common(
5181    v: Value<'static>,
5182    types: &[spg_storage::DataType],
5183) -> Value<'static> {
5184    match crate::describe::common_type(types) {
5185        Some(common) => widen_value_to(v, common),
5186        None => v,
5187    }
5188}
5189
5190pub(crate) fn value_to_text_for_array(v: &Value, style: &format::RenderStyle) -> String {
5191    match v {
5192        Value::Text(s) | Value::Json(s) => s.to_string(),
5193        Value::Int(n) => n.to_string(),
5194        Value::BigInt(n) => n.to_string(),
5195        Value::SmallInt(n) => n.to_string(),
5196        // PG renders booleans in array external form as `t` / `f`
5197        // (the bool type's output function), not `true` / `false`.
5198        Value::Bool(b) => {
5199            if *b {
5200                "t".into()
5201            } else {
5202                "f".into()
5203            }
5204        }
5205        Value::Float(x) => format::format_float_styled(*x, style),
5206        Value::Real(x) => format::format_real_styled(*x, style),
5207        Value::Date(d) => format::format_date_styled(*d, style),
5208        Value::Timestamp(t) => format::format_timestamp_styled(*t, style),
5209        Value::Numeric {
5210            scaled,
5211            scale,
5212            kind,
5213        } => format_numeric_kind(*kind, *scaled, *scale),
5214        // v7.39 — everything else renders its canonical PG text (this
5215        // Debug fallback is how `ARRAY['\xff'::bytea]` printed
5216        // `{Bytes([255])}` on the wire).
5217        _ => values::value_to_text_styled(v, style),
5218    }
5219}
5220
5221/// SQL `LIKE` matcher. Wildcards are `%` (any run, possibly empty) and `_`
5222/// (exactly one char). `\` escapes the next pattern char so `\%` matches a
5223/// literal `%`. Matches the whole input — no implicit anchoring needed
5224/// since SQL `LIKE` is always full-string. Errs on a trailing unpaired
5225/// escape the matcher actually reaches with text left (PG's lazy 22025).
5226fn like_match(text: &str, pattern: &str) -> Result<bool, EvalError> {
5227    let pat: Vec<char> = pattern.chars().collect();
5228    like_match_str(text, &pat, 0)
5229}
5230
5231/// v7.37.16 — pg_typeof spelling for a STATIC column type (the
5232/// NULL-cell fallback; the value-level table is `pg_typeof_name`).
5233/// TEXT maps to None because a NULL literal describes as TEXT — the
5234/// unknown stand-in — and pg_typeof(NULL) must stay "unknown"; every
5235/// type not listed also returns None (caller keeps the value answer).
5236pub(crate) fn pg_typeof_name_for_datatype(t: spg_storage::DataType) -> Option<&'static str> {
5237    use spg_storage::DataType as D;
5238    Some(match t {
5239        D::SmallInt => "smallint",
5240        D::Int => "integer",
5241        D::BigInt => "bigint",
5242        D::Float => "double precision",
5243        D::Real => "real",
5244        D::Numeric { .. } => "numeric",
5245        D::Bool => "boolean",
5246        D::Date => "date",
5247        D::Time => "time without time zone",
5248        D::Timestamp => "timestamp without time zone",
5249        D::Timestamptz => "timestamp with time zone",
5250        D::Name => "name",
5251        D::Xid => "xid",
5252        D::Xid8 => "xid8",
5253        D::Oid => "oid",
5254        // v7.39 (round 694) — and its array, for the same reason.
5255        D::OidArray => "oid[]",
5256        D::Uuid => "uuid",
5257        D::Interval => "interval",
5258        // v7.39 (round 871) — the rest of what a NULL cast can be
5259        // annotated with. This table decided which types survived
5260        // `pg_typeof(NULL::t)`: the twenty above answered, everything
5261        // else fell to `_ => None` and reported `unknown`. That reads
5262        // as a NULL problem and is not one — `NULL::uuid` was right all
5263        // along while `NULL::text` was wrong, because one was listed
5264        // and the other was not.
5265        //
5266        // Names are PG18's own, taken from running `pg_typeof` there
5267        // rather than from memory: `bit varying` not `varbit`, `bit`
5268        // for any width, `character varying`, `"char"` quoted.
5269        D::Text => "text",
5270        D::Multirange(k) => match k {
5271            spg_storage::RangeKind::Int4 => "int4multirange",
5272            spg_storage::RangeKind::Int8 => "int8multirange",
5273            spg_storage::RangeKind::Num => "nummultirange",
5274            spg_storage::RangeKind::Ts => "tsmultirange",
5275            spg_storage::RangeKind::TsTz => "tstzmultirange",
5276            spg_storage::RangeKind::Date => "datemultirange",
5277        },
5278        D::Varchar(_) => "character varying",
5279        // PG names `char(n)` "character"; the one-byte internal type
5280        // spelled `"char"` is a DIFFERENT type there, and SPG maps both
5281        // onto `Char(u32)` — so this arm must answer for the declared
5282        // one. Round 871's first attempt said `"char"` here and would
5283        // have reported `char(5)` as the internal type.
5284        D::Char(_) => "character",
5285        D::Json => "json",
5286        D::Jsonb => "jsonb",
5287        D::Bytes => "bytea",
5288        D::Inet => "inet",
5289        D::Cidr => "cidr",
5290        D::Macaddr => "macaddr",
5291        D::Macaddr8 => "macaddr8",
5292        D::Bit(_) => "bit",
5293        D::BitVarying(_) => "bit varying",
5294        D::Xml => "xml",
5295        D::Money => "money",
5296        D::Point => "point",
5297        D::Lseg => "lseg",
5298        D::Path => "path",
5299        D::PgBox => "box",
5300        D::Polygon => "polygon",
5301        D::Line => "line",
5302        D::Circle => "circle",
5303        D::TextArray => "text[]",
5304        D::IntArray => "integer[]",
5305        D::BigIntArray => "bigint[]",
5306        D::SmallIntArray => "smallint[]",
5307        D::FloatArray => "double precision[]",
5308        D::NumericArray => "numeric[]",
5309        D::BoolArray => "boolean[]",
5310        D::DateArray => "date[]",
5311        D::TimestampArray => "timestamp without time zone[]",
5312        D::TimestamptzArray => "timestamp with time zone[]",
5313        D::UuidArray => "uuid[]",
5314        D::JsonArray => "json[]",
5315        D::JsonbArray => "jsonb[]",
5316        D::BytesArray => "bytea[]",
5317        D::VarcharArray => "character varying[]",
5318        D::CharArray => "\"char\"[]",
5319        D::IntervalArray => "interval[]",
5320        _ => return None,
5321    })
5322}
5323
5324/// v7.37.16 — zero-allocation LIKE core: the text side walks a `&str`
5325/// cursor (char-semantic — `_` consumes one CHARACTER, `%` backtracks
5326/// only at char boundaries) instead of collecting a `Vec<char>` per
5327/// call. The old per-row collect was ~50 ns/row of pure allocator
5328/// traffic on a 50 k-row `WHERE s LIKE '%…%'` scan (the heavy.rs
5329/// like_filter 2.8× loss); the pattern side stays a compile-once
5330/// `&[char]` (see `Step::Like`).
5331pub(crate) fn like_match_str(text: &str, pat: &[char], mut pi: usize) -> Result<bool, EvalError> {
5332    let mut t = text;
5333    while pi < pat.len() {
5334        match pat[pi] {
5335            '%' => {
5336                // Collapse consecutive `%` and try every possible split.
5337                while pi < pat.len() && pat[pi] == '%' {
5338                    pi += 1;
5339                }
5340                if pi == pat.len() {
5341                    return Ok(true);
5342                }
5343                let mut rest = t;
5344                loop {
5345                    if like_match_str(rest, pat, pi)? {
5346                        return Ok(true);
5347                    }
5348                    match rest.chars().next() {
5349                        Some(c) => rest = &rest[c.len_utf8()..],
5350                        None => return Ok(false),
5351                    }
5352                }
5353            }
5354            '_' => match t.chars().next() {
5355                Some(c) => {
5356                    t = &t[c.len_utf8()..];
5357                    pi += 1;
5358                }
5359                None => return Ok(false),
5360            },
5361            // v7.39 (round 144, like_match.c) — a trailing unpaired escape is
5362            // PG's 22025 error, but LAZILY: only when the matcher reaches it
5363            // with text left. A branch where the text is already exhausted
5364            // returns false without ever "seeing" the trailing escape
5365            // ('x' LIKE 'x\' is false; 'xy' LIKE 'x\' errors).
5366            '\\' if pi + 1 >= pat.len() => {
5367                if t.is_empty() {
5368                    return Ok(false);
5369                }
5370                return Err(EvalError::TypeMismatch {
5371                    detail: "LIKE pattern must not end with escape character".into(),
5372                });
5373            }
5374            '\\' => {
5375                let want = pat[pi + 1];
5376                match t.chars().next() {
5377                    Some(c) if c == want => {
5378                        t = &t[c.len_utf8()..];
5379                        pi += 2;
5380                    }
5381                    _ => return Ok(false),
5382                }
5383            }
5384            c => match t.chars().next() {
5385                Some(tc) if tc == c => {
5386                    t = &t[c.len_utf8()..];
5387                    pi += 1;
5388                }
5389                _ => return Ok(false),
5390            },
5391        }
5392    }
5393    Ok(t.is_empty())
5394}
5395
5396/// v7.24 (round-15) — `string_to_array(text, delimiter)`.
5397fn fn_string_to_array(args: &[Value<'_>]) -> Result<Value<'static>, EvalError> {
5398    // v7.37.17 (17.6 siblings) — the 3-arg PG form adds
5399    // `null_string`: elements equal to it become SQL NULL.
5400    let (text_arg, delim_arg, null_arg) = match args {
5401        [t, d] => (t, d, None),
5402        [t, d, n] => (t, d, Some(n)),
5403        _ => {
5404            return Err(EvalError::TypeMismatch {
5405                detail: alloc::format!(
5406                    "string_to_array expects 2 or 3 arguments, got {}",
5407                    args.len()
5408                ),
5409            });
5410        }
5411    };
5412    let null_string: Option<&str> = match null_arg {
5413        None | Some(Value::Null) => None,
5414        Some(Value::Text(s)) => Some(s.as_ref()),
5415        Some(other) => {
5416            return Err(EvalError::TypeMismatch {
5417                detail: alloc::format!(
5418                    "string_to_array null_string must be text, got {}",
5419                    crate::conversions::pg_type_name_for_error_opt(other.data_type())
5420                ),
5421            });
5422        }
5423    };
5424    let text = match text_arg {
5425        Value::Null => return Ok(Value::Null),
5426        Value::Text(t) => t,
5427        other => {
5428            return Err(EvalError::TypeMismatch {
5429                detail: alloc::format!(
5430                    "string_to_array expects text, got {}",
5431                    crate::conversions::pg_type_name_for_error_opt(other.data_type())
5432                ),
5433            });
5434        }
5435    };
5436    // PG (9.1+): empty input → empty array, regardless of delimiter.
5437    if text.is_empty() {
5438        return Ok(Value::TextArray(Vec::new()));
5439    }
5440    let nullify = |p: String| -> Option<String> {
5441        if null_string == Some(p.as_str()) {
5442            None
5443        } else {
5444            Some(p)
5445        }
5446    };
5447    let parts: Vec<Option<String>> = match delim_arg {
5448        // NULL delimiter → one element per character.
5449        Value::Null => text.chars().map(|c| nullify(c.to_string())).collect(),
5450        Value::Text(d) if d.is_empty() => alloc::vec![nullify(text.to_string())],
5451        Value::Text(d) => text
5452            .split(d.as_ref())
5453            .map(|p| nullify(p.to_string()))
5454            .collect(),
5455        other => {
5456            return Err(EvalError::TypeMismatch {
5457                detail: alloc::format!(
5458                    "string_to_array delimiter must be text, got {}",
5459                    crate::conversions::pg_type_name_for_error_opt(other.data_type())
5460                ),
5461            });
5462        }
5463    };
5464    Ok(Value::TextArray(parts))
5465}
5466
5467/// v6.4.3 — `error_on_null(v)`. Returns `v` unchanged if non-NULL;
5468/// errors otherwise. Convenience to assert NOT NULL inside an
5469/// expression without wrapping it in COALESCE + raise hacks.
5470fn error_on_null(args: &[Value<'_>]) -> Result<Value<'static>, EvalError> {
5471    if args.len() != 1 {
5472        return Err(EvalError::TypeMismatch {
5473            detail: format!("error_on_null() takes 1 arg, got {}", args.len()),
5474        });
5475    }
5476    if matches!(args[0], Value::Null) {
5477        return Err(EvalError::TypeMismatch {
5478            detail: "error_on_null(): argument is NULL".into(),
5479        });
5480    }
5481    Ok(args[0].clone().into_owned())
5482}
5483
5484/// Helper: coerce a Value to an Option<String> for regex args. NULL
5485/// propagates as None (caller short-circuits to Value::Null).
5486fn text_arg(v: &Value) -> Result<Option<String>, EvalError> {
5487    match v {
5488        Value::Text(s) => Ok(Some(s.to_string())),
5489        Value::Null => Ok(None),
5490        other => Err(EvalError::TypeMismatch {
5491            detail: alloc::format!(
5492                "regex function expects TEXT arg, got {}",
5493                crate::conversions::pg_type_name_for_error_opt(other.data_type())
5494            ),
5495        }),
5496    }
5497}
5498
5499// Month-name tables shared by the date formatters in `eval::strings`
5500// (`date_format_mysql`) and `eval::datetime` via `use super::`. Kept in
5501// `eval.rs` alongside `civil_from_days` so the calendar primitives live
5502// in one place.
5503const MONTH_FULL: [&str; 12] = [
5504    "January",
5505    "February",
5506    "March",
5507    "April",
5508    "May",
5509    "June",
5510    "July",
5511    "August",
5512    "September",
5513    "October",
5514    "November",
5515    "December",
5516];
5517const MONTH_ABBR: [&str; 12] = [
5518    "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
5519];
5520
5521/// Howard Hinnant's `civil_from_days` — converts days since the Unix
5522/// epoch back to a proleptic-Gregorian (year, month, day) triple. Stays
5523/// in `eval.rs` (shared with the date SQL functions here and with
5524/// `eval::strings`); the inverse `days_from_civil` lives in
5525/// `eval::format`. Both keep the engine off `std` time facilities.
5526#[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
5527fn civil_from_days(days: i32) -> (i32, u32, u32) {
5528    let z = i64::from(days) + 719_468;
5529    let era = z.div_euclid(146_097);
5530    // doe ∈ [0, 146_097); fits in u32 with room to spare. Same for
5531    // every other quantity below — `as u32` truncations are safe by
5532    // construction.
5533    let doe = (z - era * 146_097) as u32;
5534    let yoe = (doe.saturating_sub(doe / 1460) + doe / 36524 - doe / 146_096) / 365;
5535    let y_base = i64::from(yoe) + era * 400;
5536    let doy = doe.saturating_sub(365 * yoe + yoe / 4 - yoe / 100);
5537    let mp = (5 * doy + 2) / 153;
5538    let d = doy.saturating_sub((153 * mp + 2) / 5) + 1;
5539    let m = if mp < 10 { mp + 3 } else { mp - 9 };
5540    let y = if m <= 2 { y_base + 1 } else { y_base };
5541    (y as i32, m, d)
5542}
5543
5544/// Add `months` (signed) to a `(year, month, day)` triple using PG's
5545/// clamp-to-last-day rule (so `'2024-01-31' + 1 month` → `'2024-02-29'`).
5546fn add_months_to_civil(y: i32, m: u32, d: u32, months: i32) -> (i32, u32, u32) {
5547    let total_months = i64::from(y) * 12 + i64::from(m) - 1 + i64::from(months);
5548    let new_year = i32::try_from(total_months.div_euclid(12)).unwrap_or(i32::MAX);
5549    let new_month_zero = total_months.rem_euclid(12);
5550    #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
5551    let new_month = (new_month_zero as u32) + 1;
5552    let max_day = days_in_month(new_year, new_month);
5553    (new_year, new_month, d.min(max_day))
5554}
5555
5556const fn days_in_month(y: i32, m: u32) -> u32 {
5557    match m {
5558        1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
5559        2 => {
5560            // Proleptic Gregorian leap rule.
5561            if y.rem_euclid(4) == 0 && (y.rem_euclid(100) != 0 || y.rem_euclid(400) == 0) {
5562                29
5563            } else {
5564                28
5565            }
5566        }
5567        // 4 / 6 / 9 / 11 plus any out-of-range month (callers normalise
5568        // first, but be defensive) get the 30-day fallback.
5569        _ => 30,
5570    }
5571}
5572
5573pub(crate) fn literal_to_value(l: &Literal) -> Value<'static> {
5574    match l {
5575        Literal::Integer(n) => {
5576            if let Ok(small) = i32::try_from(*n) {
5577                Value::Int(small)
5578            } else {
5579                Value::BigInt(*n)
5580            }
5581        }
5582        Literal::Float(x) => Value::Float(*x),
5583        Literal::Numeric { unscaled, scale } => Value::Numeric {
5584            scaled: *unscaled,
5585            scale: *scale,
5586            kind: spg_storage::NumericKind::Finite,
5587        },
5588        Literal::NumericBig(s) => crate::conversions::big_literal_to_value(s),
5589        Literal::String(s) => Value::text(s.clone()),
5590        Literal::Vector(v) => Value::vector(v.clone()),
5591        Literal::TextArray(items) => Value::TextArray(items.clone()),
5592        Literal::IntArray(items) => Value::IntArray(items.clone()),
5593        Literal::BigIntArray(items) => Value::BigIntArray(items.clone()),
5594        Literal::Bool(b) => Value::Bool(*b),
5595        Literal::Null => Value::Null,
5596        Literal::Interval {
5597            months,
5598            days,
5599            micros,
5600            ..
5601        } => Value::Interval {
5602            months: *months,
5603            days: *days,
5604            micros: *micros,
5605        },
5606    }
5607}
5608
5609impl crate::Engine {
5610    /// v7.39 (read01 round 63) — run a user function whose body has its own
5611    /// FROM. The arguments are substituted into the body as literals and the
5612    /// SELECT goes through the REAL executor, so it sees exactly the rows a
5613    /// hand-written query would: the row-header visibility filter applies, and
5614    /// under in-place MVCC a dead row stays dead.
5615    ///
5616    /// PG returns the FIRST row of a scalar SQL function's body (and NULL when
5617    /// it returns none).
5618    pub(crate) fn run_user_fn_query(
5619        &self,
5620        def: &spg_storage::FunctionDef,
5621        stmt: &spg_sql::ast::SelectStatement,
5622        arg_names: &[alloc::string::String],
5623        args: &spg_storage::Row<'static>,
5624        fn_depth: u16,
5625    ) -> Result<Value<'static>, EvalError> {
5626        const MAX_QUERY_FN_DEPTH: u16 = 8;
5627        if fn_depth >= MAX_QUERY_FN_DEPTH {
5628            return Err(EvalError::TypeMismatch {
5629                detail: alloc::format!(
5630                    "function {:?}: a body with its own FROM may nest at most {MAX_QUERY_FN_DEPTH} deep",
5631                    def.name
5632                ),
5633            });
5634        }
5635        // Bind the arguments — the same helper the set-returning path uses, so
5636        // both resolve an argument identically (a COLUMN of the body's own FROM
5637        // shadows a same-named argument, as in PG).
5638        let owned: alloc::vec::Vec<Value<'static>> =
5639            args.values.iter().map(|v| v.clone().into_owned()).collect();
5640        let bound =
5641            bind_user_fn_args(self.active_catalog(), stmt, arg_names, &owned).map_err(|e| {
5642                EvalError::TypeMismatch {
5643                    detail: alloc::format!("function {:?}: {e}", def.name),
5644                }
5645            })?;
5646
5647        // v7.39 (round 334, V55) — a SECURITY DEFINER body is authorised as
5648        // the function's OWNER. Measured on PG 18.4: a definer function
5649        // owned by `owner55` counts rows of a table `caller55` cannot read,
5650        // while the SECURITY INVOKER sibling is refused.
5651        let as_role = def.security_definer.then(|| def.owner.as_deref()).flatten();
5652        let out = self
5653            .exec_select_cancel_as(&bound, crate::CancelToken::none(), as_role)
5654            .map_err(|e| EvalError::TypeMismatch {
5655                detail: alloc::format!("function {:?}: {e}", def.name),
5656            })?;
5657        let crate::QueryResult::Rows { rows, .. } = out else {
5658            return Ok(Value::Null);
5659        };
5660        let Some(first) = rows.first() else {
5661            // No row: PG's scalar SQL function returns NULL.
5662            return Ok(Value::Null);
5663        };
5664        let v = first.values.first().cloned().unwrap_or(Value::Null);
5665        let declared = def.returns.trim();
5666        if declared.eq_ignore_ascii_case("VOID") {
5667            return Ok(Value::Null);
5668        }
5669        crate::eval::cast::cast_value(v.into_owned(), declared_return_cast_target(declared))
5670            .or_else(|_| Ok(Value::Null))
5671    }
5672}
5673
5674/// v7.39 (read01 round 65) — bind a call's arguments into a function body's
5675/// SELECT, as literals. Shared by the scalar path (round 63) and the
5676/// set-returning one, so both resolve an argument the same way — including the
5677/// rule that a COLUMN of the body's own FROM shadows a same-named argument.
5678pub(crate) fn bind_user_fn_args(
5679    cat: &spg_storage::Catalog,
5680    stmt: &spg_sql::ast::SelectStatement,
5681    arg_names: &[alloc::string::String],
5682    args: &[Value<'static>],
5683) -> Result<spg_sql::ast::SelectStatement, EvalError> {
5684    let mut bound = stmt.clone();
5685    let mut binds: alloc::collections::BTreeMap<alloc::string::String, spg_sql::ast::Expr> =
5686        alloc::collections::BTreeMap::new();
5687    for (i, name) in arg_names.iter().enumerate() {
5688        if name.is_empty() {
5689            continue;
5690        }
5691        let shadowed = body_from_tables(stmt).iter().any(|t| {
5692            cat.get(t).is_some_and(|tb| {
5693                tb.schema()
5694                    .columns
5695                    .iter()
5696                    .any(|c| c.name.eq_ignore_ascii_case(name))
5697            })
5698        });
5699        if shadowed {
5700            continue;
5701        }
5702        let v = args.get(i).cloned().unwrap_or(Value::Null);
5703        let lit =
5704            crate::substitute::value_to_literal_expr(v).map_err(|e| EvalError::TypeMismatch {
5705                detail: alloc::format!("argument {name} cannot be bound into the body: {e}"),
5706            })?;
5707        binds.insert(name.to_ascii_lowercase(), lit);
5708    }
5709    substitute_arg_refs_in_select(&mut bound, &binds);
5710    Ok(bound)
5711}
5712
5713/// The base tables a function body's FROM names — used to decide whether an
5714/// argument name is shadowed by a column of the same name.
5715fn body_from_tables(
5716    stmt: &spg_sql::ast::SelectStatement,
5717) -> alloc::vec::Vec<alloc::string::String> {
5718    let mut out = alloc::vec::Vec::new();
5719    if let Some(from) = &stmt.from {
5720        out.push(from.primary.name.clone());
5721        for j in &from.joins {
5722            out.push(j.table.name.clone());
5723        }
5724    }
5725    out
5726}
5727
5728/// Replace every bare reference to an argument name with its literal value.
5729fn substitute_arg_refs_in_select(
5730    stmt: &mut spg_sql::ast::SelectStatement,
5731    binds: &alloc::collections::BTreeMap<alloc::string::String, spg_sql::ast::Expr>,
5732) {
5733    use spg_sql::ast::{Expr, SelectItem};
5734    fn walk(e: &mut Expr, binds: &alloc::collections::BTreeMap<alloc::string::String, Expr>) {
5735        match e {
5736            Expr::Column(c) => {
5737                if c.qualifier.is_none()
5738                    && let Some(lit) = binds.get(&c.name.to_ascii_lowercase())
5739                {
5740                    *e = lit.clone();
5741                }
5742            }
5743            Expr::Binary { lhs, rhs, .. } => {
5744                walk(lhs, binds);
5745                walk(rhs, binds);
5746            }
5747            Expr::Unary { expr, .. } | Expr::Cast { expr, .. } => walk(expr, binds),
5748            Expr::FunctionCall { args, .. } => args.iter_mut().for_each(|a| walk(a, binds)),
5749            Expr::Case {
5750                operand,
5751                branches,
5752                else_branch,
5753            } => {
5754                if let Some(o) = operand {
5755                    walk(o, binds);
5756                }
5757                for (c, v) in branches.iter_mut() {
5758                    walk(c, binds);
5759                    walk(v, binds);
5760                }
5761                if let Some(x) = else_branch {
5762                    walk(x, binds);
5763                }
5764            }
5765            Expr::InList { expr, list, .. } => {
5766                walk(expr, binds);
5767                list.iter_mut().for_each(|it| walk(it, binds));
5768            }
5769            Expr::AnyAll { expr, array, .. } => {
5770                walk(expr, binds);
5771                walk(array, binds);
5772            }
5773            Expr::Array(items) => items.iter_mut().for_each(|it| walk(it, binds)),
5774            Expr::ArraySubscript { target, index } => {
5775                walk(target, binds);
5776                walk(index, binds);
5777            }
5778            _ => {}
5779        }
5780    }
5781    for item in &mut stmt.items {
5782        if let SelectItem::Expr { expr, .. } = item {
5783            walk(expr, binds);
5784        }
5785    }
5786    if let Some(w) = &mut stmt.where_ {
5787        walk(w, binds);
5788    }
5789    if let Some(h) = &mut stmt.having {
5790        walk(h, binds);
5791    }
5792    if let Some(gs) = &mut stmt.group_by {
5793        gs.iter_mut().for_each(|g| walk(g, binds));
5794    }
5795    for o in &mut stmt.order_by {
5796        walk(&mut o.expr, binds);
5797    }
5798    if let Some(from) = &mut stmt.from {
5799        for j in &mut from.joins {
5800            if let Some(on) = &mut j.on {
5801                walk(on, binds);
5802            }
5803        }
5804    }
5805    // v7.39 (read01 round 69) — the UNION peers. A body like
5806    // `SELECT k UNION ALL SELECT k * 10` has its second half in `unions`, and
5807    // leaving it unsubstituted made the argument look like a missing column.
5808    for (_, peer) in &mut stmt.unions {
5809        substitute_arg_refs_in_select(peer, binds);
5810    }
5811    for cte in &mut stmt.ctes {
5812        if let Some(s) = cte.body.as_select_mut() {
5813            substitute_arg_refs_in_select(s, binds);
5814        }
5815    }
5816}
5817
5818/// v7.38.4 (sentori step 54) — the cast target for a function's DECLARED
5819/// return type.
5820///
5821/// `def.returns` holds the type as the user wrote it, so an array is
5822/// `bigint[]`; a `CastTarget::Named` spells the same type `bigint_array`.
5823/// The coercion therefore could not resolve `RETURNS bigint[]`, and the
5824/// `or_else(NULL)` under every call site turned "I could not coerce this"
5825/// into a NULL answer: the body computed `{1,2}` and the caller got
5826/// nothing, with no error anywhere. Their version keys compare through one
5827/// of these, so every version-targeted push reached zero devices while
5828/// reporting success.
5829///
5830/// Shared by both coercion sites — the pure-expression body and the one
5831/// with its own FROM — because they had the same line written twice and
5832/// fixing one would have left the other.
5833pub(crate) fn declared_return_cast_target(declared: &str) -> spg_sql::ast::CastTarget {
5834    let name = declared.trim().strip_suffix("[]").map_or_else(
5835        || alloc::string::String::from(declared.trim()),
5836        |base| alloc::format!("{}_array", base.trim()),
5837    );
5838    spg_sql::ast::CastTarget::Named(name)
5839}
5840
5841impl crate::Engine {
5842    /// v7.39 (read01 round 64) — call a plpgsql function as a scalar. The body
5843    /// runs on the interpreter the DO block and triggers already use, with the
5844    /// arguments bound as locals; its `SELECT … INTO` and `FOR … IN SELECT`
5845    /// resolvers go through the READ path, so what the body sees is what a
5846    /// hand-written query would see (visibility filter and all).
5847    ///
5848    /// A body that writes is refused — the call arrives through expression
5849    /// evaluation, which holds the engine immutably. Refusing is the honest
5850    /// answer; silently dropping the write would be the worst one.
5851    pub(crate) fn call_plpgsql_scalar_fn(
5852        &self,
5853        def: &spg_storage::FunctionDef,
5854        arg_names: &[alloc::string::String],
5855        args: &spg_storage::Row<'static>,
5856    ) -> Result<Value<'static>, EvalError> {
5857        let block =
5858            spg_sql::parse_function_body(def.body.trim()).map_err(|e| EvalError::TypeMismatch {
5859                detail: alloc::format!("function {:?} body does not parse: {e}", def.name),
5860            })?;
5861        let mut locals: alloc::collections::BTreeMap<alloc::string::String, Value<'static>> =
5862            alloc::collections::BTreeMap::new();
5863        for (i, n) in arg_names.iter().enumerate() {
5864            if n.is_empty() {
5865                continue;
5866            }
5867            locals.insert(
5868                n.to_ascii_lowercase(),
5869                args.values.get(i).cloned().unwrap_or(Value::Null),
5870            );
5871        }
5872        let dts = self
5873            .session_param("default_text_search_config")
5874            .map(alloc::string::String::from);
5875
5876        let select_into = |stmt: &spg_sql::ast::Statement| -> Result<
5877            Value<'static>,
5878            crate::triggers::TriggerError,
5879        > {
5880            let spg_sql::ast::Statement::Select(s) = stmt else {
5881                return Err(crate::triggers::TriggerError::EvalFailed {
5882                    function: def.name.clone(),
5883                    cause: EvalError::TypeMismatch {
5884                        detail: "SELECT … INTO body must be a SELECT".into(),
5885                    },
5886                });
5887            };
5888            let r = self
5889                .exec_select_cancel(s, crate::CancelToken::none())
5890                .map_err(|e| crate::triggers::TriggerError::EvalFailed {
5891                    function: def.name.clone(),
5892                    cause: EvalError::TypeMismatch {
5893                        detail: alloc::format!("SELECT … INTO failed: {e}"),
5894                    },
5895                })?;
5896            match r {
5897                crate::QueryResult::Rows { rows, .. } => Ok(rows
5898                    .into_iter()
5899                    .next()
5900                    .and_then(|row| row.values.into_iter().next())
5901                    .unwrap_or(Value::Null)),
5902                _ => Ok(Value::Null),
5903            }
5904        };
5905        let for_query = |stmt: &spg_sql::ast::Statement| -> Result<
5906            (
5907                alloc::vec::Vec<alloc::string::String>,
5908                alloc::vec::Vec<alloc::vec::Vec<Value<'static>>>,
5909            ),
5910            crate::triggers::TriggerError,
5911        > {
5912            let spg_sql::ast::Statement::Select(s) = stmt else {
5913                return Err(crate::triggers::TriggerError::EvalFailed {
5914                    function: def.name.clone(),
5915                    cause: EvalError::TypeMismatch {
5916                        detail: "FOR … IN body must be a SELECT".into(),
5917                    },
5918                });
5919            };
5920            let r = self
5921                .exec_select_cancel(s, crate::CancelToken::none())
5922                .map_err(|e| crate::triggers::TriggerError::EvalFailed {
5923                    function: def.name.clone(),
5924                    cause: EvalError::TypeMismatch {
5925                        detail: alloc::format!("FOR … IN SELECT failed: {e}"),
5926                    },
5927                })?;
5928            match r {
5929                crate::QueryResult::Rows { columns, rows } => Ok((
5930                    columns.iter().map(|c| c.name.clone()).collect(),
5931                    rows.into_iter().map(|row| row.values).collect(),
5932                )),
5933                _ => Ok((alloc::vec::Vec::new(), alloc::vec::Vec::new())),
5934            }
5935        };
5936
5937        let out = crate::triggers::call_plpgsql_scalar(
5938            &def.name,
5939            &block,
5940            locals,
5941            dts.as_deref(),
5942            Some(&select_into),
5943            Some(&for_query),
5944            // A scalar call has no set to build; RETURN NEXT / RETURN QUERY are
5945            // errors here, as in PG.
5946            // (second None below: the read path holds the engine immutably, so
5947            // RAISE messages have nowhere session-bound to go — B3 residual.)
5948            None,
5949            None,
5950        )
5951        .map_err(|e| EvalError::TypeMismatch {
5952            detail: alloc::format!("{e}"),
5953        })?;
5954        let declared = def.returns.trim();
5955        let Some(v) = out else {
5956            if declared.eq_ignore_ascii_case("VOID") {
5957                return Ok(Value::Null);
5958            }
5959            // PG: a non-void function that falls out of the bottom.
5960            return Err(EvalError::TypeMismatch {
5961                detail: alloc::format!(
5962                    "control reached end of function {:?} without RETURN",
5963                    def.name
5964                ),
5965            });
5966        };
5967        if declared.eq_ignore_ascii_case("VOID") {
5968            return Ok(Value::Null);
5969        }
5970        crate::eval::cast::cast_value(
5971            v.into_owned(),
5972            spg_sql::ast::CastTarget::Named(alloc::string::String::from(declared)),
5973        )
5974        .or_else(|_| Ok(Value::Null))
5975    }
5976}
5977
5978impl crate::Engine {
5979    /// v7.39 (read01 round 66) — run a `RETURNS SETOF` plpgsql function and
5980    /// collect the rows `RETURN NEXT` / `RETURN QUERY` appended. Same
5981    /// interpreter, same read-path resolvers as the scalar call — the only
5982    /// difference is that a SINK is provided, which is what makes those two
5983    /// statements legal.
5984    pub(crate) fn call_plpgsql_setof_fn(
5985        &self,
5986        def: &spg_storage::FunctionDef,
5987        arg_names: &[alloc::string::String],
5988        args: &[Value<'static>],
5989    ) -> Result<alloc::vec::Vec<alloc::vec::Vec<Value<'static>>>, EvalError> {
5990        let block =
5991            spg_sql::parse_function_body(def.body.trim()).map_err(|e| EvalError::TypeMismatch {
5992                detail: alloc::format!("function {:?} body does not parse: {e}", def.name),
5993            })?;
5994        let mut locals: alloc::collections::BTreeMap<alloc::string::String, Value<'static>> =
5995            alloc::collections::BTreeMap::new();
5996        for (i, n) in arg_names.iter().enumerate() {
5997            if n.is_empty() {
5998                continue;
5999            }
6000            locals.insert(
6001                n.to_ascii_lowercase(),
6002                args.get(i).cloned().unwrap_or(Value::Null),
6003            );
6004        }
6005        let dts = self
6006            .session_param("default_text_search_config")
6007            .map(alloc::string::String::from);
6008        let run_select = |stmt: &spg_sql::ast::Statement,
6009                          what: &str|
6010         -> Result<crate::QueryResult, crate::triggers::TriggerError> {
6011            let spg_sql::ast::Statement::Select(s) = stmt else {
6012                return Err(crate::triggers::TriggerError::EvalFailed {
6013                    function: def.name.clone(),
6014                    cause: EvalError::TypeMismatch {
6015                        detail: alloc::format!("{what} body must be a SELECT"),
6016                    },
6017                });
6018            };
6019            self.exec_select_cancel(s, crate::CancelToken::none())
6020                .map_err(|e| crate::triggers::TriggerError::EvalFailed {
6021                    function: def.name.clone(),
6022                    cause: EvalError::TypeMismatch {
6023                        detail: alloc::format!("{what} failed: {e}"),
6024                    },
6025                })
6026        };
6027        let select_into = |stmt: &spg_sql::ast::Statement| -> Result<
6028            Value<'static>,
6029            crate::triggers::TriggerError,
6030        > {
6031            match run_select(stmt, "SELECT … INTO")? {
6032                crate::QueryResult::Rows { rows, .. } => Ok(rows
6033                    .into_iter()
6034                    .next()
6035                    .and_then(|r| r.values.into_iter().next())
6036                    .unwrap_or(Value::Null)),
6037                _ => Ok(Value::Null),
6038            }
6039        };
6040        let for_query = |stmt: &spg_sql::ast::Statement| -> Result<
6041            (
6042                alloc::vec::Vec<alloc::string::String>,
6043                alloc::vec::Vec<alloc::vec::Vec<Value<'static>>>,
6044            ),
6045            crate::triggers::TriggerError,
6046        > {
6047            match run_select(stmt, "FOR … IN / RETURN QUERY")? {
6048                crate::QueryResult::Rows { columns, rows } => Ok((
6049                    columns.iter().map(|c| c.name.clone()).collect(),
6050                    rows.into_iter().map(|r| r.values).collect(),
6051                )),
6052                _ => Ok((alloc::vec::Vec::new(), alloc::vec::Vec::new())),
6053            }
6054        };
6055        let sink: core::cell::RefCell<alloc::vec::Vec<alloc::vec::Vec<Value<'static>>>> =
6056            core::cell::RefCell::new(alloc::vec::Vec::new());
6057        crate::triggers::call_plpgsql_scalar(
6058            &def.name,
6059            &block,
6060            locals,
6061            dts.as_deref(),
6062            Some(&select_into),
6063            Some(&for_query),
6064            Some(&sink),
6065            // Read path — immutable engine borrow; B3 residual.
6066            None,
6067        )
6068        .map_err(|e| EvalError::TypeMismatch {
6069            detail: alloc::format!("{e}"),
6070        })?;
6071        Ok(sink.into_inner())
6072    }
6073}
6074
6075/// v7.39 (round 236) — resolve an ARRAY constructor's element types the way
6076/// PG does. Typed elements must share a type category; a bare string or NULL
6077/// literal is untyped and converts to whatever the typed elements resolved
6078/// to, reporting the value (not a type mismatch) when it will not convert.
6079fn unify_array_elements(
6080    items: &[Expr],
6081    materialised: &mut [Value<'static>],
6082) -> Result<(), EvalError> {
6083    unify_construct_values("ARRAY", items, materialised)
6084}
6085
6086/// v7.39 (round 238) — an `IN (...)` list must be comparable with its
6087/// needle. Reports the operator the way PG does
6088/// ("operator does not exist: integer = text"), and — like round 237 —
6089/// judges only the operands whose type is genuinely known.
6090fn require_in_list_comparable(
6091    needle: &Expr,
6092    list: &[Expr],
6093    ctx: &EvalContext<'_>,
6094) -> Result<(), EvalError> {
6095    let known_ty = |e: &Expr| {
6096        matches!(e, Expr::Cast { .. } | Expr::Literal(_) | Expr::Column(_))
6097            .then(|| crate::describe::describe_expr(e, ctx.columns).map(|s| s.ty))
6098            .flatten()
6099    };
6100    // An untyped literal adopts the needle's type, so it never conflicts.
6101    //
6102    // v7.39 (round 652) — and so does a cast to one of the reg types.
6103    // `'pg_class'::regclass` carries an oid AND a name, which is why
6104    // `compare` has arms for both, but it DESCRIBES as text — SPG has no
6105    // `DataType` for it. This check ran before any comparison and
6106    // refused `WHERE oid IN ('pg_class'::regclass, …)` as `bigint =
6107    // text`, while the identical `oid = 'pg_class'::regclass` worked.
6108    // That shape is how pg_dump, ORMs and monitoring queries name a
6109    // handful of relations at once, so it is not a corner.
6110    let reg_cast = |e: &Expr| {
6111        match e {
6112            Expr::Cast { target, .. } => match target {
6113                spg_sql::ast::CastTarget::RegClass | spg_sql::ast::CastTarget::RegType => true,
6114                // `regproc` and `regnamespace` have no variant of their
6115                // own; they arrive through the generic named path.
6116                spg_sql::ast::CastTarget::Named(n) => {
6117                    n.eq_ignore_ascii_case("regproc")
6118                        || n.eq_ignore_ascii_case("regnamespace")
6119                        || n.eq_ignore_ascii_case("regtype")
6120                        || n.eq_ignore_ascii_case("regclass")
6121                }
6122                _ => false,
6123            },
6124            _ => false,
6125        }
6126    };
6127    let untyped = |e: &Expr| {
6128        reg_cast(e)
6129            || matches!(
6130                e,
6131                Expr::Literal(spg_sql::ast::Literal::String(_))
6132                    | Expr::Literal(spg_sql::ast::Literal::Null)
6133            )
6134    };
6135    // The needle can be untyped too (`NULL IN (1,2)`): SPG has no `Unknown`
6136    // DataType, so a bare NULL describes as TEXT and would look like a text
6137    // needle conflicting with integer list items.
6138    if untyped(needle) {
6139        return Ok(());
6140    }
6141    let Some(nt) = known_ty(needle) else {
6142        return Ok(());
6143    };
6144    for item in list {
6145        if untyped(item) {
6146            continue;
6147        }
6148        let Some(it) = known_ty(item) else { continue };
6149        if !crate::conversions::types_unify(nt, it) {
6150            return Err(EvalError::TypeMismatch {
6151                detail: alloc::format!(
6152                    "operator does not exist: {} = {}",
6153                    crate::conversions::pg_type_name_for_error(nt),
6154                    crate::conversions::pg_type_name_for_error(it),
6155                ),
6156            });
6157        }
6158    }
6159    Ok(())
6160}
6161
6162/// v7.39 (round 237) — STATIC branch-type resolution for the constructs
6163/// whose branches must not all be evaluated: CASE runs only the branch it
6164/// takes, and a COALESCE / GREATEST argument may have side effects
6165/// (`COALESCE(nextval('s'), 1)`), so the check reads each branch's declared
6166/// type instead of its value. Same rule and wording as the value-driven
6167/// ARRAY path below; an untyped literal is converted here (a literal has no
6168/// side effects) so a value that will not convert is reported as PG does.
6169/// v7.39 (round 609) — takes anything that yields the branches, so the
6170/// COALESCE caller no longer builds a `Vec<&Expr>` of them for every row.
6171pub(crate) fn unify_branch_types_static<'e>(
6172    construct: &str,
6173    branches: impl IntoIterator<Item = &'e Expr> + Clone,
6174    ctx: &EvalContext<'_>,
6175) -> Result<(), EvalError> {
6176    use spg_storage::DataType;
6177    let untyped = |e: &Expr| {
6178        matches!(
6179            e,
6180            Expr::Literal(spg_sql::ast::Literal::String(_))
6181                | Expr::Literal(spg_sql::ast::Literal::Null)
6182        )
6183    };
6184    let mut resolved: Option<DataType> = None;
6185    for e in branches.clone() {
6186        if untyped(e) {
6187            continue;
6188        }
6189        // Only branches whose type is GENUINELY known take part. A general
6190        // `describe_expr` is a best-effort hint for wire type tags, not a
6191        // type checker: it reports a binary operator as its left operand's
6192        // type, so `payload->'a'` (jsonb in PG) came back as text and this
6193        // check refused a working `COALESCE(payload->'a', '{}'::jsonb)`.
6194        // Refusing a valid query is worse than missing an invalid one, so
6195        // the check confines itself to an explicit cast, a typed literal and
6196        // a plain column reference.
6197        let known = matches!(e, Expr::Cast { .. } | Expr::Literal(_) | Expr::Column(_));
6198        if !known {
6199            continue;
6200        }
6201        // 7.38.1 S5.1 — a reg* cast is an OID wearing a name: describe
6202        // says Text (the wire render), but it compares and unions with
6203        // numeric catalog columns (pg_dump: `SELECT classid … UNION
6204        // ALL SELECT 'pg_opfamily'::regclass …`). Its static claim is
6205        // not genuinely known here, so it sits the check out — the
6206        // dual RegClass value reconciles at runtime.
6207        if matches!(
6208            e,
6209            Expr::Cast {
6210                target: spg_sql::ast::CastTarget::RegType | spg_sql::ast::CastTarget::RegClass,
6211                ..
6212            }
6213        ) {
6214            continue;
6215        }
6216        let Some(ty) = crate::describe::describe_expr_type(e, ctx.columns) else {
6217            continue;
6218        };
6219        match resolved {
6220            None => resolved = Some(ty),
6221            Some(prev) if crate::conversions::types_unify(prev, ty) => {
6222                if matches!(prev, DataType::Int | DataType::SmallInt) {
6223                    resolved = Some(ty);
6224                }
6225            }
6226            Some(prev) => {
6227                return Err(EvalError::TypeMismatch {
6228                    detail: alloc::format!(
6229                        "{construct} types {} and {} cannot be matched",
6230                        crate::conversions::pg_type_name_for_error(prev),
6231                        crate::conversions::pg_type_name_for_error(ty),
6232                    ),
6233                });
6234            }
6235        }
6236    }
6237    let Some(target) = resolved else {
6238        return Ok(());
6239    };
6240    if matches!(target, DataType::Text) {
6241        return Ok(());
6242    }
6243    // v7.39 (round 398) — MySQL aggregates a mixed int/string CASE /
6244    // COALESCE to a string (`CASE WHEN 1 THEN 1 ELSE 'x' END` is '1', not an
6245    // error); PG requires the untyped string literals to coerce to the
6246    // resolved numeric type, so it refuses. Under the dialect, skip that
6247    // coercion check — the value is returned as-is / widened by the caller.
6248    if ctx.mysql_dialect {
6249        return Ok(());
6250    }
6251    for e in branches {
6252        if !untyped(e) {
6253            continue;
6254        }
6255        if let Expr::Literal(spg_sql::ast::Literal::String(lit)) = e {
6256            crate::conversions::coerce_value(Value::text(lit.clone()), target, "", 0).map_err(
6257                |err| match err {
6258                    crate::EngineError::Eval(ev) => ev,
6259                    other => EvalError::TypeMismatch {
6260                        detail: alloc::format!("{other}"),
6261                    },
6262                },
6263            )?;
6264        }
6265    }
6266    Ok(())
6267}
6268
6269/// v7.39 (round 237) — the same resolution for every construct that builds
6270/// one value out of several branches: ARRAY, CASE, COALESCE, GREATEST and
6271/// LEAST. PG names the construct in the message ("CASE types text and
6272/// integer cannot be matched"), which is why the caller passes it in.
6273pub(crate) fn unify_construct_values(
6274    construct: &str,
6275    items: &[Expr],
6276    materialised: &mut [Value<'static>],
6277) -> Result<(), EvalError> {
6278    use spg_storage::DataType;
6279    let untyped = |e: &Expr| {
6280        matches!(
6281            e,
6282            Expr::Literal(spg_sql::ast::Literal::String(_))
6283                | Expr::Literal(spg_sql::ast::Literal::Null)
6284        )
6285    };
6286    // The type the typed elements agree on, if any.
6287    let mut resolved: Option<DataType> = None;
6288    for (i, v) in materialised.iter().enumerate() {
6289        if items.get(i).is_some_and(untyped) {
6290            continue;
6291        }
6292        let Some(ty) = v.data_type() else { continue };
6293        match resolved {
6294            None => resolved = Some(ty),
6295            Some(prev) if crate::conversions::types_unify(prev, ty) => {
6296                // Keep the wider of the two so the coercion below targets it.
6297                if matches!(prev, DataType::Int | DataType::SmallInt) {
6298                    resolved = Some(ty);
6299                }
6300            }
6301            Some(prev) => {
6302                return Err(EvalError::TypeMismatch {
6303                    detail: alloc::format!(
6304                        "{construct} types {} and {} cannot be matched",
6305                        crate::conversions::pg_type_name_for_error(prev),
6306                        crate::conversions::pg_type_name_for_error(ty),
6307                    ),
6308                });
6309            }
6310        }
6311    }
6312    // Untyped literals adopt that type; a failure names the value, as PG does.
6313    let Some(target) = resolved else {
6314        return Ok(());
6315    };
6316    if matches!(target, DataType::Text) {
6317        return Ok(());
6318    }
6319    for (i, v) in materialised.iter_mut().enumerate() {
6320        if !items.get(i).is_some_and(untyped) || matches!(v, Value::Null) {
6321            continue;
6322        }
6323        *v = crate::conversions::coerce_value(v.clone(), target, "", i).map_err(|e| match e {
6324            crate::EngineError::Eval(ev) => ev,
6325            other => EvalError::TypeMismatch {
6326                detail: alloc::format!("{other}"),
6327            },
6328        })?;
6329    }
6330    Ok(())
6331}
6332
6333/// v7.39 (round 309, V30) — split `'<timestamp> <zone name>'` into the
6334/// wall-clock reading and the zone token, for the zone-less target types.
6335///
6336/// Returns `None` when the literal parses on its own (nothing to strip)
6337/// or when the trailing token is not zone-SHAPED — those keep the
6338/// ordinary "invalid input syntax" path, which is what PG answers for
6339/// `'2020-01-01 10:00:00 xyz'`. Whether a zone-shaped token is a REAL
6340/// zone is the caller's question; getting that wrong is a different
6341/// error in PG, and conflating the two would report a malformed literal
6342/// for a merely-misspelled zone.
6343///
6344/// Deliberately does not accept a bare time (`'10:00:00 America/New_York'`):
6345/// PG refuses a named zone there, and only reaches this spelling through
6346/// a full timestamp literal.
6347fn split_trailing_zone_name(txt: &str, order: format::DateOrder) -> Option<(i64, &str)> {
6348    // Already valid without help — leave it alone.
6349    if format::parse_timestamp_literal_wall_ordered(txt, order).is_some() {
6350        return None;
6351    }
6352    let trimmed = txt.trim_end();
6353    let idx = trimmed.rfind(' ')?;
6354    let (head, tail) = (trimmed[..idx].trim(), trimmed[idx + 1..].trim());
6355    // An era marker is part of the timestamp, not a zone.
6356    let zone_shaped = tail.len() > 1
6357        && tail.bytes().any(|b| b.is_ascii_alphabetic())
6358        && !tail.eq_ignore_ascii_case("bc")
6359        && !tail.eq_ignore_ascii_case("ad");
6360    if !zone_shaped {
6361        return None;
6362    }
6363    let wall = format::parse_timestamp_literal_wall_ordered(head, order)?;
6364    Some((wall, tail))
6365}
6366
6367#[cfg(test)]
6368mod tests {
6369    use super::*;
6370    use alloc::vec;
6371    use spg_sql::ast::UnOp;
6372    use spg_storage::{ColumnSchema, DataType, Row};
6373
6374    fn col(name: &str, ty: DataType) -> ColumnSchema {
6375        ColumnSchema::new(name, ty, true)
6376    }
6377
6378    fn ctx<'a>(cols: &'a [ColumnSchema], alias: Option<&'a str>) -> EvalContext<'a> {
6379        EvalContext::new(cols, alias)
6380    }
6381
6382    /// v7.32 (P4 borrow channel) differential: the borrowed comparison
6383    /// fast path in `eval_expr`'s Binary arm must be byte-for-byte the
6384    /// pre-P4 owned path (`apply_binary` on cloned operands) across a
6385    /// cross-type value matrix and every comparison operator — covering
6386    /// the fast-path types (Text/Int/Float/Date/Timestamp/Bool/Null) and
6387    /// the owned-fallback types (Numeric/Interval).
6388    #[test]
6389    fn borrowed_compare_equals_owned_apply_binary() {
6390        let vals = vec![
6391            Value::Null,
6392            Value::Bool(true),
6393            Value::Bool(false),
6394            Value::SmallInt(3),
6395            Value::Int(3),
6396            Value::Int(-1),
6397            Value::BigInt(3),
6398            Value::BigInt(100),
6399            Value::Float(3.0),
6400            Value::Float(2.5),
6401            Value::text(String::new()),
6402            Value::text("a"),
6403            Value::text("b"),
6404            Value::Date(10),
6405            Value::Timestamp(1000),
6406            Value::Numeric {
6407                scaled: 30,
6408                scale: 1,
6409                kind: spg_storage::NumericKind::Finite,
6410            },
6411            Value::Interval {
6412                months: 0,
6413                days: 0,
6414                micros: 5,
6415            },
6416        ];
6417        let ops = [
6418            BinOp::Eq,
6419            BinOp::NotEq,
6420            BinOp::Lt,
6421            BinOp::LtEq,
6422            BinOp::Gt,
6423            BinOp::GtEq,
6424        ];
6425        let cs = vec![col("x", DataType::Int), col("y", DataType::Int)];
6426        let c = ctx(&cs, None);
6427        let lhs = Expr::Column(ColumnName {
6428            qualifier: None,
6429            name: "x".into(),
6430        });
6431        let rhs = Expr::Column(ColumnName {
6432            qualifier: None,
6433            name: "y".into(),
6434        });
6435        for l in &vals {
6436            for r in &vals {
6437                let row = Row::new(vec![l.clone(), r.clone()]);
6438                for op in ops {
6439                    let got = eval_expr(
6440                        &Expr::Binary {
6441                            lhs: alloc::boxed::Box::new(lhs.clone()),
6442                            op,
6443                            rhs: alloc::boxed::Box::new(rhs.clone()),
6444                        },
6445                        &row,
6446                        &c,
6447                    );
6448                    // Pre-P4 reference: owned operands through apply_binary
6449                    // (collation fold is a no-op for non-CI columns).
6450                    let want = apply_binary(op, l.clone(), r.clone());
6451                    assert_eq!(
6452                        format!("{got:?}"),
6453                        format!("{want:?}"),
6454                        "op={op:?} l={l:?} r={r:?}"
6455                    );
6456                }
6457            }
6458        }
6459    }
6460
6461    fn lit(n: i64) -> Expr {
6462        Expr::Literal(Literal::Integer(n))
6463    }
6464
6465    fn null() -> Expr {
6466        Expr::Literal(Literal::Null)
6467    }
6468
6469    fn col_ref(name: &str) -> Expr {
6470        Expr::Column(ColumnName {
6471            qualifier: None,
6472            name: name.into(),
6473        })
6474    }
6475
6476    #[test]
6477    fn literal_evaluates_to_value() {
6478        let r = Row::new(vec![]);
6479        let cs: [ColumnSchema; 0] = [];
6480        let c = ctx(&cs, None);
6481        assert_eq!(eval_expr(&lit(42), &r, &c).unwrap(), Value::Int(42));
6482        assert_eq!(
6483            eval_expr(&Expr::Literal(Literal::Float(1.5)), &r, &c).unwrap(),
6484            Value::Float(1.5)
6485        );
6486        assert_eq!(eval_expr(&null(), &r, &c).unwrap(), Value::Null);
6487    }
6488
6489    #[test]
6490    fn column_lookup_unqualified() {
6491        let cs = vec![col("a", DataType::Int), col("b", DataType::Text)];
6492        let r = Row::new(vec![Value::Int(7), Value::text("hi")]);
6493        let c = ctx(&cs, None);
6494        assert_eq!(eval_expr(&col_ref("a"), &r, &c).unwrap(), Value::Int(7));
6495        assert_eq!(eval_expr(&col_ref("b"), &r, &c).unwrap(), Value::text("hi"));
6496    }
6497
6498    #[test]
6499    fn column_not_found_errors() {
6500        let cs = vec![col("a", DataType::Int)];
6501        let r = Row::new(vec![Value::Int(0)]);
6502        let c = ctx(&cs, None);
6503        let err = eval_expr(&col_ref("ghost"), &r, &c).unwrap_err();
6504        assert!(matches!(err, EvalError::ColumnNotFound { ref name } if name == "ghost"));
6505    }
6506
6507    #[test]
6508    fn qualified_column_matches_alias() {
6509        let cs = vec![col("a", DataType::Int)];
6510        let r = Row::new(vec![Value::Int(5)]);
6511        let c = ctx(&cs, Some("u"));
6512        let qualified = Expr::Column(ColumnName {
6513            qualifier: Some("u".into()),
6514            name: "a".into(),
6515        });
6516        assert_eq!(eval_expr(&qualified, &r, &c).unwrap(), Value::Int(5));
6517    }
6518
6519    #[test]
6520    fn qualified_column_unknown_alias_errors() {
6521        let cs = vec![col("a", DataType::Int)];
6522        let r = Row::new(vec![Value::Int(5)]);
6523        let c = ctx(&cs, Some("u"));
6524        let wrong = Expr::Column(ColumnName {
6525            qualifier: Some("x".into()),
6526            name: "a".into(),
6527        });
6528        assert!(matches!(
6529            eval_expr(&wrong, &r, &c).unwrap_err(),
6530            EvalError::UnknownQualifier { .. }
6531        ));
6532    }
6533
6534    #[test]
6535    fn arithmetic_with_widening() {
6536        let r = Row::new(vec![]);
6537        let cs: [ColumnSchema; 0] = [];
6538        let c = ctx(&cs, None);
6539        let e = Expr::Binary {
6540            lhs: alloc::boxed::Box::new(lit(2)),
6541            op: BinOp::Add,
6542            rhs: alloc::boxed::Box::new(Expr::Literal(Literal::Float(0.5))),
6543        };
6544        assert_eq!(eval_expr(&e, &r, &c).unwrap(), Value::Float(2.5));
6545    }
6546
6547    #[test]
6548    fn division_by_zero_errors() {
6549        let r = Row::new(vec![]);
6550        let cs: [ColumnSchema; 0] = [];
6551        let c = ctx(&cs, None);
6552        let e = Expr::Binary {
6553            lhs: alloc::boxed::Box::new(lit(1)),
6554            op: BinOp::Div,
6555            rhs: alloc::boxed::Box::new(lit(0)),
6556        };
6557        assert_eq!(
6558            eval_expr(&e, &r, &c).unwrap_err(),
6559            EvalError::DivisionByZero
6560        );
6561    }
6562
6563    #[test]
6564    fn comparison_returns_bool() {
6565        let r = Row::new(vec![]);
6566        let cs: [ColumnSchema; 0] = [];
6567        let c = ctx(&cs, None);
6568        let e = Expr::Binary {
6569            lhs: alloc::boxed::Box::new(lit(1)),
6570            op: BinOp::Lt,
6571            rhs: alloc::boxed::Box::new(lit(2)),
6572        };
6573        assert_eq!(eval_expr(&e, &r, &c).unwrap(), Value::Bool(true));
6574    }
6575
6576    #[test]
6577    fn null_propagates_through_arithmetic() {
6578        let r = Row::new(vec![]);
6579        let cs: [ColumnSchema; 0] = [];
6580        let c = ctx(&cs, None);
6581        let e = Expr::Binary {
6582            lhs: alloc::boxed::Box::new(lit(1)),
6583            op: BinOp::Add,
6584            rhs: alloc::boxed::Box::new(null()),
6585        };
6586        assert_eq!(eval_expr(&e, &r, &c).unwrap(), Value::Null);
6587    }
6588
6589    #[test]
6590    fn stack_depth_guard_trips_on_pathological_nesting() {
6591        // Built directly as an AST — the parser's own budgets (256
6592        // chained binary operators, 64 nesting levels) reject such SQL
6593        // long before eval sees it, so this exercises the eval-side
6594        // guard on its own. 30 000 frames overshoot the 768 KiB budget
6595        // at any conceivable frame size; the guard errors at the byte
6596        // budget, far below the worker stack, so deeper is safer.
6597        let mut e = Expr::Literal(Literal::Bool(true));
6598        for _ in 0..30_000 {
6599            e = Expr::Binary {
6600                lhs: alloc::boxed::Box::new(e),
6601                op: BinOp::And,
6602                rhs: alloc::boxed::Box::new(Expr::Literal(Literal::Bool(true))),
6603            };
6604        }
6605        let r = Row::new(vec![]);
6606        let cs: [ColumnSchema; 0] = [];
6607        let c = ctx(&cs, None);
6608        let err = eval_expr(&e, &r, &c).unwrap_err();
6609        assert!(matches!(err, EvalError::StackDepthExceeded), "{err:?}");
6610        // Dropping a 30 000-deep Box chain recurses in the drop glue —
6611        // deeper than the eval guard allows the EVAL side to go — so
6612        // leak it rather than gamble on the test thread's stack.
6613        core::mem::forget(e);
6614    }
6615
6616    #[test]
6617    fn and_three_valued_logic() {
6618        let r = Row::new(vec![]);
6619        let cs: [ColumnSchema; 0] = [];
6620        let c = ctx(&cs, None);
6621        let tt = |a: bool, b_null: bool| Expr::Binary {
6622            lhs: alloc::boxed::Box::new(Expr::Literal(Literal::Bool(a))),
6623            op: BinOp::And,
6624            rhs: alloc::boxed::Box::new(if b_null {
6625                null()
6626            } else {
6627                Expr::Literal(Literal::Bool(true))
6628            }),
6629        };
6630        // FALSE AND NULL → FALSE
6631        assert_eq!(
6632            eval_expr(&tt(false, true), &r, &c).unwrap(),
6633            Value::Bool(false)
6634        );
6635        // TRUE AND NULL → NULL
6636        assert_eq!(eval_expr(&tt(true, true), &r, &c).unwrap(), Value::Null);
6637        // TRUE AND TRUE → TRUE
6638        assert_eq!(
6639            eval_expr(&tt(true, false), &r, &c).unwrap(),
6640            Value::Bool(true)
6641        );
6642    }
6643
6644    #[test]
6645    fn or_three_valued_logic() {
6646        let r = Row::new(vec![]);
6647        let cs: [ColumnSchema; 0] = [];
6648        let c = ctx(&cs, None);
6649        let or_with_null = |a: bool| Expr::Binary {
6650            lhs: alloc::boxed::Box::new(Expr::Literal(Literal::Bool(a))),
6651            op: BinOp::Or,
6652            rhs: alloc::boxed::Box::new(null()),
6653        };
6654        // TRUE OR NULL → TRUE
6655        assert_eq!(
6656            eval_expr(&or_with_null(true), &r, &c).unwrap(),
6657            Value::Bool(true)
6658        );
6659        // FALSE OR NULL → NULL
6660        assert_eq!(
6661            eval_expr(&or_with_null(false), &r, &c).unwrap(),
6662            Value::Null
6663        );
6664    }
6665
6666    #[test]
6667    fn not_on_null_is_null() {
6668        let r = Row::new(vec![]);
6669        let cs: [ColumnSchema; 0] = [];
6670        let c = ctx(&cs, None);
6671        let e = Expr::Unary {
6672            op: UnOp::Not,
6673            expr: alloc::boxed::Box::new(null()),
6674        };
6675        assert_eq!(eval_expr(&e, &r, &c).unwrap(), Value::Null);
6676    }
6677
6678    #[test]
6679    fn text_comparison_lexicographic() {
6680        let r = Row::new(vec![]);
6681        let cs: [ColumnSchema; 0] = [];
6682        let c = ctx(&cs, None);
6683        let e = Expr::Binary {
6684            lhs: alloc::boxed::Box::new(Expr::Literal(Literal::String("apple".into()))),
6685            op: BinOp::Lt,
6686            rhs: alloc::boxed::Box::new(Expr::Literal(Literal::String("banana".into()))),
6687        };
6688        assert_eq!(eval_expr(&e, &r, &c).unwrap(), Value::Bool(true));
6689    }
6690
6691    #[test]
6692    fn interval_format_basics() {
6693        // v7.37.5 β — three-arg signature. PG byte-equal:
6694        // `'1 day'` ≠ `'24 hours'` now, the format reflects it.
6695        assert_eq!(format_interval(0, 0, 0), "00:00:00");
6696        assert_eq!(format_interval(0, 1, 0), "1 day");
6697        assert_eq!(format_interval(0, -1, 0), "-1 days");
6698        assert_eq!(format_interval(0, 0, 86_400_000_000), "24:00:00");
6699        assert_eq!(format_interval(0, 0, 3_600_000_000), "01:00:00");
6700        assert_eq!(format_interval(0, 1, 9_000_000), "1 day 00:00:09");
6701        assert_eq!(format_interval(14, 0, 0), "1 year 2 mons");
6702        assert_eq!(format_interval(-1, 0, 0), "-1 mons");
6703    }
6704
6705    #[test]
6706    fn interval_format_pg_byte_equal_day_vs_24h() {
6707        // v7.37.5 β — the PG-canonical distinction `'1 day'` ≠ `'24 hours'`
6708        // is preserved in the formatter, not just the parser.
6709        assert_eq!(format_interval(0, 1, 0), "1 day");
6710        assert_eq!(format_interval(0, 0, 86_400_000_000), "24:00:00");
6711        assert_ne!(
6712            format_interval(0, 1, 0),
6713            format_interval(0, 0, 86_400_000_000),
6714        );
6715    }
6716}