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