Skip to main content

spg_engine/
lib.rs

1//! SPG execution engine — v0.3 wires the SQL front-end to the in-memory
2//! storage layer. Implements `CREATE TABLE`, single-row `INSERT VALUES`, and
3//! `SELECT * FROM <table>` (no WHERE yet — that lands in v0.4 alongside
4//! expression evaluation against rows).
5#![no_std]
6
7extern crate alloc;
8
9pub mod aggregate;
10pub mod describe;
11pub mod eval;
12pub mod json;
13pub mod memoize;
14pub mod plan_cache;
15pub mod publications;
16pub mod query_stats;
17pub mod reorder;
18pub mod selectivity;
19pub mod statistics;
20pub mod subscriptions;
21pub mod users;
22
23pub use crate::users::{Role, ScramSecrets, UserError, UserStore};
24
25use alloc::borrow::Cow;
26use alloc::boxed::Box;
27use alloc::collections::BTreeMap;
28use alloc::string::{String, ToString};
29use alloc::vec::Vec;
30use core::fmt;
31
32use spg_sql::ast::{
33    BinOp, ColumnDef, ColumnName, ColumnTypeName, CreateIndexStatement, CreatePublicationStatement,
34    CreateSubscriptionStatement, CreateTableStatement, CreateUserStatement, Expr, FrameBound,
35    FrameKind, FromClause, IndexMethod, InsertStatement, JoinKind, Literal, OrderBy, SelectItem,
36    SelectStatement, Statement, TableRef, UnOp, UnionKind, VecEncoding as SqlVecEncoding,
37    WindowFrame,
38};
39use spg_sql::parser::{self, ParseError};
40use spg_storage::{
41    Catalog, ColumnSchema, CompactReport, DataType, IndexKey, IndexKind, Row, StorageError, Table,
42    TableSchema, Value, VecEncoding,
43};
44
45use crate::eval::{EvalContext, EvalError};
46
47/// Result of executing one statement.
48#[derive(Debug, Clone, PartialEq)]
49#[non_exhaustive]
50pub enum QueryResult {
51    /// DDL or DML succeeded.
52    ///
53    /// `affected` is the row count for `INSERT` and 0 elsewhere.
54    /// `modified_catalog` tells the server whether this statement
55    /// caused the *committed* catalog to change — it's the signal to
56    /// snapshot/audit. False for `BEGIN`/`ROLLBACK`, false for writeful
57    /// statements executed inside a transaction (those only touch the
58    /// shadow), and true for `COMMIT` and for writes outside a TX.
59    CommandOk {
60        affected: usize,
61        modified_catalog: bool,
62    },
63    /// `SELECT` returned a (possibly empty) row set.
64    Rows {
65        columns: Vec<ColumnSchema>,
66        rows: Vec<Row>,
67    },
68}
69
70/// All errors the engine can return.
71///
72/// Marked `#[non_exhaustive]` from v7.5.0 onward: external `match`
73/// must include a `_` arm so new variants in subsequent v7.x releases
74/// are not breaking changes.
75#[derive(Debug, Clone, PartialEq)]
76#[non_exhaustive]
77pub enum EngineError {
78    Parse(ParseError),
79    Storage(StorageError),
80    Eval(EvalError),
81    /// Front-end accepted a construct that the v0.x executor doesn't support.
82    Unsupported(String),
83    /// `BEGIN` while another transaction is already open.
84    TransactionAlreadyOpen,
85    /// `COMMIT` / `ROLLBACK` with no active transaction.
86    NoActiveTransaction,
87    /// v4.0 sentinel: `execute_readonly` got a statement that
88    /// mutates engine state (INSERT / CREATE / BEGIN / COMMIT / …).
89    /// The caller should retake the write lock and dispatch through
90    /// `execute(&mut self)` instead.
91    WriteRequired,
92    /// v4.2: a SELECT would have returned more rows than the
93    /// configured `max_query_rows` cap. Carries the cap.
94    RowLimitExceeded(usize),
95    /// v4.5: cooperative cancellation — the host (server's
96    /// per-query watchdog) set the cancel flag while a long-running
97    /// SELECT / UPDATE / DELETE was scanning rows. The partial work
98    /// is discarded; the caller should surface this as a timeout
99    /// to the client.
100    Cancelled,
101}
102
103impl fmt::Display for EngineError {
104    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
105        match self {
106            Self::Parse(e) => write!(f, "parse: {e}"),
107            Self::Storage(e) => write!(f, "storage: {e}"),
108            Self::Eval(e) => write!(f, "eval: {e}"),
109            Self::Unsupported(s) => write!(f, "unsupported: {s}"),
110            Self::TransactionAlreadyOpen => f.write_str("a transaction is already open"),
111            Self::NoActiveTransaction => f.write_str("no active transaction"),
112            Self::WriteRequired => {
113                f.write_str("statement requires a write lock (use execute, not execute_readonly)")
114            }
115            Self::RowLimitExceeded(n) => {
116                write!(f, "query exceeded max_query_rows={n}")
117            }
118            Self::Cancelled => f.write_str("query cancelled (timeout or client request)"),
119        }
120    }
121}
122
123impl From<ParseError> for EngineError {
124    fn from(e: ParseError) -> Self {
125        Self::Parse(e)
126    }
127}
128impl From<StorageError> for EngineError {
129    fn from(e: StorageError) -> Self {
130        Self::Storage(e)
131    }
132}
133impl From<EvalError> for EngineError {
134    fn from(e: EvalError) -> Self {
135        Self::Eval(e)
136    }
137}
138
139/// The execution engine. Holds the catalog and (later) other server-scope
140/// state. `Engine::new()` is intentionally cheap so callers can construct one
141/// per database, per test.
142/// Function pointer that returns "now" as microseconds since Unix
143/// epoch. The engine is `no_std`, so it can't reach for `std::time`
144/// itself — callers (`spg-server`, the sqllogictest runner) inject a
145/// concrete implementation. `None` means `NOW()` / `CURRENT_*` raise
146/// `Unsupported`.
147pub type ClockFn = fn() -> i64;
148
149/// Function pointer that produces 16 cryptographically random bytes.
150/// Like `ClockFn`, the engine is `no_std` and can't reach for /dev/urandom
151/// itself — host (`spg-server`) injects an OS-backed source. `None`
152/// means SQL-driven `CREATE USER` falls back to a deterministic salt
153/// derived from the username (acceptable in tests; the server always
154/// installs a real RNG so production paths never see this).
155pub type SaltFn = fn() -> [u8; 16];
156
157/// v4.5 cooperative cancellation token. A long-running SELECT /
158/// UPDATE / DELETE checks `is_cancelled` at row-loop checkpoints
159/// and bails with `EngineError::Cancelled`. The host
160/// (`spg-server`) creates an `AtomicBool` per query, spawns a
161/// watchdog thread that sets it after `SPG_QUERY_TIMEOUT_MS`,
162/// and passes it via `execute_with_cancel` / `execute_readonly_with_cancel`.
163///
164/// `CancelToken::none()` is a no-op — used by the legacy `execute`
165/// and `execute_readonly` entry points so existing callers don't
166/// change.
167#[derive(Debug, Clone, Copy)]
168pub struct CancelToken<'a> {
169    flag: Option<&'a core::sync::atomic::AtomicBool>,
170}
171
172impl<'a> CancelToken<'a> {
173    #[must_use]
174    pub const fn none() -> Self {
175        Self { flag: None }
176    }
177
178    #[must_use]
179    pub const fn from_flag(f: &'a core::sync::atomic::AtomicBool) -> Self {
180        Self { flag: Some(f) }
181    }
182
183    #[must_use]
184    pub fn is_cancelled(self) -> bool {
185        self.flag
186            .is_some_and(|f| f.load(core::sync::atomic::Ordering::Relaxed))
187    }
188
189    /// Returns `Err(Cancelled)` if the token has been tripped.
190    /// Used at row-loop checkpoints to bail cooperatively without
191    /// scattering raw `is_cancelled` checks across the executor.
192    #[inline]
193    pub fn check(self) -> Result<(), EngineError> {
194        if self.is_cancelled() {
195            Err(EngineError::Cancelled)
196        } else {
197            Ok(())
198        }
199    }
200}
201
202// ---- snapshot envelope (v4.1, extended with CRC32 in v4.37,  ----
203// ----   publications in v6.1.2 v3, subscriptions in v6.1.4 v4) ----
204//
205// Wraps a catalog blob + a user blob behind a small header so the
206// server can persist both atomically without inventing a new file.
207// Bare catalog blobs (v3.x) still load via `restore_envelope` since
208// the magic check fails fast and the function falls back to
209// `Catalog::deserialize`.
210//
211// Layout — v1 (v4.1, no CRC):
212//   [8 bytes magic "SPGENV01"]
213//   [u8 version = 1]
214//   [u32 catalog_len][catalog bytes]
215//   [u32 users_len][users bytes]
216//
217// Layout — v2 (v4.37, CRC32 of body):
218//   [8 bytes magic "SPGENV01"]
219//   [u8 version = 2]
220//   [u32 catalog_len][catalog bytes]
221//   [u32 users_len][users bytes]
222//   [u32 crc32]                      ← CRC32 of every byte before it.
223//
224// Layout — v3 (v6.1.2, publications trailer):
225//   [8 bytes magic "SPGENV01"]
226//   [u8 version = 3]
227//   [u32 catalog_len][catalog bytes]
228//   [u32 users_len][users bytes]
229//   [u32 pubs_len][publications bytes]
230//   [u32 crc32]
231//
232// Layout — v4 (v6.1.4, subscriptions trailer):
233//   [8 bytes magic "SPGENV01"]
234//   [u8 version = 4]
235//   [u32 catalog_len][catalog bytes]
236//   [u32 users_len][users bytes]
237//   [u32 pubs_len][publications bytes]
238//   [u32 subs_len][subscriptions bytes]
239//   [u32 crc32]
240//
241// Layout — v5 (v6.2.0, statistics trailer):
242//   [8 bytes magic "SPGENV01"]
243//   [u8 version = 5]
244//   [u32 catalog_len][catalog bytes]
245//   [u32 users_len][users bytes]
246//   [u32 pubs_len][publications bytes]
247//   [u32 subs_len][subscriptions bytes]
248//   [u32 stats_len][statistics bytes]      ← NEW
249//   [u32 crc32]
250//
251// Writers emit v5 from v6.2.0 on. Readers accept all of {v1, v2,
252// v3, v4, v5}: v1/v2 load with empty publications / subscriptions /
253// statistics; v3 loads with empty subscriptions + statistics; v4
254// loads with empty statistics; v5 deserialises all three. Older
255// SPG versions reading a v5 envelope fall through the version
256// match to `EnvelopeParse::Bare` — pre-v6.2.0 binaries cannot
257// open v6.2.0+ snapshots (matches the v6.1.2 / v6.1.4 breaks).
258
259const ENVELOPE_MAGIC: &[u8; 8] = b"SPGENV01";
260const ENVELOPE_VERSION_V1: u8 = 1;
261const ENVELOPE_VERSION_V2: u8 = 2;
262const ENVELOPE_VERSION_V3: u8 = 3;
263const ENVELOPE_VERSION_V4: u8 = 4;
264const ENVELOPE_VERSION_V5: u8 = 5;
265
266fn build_envelope(catalog: &[u8], users: &[u8], pubs: &[u8], subs: &[u8], stats: &[u8]) -> Vec<u8> {
267    let mut out = Vec::with_capacity(
268        8 + 1
269            + 4
270            + catalog.len()
271            + 4
272            + users.len()
273            + 4
274            + pubs.len()
275            + 4
276            + subs.len()
277            + 4
278            + stats.len()
279            + 4,
280    );
281    out.extend_from_slice(ENVELOPE_MAGIC);
282    out.push(ENVELOPE_VERSION_V5);
283    out.extend_from_slice(
284        &u32::try_from(catalog.len())
285            .expect("≤ 4G catalog")
286            .to_le_bytes(),
287    );
288    out.extend_from_slice(catalog);
289    out.extend_from_slice(
290        &u32::try_from(users.len())
291            .expect("≤ 4G users")
292            .to_le_bytes(),
293    );
294    out.extend_from_slice(users);
295    out.extend_from_slice(
296        &u32::try_from(pubs.len())
297            .expect("≤ 4G publications")
298            .to_le_bytes(),
299    );
300    out.extend_from_slice(pubs);
301    out.extend_from_slice(
302        &u32::try_from(subs.len())
303            .expect("≤ 4G subscriptions")
304            .to_le_bytes(),
305    );
306    out.extend_from_slice(subs);
307    out.extend_from_slice(
308        &u32::try_from(stats.len())
309            .expect("≤ 4G statistics")
310            .to_le_bytes(),
311    );
312    out.extend_from_slice(stats);
313    let crc = spg_crypto::crc32::crc32(&out);
314    out.extend_from_slice(&crc.to_le_bytes());
315    out
316}
317
318/// Outcome of envelope parsing: either bare-catalog fallback, a
319/// successfully split section trio from a v1/v2/v3 envelope, or an
320/// explicit corruption error from a v2/v3 CRC mismatch. `Bare`
321/// (catalog-only fallback) preserves v3.x readability. v1/v2
322/// envelopes set `publications` to `None`; v3 sets it to the
323/// publications byte slice.
324enum EnvelopeParse<'a> {
325    Bare,
326    Pair {
327        catalog: &'a [u8],
328        users: &'a [u8],
329        publications: Option<&'a [u8]>,
330        subscriptions: Option<&'a [u8]>,
331        statistics: Option<&'a [u8]>,
332    },
333    CrcMismatch {
334        expected: u32,
335        computed: u32,
336    },
337}
338
339/// Returns `EnvelopeParse::Pair` for a valid v1 / v2 / v3 envelope,
340/// `Bare` for a buffer that doesn't look like an envelope (v3.x
341/// bare catalog fallback), and `CrcMismatch` for a v2/v3 envelope
342/// whose trailing CRC32 doesn't match the body.
343fn split_envelope(buf: &[u8]) -> EnvelopeParse<'_> {
344    if buf.len() < 8 + 1 + 4 || &buf[..8] != ENVELOPE_MAGIC {
345        return EnvelopeParse::Bare;
346    }
347    let version = buf[8];
348    if !matches!(
349        version,
350        ENVELOPE_VERSION_V1
351            | ENVELOPE_VERSION_V2
352            | ENVELOPE_VERSION_V3
353            | ENVELOPE_VERSION_V4
354            | ENVELOPE_VERSION_V5
355    ) {
356        return EnvelopeParse::Bare;
357    }
358    let mut p = 9usize;
359    let Some(cat_len_bytes) = buf.get(p..p + 4) else {
360        return EnvelopeParse::Bare;
361    };
362    let Ok(cat_len_arr) = cat_len_bytes.try_into() else {
363        return EnvelopeParse::Bare;
364    };
365    let cat_len = u32::from_le_bytes(cat_len_arr) as usize;
366    p += 4;
367    if p + cat_len + 4 > buf.len() {
368        return EnvelopeParse::Bare;
369    }
370    let catalog = &buf[p..p + cat_len];
371    p += cat_len;
372    let Some(user_len_bytes) = buf.get(p..p + 4) else {
373        return EnvelopeParse::Bare;
374    };
375    let Ok(user_len_arr) = user_len_bytes.try_into() else {
376        return EnvelopeParse::Bare;
377    };
378    let user_len = u32::from_le_bytes(user_len_arr) as usize;
379    p += 4;
380    if p + user_len > buf.len() {
381        return EnvelopeParse::Bare;
382    }
383    let users = &buf[p..p + user_len];
384    p += user_len;
385    let publications = if matches!(
386        version,
387        ENVELOPE_VERSION_V3 | ENVELOPE_VERSION_V4 | ENVELOPE_VERSION_V5
388    ) {
389        // [u32 pubs_len][publications bytes]
390        let Some(pubs_len_bytes) = buf.get(p..p + 4) else {
391            return EnvelopeParse::Bare;
392        };
393        let Ok(pubs_len_arr) = pubs_len_bytes.try_into() else {
394            return EnvelopeParse::Bare;
395        };
396        let pubs_len = u32::from_le_bytes(pubs_len_arr) as usize;
397        p += 4;
398        if p + pubs_len > buf.len() {
399            return EnvelopeParse::Bare;
400        }
401        let pubs_slice = &buf[p..p + pubs_len];
402        p += pubs_len;
403        Some(pubs_slice)
404    } else {
405        None
406    };
407    let subscriptions = if matches!(version, ENVELOPE_VERSION_V4 | ENVELOPE_VERSION_V5) {
408        // [u32 subs_len][subscriptions bytes]
409        let Some(subs_len_bytes) = buf.get(p..p + 4) else {
410            return EnvelopeParse::Bare;
411        };
412        let Ok(subs_len_arr) = subs_len_bytes.try_into() else {
413            return EnvelopeParse::Bare;
414        };
415        let subs_len = u32::from_le_bytes(subs_len_arr) as usize;
416        p += 4;
417        if p + subs_len > buf.len() {
418            return EnvelopeParse::Bare;
419        }
420        let subs_slice = &buf[p..p + subs_len];
421        p += subs_len;
422        Some(subs_slice)
423    } else {
424        None
425    };
426    let statistics = if version == ENVELOPE_VERSION_V5 {
427        // [u32 stats_len][statistics bytes]
428        let Some(stats_len_bytes) = buf.get(p..p + 4) else {
429            return EnvelopeParse::Bare;
430        };
431        let Ok(stats_len_arr) = stats_len_bytes.try_into() else {
432            return EnvelopeParse::Bare;
433        };
434        let stats_len = u32::from_le_bytes(stats_len_arr) as usize;
435        p += 4;
436        if p + stats_len > buf.len() {
437            return EnvelopeParse::Bare;
438        }
439        let stats_slice = &buf[p..p + stats_len];
440        p += stats_len;
441        Some(stats_slice)
442    } else {
443        None
444    };
445    if matches!(
446        version,
447        ENVELOPE_VERSION_V2 | ENVELOPE_VERSION_V3 | ENVELOPE_VERSION_V4 | ENVELOPE_VERSION_V5
448    ) {
449        if p + 4 != buf.len() {
450            return EnvelopeParse::Bare;
451        }
452        let Ok(crc_arr) = buf[p..p + 4].try_into() else {
453            return EnvelopeParse::Bare;
454        };
455        let expected = u32::from_le_bytes(crc_arr);
456        let computed = spg_crypto::crc32::crc32(&buf[..p]);
457        if expected != computed {
458            return EnvelopeParse::CrcMismatch { expected, computed };
459        }
460    } else if p != buf.len() {
461        // v1: must end exactly at the users section.
462        return EnvelopeParse::Bare;
463    }
464    EnvelopeParse::Pair {
465        catalog,
466        users,
467        publications,
468        subscriptions,
469        statistics,
470    }
471}
472
473/// v4.41.1 opaque transaction handle. Returned by `Engine::alloc_tx_id`,
474/// threaded through `Engine::execute_in` so dispatch can identify which
475/// in-flight TX a statement belongs to. `IMPLICIT_TX` is the reserved
476/// slot every legacy caller — engine self-tests, spg-cli, spg-embedded,
477/// startup replay — implicitly uses through the unchanged
478/// `Engine::execute(sql)` API. v4.41.1 keeps at most one active slot at
479/// runtime (dispatch holds `engine.write()` across the wrap, same as
480/// v4.34); the map shape is here to let v4.42 turn on N in-flight
481/// implicit TXs without reshuffling the engine internals.
482#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
483pub struct TxId(pub u64);
484
485/// Reserved slot used by `Engine::execute(sql)` — the legacy single-
486/// global-shadow path. New `alloc_tx_id` handles start at 1.
487pub const IMPLICIT_TX: TxId = TxId(0);
488
489/// v6.7.3 — default segment-size threshold used by `COMPACT COLD
490/// SEGMENTS` when no explicit target is supplied. Segments whose
491/// `OwnedSegment::bytes().len()` is **strictly** less than this
492/// value are eligible to merge. spg-server reads
493/// `SPG_COMPACTION_TARGET_SEGMENT_BYTES` to override.
494pub const COMPACTION_TARGET_DEFAULT_BYTES: u64 = 4 * 1024 * 1024;
495
496/// Per-slot transaction state. Held inside `tx_catalogs[tx_id]` for the
497/// lifetime of a BEGIN..COMMIT (or BEGIN..ROLLBACK) window. Drops when
498/// the TX commits (its `catalog` is moved over `Engine.catalog`) or
499/// rolls back (slot removed, catalog discarded).
500#[derive(Debug, Default, Clone)]
501struct TxState {
502    /// The TX's shadow copy of the catalog. Started as a clone of
503    /// `Engine.catalog` at BEGIN time; writes flow into it; COMMIT
504    /// installs it over `Engine.catalog`. `Catalog::clone()` is O(1)
505    /// since v4.40 (`PersistentVec` rows + `PersistentBTreeMap` indices).
506    catalog: Catalog,
507    /// Per-TX savepoint stack. Each entry pairs the savepoint name with
508    /// a clone of `catalog` at the moment `SAVEPOINT <name>` fired.
509    /// `ROLLBACK TO <name>` restores from the entry and pops everything
510    /// after it; `RELEASE <name>` discards the entry and everything
511    /// after; COMMIT/ROLLBACK clears the whole stack.
512    savepoints: Vec<(String, Catalog)>,
513}
514
515/// v7.11.0 — frozen read-only view of the engine's committed state.
516/// Constructed via [`Engine::clone_snapshot`]. Holds clones of the
517/// catalog, statistics, clock function, and row-cap config — the
518/// four fields the `execute_readonly` path actually reads. Cheap to
519/// `Clone` (each clone shares the underlying `PersistentVec` row
520/// storage; only the trie root pointers copy). Send + Sync so a
521/// snapshot can be moved across `tokio::task::spawn_blocking`
522/// boundaries without coordination.
523///
524/// The contract: a snapshot reflects the engine's state at the
525/// moment `clone_snapshot()` returned. Subsequent writes to the
526/// engine are NOT visible. Callers who need fresher data take a
527/// new snapshot.
528#[derive(Debug, Clone)]
529pub struct CatalogSnapshot {
530    catalog: Catalog,
531    statistics: statistics::Statistics,
532    clock: Option<ClockFn>,
533    max_query_rows: Option<usize>,
534}
535
536#[derive(Debug, Default)]
537pub struct Engine {
538    /// Committed catalog — what survives `Engine::snapshot()` and what
539    /// outside-TX `SELECT`s read.
540    catalog: Catalog,
541    /// Active TX slots, keyed by `TxId`. Empty when no TX is in flight.
542    /// v4.41.1 runtime invariant: at most one entry (single-writer
543    /// model unchanged). v4.42 will let dispatch hold multiple entries
544    /// concurrently for group commit + engine MVCC.
545    tx_catalogs: BTreeMap<TxId, TxState>,
546    /// Which slot the next exec_* call should mutate. Set by
547    /// `execute_in(sql, tx_id)` at the entry point; legacy `execute(sql)`
548    /// sets it to `IMPLICIT_TX`. None when no TX is in flight (read /
549    /// write goes straight against `catalog`).
550    current_tx: Option<TxId>,
551    /// Monotonic counter for `alloc_tx_id`. Starts at 1 — slot 0 is
552    /// reserved for `IMPLICIT_TX`.
553    next_tx_id: u64,
554    /// Optional wall clock used to satisfy `NOW()` / `CURRENT_TIMESTAMP`
555    /// / `CURRENT_DATE`. Set by the host environment.
556    clock: Option<ClockFn>,
557    /// v4.1 cryptographic RNG for per-user password salt. Set by the
558    /// host. `None` means SQL-driven `CREATE USER` uses a
559    /// deterministic fallback — see `SaltFn`.
560    salt_fn: Option<SaltFn>,
561    /// v4.2 per-query row cap. `None` = unlimited. When set, a
562    /// SELECT that materialises more than `n` rows returns
563    /// `EngineError::RowLimitExceeded`. Enforced before the result
564    /// is shaped into wire frames so a runaway scan can't blow the
565    /// server's heap.
566    max_query_rows: Option<usize>,
567    /// v4.1 RBAC user table. Empty means "no RBAC configured yet" —
568    /// the server decides what that means at the auth boundary
569    /// (open mode vs legacy single-password mode). User CRUD goes
570    /// through `create_user`/`drop_user`/`verify_user`; persistence
571    /// rides the snapshot envelope alongside the catalog.
572    users: UserStore,
573    /// v6.1.2 logical-replication publication catalog. Empty until
574    /// `CREATE PUBLICATION` runs. Persistence rides the v3 envelope
575    /// trailer (see `build_envelope`).
576    publications: publications::Publications,
577    /// v6.1.4 logical-replication subscription catalog. Empty until
578    /// `CREATE SUBSCRIPTION` runs. Persistence rides the v4 envelope
579    /// trailer.
580    subscriptions: subscriptions::Subscriptions,
581    /// v6.2.0 — per-column statistics for the cost-based optimizer.
582    /// Populated by `ANALYZE`; queried via `spg_statistic` virtual
583    /// table. Persistence rides the v5 envelope trailer.
584    statistics: statistics::Statistics,
585    /// v6.3.0 — engine-level plan cache. Caches the post-`prepare()`
586    /// `Statement` keyed on SQL text. In-memory only — does NOT ride
587    /// the snapshot envelope (rebuilt on demand after restart).
588    plan_cache: plan_cache::PlanCache,
589    /// v6.5.1 — per-distinct-SQL execution stats. In-memory only,
590    /// surfaced via `spg_stat_query` virtual table. Updated by the
591    /// `execute_*` paths after a successful execute.
592    query_stats: query_stats::QueryStats,
593    /// v6.5.2 — connection-state provider callback. spg-server
594    /// registers a function at startup that snapshots its
595    /// per-pgwire-connection registry into `ActivityRow`s; engine
596    /// reads through it on every `SELECT * FROM spg_stat_activity`.
597    /// `None` ⇒ no-data (returns empty rows; matches the no_std
598    /// embedded callers that don't run pgwire).
599    activity_provider: Option<ActivityProvider>,
600    /// v6.5.3 — audit-chain provider + verifier. Same pattern as
601    /// activity_provider: spg-server registers both at startup;
602    /// engine reads through on `SELECT * FROM spg_audit_chain` and
603    /// `SELECT * FROM spg_audit_verify`. `None` ⇒ no-data.
604    audit_chain_provider: Option<AuditChainProvider>,
605    audit_verifier: Option<AuditVerifier>,
606    /// v6.5.6 — slow-query log threshold in microseconds. When set,
607    /// every successful execute whose elapsed exceeds the threshold
608    /// gets fed to the registered slow-query log callback (so
609    /// spg-server can emit a structured log line). Default `None`
610    /// = no slow-query logging.
611    slow_query_threshold_us: Option<u64>,
612    slow_query_logger: Option<SlowQueryLogger>,
613}
614
615/// v6.5.6 — callback signature for slow-query log emission. Called
616/// with `(sql, elapsed_us)` once per successful execute that crosses
617/// the threshold.
618pub type SlowQueryLogger = fn(&str, u64);
619
620/// v6.5.4 — synthesise a `CREATE TABLE` statement from catalog
621/// state. Round-trips through `Engine::execute` to recreate the
622/// same schema (sans data + indexes — indexes are emitted as a
623/// separate `CREATE INDEX` chain in `spg_database_ddl`).
624fn render_create_table(name: &str, columns: &[ColumnSchema]) -> String {
625    let mut out = alloc::format!("CREATE TABLE {name} (");
626    for (i, col) in columns.iter().enumerate() {
627        if i > 0 {
628            out.push_str(", ");
629        }
630        out.push_str(&col.name);
631        out.push(' ');
632        out.push_str(&render_data_type(col.ty));
633        if !col.nullable {
634            out.push_str(" NOT NULL");
635        }
636        if col.auto_increment {
637            out.push_str(" AUTO_INCREMENT");
638        }
639    }
640    out.push(')');
641    out
642}
643
644fn render_data_type(ty: DataType) -> String {
645    match ty {
646        DataType::SmallInt => "SMALLINT".into(),
647        DataType::Int => "INT".into(),
648        DataType::BigInt => "BIGINT".into(),
649        DataType::Float => "FLOAT".into(),
650        DataType::Text => "TEXT".into(),
651        DataType::Varchar(n) => alloc::format!("VARCHAR({n})"),
652        DataType::Char(n) => alloc::format!("CHAR({n})"),
653        DataType::Bool => "BOOL".into(),
654        DataType::Vector { dim, encoding } => match encoding {
655            spg_storage::VecEncoding::F32 => alloc::format!("VECTOR({dim})"),
656            spg_storage::VecEncoding::Sq8 => alloc::format!("VECTOR({dim}) USING SQ8"),
657            spg_storage::VecEncoding::F16 => alloc::format!("VECTOR({dim}) USING HALF"),
658        },
659        DataType::Numeric { precision, scale } => {
660            alloc::format!("NUMERIC({precision},{scale})")
661        }
662        DataType::Date => "DATE".into(),
663        DataType::Timestamp => "TIMESTAMP".into(),
664        DataType::Interval => "INTERVAL".into(),
665        DataType::Json => "JSON".into(),
666        DataType::Jsonb => "JSONB".into(),
667        DataType::Timestamptz => "TIMESTAMPTZ".into(),
668        DataType::Bytes => "BYTEA".into(),
669        DataType::TextArray => "TEXT[]".into(),
670        DataType::IntArray => "INT[]".into(),
671        DataType::BigIntArray => "BIGINT[]".into(),
672    }
673}
674
675/// v6.5.2 — one row of `spg_stat_activity`. Engine-public so
676/// spg-server can construct rows without re-exporting internal
677/// dispatch types.
678#[derive(Debug, Clone)]
679pub struct ActivityRow {
680    pub pid: u32,
681    pub user: String,
682    pub started_at_us: i64,
683    pub current_sql: String,
684    pub wait_event: String,
685    pub elapsed_us: i64,
686    pub in_transaction: bool,
687}
688
689/// v6.5.2 — provider callback type. Fresh snapshot returned each
690/// call; engine doesn't cache the slice.
691pub type ActivityProvider = fn() -> Vec<ActivityRow>;
692
693/// v6.5.3 — one row of `spg_audit_chain`. Engine-public so
694/// spg-server can construct rows directly from `AuditEntry`.
695#[derive(Debug, Clone)]
696pub struct AuditRow {
697    pub seq: i64,
698    pub ts_ms: i64,
699    pub prev_hash_hex: String,
700    pub entry_hash_hex: String,
701    pub sql: String,
702}
703
704/// v6.5.3 — chain-table provider + verifier. spg-server registers
705/// fn pointers that snapshot / verify the audit log. `verify`
706/// returns `(verified_count, broken_at_seq)` — `broken_at_seq` is
707/// `-1` on a clean chain.
708pub type AuditChainProvider = fn() -> Vec<AuditRow>;
709pub type AuditVerifier = fn() -> (i64, i64);
710
711impl Engine {
712    pub fn new() -> Self {
713        Self {
714            catalog: Catalog::new(),
715            tx_catalogs: BTreeMap::new(),
716            current_tx: None,
717            next_tx_id: 1,
718            clock: None,
719            salt_fn: None,
720            max_query_rows: None,
721            users: UserStore::new(),
722            publications: publications::Publications::new(),
723            subscriptions: subscriptions::Subscriptions::new(),
724            statistics: statistics::Statistics::new(),
725            plan_cache: plan_cache::PlanCache::new(),
726            query_stats: query_stats::QueryStats::new(),
727            activity_provider: None,
728            audit_chain_provider: None,
729            audit_verifier: None,
730            slow_query_threshold_us: None,
731            slow_query_logger: None,
732        }
733    }
734
735    /// v7.11.0 — clone the engine's committed catalog + read-time
736    /// state into a frozen `CatalogSnapshot`. Cheap (`Catalog` is
737    /// backed by `PersistentVec`; cloning is O(log n) per table).
738    /// Subsequent writes to this engine are invisible to the
739    /// snapshot; the snapshot is self-contained and can be moved
740    /// to another thread for concurrent `execute_readonly_on_snapshot`
741    /// calls. The basis for [`AsyncReadHandle`] in spg-embedded-tokio
742    /// and any other read-fanout pattern.
743    #[must_use]
744    pub fn clone_snapshot(&self) -> CatalogSnapshot {
745        CatalogSnapshot {
746            catalog: self.active_catalog().clone(),
747            statistics: self.statistics.clone(),
748            clock: self.clock,
749            max_query_rows: self.max_query_rows,
750        }
751    }
752
753    /// v7.11.1 — execute a read-only SQL statement against a
754    /// `CatalogSnapshot` without touching this engine. Same
755    /// semantics as `execute_readonly` but parameterised on the
756    /// snapshot's catalog. Reject DDL/DML the same way
757    /// `execute_readonly` does. Static-on-Self so the caller can
758    /// dispatch without holding an `Engine` borrow alongside the
759    /// snapshot.
760    pub fn execute_readonly_on_snapshot(
761        snapshot: &CatalogSnapshot,
762        sql: &str,
763    ) -> Result<QueryResult, EngineError> {
764        Self::execute_readonly_on_snapshot_with_cancel(snapshot, sql, CancelToken::none())
765    }
766
767    /// v7.11.1 — `execute_readonly_on_snapshot` with cooperative
768    /// cancellation. Builds a transient `Engine` over the snapshot
769    /// state, runs `execute_readonly_with_cancel`, drops. The
770    /// transient engine is cheap to construct (no I/O; everything
771    /// is just struct moves) and lets the existing read path stay
772    /// untouched.
773    pub fn execute_readonly_on_snapshot_with_cancel(
774        snapshot: &CatalogSnapshot,
775        sql: &str,
776        cancel: CancelToken<'_>,
777    ) -> Result<QueryResult, EngineError> {
778        let transient = Engine {
779            catalog: snapshot.catalog.clone(),
780            statistics: snapshot.statistics.clone(),
781            clock: snapshot.clock,
782            max_query_rows: snapshot.max_query_rows,
783            ..Engine::default()
784        };
785        transient.execute_readonly_with_cancel(sql, cancel)
786    }
787
788    /// Construct an engine restored from a previously-snapshotted catalog
789    /// (see `snapshot()`).
790    pub fn restore(catalog: Catalog) -> Self {
791        Self {
792            catalog,
793            tx_catalogs: BTreeMap::new(),
794            current_tx: None,
795            next_tx_id: 1,
796            clock: None,
797            salt_fn: None,
798            max_query_rows: None,
799            users: UserStore::new(),
800            publications: publications::Publications::new(),
801            subscriptions: subscriptions::Subscriptions::new(),
802            statistics: statistics::Statistics::new(),
803            plan_cache: plan_cache::PlanCache::new(),
804            query_stats: query_stats::QueryStats::new(),
805            activity_provider: None,
806            audit_chain_provider: None,
807            audit_verifier: None,
808            slow_query_threshold_us: None,
809            slow_query_logger: None,
810        }
811    }
812
813    /// Restore an engine + user table from a v4.1 envelope produced
814    /// by `snapshot_with_users()`. Falls back to plain catalog-only
815    /// restore if the envelope magic isn't present (so v3.x snapshot
816    /// files still load). v6.1.2 adds the optional publications
817    /// trailer (envelope v3); a v1/v2 envelope deserialises to an
818    /// empty publication table.
819    pub fn restore_envelope(buf: &[u8]) -> Result<Self, EngineError> {
820        match split_envelope(buf) {
821            EnvelopeParse::Pair {
822                catalog: catalog_bytes,
823                users: user_bytes,
824                publications: pub_bytes,
825                subscriptions: sub_bytes,
826                statistics: stats_bytes,
827            } => {
828                let catalog = Catalog::deserialize(catalog_bytes).map_err(EngineError::Storage)?;
829                let users = users::deserialize_users(user_bytes)
830                    .map_err(|e| EngineError::Unsupported(alloc::format!("users restore: {e}")))?;
831                let publications = match pub_bytes {
832                    Some(b) => publications::Publications::deserialize(b).map_err(|e| {
833                        EngineError::Unsupported(alloc::format!("publications restore: {e:?}"))
834                    })?,
835                    None => publications::Publications::new(),
836                };
837                let subscriptions = match sub_bytes {
838                    Some(b) => subscriptions::Subscriptions::deserialize(b).map_err(|e| {
839                        EngineError::Unsupported(alloc::format!("subscriptions restore: {e:?}"))
840                    })?,
841                    None => subscriptions::Subscriptions::new(),
842                };
843                let statistics = match stats_bytes {
844                    Some(b) => statistics::Statistics::deserialize(b).map_err(|e| {
845                        EngineError::Unsupported(alloc::format!("statistics restore: {e:?}"))
846                    })?,
847                    None => statistics::Statistics::new(),
848                };
849                Ok(Self {
850                    catalog,
851                    tx_catalogs: BTreeMap::new(),
852                    current_tx: None,
853                    next_tx_id: 1,
854                    clock: None,
855                    salt_fn: None,
856                    max_query_rows: None,
857                    users,
858                    publications,
859                    subscriptions,
860                    statistics,
861                    plan_cache: plan_cache::PlanCache::new(),
862                    query_stats: query_stats::QueryStats::new(),
863                    activity_provider: None,
864                    audit_chain_provider: None,
865                    audit_verifier: None,
866                    slow_query_threshold_us: None,
867                    slow_query_logger: None,
868                })
869            }
870            EnvelopeParse::CrcMismatch { expected, computed } => {
871                Err(EngineError::Storage(StorageError::Corrupt(alloc::format!(
872                    "snapshot envelope CRC32 mismatch (expected={expected:#010x}, computed={computed:#010x})"
873                ))))
874            }
875            EnvelopeParse::Bare => {
876                let catalog = Catalog::deserialize(buf).map_err(EngineError::Storage)?;
877                Ok(Self::restore(catalog))
878            }
879        }
880    }
881
882    pub const fn users(&self) -> &UserStore {
883        &self.users
884    }
885
886    /// `salt` is supplied by the caller (the host has a random
887    /// source; the engine is `no_std`). Caller should pass a fresh
888    /// 16-byte random value per user.
889    pub fn create_user(
890        &mut self,
891        name: &str,
892        password: &str,
893        role: Role,
894        salt: [u8; 16],
895    ) -> Result<(), UserError> {
896        self.users.create(name, password, role, salt)?;
897        // v4.8: also derive SCRAM-SHA-256 secrets so PG-wire SASL
898        // auth can verify without re-running PBKDF2 per attempt.
899        // Uses a fresh salt from the host RNG (falls back to a
900        // deterministic per-username salt when no RNG is wired, same
901        // as the legacy hash path).
902        let scram_salt = self.salt_fn.map_or_else(
903            || {
904                let mut s = [0u8; users::SCRAM_SALT_LEN];
905                let digest = spg_crypto::hash(name.as_bytes());
906                // Use bytes 16..32 of BLAKE3 so we don't reuse the
907                // exact same fallback salt as the BLAKE3 hash path.
908                s.copy_from_slice(&digest[16..32]);
909                s
910            },
911            |f| f(),
912        );
913        self.users
914            .enable_scram(name, password, scram_salt, users::SCRAM_DEFAULT_ITERS)?;
915        Ok(())
916    }
917
918    pub fn drop_user(&mut self, name: &str) -> Result<(), UserError> {
919        self.users.drop(name)
920    }
921
922    pub fn verify_user(&self, name: &str, password: &str) -> Option<Role> {
923        self.users.verify(name, password)
924    }
925
926    /// Builder: attach a wall clock so `NOW()` / `CURRENT_TIMESTAMP` /
927    /// `CURRENT_DATE` evaluate to a real value instead of erroring out.
928    #[must_use]
929    pub const fn with_clock(mut self, clock: ClockFn) -> Self {
930        self.clock = Some(clock);
931        self
932    }
933
934    /// Builder: attach an OS-backed RNG for per-user password salts.
935    /// The host (`spg-server`) typically wires this to `/dev/urandom`.
936    #[must_use]
937    pub const fn with_salt_fn(mut self, f: SaltFn) -> Self {
938        self.salt_fn = Some(f);
939        self
940    }
941
942    /// Builder: cap the number of rows a single SELECT may return.
943    /// Exceeding the cap raises `EngineError::RowLimitExceeded` —
944    /// the bound is checked inside the executor so a runaway
945    /// catalog scan can't allocate millions of rows before the
946    /// server gets a chance to reject the result.
947    #[must_use]
948    pub const fn with_max_query_rows(mut self, n: usize) -> Self {
949        self.max_query_rows = Some(n);
950        self
951    }
952
953    /// The *committed* catalog. Note: during a transaction this returns the
954    /// pre-TX state — `SELECT` inside a TX goes through `execute()` and reads
955    /// the shadow. Tests that inspect outside-TX state should use this.
956    pub const fn catalog(&self) -> &Catalog {
957        &self.catalog
958    }
959
960    /// Serialize the *committed* catalog to bytes. v0.6 was full-snapshot; v0.9
961    /// adds the rule that an open TX's shadow is never snapshotted — only the
962    /// post-COMMIT state is persisted. v4.1 wraps the catalog in an envelope
963    /// when there are users to persist; an empty user table snapshots as the
964    /// bare catalog format (backwards-compat with v3.x readers). v6.1.2
965    /// adds publications to the envelope condition: either non-empty
966    /// users OR non-empty publications now triggers the envelope path.
967    pub fn snapshot(&self) -> Vec<u8> {
968        if self.users.is_empty()
969            && self.publications.is_empty()
970            && self.subscriptions.is_empty()
971            && self.statistics.is_empty()
972        {
973            self.catalog.serialize()
974        } else {
975            build_envelope(
976                &self.catalog.serialize(),
977                &users::serialize_users(&self.users),
978                &self.publications.serialize(),
979                &self.subscriptions.serialize(),
980                &self.statistics.serialize(),
981            )
982        }
983    }
984
985    /// True when at least one TX slot is in flight. v4.41.1 runtime
986    /// invariant: at most one slot active at a time (dispatch holds
987    /// `engine.write()` across the entire wrap). v4.42 will let this
988    /// return true with multiple slots concurrently.
989    pub fn in_transaction(&self) -> bool {
990        !self.tx_catalogs.is_empty()
991    }
992
993    /// v4.41.1 allocate a fresh TX handle. Used by spg-server dispatch
994    /// to scope each implicit-wrap BEGIN..stmt..COMMIT to its own slot
995    /// in `tx_catalogs`. v4.42 — the commit-barrier leader allocates
996    /// one of these per task in its group, runs `BEGIN`+sql+`COMMIT`
997    /// sequentially under a single `engine.write()` so each task's
998    /// mutations accumulate into shared state, then either keeps the
999    /// accumulated state (fsync OK) or restores the pre-image via
1000    /// `replace_catalog` (fsync err).
1001    pub fn alloc_tx_id(&mut self) -> TxId {
1002        let id = TxId(self.next_tx_id);
1003        self.next_tx_id = self.next_tx_id.saturating_add(1);
1004        id
1005    }
1006
1007    /// v4.42 — atomically replace the live catalog. Used by the
1008    /// commit-barrier leader to roll back a group whose batched
1009    /// fsync failed: the leader snapshots `engine.catalog().clone()`
1010    /// (O(1) Arc bump after the v4.39/v4.40 persistent migration)
1011    /// at group start, sequentially applies each task's BEGIN+sql+
1012    /// COMMIT under the same write lock to accumulate mutations
1013    /// into shared state, batches the WAL bytes, fsyncs once, and
1014    /// on failure calls this with the pre-image to undo every
1015    /// task in the group at once.
1016    ///
1017    /// **Does NOT touch `tx_catalogs` / `current_tx`.** Any
1018    /// explicit-TX slot from a concurrent client (created via the
1019    /// legacy `IMPLICIT_TX`-less dispatch path or via the future
1020    /// MVCC-readers v5+ work) has its own snapshot baked into the
1021    /// slot — restoring `self.catalog` to the pre-image leaves
1022    /// those slots untouched, exactly as they were when the leader
1023    /// took the lock. The leader's own implicit-TX slots are all
1024    /// already discarded (`exec_commit` removed them as each
1025    /// task's COMMIT ran) by the time this is reached.
1026    pub fn replace_catalog(&mut self, catalog: Catalog) {
1027        self.catalog = catalog;
1028    }
1029
1030    /// v6.7.0 — public shim around `Catalog::freeze_oldest_to_cold`
1031    /// so tests + the spg-server freezer can drive a freeze without
1032    /// reaching into the private `active_catalog_mut`. v6.7.4
1033    /// parallel freezer will build on this surface.
1034    ///
1035    /// Marks the table's cached `cold_row_count` stale because the
1036    /// freeze added cold locators that ANALYZE hasn't yet refreshed.
1037    pub fn freeze_oldest_to_cold(
1038        &mut self,
1039        table_name: &str,
1040        index_name: &str,
1041        max_rows: usize,
1042    ) -> Result<spg_storage::FreezeReport, EngineError> {
1043        let report = self
1044            .active_catalog_mut()
1045            .freeze_oldest_to_cold(table_name, index_name, max_rows)
1046            .map_err(EngineError::Storage)?;
1047        if let Some(t) = self.active_catalog_mut().get_mut(table_name) {
1048            t.mark_cold_row_count_stale();
1049        }
1050        Ok(report)
1051    }
1052
1053    /// v6.7.5 — public shim used by the spg-server follower's
1054    /// segment-forwarding receiver. Registers a cold-tier segment
1055    /// at a specific id (the master's id, as transmitted on the
1056    /// wire) so the follower's BTree-Cold locators stay byte-
1057    /// identical with the master's. Wraps
1058    /// `Catalog::load_segment_bytes_at` under the standard
1059    /// clone-mutate-replace pattern.
1060    ///
1061    /// Returns `Ok(())` on success **and** on the "slot already
1062    /// occupied" case — a follower mid-reconnect may receive a
1063    /// segment chunk for a segment_id it already has on disk
1064    /// (forwarded last session); the caller should treat that
1065    /// path as a no-op rather than a fatal error.
1066    pub fn receive_cold_segment(
1067        &mut self,
1068        segment_id: u32,
1069        bytes: Vec<u8>,
1070    ) -> Result<(), EngineError> {
1071        let mut new_cat = self.catalog.clone();
1072        match new_cat.load_segment_bytes_at(segment_id, bytes) {
1073            Ok(()) => {
1074                self.replace_catalog(new_cat);
1075                Ok(())
1076            }
1077            Err(StorageError::Corrupt(msg)) if msg.contains("already occupied") => Ok(()),
1078            Err(e) => Err(EngineError::Storage(e)),
1079        }
1080    }
1081
1082    /// v6.7.3 — public shim around `Catalog::compact_cold_segments`
1083    /// driving every BTree index on every user table. Returns one
1084    /// `(table, index, report)` triple for each merge that
1085    /// actually happened (no-op (table, index) pairs are filtered
1086    /// out so callers can size persist-side work to the live
1087    /// merges). Caller is responsible for persisting each
1088    /// `report.merged_segment_bytes` and updating the on-disk
1089    /// segment registry; engine layer is no_std and never
1090    /// touches disk.
1091    ///
1092    /// Marks every touched table's cached `cold_row_count` stale
1093    /// — compaction GC'd some shadowed rows, so the count must be
1094    /// re-derived on the next ANALYZE.
1095    pub fn compact_cold_segments_with_target(
1096        &mut self,
1097        target_segment_bytes: u64,
1098    ) -> Result<Vec<(String, String, CompactReport)>, EngineError> {
1099        let table_names = self.active_catalog().table_names();
1100        let mut reports: Vec<(String, String, CompactReport)> = Vec::new();
1101        for tname in table_names {
1102            if is_internal_table_name(&tname) {
1103                continue;
1104            }
1105            let idx_names: Vec<String> = {
1106                let Some(t) = self.active_catalog().get(&tname) else {
1107                    continue;
1108                };
1109                t.indices()
1110                    .iter()
1111                    .filter(|i| matches!(i.kind, IndexKind::BTree(_)))
1112                    .map(|i| i.name.clone())
1113                    .collect()
1114            };
1115            for iname in idx_names {
1116                let report = self
1117                    .active_catalog_mut()
1118                    .compact_cold_segments(&tname, &iname, target_segment_bytes)
1119                    .map_err(EngineError::Storage)?;
1120                if report.merged_segment_id.is_some() {
1121                    if let Some(t) = self.active_catalog_mut().get_mut(&tname) {
1122                        t.mark_cold_row_count_stale();
1123                    }
1124                    reports.push((tname.clone(), iname, report));
1125                }
1126            }
1127        }
1128        Ok(reports)
1129    }
1130
1131    fn active_catalog(&self) -> &Catalog {
1132        match self.current_tx {
1133            Some(t) => self
1134                .tx_catalogs
1135                .get(&t)
1136                .map_or(&self.catalog, |s| &s.catalog),
1137            None => &self.catalog,
1138        }
1139    }
1140
1141    fn active_catalog_mut(&mut self) -> &mut Catalog {
1142        let tx = self.current_tx;
1143        match tx {
1144            Some(t) => match self.tx_catalogs.get_mut(&t) {
1145                Some(s) => &mut s.catalog,
1146                None => &mut self.catalog,
1147            },
1148            None => &mut self.catalog,
1149        }
1150    }
1151
1152    /// Read-only execute path. Succeeds for `SELECT` / `SHOW TABLES`
1153    /// / `SHOW COLUMNS`; returns `EngineError::WriteRequired` for
1154    /// every other statement, so the caller can fall through to the
1155    /// `&mut self` `execute` path under a write lock. Engine state is
1156    /// not mutated even on the success path (`rewrite_clock_calls`
1157    /// and `resolve_order_by_position` both mutate the locally-owned
1158    /// AST, not `self`).
1159    ///
1160    /// **v4.0 concurrency**: this is the entry point the server takes
1161    /// under an `RwLock::read()` so multiple `SELECT` clients run in
1162    /// parallel without serialising on a single mutex.
1163    pub fn execute_readonly(&self, sql: &str) -> Result<QueryResult, EngineError> {
1164        self.execute_readonly_with_cancel(sql, CancelToken::none())
1165    }
1166
1167    /// v4.5 — read path with cooperative cancellation. Token's
1168    /// `is_cancelled` is checked at the start (so a watchdog that
1169    /// already fired returns Cancelled immediately) and at row-loop
1170    /// checkpoints inside `exec_select`. SHOW paths are O(small) and
1171    /// don't bother checking.
1172    pub fn execute_readonly_with_cancel(
1173        &self,
1174        sql: &str,
1175        cancel: CancelToken<'_>,
1176    ) -> Result<QueryResult, EngineError> {
1177        cancel.check()?;
1178        let mut stmt = parser::parse_statement(sql)?;
1179        let now_micros = self.clock.map(|f| f());
1180        rewrite_clock_calls(&mut stmt, now_micros);
1181        if let Statement::Select(s) = &mut stmt {
1182            resolve_order_by_position(s);
1183            // v6.2.3 — cost-based JOIN reorder (read path).
1184            reorder::reorder_joins(s, &self.catalog, &self.statistics);
1185        }
1186        let result = match stmt {
1187            Statement::Select(s) => self.exec_select_cancel(&s, cancel),
1188            Statement::ShowTables => Ok(self.exec_show_tables()),
1189            Statement::ShowColumns(table) => self.exec_show_columns(&table),
1190            Statement::ShowUsers => Ok(self.exec_show_users()),
1191            Statement::ShowPublications => Ok(self.exec_show_publications()),
1192            Statement::ShowSubscriptions => Ok(self.exec_show_subscriptions()),
1193            Statement::WaitForWalPosition { .. } => Err(EngineError::Unsupported(
1194                "WAIT FOR WAL POSITION must be handled by the server layer".into(),
1195            )),
1196            Statement::Explain(e) => self.exec_explain(&e, cancel),
1197            _ => Err(EngineError::WriteRequired),
1198        };
1199        self.enforce_row_limit(result)
1200    }
1201
1202    /// v4.2: cap result-set size. Applied after the executor
1203    /// materialises rows but before they leave the engine — wrapping
1204    /// every Rows-returning exec_* function would scatter the check.
1205    fn enforce_row_limit(
1206        &self,
1207        result: Result<QueryResult, EngineError>,
1208    ) -> Result<QueryResult, EngineError> {
1209        if let (Ok(QueryResult::Rows { rows, .. }), Some(cap)) = (&result, self.max_query_rows)
1210            && rows.len() > cap
1211        {
1212            return Err(EngineError::RowLimitExceeded(cap));
1213        }
1214        result
1215    }
1216
1217    pub fn execute(&mut self, sql: &str) -> Result<QueryResult, EngineError> {
1218        self.execute_in_with_cancel(sql, IMPLICIT_TX, CancelToken::none())
1219    }
1220
1221    /// v4.5 — write path with cooperative cancellation. Same dispatch
1222    /// as `execute_in_with_cancel(sql, IMPLICIT_TX, cancel)`. Kept as
1223    /// a separate entry point for backward-compat with the v4.5
1224    /// public API.
1225    pub fn execute_with_cancel(
1226        &mut self,
1227        sql: &str,
1228        cancel: CancelToken<'_>,
1229    ) -> Result<QueryResult, EngineError> {
1230        self.execute_in_with_cancel(sql, IMPLICIT_TX, cancel)
1231    }
1232
1233    /// v4.41.1 multi-slot write entry. Routes `sql` through the TX
1234    /// slot identified by `tx_id` so spg-server dispatch can scope
1235    /// each implicit-wrap BEGIN..stmt..COMMIT to its own slot in
1236    /// `tx_catalogs`. `IMPLICIT_TX` is the legacy single-slot path
1237    /// every other caller (engine self-tests, replay, spg-embedded)
1238    /// implicitly takes via `execute()` / `execute_with_cancel()`.
1239    pub fn execute_in(&mut self, sql: &str, tx_id: TxId) -> Result<QueryResult, EngineError> {
1240        self.execute_in_with_cancel(sql, tx_id, CancelToken::none())
1241    }
1242
1243    /// v4.41.1 write path with cooperative cancellation + explicit TX
1244    /// scope. Sets `self.current_tx` for the duration of the call so
1245    /// every `exec_*` helper transparently sees its TX's shadow
1246    /// catalog and savepoint stack; restores on exit so the field is
1247    /// only valid mid-call (no leakage across calls).
1248    pub fn execute_in_with_cancel(
1249        &mut self,
1250        sql: &str,
1251        tx_id: TxId,
1252        cancel: CancelToken<'_>,
1253    ) -> Result<QueryResult, EngineError> {
1254        let saved = self.current_tx;
1255        self.current_tx = Some(tx_id);
1256        let result = self.execute_inner_with_cancel(sql, cancel);
1257        self.current_tx = saved;
1258        result
1259    }
1260
1261    /// v6.1.1 — parse and pre-process a SQL string ONCE so the
1262    /// resulting [`Statement`] can be cached and re-executed via
1263    /// [`Engine::execute_prepared`]. Returns the same `Statement`
1264    /// the simple-query path would synthesise internally (clock
1265    /// rewrites + ORDER BY position-ref resolution applied at
1266    /// prepare time, since both are session-independent). The
1267    /// `$N` placeholders in the SQL stay as `Expr::Placeholder(n)`
1268    /// nodes; they're resolved to concrete values per-call by
1269    /// `execute_prepared`'s substitution walk.
1270    ///
1271    /// Pgwire's `Parse` (P) message lands here.
1272    pub fn prepare(&self, sql: &str) -> Result<Statement, ParseError> {
1273        let mut stmt = parser::parse_statement(sql)?;
1274        let now_micros = self.clock.map(|f| f());
1275        rewrite_clock_calls(&mut stmt, now_micros);
1276        if let Statement::Select(s) = &mut stmt {
1277            // v6.4.1 — expand `GROUP BY ALL` to every non-aggregate
1278            // SELECT-list item BEFORE position / alias resolution so
1279            // downstream passes see the explicit list.
1280            expand_group_by_all(s);
1281            resolve_order_by_position(s);
1282            // v6.2.3 — cost-based JOIN reorder. No-op for
1283            // single-table FROMs or any non-INNER join shape.
1284            reorder::reorder_joins(s, &self.catalog, &self.statistics);
1285        }
1286        Ok(stmt)
1287    }
1288
1289    /// v6.3.0 — cached prepare. Returns a cloned `Statement` from
1290    /// the plan cache on hit, runs the full `prepare()` path on miss
1291    /// and inserts the resulting plan before returning. Skipping the
1292    /// parse + JOIN-reorder pipeline on hit is the dominant win for
1293    /// JDBC / sqlx / pgx clients that reuse the same SQL string.
1294    ///
1295    /// Returns a cloned `Statement` (not a borrow) because the
1296    /// pgwire layer owns its `PreparedStmt` map per-session and the
1297    /// engine-level cache must stay available for other sessions.
1298    /// Clone cost on a 5-table JOIN AST is well under the parse cost
1299    /// it replaces.
1300    pub fn prepare_cached(&mut self, sql: &str) -> Result<Statement, ParseError> {
1301        // v6.3.1 — version-aware lookup. If the cached plan was
1302        // prepared before the most recent ANALYZE, evict and replan.
1303        let current_version = self.statistics.version();
1304        if let Some(plan) = self.plan_cache.get(sql) {
1305            if plan.statistics_version == current_version {
1306                return Ok(plan.stmt.clone());
1307            }
1308            // Stale entry — fall through to evict + re-prepare.
1309        }
1310        self.plan_cache.evict(sql);
1311        let stmt = self.prepare(sql)?;
1312        let source_tables = plan_cache::collect_source_tables(&stmt);
1313        let plan = plan_cache::PreparedPlan {
1314            stmt: stmt.clone(),
1315            statistics_version: current_version,
1316            source_tables,
1317            describe_columns: alloc::vec::Vec::new(),
1318        };
1319        self.plan_cache.insert(String::from(sql), plan);
1320        Ok(stmt)
1321    }
1322
1323    /// v6.3.0 — read-only accessor for tests and v6.3.1 invalidation.
1324    pub fn plan_cache(&self) -> &plan_cache::PlanCache {
1325        &self.plan_cache
1326    }
1327
1328    /// v6.3.0 — mutable accessor for v6.3.1 invalidation hooks.
1329    pub fn plan_cache_mut(&mut self) -> &mut plan_cache::PlanCache {
1330        &mut self.plan_cache
1331    }
1332
1333    /// v6.3.3 — Describe a prepared `Statement` without executing.
1334    /// Returns `(parameter_oids, output_columns)`. Empty
1335    /// `output_columns` means the statement has no row-producing
1336    /// shape we could resolve here (JOIN, subquery, non-SELECT, …)
1337    /// — pgwire layer maps that to a `NoData` reply.
1338    pub fn describe_prepared(&self, stmt: &Statement) -> (Vec<u32>, Vec<ColumnSchema>) {
1339        describe::describe_prepared(stmt, self.active_catalog())
1340    }
1341
1342    /// v6.1.1 — execute a [`Statement`] previously returned by
1343    /// [`Engine::prepare`], substituting `Expr::Placeholder(n)`
1344    /// nodes for the corresponding [`Value`] in `params` (1-based
1345    /// per PG: `$1` → `params[0]`). Bind-time string parameters
1346    /// are decoded into typed `Value`s by the pgwire layer before
1347    /// this call so the resulting AST hits the same execution
1348    /// path as a simple query — no SQL re-parse.
1349    ///
1350    /// Pgwire's `Execute` (E) message after a `Bind` (B) lands here.
1351    pub fn execute_prepared(
1352        &mut self,
1353        mut stmt: Statement,
1354        params: &[Value],
1355    ) -> Result<QueryResult, EngineError> {
1356        substitute_placeholders(&mut stmt, params)?;
1357        self.execute_stmt_with_cancel(stmt, CancelToken::none())
1358    }
1359
1360    fn execute_inner_with_cancel(
1361        &mut self,
1362        sql: &str,
1363        cancel: CancelToken<'_>,
1364    ) -> Result<QueryResult, EngineError> {
1365        cancel.check()?;
1366        let stmt = self.prepare(sql)?;
1367        // v6.5.1 — wrap the executor with a wall-clock window so we
1368        // can record into spg_stat_query. Skip when the engine has
1369        // no clock attached (no_std embedded callers).
1370        let start_us = self.clock.map(|f| f());
1371        let result = self.execute_stmt_with_cancel(stmt, cancel);
1372        if let (Some(t0), Ok(_)) = (start_us, &result) {
1373            let now = self.clock.map_or(t0, |f| f());
1374            let elapsed = now.saturating_sub(t0).max(0) as u64;
1375            self.query_stats.record(sql, elapsed, now as u64);
1376            // v6.5.6 — slow-query log: fire callback when elapsed
1377            // exceeds the configured floor.
1378            if let (Some(threshold), Some(logger)) =
1379                (self.slow_query_threshold_us, self.slow_query_logger)
1380                && elapsed >= threshold
1381            {
1382                logger(sql, elapsed);
1383            }
1384        }
1385        result
1386    }
1387
1388    fn execute_stmt_with_cancel(
1389        &mut self,
1390        stmt: Statement,
1391        cancel: CancelToken<'_>,
1392    ) -> Result<QueryResult, EngineError> {
1393        cancel.check()?;
1394        let result = match stmt {
1395            Statement::CreateTable(s) => self.exec_create_table(s),
1396            // v7.9.15 — CREATE EXTENSION is a no-op on SPG. Returns
1397            // CommandOk with affected=0; modified_catalog=false so
1398            // the WAL doesn't grow a useless entry. mailrs F3.
1399            Statement::CreateExtension(_) => Ok(QueryResult::CommandOk {
1400                affected: 0,
1401                modified_catalog: false,
1402            }),
1403            // v7.9.27 — DO $$ ... $$ is also a no-op (SPG has no
1404            // PL/pgSQL). mailrs H1 + pg_dump compat.
1405            Statement::DoBlock => Ok(QueryResult::CommandOk {
1406                affected: 0,
1407                modified_catalog: false,
1408            }),
1409            Statement::CreateIndex(s) => self.exec_create_index(s),
1410            Statement::Insert(s) => self.exec_insert(s),
1411            Statement::Update(s) => self.exec_update_cancel(&s, cancel),
1412            Statement::Delete(s) => self.exec_delete_cancel(&s, cancel),
1413            Statement::Select(s) => self.exec_select_cancel(&s, cancel),
1414            Statement::Begin => self.exec_begin(),
1415            Statement::Commit => self.exec_commit(),
1416            Statement::Rollback => self.exec_rollback(),
1417            Statement::Savepoint(name) => self.exec_savepoint(name),
1418            Statement::RollbackToSavepoint(name) => self.exec_rollback_to_savepoint(&name),
1419            Statement::ReleaseSavepoint(name) => self.exec_release_savepoint(&name),
1420            Statement::ShowTables => Ok(self.exec_show_tables()),
1421            Statement::ShowColumns(table) => self.exec_show_columns(&table),
1422            Statement::ShowUsers => Ok(self.exec_show_users()),
1423            Statement::ShowPublications => Ok(self.exec_show_publications()),
1424            Statement::ShowSubscriptions => Ok(self.exec_show_subscriptions()),
1425            Statement::CreateUser(s) => self.exec_create_user(&s),
1426            Statement::DropUser(name) => self.exec_drop_user(&name),
1427            Statement::Explain(e) => self.exec_explain(&e, cancel),
1428            Statement::AlterIndex(s) => self.exec_alter_index(s),
1429            Statement::AlterTable(s) => self.exec_alter_table(s),
1430            Statement::CreatePublication(s) => self.exec_create_publication(s),
1431            Statement::DropPublication(name) => self.exec_drop_publication(&name),
1432            Statement::CreateSubscription(s) => self.exec_create_subscription(s),
1433            Statement::DropSubscription(name) => self.exec_drop_subscription(&name),
1434            // v6.1.7 — WAIT FOR WAL POSITION needs `lag_state`,
1435            // which lives in spg-server's ServerState. The engine
1436            // surfaces a clear error; the server-layer dispatch
1437            // intercepts the SQL before it reaches the engine on
1438            // a server build, so this arm only fires for
1439            // engine-only callers (spg-embedded, lib tests).
1440            Statement::WaitForWalPosition { .. } => Err(EngineError::Unsupported(
1441                "WAIT FOR WAL POSITION must be handled by the server layer".into(),
1442            )),
1443            // v6.2.0 — ANALYZE recomputes per-column histograms.
1444            Statement::Analyze(target) => self.exec_analyze(target.as_deref()),
1445            // v6.7.3 — COMPACT COLD SEGMENTS.
1446            Statement::CompactColdSegments => self.exec_compact_cold_segments(),
1447        };
1448        self.enforce_row_limit(result)
1449    }
1450
1451    /// v6.1.2 — `CREATE PUBLICATION` runtime path. Duplicate names
1452    /// surface as `EngineError::Unsupported` so the existing PG-wire
1453    /// error mapping stays uniform; the message carries the name so
1454    /// operators can grep replication-log noise. Inside-transaction
1455    /// invocation is rejected (matches `CREATE USER` / `DROP USER`
1456    /// stance) — replication-catalog mutation is a connection-level
1457    /// administrative op, not a transactional one.
1458    fn exec_create_publication(
1459        &mut self,
1460        s: CreatePublicationStatement,
1461    ) -> Result<QueryResult, EngineError> {
1462        // v6.1.4 — the v6.1.2 "no DDL inside a transaction" guard
1463        // was over-cautious: it also blocked the auto-commit wrap
1464        // path (which begins an internal TX around every WAL-
1465        // logged statement). PG itself allows CREATE PUBLICATION
1466        // inside a transaction (it rolls back with the TX).
1467        self.publications
1468            .create(s.name, s.scope)
1469            .map_err(|e| EngineError::Unsupported(alloc::format!("CREATE PUBLICATION: {e:?}")))?;
1470        Ok(QueryResult::CommandOk {
1471            affected: 1,
1472            modified_catalog: true,
1473        })
1474    }
1475
1476    /// v6.1.2 — `DROP PUBLICATION` runtime path. PG-compatible silent
1477    /// no-op when the publication doesn't exist (returns `affected=0`
1478    /// in that case so the wire-level command tag distinguishes
1479    /// "dropped" from "no-op", though both succeed).
1480    fn exec_drop_publication(&mut self, name: &str) -> Result<QueryResult, EngineError> {
1481        let removed = self.publications.drop(name);
1482        Ok(QueryResult::CommandOk {
1483            affected: usize::from(removed),
1484            modified_catalog: removed,
1485        })
1486    }
1487
1488    /// v6.1.2 — read access to the publication catalog. Used by
1489    /// the v6.1.5 publisher-side WAL filter, by `SHOW PUBLICATIONS`
1490    /// (v6.1.3+), and by e2e tests that need to assert state without
1491    /// going through the wire.
1492    pub const fn publications(&self) -> &publications::Publications {
1493        &self.publications
1494    }
1495
1496    /// v6.1.4 — `CREATE SUBSCRIPTION` runtime path. Defaults
1497    /// `enabled = true` and `last_received_pos = 0` for a freshly-
1498    /// created subscription. The actual worker thread is spawned
1499    /// by spg-server once the engine returns success.
1500    fn exec_create_subscription(
1501        &mut self,
1502        s: CreateSubscriptionStatement,
1503    ) -> Result<QueryResult, EngineError> {
1504        // See exec_create_publication — the in_transaction gate
1505        // was over-cautious; the auto-commit wrap path holds an
1506        // internal TX that this check was incorrectly blocking.
1507        let sub = subscriptions::Subscription {
1508            conn_str: s.conn_str,
1509            publications: s.publications,
1510            enabled: true,
1511            last_received_pos: 0,
1512        };
1513        self.subscriptions
1514            .create(s.name, sub)
1515            .map_err(|e| EngineError::Unsupported(alloc::format!("CREATE SUBSCRIPTION: {e:?}")))?;
1516        Ok(QueryResult::CommandOk {
1517            affected: 1,
1518            modified_catalog: true,
1519        })
1520    }
1521
1522    /// v6.1.4 — `DROP SUBSCRIPTION`. Silent no-op when the name
1523    /// doesn't exist (PG-compatible). The associated worker is
1524    /// torn down by spg-server when it observes the catalog
1525    /// change at the next snapshot or via the engine's
1526    /// subscriptions accessor (the worker polls the catalog on
1527    /// reconnect; v6.1.5's filter-side will tighten this to an
1528    /// explicit signal).
1529    fn exec_drop_subscription(&mut self, name: &str) -> Result<QueryResult, EngineError> {
1530        let removed = self.subscriptions.drop(name);
1531        Ok(QueryResult::CommandOk {
1532            affected: usize::from(removed),
1533            modified_catalog: removed,
1534        })
1535    }
1536
1537    /// v6.1.4 — read access to the subscription catalog. Used by
1538    /// the subscription worker (read its own row to find its
1539    /// publications + last applied position), by SHOW SUBSCRIPTIONS,
1540    /// and by e2e tests asserting state directly.
1541    pub const fn subscriptions(&self) -> &subscriptions::Subscriptions {
1542        &self.subscriptions
1543    }
1544
1545    /// v6.1.4 — write access to `last_received_pos`. Worker
1546    /// calls this after each apply batch (under the engine's
1547    /// write-lock). Returns `false` when the subscription was
1548    /// dropped between when the worker received the record and
1549    /// when this call landed.
1550    pub fn subscription_advance(&mut self, name: &str, pos: u64) -> bool {
1551        self.subscriptions.update_last_received_pos(name, pos)
1552    }
1553
1554    /// v6.1.4 — `SHOW SUBSCRIPTIONS` row materialisation. Returns
1555    /// `(name, conn_str, publications, enabled, last_received_pos)`
1556    /// ordered by subscription name. The `publications` column is
1557    /// the comma-joined list ("p1, p2") for ergonomic SHOW output;
1558    /// callers wanting structured access read `Engine::subscriptions`.
1559    fn exec_show_subscriptions(&self) -> QueryResult {
1560        let columns = alloc::vec![
1561            ColumnSchema::new("name", DataType::Text, false),
1562            ColumnSchema::new("conn_str", DataType::Text, false),
1563            ColumnSchema::new("publications", DataType::Text, false),
1564            ColumnSchema::new("enabled", DataType::Bool, false),
1565            ColumnSchema::new("last_received_pos", DataType::BigInt, false),
1566        ];
1567        let rows: Vec<Row> = self
1568            .subscriptions
1569            .iter()
1570            .map(|(name, sub)| {
1571                Row::new(alloc::vec![
1572                    Value::Text(name.clone()),
1573                    Value::Text(sub.conn_str.clone()),
1574                    Value::Text(sub.publications.join(", ")),
1575                    Value::Bool(sub.enabled),
1576                    Value::BigInt(i64::try_from(sub.last_received_pos).unwrap_or(i64::MAX)),
1577                ])
1578            })
1579            .collect();
1580        QueryResult::Rows { columns, rows }
1581    }
1582
1583    /// v6.2.0 — materialise `spg_statistic` rows. One row per
1584    /// `(table, column)` pair tracked in `Statistics`, with
1585    /// `histogram_bounds` rendered as a `[v0, v1, ...]` string —
1586    /// the same canonical form vector literals use for round-trip.
1587    fn exec_spg_statistic(&self) -> QueryResult {
1588        let columns = alloc::vec![
1589            ColumnSchema::new("table_name", DataType::Text, false),
1590            ColumnSchema::new("column_name", DataType::Text, false),
1591            ColumnSchema::new("null_frac", DataType::Float, false),
1592            ColumnSchema::new("n_distinct", DataType::BigInt, false),
1593            ColumnSchema::new("histogram_bounds", DataType::Text, false),
1594            // v6.7.0 — appended column (v6.2.0 stability contract
1595            // allows APPEND to spg_statistic, not reorder/rename).
1596            // Reports the cached per-table cold-row count; same
1597            // value across every column row of the same table.
1598            ColumnSchema::new("cold_row_count", DataType::BigInt, false),
1599        ];
1600        let rows: Vec<Row> = self
1601            .statistics
1602            .iter()
1603            .map(|((t, c), s)| {
1604                let cold = self
1605                    .catalog
1606                    .get(t)
1607                    .map_or(0, |table| table.cold_row_count());
1608                Row::new(alloc::vec![
1609                    Value::Text(t.clone()),
1610                    Value::Text(c.clone()),
1611                    Value::Float(f64::from(s.null_frac)),
1612                    Value::BigInt(i64::try_from(s.n_distinct).unwrap_or(i64::MAX)),
1613                    Value::Text(render_histogram_bounds(&s.histogram_bounds)),
1614                    Value::BigInt(i64::try_from(cold).unwrap_or(i64::MAX)),
1615                ])
1616            })
1617            .collect();
1618        QueryResult::Rows { columns, rows }
1619    }
1620
1621    /// v6.5.0 — materialise `spg_stat_replication` rows. One row
1622    /// per subscription with `(name, conn_str, publications,
1623    /// last_received_pos, enabled)`. Surface mirrors
1624    /// `SHOW SUBSCRIPTIONS` but follows the virtual-table dispatch
1625    /// shape so it composes with SELECT clauses (WHERE, projection
1626    /// onto specific columns, etc).
1627    fn exec_spg_stat_replication(&self) -> QueryResult {
1628        let columns = alloc::vec![
1629            ColumnSchema::new("name", DataType::Text, false),
1630            ColumnSchema::new("conn_str", DataType::Text, false),
1631            ColumnSchema::new("publications", DataType::Text, false),
1632            ColumnSchema::new("last_received_pos", DataType::BigInt, false),
1633            ColumnSchema::new("enabled", DataType::Bool, false),
1634        ];
1635        let rows: Vec<Row> = self
1636            .subscriptions
1637            .iter()
1638            .map(|(name, sub)| {
1639                Row::new(alloc::vec![
1640                    Value::Text(name.clone()),
1641                    Value::Text(sub.conn_str.clone()),
1642                    Value::Text(sub.publications.join(",")),
1643                    Value::BigInt(i64::try_from(sub.last_received_pos).unwrap_or(i64::MAX)),
1644                    Value::Bool(sub.enabled),
1645                ])
1646            })
1647            .collect();
1648        QueryResult::Rows { columns, rows }
1649    }
1650
1651    /// v6.5.0 — materialise `spg_stat_segment` rows. One row per
1652    /// cold-tier segment with `(segment_id, num_rows, num_pages,
1653    /// total_bytes)`.
1654    ///
1655    /// v6.7.0 — appended `table_name` column resolves the v6.5.0
1656    /// carve-out. Walks every user table's BTree indices to find
1657    /// which table's Cold locators point at each segment. Empty
1658    /// string for orphan segments (loaded via SPG_PRELOAD_COLD_SEGMENT
1659    /// before any index registered a locator). The walk is
1660    /// O(tables × indices × keys); cached per call, not across
1661    /// calls — re-walked on every `SELECT * FROM spg_stat_segment`.
1662    fn exec_spg_stat_segment(&self) -> QueryResult {
1663        let columns = alloc::vec![
1664            ColumnSchema::new("segment_id", DataType::BigInt, false),
1665            ColumnSchema::new("table_name", DataType::Text, false),
1666            ColumnSchema::new("num_rows", DataType::BigInt, false),
1667            ColumnSchema::new("num_pages", DataType::BigInt, false),
1668            ColumnSchema::new("total_bytes", DataType::BigInt, false),
1669        ];
1670        // v6.7.0 — build a segment_id → table_name map by walking
1671        // every user table's BTree indices once. O(tables × indices
1672        // × keys) for the v6.5.0 carve-out resolution; acceptable
1673        // because spg_stat_segment is operator-facing (not on a
1674        // hot-loop path).
1675        let mut segment_owners: alloc::collections::BTreeMap<u32, String> = BTreeMap::new();
1676        for tname in self.catalog.table_names() {
1677            if is_internal_table_name(&tname) {
1678                continue;
1679            }
1680            let Some(t) = self.catalog.get(&tname) else {
1681                continue;
1682            };
1683            for idx in t.indices() {
1684                if let spg_storage::IndexKind::BTree(map) = &idx.kind {
1685                    for (_, locs) in map.iter() {
1686                        for loc in locs {
1687                            if let spg_storage::RowLocator::Cold { segment_id, .. } = loc {
1688                                segment_owners
1689                                    .entry(*segment_id)
1690                                    .or_insert_with(|| tname.clone());
1691                            }
1692                        }
1693                    }
1694                }
1695            }
1696        }
1697        let rows: Vec<Row> = self
1698            .catalog
1699            .cold_segment_ids_global()
1700            .iter()
1701            .filter_map(|&id| {
1702                let seg = self.catalog.cold_segment(id)?;
1703                let meta = seg.meta();
1704                let owner = segment_owners.get(&id).cloned().unwrap_or_default();
1705                Some(Row::new(alloc::vec![
1706                    Value::BigInt(i64::from(id)),
1707                    Value::Text(owner),
1708                    Value::BigInt(i64::try_from(meta.num_rows).unwrap_or(i64::MAX)),
1709                    Value::BigInt(i64::from(meta.num_pages)),
1710                    Value::BigInt(i64::try_from(meta.total_bytes).unwrap_or(i64::MAX)),
1711                ]))
1712            })
1713            .collect();
1714        QueryResult::Rows { columns, rows }
1715    }
1716
1717    /// v6.5.1 — materialise `spg_stat_query` rows. One row per
1718    /// distinct SQL text recorded since the engine booted, capped
1719    /// at `QUERY_STATS_MAX` (1024). Columns:
1720    ///   sql, exec_count, total_us, mean_us, max_us, last_seen_us
1721    /// mean_us = total_us / exec_count (saturating).
1722    fn exec_spg_stat_query(&self) -> QueryResult {
1723        let columns = alloc::vec![
1724            ColumnSchema::new("sql", DataType::Text, false),
1725            ColumnSchema::new("exec_count", DataType::BigInt, false),
1726            ColumnSchema::new("total_us", DataType::BigInt, false),
1727            ColumnSchema::new("mean_us", DataType::BigInt, false),
1728            ColumnSchema::new("max_us", DataType::BigInt, false),
1729            ColumnSchema::new("last_seen_us", DataType::BigInt, false),
1730        ];
1731        let rows: Vec<Row> = self
1732            .query_stats
1733            .snapshot()
1734            .into_iter()
1735            .map(|(sql, s)| {
1736                let mean = if s.exec_count == 0 {
1737                    0
1738                } else {
1739                    s.total_us / s.exec_count
1740                };
1741                Row::new(alloc::vec![
1742                    Value::Text(sql),
1743                    Value::BigInt(i64::try_from(s.exec_count).unwrap_or(i64::MAX)),
1744                    Value::BigInt(i64::try_from(s.total_us).unwrap_or(i64::MAX)),
1745                    Value::BigInt(i64::try_from(mean).unwrap_or(i64::MAX)),
1746                    Value::BigInt(i64::try_from(s.max_us).unwrap_or(i64::MAX)),
1747                    Value::BigInt(i64::try_from(s.last_seen_us).unwrap_or(i64::MAX)),
1748                ])
1749            })
1750            .collect();
1751        QueryResult::Rows { columns, rows }
1752    }
1753
1754    /// v6.5.2 — register a connection-state provider. spg-server
1755    /// calls this at startup with a function that snapshots its
1756    /// per-pgwire-connection registry. Engine reads through the
1757    /// callback on `SELECT * FROM spg_stat_activity`.
1758    #[must_use]
1759    pub const fn with_activity_provider(mut self, f: ActivityProvider) -> Self {
1760        self.activity_provider = Some(f);
1761        self
1762    }
1763
1764    /// v6.5.3 — register audit chain provider + verifier.
1765    #[must_use]
1766    pub const fn with_audit_providers(
1767        mut self,
1768        chain: AuditChainProvider,
1769        verify: AuditVerifier,
1770    ) -> Self {
1771        self.audit_chain_provider = Some(chain);
1772        self.audit_verifier = Some(verify);
1773        self
1774    }
1775
1776    /// v6.5.6 — register a slow-query log callback. `threshold_us`
1777    /// is the floor (in microseconds); only executes above the floor
1778    /// fire the callback. spg-server wires this from
1779    /// `SPG_SLOW_QUERY_THRESHOLD_MS` (default 100 ms).
1780    #[must_use]
1781    pub const fn with_slow_query_log(mut self, threshold_us: u64, logger: SlowQueryLogger) -> Self {
1782        self.slow_query_threshold_us = Some(threshold_us);
1783        self.slow_query_logger = Some(logger);
1784        self
1785    }
1786
1787    /// v6.5.6 — operator knob for plan cache cap. spg-server reads
1788    /// `SPG_PLAN_CACHE_MAX` env at startup; uses this to override
1789    /// the compile-time default of 256.
1790    pub fn set_plan_cache_max(&mut self, n: usize) {
1791        self.plan_cache.set_max_entries(n);
1792    }
1793
1794    /// v6.5.2 — materialise `spg_stat_activity` rows. Pulls a fresh
1795    /// snapshot from the registered `ActivityProvider`. Returns an
1796    /// empty result set when no provider is registered (the no_std
1797    /// embedded path with no pgwire layer).
1798    fn exec_spg_stat_activity(&self) -> QueryResult {
1799        let columns = alloc::vec![
1800            ColumnSchema::new("pid", DataType::Int, false),
1801            ColumnSchema::new("user", DataType::Text, false),
1802            ColumnSchema::new("started_at_us", DataType::BigInt, false),
1803            ColumnSchema::new("current_sql", DataType::Text, false),
1804            ColumnSchema::new("wait_event", DataType::Text, false),
1805            ColumnSchema::new("elapsed_us", DataType::BigInt, false),
1806            ColumnSchema::new("in_transaction", DataType::Bool, false),
1807        ];
1808        let rows: Vec<Row> = self
1809            .activity_provider
1810            .map(|f| f())
1811            .unwrap_or_default()
1812            .into_iter()
1813            .map(|r| {
1814                Row::new(alloc::vec![
1815                    Value::Int(i32::try_from(r.pid).unwrap_or(i32::MAX)),
1816                    Value::Text(r.user),
1817                    Value::BigInt(r.started_at_us),
1818                    Value::Text(r.current_sql),
1819                    Value::Text(r.wait_event),
1820                    Value::BigInt(r.elapsed_us),
1821                    Value::Bool(r.in_transaction),
1822                ])
1823            })
1824            .collect();
1825        QueryResult::Rows { columns, rows }
1826    }
1827
1828    /// v6.5.4 — materialise `spg_table_ddl` rows. One row per user
1829    /// table with `(table_name, ddl)`. Reconstructed from catalog
1830    /// state on demand.
1831    fn exec_spg_table_ddl(&self) -> QueryResult {
1832        let columns = alloc::vec![
1833            ColumnSchema::new("table_name", DataType::Text, false),
1834            ColumnSchema::new("ddl", DataType::Text, false),
1835        ];
1836        let rows: Vec<Row> = self
1837            .catalog
1838            .table_names()
1839            .into_iter()
1840            .filter(|n| !is_internal_table_name(n))
1841            .filter_map(|name| {
1842                let table = self.catalog.get(&name)?;
1843                let ddl = render_create_table(&name, &table.schema().columns);
1844                Some(Row::new(alloc::vec![Value::Text(name), Value::Text(ddl),]))
1845            })
1846            .collect();
1847        QueryResult::Rows { columns, rows }
1848    }
1849
1850    /// v6.5.4 — materialise `spg_role_ddl` rows. One row per user
1851    /// with `(role_name, ddl)`. Password is redacted (matches the
1852    /// `Statement::CreateUser` Display which prints `'<redacted>'`).
1853    fn exec_spg_role_ddl(&self) -> QueryResult {
1854        let columns = alloc::vec![
1855            ColumnSchema::new("role_name", DataType::Text, false),
1856            ColumnSchema::new("ddl", DataType::Text, false),
1857        ];
1858        let rows: Vec<Row> = self
1859            .users
1860            .iter()
1861            .map(|(name, rec)| {
1862                let ddl = alloc::format!(
1863                    "CREATE USER {name} WITH PASSWORD '<redacted>' ROLE '{}'",
1864                    rec.role.as_str(),
1865                );
1866                Row::new(alloc::vec![
1867                    Value::Text(String::from(name)),
1868                    Value::Text(ddl)
1869                ])
1870            })
1871            .collect();
1872        QueryResult::Rows { columns, rows }
1873    }
1874
1875    /// v6.5.4 — materialise `spg_database_ddl`: single row whose
1876    /// `ddl` column concatenates every user table's CREATE +
1877    /// every role's CREATE in deterministic catalog order. Suitable
1878    /// for piping back through `Engine::execute` to recreate a
1879    /// schema-equivalent database.
1880    fn exec_spg_database_ddl(&self) -> QueryResult {
1881        let columns = alloc::vec![ColumnSchema::new("ddl", DataType::Text, false)];
1882        let mut out = String::new();
1883        for (name, rec) in self.users.iter() {
1884            out.push_str(&alloc::format!(
1885                "CREATE USER {name} WITH PASSWORD '<redacted>' ROLE '{}';\n",
1886                rec.role.as_str(),
1887            ));
1888        }
1889        for name in self.catalog.table_names() {
1890            if is_internal_table_name(&name) {
1891                continue;
1892            }
1893            if let Some(table) = self.catalog.get(&name) {
1894                out.push_str(&render_create_table(&name, &table.schema().columns));
1895                out.push_str(";\n");
1896            }
1897        }
1898        QueryResult::Rows {
1899            columns,
1900            rows: alloc::vec![Row::new(alloc::vec![Value::Text(out)])],
1901        }
1902    }
1903
1904    /// v6.5.3 — materialise `spg_audit_chain` rows. Pulls a fresh
1905    /// snapshot from the registered provider; empty when no
1906    /// provider is set.
1907    fn exec_spg_audit_chain(&self) -> QueryResult {
1908        let columns = alloc::vec![
1909            ColumnSchema::new("seq", DataType::BigInt, false),
1910            ColumnSchema::new("ts_ms", DataType::BigInt, false),
1911            ColumnSchema::new("prev_hash", DataType::Text, false),
1912            ColumnSchema::new("entry_hash", DataType::Text, false),
1913            ColumnSchema::new("sql", DataType::Text, false),
1914        ];
1915        let rows: Vec<Row> = self
1916            .audit_chain_provider
1917            .map(|f| f())
1918            .unwrap_or_default()
1919            .into_iter()
1920            .map(|r| {
1921                Row::new(alloc::vec![
1922                    Value::BigInt(r.seq),
1923                    Value::BigInt(r.ts_ms),
1924                    Value::Text(r.prev_hash_hex),
1925                    Value::Text(r.entry_hash_hex),
1926                    Value::Text(r.sql),
1927                ])
1928            })
1929            .collect();
1930        QueryResult::Rows { columns, rows }
1931    }
1932
1933    /// v6.5.3 — materialise `spg_audit_verify` single-row result.
1934    /// `(verified_count, broken_at_seq)` — broken_at_seq is `-1`
1935    /// on a clean chain. Returns one row with both values 0 when
1936    /// no verifier is registered (no-data fallback for embedded
1937    /// callers).
1938    fn exec_spg_audit_verify(&self) -> QueryResult {
1939        let columns = alloc::vec![
1940            ColumnSchema::new("verified_count", DataType::BigInt, false),
1941            ColumnSchema::new("broken_at_seq", DataType::BigInt, false),
1942        ];
1943        let (verified, broken) = self.audit_verifier.map(|f| f()).unwrap_or((0, -1));
1944        let row = Row::new(alloc::vec![Value::BigInt(verified), Value::BigInt(broken),]);
1945        QueryResult::Rows {
1946            columns,
1947            rows: alloc::vec![row],
1948        }
1949    }
1950
1951    /// v6.5.1 — read-only accessor for tests + v6.5.6 ops resets.
1952    pub fn query_stats(&self) -> &query_stats::QueryStats {
1953        &self.query_stats
1954    }
1955
1956    /// v6.5.1 — mutable accessor (clear, etc).
1957    pub fn query_stats_mut(&mut self) -> &mut query_stats::QueryStats {
1958        &mut self.query_stats
1959    }
1960
1961    /// v6.2.0 — read access to the per-column statistics table.
1962    /// Used by the planner (v6.2.2 selectivity functions read this),
1963    /// by `SELECT * FROM spg_statistic`, and by e2e tests.
1964    pub const fn statistics(&self) -> &statistics::Statistics {
1965        &self.statistics
1966    }
1967
1968    /// v6.2.1 — return tables whose modified-row count crossed the
1969    /// auto-analyze threshold since the last ANALYZE on that table.
1970    /// The threshold is `0.1 × max(row_count, MIN_ROWS_FOR_AUTO_
1971    /// ANALYZE)` — combines PG-style fractional + absolute lower
1972    /// bound so a fresh / tiny table doesn't get hammered on every
1973    /// INSERT.
1974    ///
1975    /// Designed to be cheap: walks every user table's
1976    /// `Catalog::table_names()` + reads `statistics::modified_
1977    /// since_last_analyze()` (BTreeMap lookup). The background
1978    /// worker calls this under `engine.read()` then drops the lock
1979    /// before re-acquiring `engine.write()` for the actual ANALYZE.
1980    pub fn tables_needing_analyze(&self) -> Vec<String> {
1981        const MIN_ROWS: u64 = 100;
1982        let mut out = Vec::new();
1983        for name in self.catalog.table_names() {
1984            if is_internal_table_name(&name) {
1985                continue;
1986            }
1987            let Some(table) = self.catalog.get(&name) else {
1988                continue;
1989            };
1990            let row_count = table.rows().len() as u64;
1991            let modified = self.statistics.modified_since_last_analyze(&name);
1992            // Threshold: ceil(0.1 × max(row_count, MIN_ROWS)),
1993            // computed in integer arithmetic so spg-engine stays
1994            // no_std without pulling in libm. `(n + 9) / 10` is
1995            // `ceil(n / 10)` for non-negative `n`.
1996            let base = row_count.max(MIN_ROWS);
1997            let threshold = base.saturating_add(9) / 10;
1998            if modified >= threshold {
1999                out.push(name);
2000            }
2001        }
2002        out
2003    }
2004
2005    /// v6.2.0 — `ANALYZE [<table>]` runtime. Bare `ANALYZE` walks
2006    /// every user table; `ANALYZE <name>` re-stats one. For each
2007    /// target table, single-pass scan + per-column histogram +
2008    /// `null_frac` + `n_distinct`. Replaces the table's prior
2009    /// stats; resets the modified-row counter.
2010    ///
2011    /// v6.2.0 doesn't sample — it scans the full table. v6.2.x
2012    /// can add reservoir sampling at the > 100 K-row mark; not a
2013    /// scope blocker for the current commit since rows ≤ 100 K
2014    /// analyse in milliseconds.
2015    fn exec_analyze(&mut self, target: Option<&str>) -> Result<QueryResult, EngineError> {
2016        let names: Vec<String> = if let Some(name) = target {
2017            // Verify the table exists; surface a clear error if not.
2018            if self.catalog.get(name).is_none() {
2019                return Err(EngineError::Storage(StorageError::TableNotFound {
2020                    name: name.to_string(),
2021                }));
2022            }
2023            alloc::vec![name.to_string()]
2024        } else {
2025            self.catalog
2026                .table_names()
2027                .into_iter()
2028                .filter(|n| !is_internal_table_name(n))
2029                .collect()
2030        };
2031        let mut analysed = 0usize;
2032        for table_name in &names {
2033            self.analyze_one_table(table_name)?;
2034            analysed += 1;
2035        }
2036        // v6.3.1 — plan cache invalidation. Bump stats version so
2037        // future lookups see the new generation, and selectively
2038        // evict every plan whose `source_tables` overlap with the
2039        // ANALYZE target set. Bare ANALYZE (all tables) clears the
2040        // whole cache.
2041        if analysed > 0 {
2042            self.statistics.bump_version();
2043            if target.is_some() {
2044                for t in &names {
2045                    self.plan_cache.evict_referencing(t);
2046                }
2047            } else {
2048                self.plan_cache.clear();
2049            }
2050        }
2051        Ok(QueryResult::CommandOk {
2052            affected: analysed,
2053            modified_catalog: true,
2054        })
2055    }
2056
2057    /// v6.7.3 — `COMPACT COLD SEGMENTS` runtime path. Drives the
2058    /// engine-layer compaction shim with the default
2059    /// 4 MiB segment-size threshold. spg-server intercepts the
2060    /// SQL before it reaches the engine on a server build —
2061    /// it reads `SPG_COMPACTION_TARGET_SEGMENT_BYTES`, calls
2062    /// `Engine::compact_cold_segments_with_target` directly with
2063    /// the env value, and persists every merged segment to
2064    /// `<db>.spg/segments/`. This arm only fires for engine-only
2065    /// callers (spg-embedded, lib tests); in that mode merged
2066    /// segments live in memory and are dropped at process exit.
2067    fn exec_compact_cold_segments(&mut self) -> Result<QueryResult, EngineError> {
2068        let target = COMPACTION_TARGET_DEFAULT_BYTES;
2069        let reports = self.compact_cold_segments_with_target(target)?;
2070        let columns = alloc::vec![
2071            ColumnSchema::new("table_name", DataType::Text, false),
2072            ColumnSchema::new("index_name", DataType::Text, false),
2073            ColumnSchema::new("sources_merged", DataType::BigInt, false),
2074            ColumnSchema::new("merged_segment_id", DataType::BigInt, false),
2075            ColumnSchema::new("merged_rows", DataType::BigInt, false),
2076            ColumnSchema::new("deleted_rows_pruned", DataType::BigInt, false),
2077            ColumnSchema::new("bytes_reclaimed_estimate", DataType::BigInt, false),
2078        ];
2079        let rows: Vec<Row> = reports
2080            .into_iter()
2081            .map(|(tname, iname, report)| {
2082                Row::new(alloc::vec![
2083                    Value::Text(tname),
2084                    Value::Text(iname),
2085                    Value::BigInt(i64::try_from(report.sources.len()).unwrap_or(i64::MAX)),
2086                    Value::BigInt(i64::from(report.merged_segment_id.unwrap_or(0))),
2087                    Value::BigInt(i64::try_from(report.merged_rows).unwrap_or(i64::MAX)),
2088                    Value::BigInt(i64::try_from(report.deleted_rows_pruned).unwrap_or(i64::MAX),),
2089                    Value::BigInt(
2090                        i64::try_from(report.bytes_reclaimed_estimate).unwrap_or(i64::MAX),
2091                    ),
2092                ])
2093            })
2094            .collect();
2095        Ok(QueryResult::Rows { columns, rows })
2096    }
2097
2098    /// Walk a single table's rows once and (re-)populate per-column
2099    /// stats. Drops the existing stats for `table` first so columns
2100    /// that have been DROP-ed between ANALYZEs don't leave stale
2101    /// rows.
2102    fn analyze_one_table(&mut self, table_name: &str) -> Result<(), EngineError> {
2103        let table = self.catalog.get(table_name).ok_or_else(|| {
2104            EngineError::Storage(StorageError::TableNotFound {
2105                name: table_name.to_string(),
2106            })
2107        })?;
2108        let schema = table.schema().clone();
2109        let row_count = table.rows().len();
2110        // For each column, collect (sorted) non-NULL textual values
2111        // + count NULLs; then ask `statistics::build_histogram` to
2112        // produce the 101 bounds and `estimate_n_distinct` the
2113        // distinct count.
2114        self.statistics.clear_table(table_name);
2115        for (col_pos, col_schema) in schema.columns.iter().enumerate() {
2116            // v6.2.0 skip: vector columns have their own stats
2117            // shape (HNSW graph topology). v6.2 deliberation #1.
2118            if matches!(col_schema.ty, DataType::Vector { .. }) {
2119                continue;
2120            }
2121            let mut non_null_values: Vec<Value> = Vec::with_capacity(row_count);
2122            let mut nulls: u64 = 0;
2123            for row in table.rows() {
2124                match row.values.get(col_pos) {
2125                    Some(Value::Null) | None => nulls += 1,
2126                    Some(v) => non_null_values.push(v.clone()),
2127                }
2128            }
2129            // Sort by type-aware ordering (Int as int, Text as
2130            // lex, etc.) so histogram bounds reflect the column's
2131            // natural order — not lexicographic on the string
2132            // representation, which would put "9" after "49".
2133            non_null_values.sort_by(|a, b| sort_values_for_histogram(a, b));
2134            let non_null: Vec<String> = non_null_values.iter().map(canonical_value_repr).collect();
2135            let null_frac = if row_count == 0 {
2136                0.0
2137            } else {
2138                #[allow(clippy::cast_precision_loss)]
2139                let f = nulls as f32 / row_count as f32;
2140                f
2141            };
2142            let n_distinct = statistics::estimate_n_distinct(&non_null);
2143            let histogram_bounds = statistics::build_histogram(&non_null);
2144            self.statistics.set(
2145                table_name.to_string(),
2146                col_schema.name.clone(),
2147                statistics::ColumnStats {
2148                    null_frac,
2149                    n_distinct,
2150                    histogram_bounds,
2151                },
2152            );
2153        }
2154        self.statistics.reset_modified(table_name);
2155        // v6.7.0 — refresh the per-table cold_rows cache. Walk the
2156        // BTree indices and count Cold locators (MAX across
2157        // indices); store the result on the table. Surfaced via
2158        // `spg_statistic.cold_row_count` (new column) and
2159        // `spg_stat_segment.table_name` (new column).
2160        let cold_count = {
2161            let table = self
2162                .active_catalog()
2163                .get(table_name)
2164                .expect("table still present");
2165            table.count_cold_locators()
2166        };
2167        let table_mut = self
2168            .active_catalog_mut()
2169            .get_mut(table_name)
2170            .expect("table still present");
2171        table_mut.set_cold_row_count(cold_count);
2172        Ok(())
2173    }
2174
2175    /// v6.1.3 — `SHOW PUBLICATIONS` row materialisation. Returns
2176    /// `(name, scope, table_count)` ordered by publication name.
2177    ///   - `scope` is the human-readable string:
2178    ///       `"FOR ALL TABLES"` /
2179    ///       `"FOR TABLE t1, t2"` /
2180    ///       `"FOR ALL TABLES EXCEPT t1, t2"`.
2181    ///   - `table_count` is NULL for `AllTables`, the list length
2182    ///     otherwise. NULLability lets clients distinguish "publish
2183    ///     everything" from "publish exactly 0 tables" (the v6.1.3
2184    ///     parser forbids the empty list, but the column shape is
2185    ///     ready for the v6.1.5 publisher-side semantics).
2186    fn exec_show_publications(&self) -> QueryResult {
2187        let columns = alloc::vec![
2188            ColumnSchema::new("name", DataType::Text, false),
2189            ColumnSchema::new("scope", DataType::Text, false),
2190            ColumnSchema::new("table_count", DataType::Int, true),
2191        ];
2192        let rows: Vec<Row> = self
2193            .publications
2194            .iter()
2195            .map(|(name, scope)| {
2196                let (scope_str, count_val) = match scope {
2197                    spg_sql::ast::PublicationScope::AllTables => {
2198                        ("FOR ALL TABLES".to_string(), Value::Null)
2199                    }
2200                    spg_sql::ast::PublicationScope::ForTables(ts) => (
2201                        alloc::format!("FOR TABLE {}", ts.join(", ")),
2202                        Value::Int(i32::try_from(ts.len()).unwrap_or(i32::MAX)),
2203                    ),
2204                    spg_sql::ast::PublicationScope::AllTablesExcept(ts) => (
2205                        alloc::format!("FOR ALL TABLES EXCEPT {}", ts.join(", ")),
2206                        Value::Int(i32::try_from(ts.len()).unwrap_or(i32::MAX)),
2207                    ),
2208                };
2209                Row::new(alloc::vec![
2210                    Value::Text(name.clone()),
2211                    Value::Text(scope_str),
2212                    count_val,
2213                ])
2214            })
2215            .collect();
2216        QueryResult::Rows { columns, rows }
2217    }
2218
2219    /// v4.1 `SHOW USERS` — `(name, role)` per row, ordered by name.
2220    fn exec_show_users(&self) -> QueryResult {
2221        let columns = alloc::vec![
2222            ColumnSchema::new("name", DataType::Text, false),
2223            ColumnSchema::new("role", DataType::Text, false),
2224        ];
2225        let rows: Vec<Row> = self
2226            .users
2227            .iter()
2228            .map(|(name, rec)| {
2229                Row::new(alloc::vec![
2230                    Value::Text(name.to_string()),
2231                    Value::Text(rec.role.as_str().to_string()),
2232                ])
2233            })
2234            .collect();
2235        QueryResult::Rows { columns, rows }
2236    }
2237
2238    fn exec_create_user(&mut self, s: &CreateUserStatement) -> Result<QueryResult, EngineError> {
2239        if self.in_transaction() {
2240            return Err(EngineError::Unsupported(
2241                "CREATE USER is not allowed inside a transaction".into(),
2242            ));
2243        }
2244        let role = users::Role::parse(&s.role).ok_or_else(|| {
2245            EngineError::Unsupported(alloc::format!("invalid role: {:?}", s.role))
2246        })?;
2247        // Prefer the host-injected RNG. Falls back to a deterministic
2248        // salt derived from the username only when no RNG is wired —
2249        // acceptable for tests; the server always installs one.
2250        let salt = self.salt_fn.map_or_else(
2251            || {
2252                let mut s_bytes = [0u8; 16];
2253                let digest = spg_crypto::hash(s.name.as_bytes());
2254                s_bytes.copy_from_slice(&digest[..16]);
2255                s_bytes
2256            },
2257            |f| f(),
2258        );
2259        self.users
2260            .create(&s.name, &s.password, role, salt)
2261            .map_err(|e| EngineError::Unsupported(alloc::format!("CREATE USER: {e}")))?;
2262        Ok(QueryResult::CommandOk {
2263            affected: 1,
2264            modified_catalog: true,
2265        })
2266    }
2267
2268    fn exec_drop_user(&mut self, name: &str) -> Result<QueryResult, EngineError> {
2269        if self.in_transaction() {
2270            return Err(EngineError::Unsupported(
2271                "DROP USER is not allowed inside a transaction".into(),
2272            ));
2273        }
2274        self.users
2275            .drop(name)
2276            .map_err(|e| EngineError::Unsupported(alloc::format!("DROP USER: {e}")))?;
2277        Ok(QueryResult::CommandOk {
2278            affected: 1,
2279            modified_catalog: true,
2280        })
2281    }
2282
2283    /// v4.4 `UPDATE <table> SET col = expr [, ...] [WHERE cond]`.
2284    /// Filter pass uses the same WHERE eval as `exec_select`. Per
2285    /// matched row, evaluate each RHS expression against the *old*
2286    /// row, then call `Table::update_row` which rebuilds indices.
2287    /// Indexed columns are correctly reflected because rebuild
2288    /// happens after the cell rewrite.
2289    fn exec_update_cancel(
2290        &mut self,
2291        stmt: &spg_sql::ast::UpdateStatement,
2292        cancel: CancelToken<'_>,
2293    ) -> Result<QueryResult, EngineError> {
2294        // v5.2.3: if the WHERE is a PK equality and matches a cold-
2295        // tier row, promote it back to the hot tier *before* the
2296        // hot-row walk. The promote pushes the row to the end of
2297        // `table.rows`, where the upcoming SET-evaluation loop will
2298        // pick it up and apply the assignments. Lookups for the key
2299        // never observe a gap because `promote_cold_row` inserts the
2300        // hot row before retiring the cold locator.
2301        if let Some(w) = &stmt.where_ {
2302            let schema_cols = self
2303                .active_catalog()
2304                .get(&stmt.table)
2305                .ok_or_else(|| {
2306                    EngineError::Storage(StorageError::TableNotFound {
2307                        name: stmt.table.clone(),
2308                    })
2309                })?
2310                .schema()
2311                .columns
2312                .clone();
2313            if let Some((col_pos, key)) = try_pk_predicate(w, &schema_cols, stmt.table.as_str())
2314                && let Some(idx_name) = self
2315                    .active_catalog()
2316                    .get(&stmt.table)
2317                    .and_then(|t| t.index_on(col_pos).map(|i| i.name.clone()))
2318            {
2319                // Promote may be a no-op (key is hot-only or absent);
2320                // we don't care about the return value here — the
2321                // subsequent hot walk will either match or not.
2322                let _ = self
2323                    .active_catalog_mut()
2324                    .promote_cold_row(&stmt.table, &idx_name, &key);
2325            }
2326        }
2327
2328        let table = self
2329            .active_catalog_mut()
2330            .get_mut(&stmt.table)
2331            .ok_or_else(|| {
2332                EngineError::Storage(StorageError::TableNotFound {
2333                    name: stmt.table.clone(),
2334                })
2335            })?;
2336        let schema_cols: Vec<ColumnSchema> = table.schema().columns.clone();
2337        // Resolve each SET target to a column position once, validate
2338        // up front so a typo'd column doesn't leave a partial mutation
2339        // behind.
2340        let mut targets: Vec<(usize, &Expr)> = Vec::with_capacity(stmt.assignments.len());
2341        for (col, expr) in &stmt.assignments {
2342            let pos = schema_cols
2343                .iter()
2344                .position(|c| c.name == *col)
2345                .ok_or_else(|| {
2346                    EngineError::Eval(EvalError::ColumnNotFound { name: col.clone() })
2347                })?;
2348            targets.push((pos, expr));
2349        }
2350        let ctx = EvalContext::new(&schema_cols, Some(stmt.table.as_str()));
2351        // Walk every row, evaluate WHERE then SET expressions. We
2352        // gather (position, new_values) tuples first and apply them
2353        // afterwards so the WHERE/RHS evaluation reads the original
2354        // row state — matches PG semantics (UPDATE doesn't see its
2355        // own writes).
2356        let mut planned: Vec<(usize, Vec<Value>)> = Vec::new();
2357        for (i, row) in table.rows().iter().enumerate() {
2358            // v4.5: cooperative cancel checkpoint every 256 rows so
2359            // a runaway UPDATE without WHERE doesn't drag past the
2360            // server's query-timeout watchdog.
2361            if i.is_multiple_of(256) {
2362                cancel.check()?;
2363            }
2364            if let Some(w) = &stmt.where_ {
2365                let cond = eval::eval_expr(w, row, &ctx)?;
2366                if !matches!(cond, Value::Bool(true)) {
2367                    continue;
2368                }
2369            }
2370            let mut new_vals = row.values.clone();
2371            for (pos, expr) in &targets {
2372                let v = eval::eval_expr(expr, row, &ctx)?;
2373                new_vals[*pos] =
2374                    coerce_value(v, schema_cols[*pos].ty, &schema_cols[*pos].name, *pos)?;
2375            }
2376            planned.push((i, new_vals));
2377        }
2378        // v7.6.6 — capture pre-update row values for the FK
2379        // enforcement passes below. `planned` carries new values
2380        // only; pair them with the old row.
2381        let plan_with_old: Vec<(usize, Vec<Value>, Vec<Value>)> = planned
2382            .iter()
2383            .map(|(pos, new_vals)| (*pos, table.rows()[*pos].values.clone(), new_vals.clone()))
2384            .collect();
2385        let self_fks = table.schema().foreign_keys.clone();
2386        let affected = planned.len();
2387        // Release mutable borrow on `table` for the FK passes.
2388        let _ = table;
2389        // v7.6.6 — Stage 2a: outbound FK check. For every row whose
2390        // local FK columns changed, the new value must exist in the
2391        // parent.
2392        if !self_fks.is_empty() {
2393            let new_rows: Vec<Vec<Value>> = planned
2394                .iter()
2395                .map(|(_pos, new_vals)| new_vals.clone())
2396                .collect();
2397            enforce_fk_inserts(self.active_catalog(), &stmt.table, &self_fks, &new_rows)?;
2398        }
2399        // v7.6.6 — Stage 2b: inbound FK check. For every row that
2400        // changed value in a column that *some other table* uses as
2401        // a FK parent column, react per `on_update` action.
2402        let child_plan =
2403            plan_fk_parent_updates(self.active_catalog(), &stmt.table, &plan_with_old)?;
2404        // Stage 3a — apply each child-side action.
2405        for step in &child_plan {
2406            apply_fk_child_step(self.active_catalog_mut(), step)?;
2407        }
2408        // Stage 3b — apply the original UPDATE.
2409        let table = self
2410            .active_catalog_mut()
2411            .get_mut(&stmt.table)
2412            .ok_or_else(|| {
2413                EngineError::Storage(StorageError::TableNotFound {
2414                    name: stmt.table.clone(),
2415                })
2416            })?;
2417        // v7.9.4 — snapshot post-update values for RETURNING.
2418        let updated_for_returning: Vec<Vec<Value>> = if stmt.returning.is_some() {
2419            planned.iter().map(|(_pos, vals)| vals.clone()).collect()
2420        } else {
2421            Vec::new()
2422        };
2423        for (pos, vals) in planned {
2424            table.update_row(pos, vals)?;
2425        }
2426        let _ = table;
2427        // v6.2.1 — auto-analyze modified-row tracking for UPDATE.
2428        if !self.in_transaction() && affected > 0 {
2429            self.statistics
2430                .record_modifications(&stmt.table, affected as u64);
2431        }
2432        // v7.9.4 — RETURNING projection.
2433        if let Some(items) = &stmt.returning {
2434            return self.build_returning_rows(&stmt.table, items, updated_for_returning);
2435        }
2436        Ok(QueryResult::CommandOk {
2437            affected,
2438            modified_catalog: !self.in_transaction(),
2439        })
2440    }
2441
2442    /// v4.4 `DELETE FROM <table> [WHERE cond]`. Collects matching
2443    /// positions then delegates to `Table::delete_rows` (single index
2444    /// rebuild for the batch).
2445    fn exec_delete_cancel(
2446        &mut self,
2447        stmt: &spg_sql::ast::DeleteStatement,
2448        cancel: CancelToken<'_>,
2449    ) -> Result<QueryResult, EngineError> {
2450        // v5.2.3: PK-targeted DELETE → first retire any cold-tier
2451        // locator for the key. The cold row body stays in the
2452        // segment (becoming shadowed garbage that a future
2453        // compaction pass reclaims) but the index no longer
2454        // resolves it. The shadow count contributes to the
2455        // affected total; the subsequent hot walk handles any hot
2456        // rows for the same key.
2457        let mut cold_shadow_count: usize = 0;
2458        if let Some(w) = &stmt.where_ {
2459            let schema_cols = self
2460                .active_catalog()
2461                .get(&stmt.table)
2462                .ok_or_else(|| {
2463                    EngineError::Storage(StorageError::TableNotFound {
2464                        name: stmt.table.clone(),
2465                    })
2466                })?
2467                .schema()
2468                .columns
2469                .clone();
2470            if let Some((col_pos, key)) = try_pk_predicate(w, &schema_cols, stmt.table.as_str())
2471                && let Some(idx_name) = self
2472                    .active_catalog()
2473                    .get(&stmt.table)
2474                    .and_then(|t| t.index_on(col_pos).map(|i| i.name.clone()))
2475            {
2476                cold_shadow_count = self
2477                    .active_catalog_mut()
2478                    .shadow_cold_row(&stmt.table, &idx_name, &key)
2479                    .unwrap_or(0);
2480            }
2481        }
2482
2483        let table = self
2484            .active_catalog_mut()
2485            .get_mut(&stmt.table)
2486            .ok_or_else(|| {
2487                EngineError::Storage(StorageError::TableNotFound {
2488                    name: stmt.table.clone(),
2489                })
2490            })?;
2491        let schema_cols: Vec<ColumnSchema> = table.schema().columns.clone();
2492        let ctx = EvalContext::new(&schema_cols, Some(stmt.table.as_str()));
2493        let mut positions: Vec<usize> = Vec::new();
2494        // v7.6.3 — collect every to-delete row's full Value tuple
2495        // alongside its position, so the FK enforcement pass can
2496        // run after the mut borrow drops.
2497        let mut to_delete_rows: Vec<Vec<Value>> = Vec::new();
2498        for (i, row) in table.rows().iter().enumerate() {
2499            if i.is_multiple_of(256) {
2500                cancel.check()?;
2501            }
2502            let keep = if let Some(w) = &stmt.where_ {
2503                let cond = eval::eval_expr(w, row, &ctx)?;
2504                !matches!(cond, Value::Bool(true))
2505            } else {
2506                false
2507            };
2508            if !keep {
2509                positions.push(i);
2510                to_delete_rows.push(row.values.clone());
2511            }
2512        }
2513        // v7.6.3 / v7.6.4 — Stage 2: FK enforcement on the immutable
2514        // catalog. Release the mut borrow and run reverse-scan
2515        // against every child table whose FK targets this table.
2516        // RESTRICT / NoAction raise an error; CASCADE returns a
2517        // cascade plan that stage 3 applies after the primary delete.
2518        // SET NULL / SET DEFAULT remain Unsupported until v7.6.5.
2519        let _ = table;
2520        let cascade_plan = plan_fk_parent_deletions(
2521            self.active_catalog(),
2522            &stmt.table,
2523            &positions,
2524            &to_delete_rows,
2525        )?;
2526        // Stage 3a — apply each FK child step (SET NULL / SET
2527        // DEFAULT / CASCADE delete) before deleting the parent.
2528        // The plan is already ordered: nulls/defaults first, then
2529        // cascade deletes (so a row mutated and later deleted
2530        // surfaces as deleted — though v7.6.5 doesn't produce
2531        // that overlap today).
2532        for step in &cascade_plan {
2533            apply_fk_child_step(self.active_catalog_mut(), step)?;
2534        }
2535        // Stage 3b — actually delete the original target rows.
2536        let table = self
2537            .active_catalog_mut()
2538            .get_mut(&stmt.table)
2539            .ok_or_else(|| {
2540                EngineError::Storage(StorageError::TableNotFound {
2541                    name: stmt.table.clone(),
2542                })
2543            })?;
2544        let affected = table.delete_rows(&positions) + cold_shadow_count;
2545        let _ = table;
2546        // v6.2.1 — auto-analyze modified-row tracking for DELETE.
2547        if !self.in_transaction() && affected > 0 {
2548            self.statistics
2549                .record_modifications(&stmt.table, affected as u64);
2550        }
2551        // v7.9.4 — RETURNING projection over the soon-to-be-gone
2552        // rows. `to_delete_rows` was snapshotted in stage 1 before
2553        // mutation, so the projection sees the pre-delete state
2554        // (matches PG semantics: DELETE RETURNING returns the row
2555        // as it was just before removal).
2556        if let Some(items) = &stmt.returning {
2557            return self.build_returning_rows(&stmt.table, items, to_delete_rows);
2558        }
2559        Ok(QueryResult::CommandOk {
2560            affected,
2561            modified_catalog: !self.in_transaction(),
2562        })
2563    }
2564
2565    /// `SHOW TABLES` — one row per table in the active catalog.
2566    /// Column name is `name` so result-set consumers can downstream
2567    /// `SELECT name FROM ...` style logic if needed.
2568    /// v4.26: `EXPLAIN [ANALYZE] <select>`. Returns a single-column
2569    /// `QUERY PLAN` text table — first line names the top operator
2570    /// (Scan / Aggregate / Window / etc.), indented children list
2571    /// FROM joins, WHERE filters, ORDER BY / LIMIT, projection
2572    /// shape, and any active index hits. `ANALYZE` execs the inner
2573    /// SELECT and appends actual-row + elapsed-micros annotations.
2574    #[allow(clippy::format_push_string)]
2575    fn exec_explain(
2576        &self,
2577        e: &spg_sql::ast::ExplainStatement,
2578        cancel: CancelToken<'_>,
2579    ) -> Result<QueryResult, EngineError> {
2580        let mut lines = Vec::<String>::new();
2581        explain_select(&e.inner, self, 0, &mut lines);
2582        if e.suggest {
2583            // v6.8.3 — index advisor. Walks the SELECT's FROM
2584            // tables + WHERE column refs; for each (table, column)
2585            // pair that lacks an index, append a SUGGEST line with
2586            // a copy-pastable `CREATE INDEX` statement. This is a
2587            // pure-syntax heuristic — no cardinality estimation —
2588            // matching the v6.8.3 design intent of "tell the
2589            // operator where indexes are missing", not "give the
2590            // mathematically optimal index set".
2591            let suggestions = build_index_suggestions(&e.inner, self);
2592            for s in suggestions {
2593                lines.push(s);
2594            }
2595        } else if e.analyze {
2596            // v6.2.4 — EXPLAIN ANALYZE annotates each operator line
2597            // with `(rows=N)` where the row count is computable
2598            // without re-executing the full query:
2599            //   - Top-level operator (first non-indented line):
2600            //     rows = final result.len()
2601            //   - "From: <table> [full scan]" lines: rows =
2602            //     table.rows().len() (catalog read; no execution)
2603            //   - "From: <table> [index seek]": indeterminate —
2604            //     the index step would need re-execution; v6.2.5
2605            //     adds per-operator wall-clock + hot/cold rows
2606            //     instrumentation that makes this concrete.
2607            //   - Everything else: marked `(—)` so the surface
2608            //     stays well-defined without silently dropping
2609            //     stats. v6.2.5 fills in via inline executor
2610            //     instrumentation.
2611            // Total elapsed lands on a trailing `Total: …` line.
2612            let started = self.clock.map(|f| f());
2613            let exec = self.exec_select_cancel(&e.inner, cancel)?;
2614            let elapsed_micros = match (self.clock, started) {
2615                (Some(f), Some(s)) => Some(f().saturating_sub(s)),
2616                _ => None,
2617            };
2618            let row_count = if let QueryResult::Rows { rows, .. } = &exec {
2619                rows.len()
2620            } else {
2621                0
2622            };
2623            annotate_explain_lines(&mut lines, row_count, self);
2624            let mut total = alloc::format!("Total: rows={row_count}");
2625            if let Some(us) = elapsed_micros {
2626                total.push_str(&alloc::format!(" elapsed={us}us"));
2627            }
2628            lines.push(total);
2629        }
2630        let columns = alloc::vec![ColumnSchema::new("QUERY PLAN", DataType::Text, false)];
2631        let rows: Vec<Row> = lines
2632            .into_iter()
2633            .map(|l| Row::new(alloc::vec![Value::Text(l)]))
2634            .collect();
2635        Ok(QueryResult::Rows { columns, rows })
2636    }
2637
2638    fn exec_show_tables(&self) -> QueryResult {
2639        let columns = alloc::vec![ColumnSchema::new("name", DataType::Text, false)];
2640        let rows: Vec<Row> = self
2641            .active_catalog()
2642            .table_names()
2643            .into_iter()
2644            .map(|n| Row::new(alloc::vec![Value::Text(n)]))
2645            .collect();
2646        QueryResult::Rows { columns, rows }
2647    }
2648
2649    /// `SHOW COLUMNS FROM <table>` — one row per column with the
2650    /// declared name, SQL type rendering, and nullability flag.
2651    fn exec_show_columns(&self, table_name: &str) -> Result<QueryResult, EngineError> {
2652        let table =
2653            self.active_catalog()
2654                .get(table_name)
2655                .ok_or_else(|| StorageError::TableNotFound {
2656                    name: table_name.into(),
2657                })?;
2658        let columns = alloc::vec![
2659            ColumnSchema::new("name", DataType::Text, false),
2660            ColumnSchema::new("type", DataType::Text, false),
2661            ColumnSchema::new("nullable", DataType::Bool, false),
2662        ];
2663        let rows: Vec<Row> = table
2664            .schema()
2665            .columns
2666            .iter()
2667            .map(|c| {
2668                Row::new(alloc::vec![
2669                    Value::Text(c.name.clone()),
2670                    Value::Text(alloc::format!("{}", c.ty)),
2671                    Value::Bool(c.nullable),
2672                ])
2673            })
2674            .collect();
2675        Ok(QueryResult::Rows { columns, rows })
2676    }
2677
2678    fn exec_begin(&mut self) -> Result<QueryResult, EngineError> {
2679        let tx_id = self.current_tx.ok_or(EngineError::NoActiveTransaction)?;
2680        if self.tx_catalogs.contains_key(&tx_id) {
2681            return Err(EngineError::TransactionAlreadyOpen);
2682        }
2683        self.tx_catalogs.insert(
2684            tx_id,
2685            TxState {
2686                catalog: self.catalog.clone(),
2687                savepoints: Vec::new(),
2688            },
2689        );
2690        Ok(QueryResult::CommandOk {
2691            affected: 0,
2692            modified_catalog: false,
2693        })
2694    }
2695
2696    fn exec_commit(&mut self) -> Result<QueryResult, EngineError> {
2697        let tx_id = self.current_tx.ok_or(EngineError::NoActiveTransaction)?;
2698        let state = self
2699            .tx_catalogs
2700            .remove(&tx_id)
2701            .ok_or(EngineError::NoActiveTransaction)?;
2702        self.catalog = state.catalog;
2703        // All savepoints become permanent at COMMIT and the stack
2704        // resets for the next TX (`state.savepoints` is discarded with
2705        // `state`).
2706        Ok(QueryResult::CommandOk {
2707            affected: 0,
2708            modified_catalog: true,
2709        })
2710    }
2711
2712    fn exec_rollback(&mut self) -> Result<QueryResult, EngineError> {
2713        let tx_id = self.current_tx.ok_or(EngineError::NoActiveTransaction)?;
2714        if self.tx_catalogs.remove(&tx_id).is_none() {
2715            return Err(EngineError::NoActiveTransaction);
2716        }
2717        // savepoints discarded with the TxState
2718        Ok(QueryResult::CommandOk {
2719            affected: 0,
2720            modified_catalog: false,
2721        })
2722    }
2723
2724    fn exec_savepoint(&mut self, name: String) -> Result<QueryResult, EngineError> {
2725        let tx_id = self.current_tx.ok_or(EngineError::NoActiveTransaction)?;
2726        let state = self
2727            .tx_catalogs
2728            .get_mut(&tx_id)
2729            .ok_or(EngineError::NoActiveTransaction)?;
2730        // PG re-uses an existing savepoint name by dropping the older
2731        // entry and pushing a fresh one — match that behaviour so
2732        // application code can `SAVEPOINT sp; ...; SAVEPOINT sp` freely.
2733        state.savepoints.retain(|(n, _)| n != &name);
2734        let snapshot = state.catalog.clone();
2735        state.savepoints.push((name, snapshot));
2736        Ok(QueryResult::CommandOk {
2737            affected: 0,
2738            modified_catalog: false,
2739        })
2740    }
2741
2742    fn exec_rollback_to_savepoint(&mut self, name: &str) -> Result<QueryResult, EngineError> {
2743        let tx_id = self.current_tx.ok_or(EngineError::NoActiveTransaction)?;
2744        let state = self
2745            .tx_catalogs
2746            .get_mut(&tx_id)
2747            .ok_or(EngineError::NoActiveTransaction)?;
2748        let pos = state
2749            .savepoints
2750            .iter()
2751            .rposition(|(n, _)| n == name)
2752            .ok_or_else(|| {
2753                EngineError::Unsupported(alloc::format!("savepoint not found: {name}"))
2754            })?;
2755        // The savepoint stays on the stack (PG semantics): a later
2756        // `RELEASE` or further `ROLLBACK TO` is still allowed. Everything
2757        // after it is discarded.
2758        let snapshot = state.savepoints[pos].1.clone();
2759        state.savepoints.truncate(pos + 1);
2760        state.catalog = snapshot;
2761        Ok(QueryResult::CommandOk {
2762            affected: 0,
2763            modified_catalog: false,
2764        })
2765    }
2766
2767    fn exec_release_savepoint(&mut self, name: &str) -> Result<QueryResult, EngineError> {
2768        let tx_id = self.current_tx.ok_or(EngineError::NoActiveTransaction)?;
2769        let state = self
2770            .tx_catalogs
2771            .get_mut(&tx_id)
2772            .ok_or(EngineError::NoActiveTransaction)?;
2773        let pos = state
2774            .savepoints
2775            .iter()
2776            .rposition(|(n, _)| n == name)
2777            .ok_or_else(|| {
2778                EngineError::Unsupported(alloc::format!("savepoint not found: {name}"))
2779            })?;
2780        // RELEASE keeps the work since the savepoint, just discards the
2781        // bookmark plus everything nested under it.
2782        state.savepoints.truncate(pos);
2783        Ok(QueryResult::CommandOk {
2784            affected: 0,
2785            modified_catalog: false,
2786        })
2787    }
2788
2789    /// v6.0.4 — synchronous `ALTER INDEX <name> REBUILD [WITH
2790    /// (encoding = …)]`. Walks every table in the active catalog
2791    /// looking for an index matching `stmt.name`, then delegates the
2792    /// rebuild (including any encoding switch) to
2793    /// `Table::rebuild_nsw_index`. The "live" non-blocking
2794    /// optimisation is v6.0.4.1 / v6.1.x territory.
2795    /// v6.7.2 — `ALTER TABLE t SET hot_tier_bytes = X`. Dispatch
2796    /// arm. Currently the only setting is `hot_tier_bytes`; later
2797    /// v6.7.x can extend `AlterTableTarget` without touching this
2798    /// arm structure.
2799    fn exec_alter_table(
2800        &mut self,
2801        s: spg_sql::ast::AlterTableStatement,
2802    ) -> Result<QueryResult, EngineError> {
2803        match s.target {
2804            spg_sql::ast::AlterTableTarget::SetHotTierBytes(n) => {
2805                let table = self.active_catalog_mut().get_mut(&s.name).ok_or_else(|| {
2806                    EngineError::Storage(StorageError::TableNotFound {
2807                        name: s.name.clone(),
2808                    })
2809                })?;
2810                table.schema_mut().hot_tier_bytes = Some(n);
2811            }
2812            spg_sql::ast::AlterTableTarget::AddForeignKey(fk) => {
2813                // v7.6.8 — resolve FK against the live catalog first
2814                // (validates parent table, columns, indices). Then
2815                // verify every existing row in the child table
2816                // satisfies the new constraint. Then install it.
2817                let cols_snapshot = self
2818                    .active_catalog()
2819                    .get(&s.name)
2820                    .ok_or_else(|| {
2821                        EngineError::Storage(StorageError::TableNotFound {
2822                            name: s.name.clone(),
2823                        })
2824                    })?
2825                    .schema()
2826                    .columns
2827                    .clone();
2828                let storage_fk =
2829                    resolve_foreign_key(&s.name, &cols_snapshot, fk, self.active_catalog())?;
2830                // Verify existing rows. Treat them as a virtual
2831                // INSERT batch — reusing the v7.6.2 enforce helper.
2832                let existing_rows: Vec<Vec<Value>> = self
2833                    .active_catalog()
2834                    .get(&s.name)
2835                    .expect("checked above")
2836                    .rows()
2837                    .iter()
2838                    .map(|r| r.values.clone())
2839                    .collect();
2840                enforce_fk_inserts(
2841                    self.active_catalog(),
2842                    &s.name,
2843                    core::slice::from_ref(&storage_fk),
2844                    &existing_rows,
2845                )?;
2846                // Reject duplicate constraint name.
2847                let table = self
2848                    .active_catalog_mut()
2849                    .get_mut(&s.name)
2850                    .expect("checked above");
2851                if let Some(name) = &storage_fk.name
2852                    && table
2853                        .schema()
2854                        .foreign_keys
2855                        .iter()
2856                        .any(|f| f.name.as_ref() == Some(name))
2857                {
2858                    return Err(EngineError::Unsupported(alloc::format!(
2859                        "ALTER TABLE ADD CONSTRAINT: a constraint named {name:?} already exists"
2860                    )));
2861                }
2862                table.schema_mut().foreign_keys.push(storage_fk);
2863            }
2864            spg_sql::ast::AlterTableTarget::DropForeignKey(name) => {
2865                let table = self.active_catalog_mut().get_mut(&s.name).ok_or_else(|| {
2866                    EngineError::Storage(StorageError::TableNotFound {
2867                        name: s.name.clone(),
2868                    })
2869                })?;
2870                let fks = &mut table.schema_mut().foreign_keys;
2871                let before = fks.len();
2872                fks.retain(|f| f.name.as_ref() != Some(&name));
2873                if fks.len() == before {
2874                    return Err(EngineError::Unsupported(alloc::format!(
2875                        "ALTER TABLE DROP CONSTRAINT: no FK named {name:?} on {:?}",
2876                        s.name
2877                    )));
2878                }
2879            }
2880        }
2881        Ok(QueryResult::CommandOk {
2882            affected: 0,
2883            modified_catalog: !self.in_transaction(),
2884        })
2885    }
2886
2887    fn exec_alter_index(
2888        &mut self,
2889        stmt: spg_sql::ast::AlterIndexStatement,
2890    ) -> Result<QueryResult, EngineError> {
2891        // Translate the optional SQL-side encoding choice into the
2892        // storage-side enum; the same SqlVecEncoding -> VecEncoding
2893        // bridge `column_type_to_data_type` uses.
2894        let spg_sql::ast::AlterIndexStatement {
2895            name: idx_name,
2896            target,
2897        } = stmt;
2898        let spg_sql::ast::AlterIndexTarget::Rebuild { encoding } = target;
2899        let target = encoding.map(|e| match e {
2900            SqlVecEncoding::F32 => VecEncoding::F32,
2901            SqlVecEncoding::Sq8 => VecEncoding::Sq8,
2902            SqlVecEncoding::F16 => VecEncoding::F16,
2903        });
2904        // Linear scan: index names are globally unique within a
2905        // catalog (enforced by add_nsw_index_inner) so the first
2906        // match is the only one. Save the table name to avoid
2907        // borrowing while we then take a mut borrow.
2908        let table_name = {
2909            let cat = self.active_catalog();
2910            let mut found: Option<String> = None;
2911            for tname in cat.table_names() {
2912                if let Some(t) = cat.get(&tname)
2913                    && t.indices().iter().any(|i| i.name == idx_name)
2914                {
2915                    found = Some(tname);
2916                    break;
2917                }
2918            }
2919            found.ok_or_else(|| {
2920                EngineError::Storage(StorageError::IndexNotFound {
2921                    name: idx_name.clone(),
2922                })
2923            })?
2924        };
2925        let table = self
2926            .active_catalog_mut()
2927            .get_mut(&table_name)
2928            .expect("table found above");
2929        table.rebuild_nsw_index(&idx_name, target)?;
2930        // v6.3.1 — ALTER INDEX REBUILD potentially with new encoding
2931        // changes cost characteristics; evict any cached plans.
2932        self.plan_cache.evict_referencing(&table_name);
2933        Ok(QueryResult::CommandOk {
2934            affected: 0,
2935            modified_catalog: !self.in_transaction(),
2936        })
2937    }
2938
2939    fn exec_create_index(
2940        &mut self,
2941        stmt: CreateIndexStatement,
2942    ) -> Result<QueryResult, EngineError> {
2943        let table = self
2944            .active_catalog_mut()
2945            .get_mut(&stmt.table)
2946            .ok_or_else(|| {
2947                EngineError::Storage(StorageError::TableNotFound {
2948                    name: stmt.table.clone(),
2949                })
2950            })?;
2951        // `IF NOT EXISTS` reduces DuplicateIndex to a no-op CommandOk.
2952        if stmt.if_not_exists && table.indices().iter().any(|i| i.name == stmt.name) {
2953            return Ok(QueryResult::CommandOk {
2954                affected: 0,
2955                modified_catalog: false,
2956            });
2957        }
2958        // v7.9.14 — multi-column index parses through; engine
2959        // builds a single-column BTree on the leading column only.
2960        // The extras live on the AST so spg-server's dispatcher
2961        // can emit a PG-wire NoticeResponse / log line. Composite
2962        // BTree keys land in v7.10.
2963        let _ = &stmt.extra_columns; // intentional drop on engine side
2964        let table_name = stmt.table.clone();
2965        // v6.8.0 — resolve INCLUDE column names to positions. Done
2966        // before `add_index` so a typo error surfaces before any
2967        // catalog mutation lands.
2968        let included_positions: Vec<usize> = if stmt.included_columns.is_empty() {
2969            Vec::new()
2970        } else {
2971            let schema = table.schema();
2972            stmt.included_columns
2973                .iter()
2974                .map(|c| {
2975                    schema.column_position(c).ok_or_else(|| {
2976                        EngineError::Storage(StorageError::ColumnNotFound { column: c.clone() })
2977                    })
2978                })
2979                .collect::<Result<Vec<_>, _>>()?
2980        };
2981        match stmt.method {
2982            IndexMethod::BTree => table.add_index(stmt.name.clone(), &stmt.column)?,
2983            IndexMethod::Hnsw => {
2984                if !included_positions.is_empty() {
2985                    return Err(EngineError::Unsupported(
2986                        "INCLUDE columns are not supported on HNSW indexes".into(),
2987                    ));
2988                }
2989                table.add_nsw_index(stmt.name.clone(), &stmt.column, spg_storage::NSW_DEFAULT_M)?;
2990            }
2991            // v6.7.1 — BRIN. Pure metadata; no in-memory data.
2992            IndexMethod::Brin => {
2993                if !included_positions.is_empty() {
2994                    return Err(EngineError::Unsupported(
2995                        "INCLUDE columns are not supported on BRIN indexes".into(),
2996                    ));
2997                }
2998                table.add_brin_index(stmt.name.clone(), &stmt.column)?;
2999            }
3000        }
3001        if !included_positions.is_empty()
3002            && let Some(idx) = table.indices_mut().iter_mut().find(|i| i.name == stmt.name)
3003        {
3004            idx.included_columns = included_positions;
3005        }
3006        // v6.8.1 — persist partial-index predicate. Stored as the
3007        // expression's Display form so the catalog snapshot stays
3008        // pure (storage has no spg-sql dependency). The runtime
3009        // maintenance path treats partial indexes identically to
3010        // full indexes for v6.8.1 (over-maintenance is safe; the
3011        // planner-side "use partial when query WHERE implies the
3012        // predicate" pass is STABILITY carve-out).
3013        if let Some(pred_expr) = &stmt.partial_predicate {
3014            let canonical = pred_expr.to_string();
3015            if matches!(stmt.method, IndexMethod::Hnsw | IndexMethod::Brin) {
3016                return Err(EngineError::Unsupported(
3017                    "WHERE predicates are not supported on HNSW or BRIN indexes".into(),
3018                ));
3019            }
3020            if let Some(idx) = table.indices_mut().iter_mut().find(|i| i.name == stmt.name) {
3021                idx.partial_predicate = Some(canonical);
3022            }
3023        }
3024        // v6.8.2 — persist expression index key. Same Display-form
3025        // storage; the runtime maintenance pass evaluates each
3026        // row's expression to derive the index key, but for v6.8.2
3027        // the engine falls through to the bare-column-reference
3028        // path and the expression is preserved for format-layer
3029        // round-trip + future planner work. Carved-out in
3030        // STABILITY § "Out of v6.8".
3031        if let Some(key_expr) = &stmt.expression {
3032            if matches!(stmt.method, IndexMethod::Hnsw | IndexMethod::Brin) {
3033                return Err(EngineError::Unsupported(
3034                    "Expression keys are not supported on HNSW or BRIN indexes".into(),
3035                ));
3036            }
3037            let canonical = key_expr.to_string();
3038            if let Some(idx) = table.indices_mut().iter_mut().find(|i| i.name == stmt.name) {
3039                idx.expression = Some(canonical);
3040            }
3041        }
3042        // v7.9.29 — persist `is_unique` flag on the storage Index.
3043        // Combined with `partial_predicate`, INSERT enforcement
3044        // checks that no other row whose predicate evaluates true
3045        // shares the same indexed key. Parser already rejected
3046        // `UNIQUE` on HNSW / BRIN, so plain BTree here.
3047        // For multi-column UNIQUE INDEX the extras matter (the
3048        // full tuple is the uniqueness key), so resolve them to
3049        // column positions and persist on the index too.
3050        if stmt.is_unique {
3051            let mut extra_positions: alloc::vec::Vec<usize> = alloc::vec::Vec::new();
3052            for col_name in &stmt.extra_columns {
3053                let pos = table
3054                    .schema()
3055                    .columns
3056                    .iter()
3057                    .position(|c| c.name.eq_ignore_ascii_case(col_name))
3058                    .ok_or_else(|| {
3059                        EngineError::Unsupported(alloc::format!(
3060                            "UNIQUE INDEX {:?}: extra column {col_name:?} not in table {:?}",
3061                            stmt.name,
3062                            stmt.table
3063                        ))
3064                    })?;
3065                extra_positions.push(pos);
3066            }
3067            if let Some(idx) = table.indices_mut().iter_mut().find(|i| i.name == stmt.name) {
3068                idx.is_unique = true;
3069                idx.extra_column_positions = extra_positions;
3070            }
3071            // At index-creation time, check the existing rows for
3072            // pre-existing duplicates that would have violated the
3073            // new constraint — otherwise CREATE UNIQUE INDEX would
3074            // silently leave duplicates in place.
3075            let snapshot_indices = table.indices().to_vec();
3076            let snapshot_rows: alloc::vec::Vec<spg_storage::Row> =
3077                table.rows().iter().cloned().collect();
3078            let snapshot_schema = table.schema().clone();
3079            let idx_ref = snapshot_indices
3080                .iter()
3081                .find(|i| i.name == stmt.name)
3082                .expect("just-added index");
3083            check_existing_unique_violation(idx_ref, &snapshot_schema, &snapshot_rows)?;
3084        }
3085        // v6.3.1 — adding an index can change the optimal plan for
3086        // any cached query that references this table.
3087        self.plan_cache.evict_referencing(&table_name);
3088        Ok(QueryResult::CommandOk {
3089            affected: 0,
3090            modified_catalog: !self.in_transaction(),
3091        })
3092    }
3093
3094    fn exec_create_table(
3095        &mut self,
3096        stmt: CreateTableStatement,
3097    ) -> Result<QueryResult, EngineError> {
3098        if stmt.if_not_exists && self.active_catalog().get(&stmt.name).is_some() {
3099            return Ok(QueryResult::CommandOk {
3100                affected: 0,
3101                modified_catalog: false,
3102            });
3103        }
3104        let table_name = stmt.name.clone();
3105        // v7.9.13 — pluck the names of any columns marked
3106        // `PRIMARY KEY` inline so the post-create-table pass can
3107        // build an implicit BTree index. mailrs F1.
3108        let inline_pk_columns: Vec<String> = stmt
3109            .columns
3110            .iter()
3111            .filter(|c| c.is_primary_key)
3112            .map(|c| c.name.clone())
3113            .collect();
3114        // v7.9.19 — table-level constraints: PRIMARY KEY (a, b, ...)
3115        // and UNIQUE (a, b, ...). Each builds a BTree index on the
3116        // leading column (the existing single-column storage tier)
3117        // and registers a UniquenessConstraint on the schema for
3118        // INSERT-time enforcement of the full tuple. mailrs G1/G6.
3119        let cols = stmt
3120            .columns
3121            .into_iter()
3122            .map(column_def_to_schema)
3123            .collect::<Result<Vec<_>, _>>()?;
3124        // Composite NOT-NULL implication for PRIMARY KEY columns.
3125        let mut cols = cols;
3126        for tc in &stmt.table_constraints {
3127            if let spg_sql::ast::TableConstraint::PrimaryKey { columns, .. } = tc {
3128                for col_name in columns {
3129                    if let Some(col) = cols.iter_mut().find(|c| c.name == *col_name) {
3130                        col.nullable = false;
3131                    }
3132                }
3133            }
3134        }
3135        // v7.6.1 — resolve every FK in the statement against the
3136        // already-known catalog. Validates: parent table exists,
3137        // parent column names exist, arity matches, parent columns
3138        // have a PK / UNIQUE index. Self-referencing FKs (parent
3139        // table == this table) resolve against the column list we
3140        // just built — they don't need the catalog yet.
3141        let mut fks: Vec<spg_storage::ForeignKeyConstraint> =
3142            Vec::with_capacity(stmt.foreign_keys.len());
3143        for fk in stmt.foreign_keys {
3144            fks.push(resolve_foreign_key(
3145                &table_name,
3146                &cols,
3147                fk,
3148                self.active_catalog(),
3149            )?);
3150        }
3151        let mut schema = TableSchema::new(table_name.clone(), cols);
3152        schema.foreign_keys = fks;
3153        // v7.9.19 — translate AST table_constraints to storage
3154        // UniquenessConstraints (column name → position) so the
3155        // INSERT enforcement helper sees positions directly.
3156        let mut uc_storage: Vec<spg_storage::UniquenessConstraint> = Vec::new();
3157        for tc in &stmt.table_constraints {
3158            let (is_pk, names) = match tc {
3159                spg_sql::ast::TableConstraint::PrimaryKey { columns, .. } => {
3160                    (true, columns.clone())
3161                }
3162                spg_sql::ast::TableConstraint::Unique { columns, .. } => (false, columns.clone()),
3163            };
3164            let mut positions = Vec::with_capacity(names.len());
3165            for n in &names {
3166                let pos = schema
3167                    .columns
3168                    .iter()
3169                    .position(|c| c.name == *n)
3170                    .ok_or_else(|| {
3171                        EngineError::Unsupported(alloc::format!(
3172                            "table constraint references unknown column {n:?}"
3173                        ))
3174                    })?;
3175                positions.push(pos);
3176            }
3177            uc_storage.push(spg_storage::UniquenessConstraint {
3178                is_primary_key: is_pk,
3179                columns: positions,
3180            });
3181        }
3182        schema.uniqueness_constraints = uc_storage.clone();
3183        self.active_catalog_mut().create_table(schema)?;
3184        // v7.9.13 — implicit BTree per inline PK column +
3185        // v7.9.19 — implicit BTree on the leading column of every
3186        // table-level PRIMARY KEY / UNIQUE constraint.
3187        let table = self
3188            .active_catalog_mut()
3189            .get_mut(&table_name)
3190            .expect("just created");
3191        for (i, col_name) in inline_pk_columns.iter().enumerate() {
3192            let idx_name = if inline_pk_columns.len() == 1 {
3193                alloc::format!("{table_name}_pkey")
3194            } else {
3195                alloc::format!("{table_name}_pkey_{i}")
3196            };
3197            if let Err(e) = table.add_index(idx_name, col_name) {
3198                return Err(EngineError::Storage(e));
3199            }
3200        }
3201        for (i, tc) in stmt.table_constraints.iter().enumerate() {
3202            let (is_pk, names) = match tc {
3203                spg_sql::ast::TableConstraint::PrimaryKey { columns, .. } => (true, columns),
3204                spg_sql::ast::TableConstraint::Unique { columns, .. } => (false, columns),
3205            };
3206            let leading = &names[0];
3207            // Skip if a same-column BTree already exists (e.g.
3208            // inline PK on the leading column).
3209            let already = table.indices().iter().any(|idx| {
3210                matches!(idx.kind, spg_storage::IndexKind::BTree(_))
3211                    && table.schema().columns[idx.column_position].name == *leading
3212            });
3213            if already {
3214                continue;
3215            }
3216            let suffix = if is_pk { "pkey" } else { "key" };
3217            let idx_name = if names.len() == 1 {
3218                alloc::format!("{table_name}_{leading}_{suffix}")
3219            } else {
3220                alloc::format!("{table_name}_{leading}_{suffix}_{i}")
3221            };
3222            if let Err(e) = table.add_index(idx_name, leading) {
3223                return Err(EngineError::Storage(e));
3224            }
3225        }
3226        Ok(QueryResult::CommandOk {
3227            affected: 0,
3228            modified_catalog: !self.in_transaction(),
3229        })
3230    }
3231
3232    fn exec_insert(&mut self, stmt: InsertStatement) -> Result<QueryResult, EngineError> {
3233        // v7.9.21 — snapshot the clock fn pointer before the mut
3234        // borrow on the catalog opens; runtime DEFAULT eval needs
3235        // it inside the row hot loop.
3236        let clock = self.clock;
3237        let table = self
3238            .active_catalog_mut()
3239            .get_mut(&stmt.table)
3240            .ok_or_else(|| {
3241                EngineError::Storage(StorageError::TableNotFound {
3242                    name: stmt.table.clone(),
3243                })
3244            })?;
3245        // v3.1.5: clone the columns vector only (not the whole
3246        // TableSchema — saves one String alloc for the table name).
3247        // We need an owned snapshot because we'll call `table.insert`
3248        // (mutable borrow on `table`) inside the row loop while
3249        // reading schema fields.
3250        let column_meta: Vec<ColumnSchema> = table.schema().columns.clone();
3251        let schema_cols_len = column_meta.len();
3252        // Build a permutation `tuple_pos[c] = Some(j)` meaning schema
3253        // column `c` is filled from the `j`-th tuple slot; `None` means
3254        // "fill with NULL". Validated once and reused for every row.
3255        let tuple_pos: Option<Vec<Option<usize>>> = match &stmt.columns {
3256            None => None, // 1-1 mapping, fast path
3257            Some(cols) => {
3258                let mut map = alloc::vec![None; schema_cols_len];
3259                for (j, name) in cols.iter().enumerate() {
3260                    let idx = column_meta
3261                        .iter()
3262                        .position(|c| c.name == *name)
3263                        .ok_or_else(|| {
3264                            EngineError::Eval(EvalError::ColumnNotFound { name: name.clone() })
3265                        })?;
3266                    if map[idx].is_some() {
3267                        return Err(EngineError::Storage(StorageError::ArityMismatch {
3268                            expected: schema_cols_len,
3269                            actual: cols.len(),
3270                        }));
3271                    }
3272                    map[idx] = Some(j);
3273                }
3274                // Omitted columns must either be nullable, carry a
3275                // DEFAULT, or be AUTO_INCREMENT. Catch NOT NULL
3276                // omissions up front so the WAL stays clean.
3277                for (i, col) in column_meta.iter().enumerate() {
3278                    if map[i].is_none()
3279                        && !col.nullable
3280                        && col.default.is_none()
3281                        && col.runtime_default.is_none()
3282                        && !col.auto_increment
3283                    {
3284                        return Err(EngineError::Storage(StorageError::NullInNotNull {
3285                            column: col.name.clone(),
3286                        }));
3287                    }
3288                }
3289                Some(map)
3290            }
3291        };
3292        let expected_tuple_len = stmt.columns.as_ref().map_or(schema_cols_len, Vec::len);
3293        // v7.6.2 — snapshot this table's FK list before the
3294        // mutable-borrow window so we can run parent lookups
3295        // against the immutable catalog after parsing. Empty vec is
3296        // the no-FK fast path; clone cost is O(fks * arity) which
3297        // is < 100 ns for typical schemas.
3298        let fks = table.schema().foreign_keys.clone();
3299        let mut affected = 0usize;
3300        // Stage 1 — parse + AUTO_INC + coerce all rows under the
3301        // single mutable borrow.
3302        let mut all_values: Vec<Vec<Value>> = Vec::with_capacity(stmt.rows.len());
3303        for tuple in stmt.rows {
3304            if tuple.len() != expected_tuple_len {
3305                return Err(EngineError::Storage(StorageError::ArityMismatch {
3306                    expected: expected_tuple_len,
3307                    actual: tuple.len(),
3308                }));
3309            }
3310            // Fast path: no column-list permutation → tuple slot j
3311            // maps to schema column j. We can zip schema with tuple
3312            // and skip the `raw_tuple` staging allocation entirely.
3313            let values: Vec<Value> = if let Some(map) = &tuple_pos {
3314                // Permuted path: still need raw_tuple to index by `map[i]`.
3315                let raw_tuple: Vec<Value> = tuple
3316                    .into_iter()
3317                    .map(literal_expr_to_value)
3318                    .collect::<Result<_, _>>()?;
3319                let mut out = Vec::with_capacity(schema_cols_len);
3320                for (i, col) in column_meta.iter().enumerate() {
3321                    let mut raw = match map[i] {
3322                        Some(j) => raw_tuple[j].clone(),
3323                        None => resolve_column_default_free(col, clock)?,
3324                    };
3325                    if col.auto_increment && raw.is_null() {
3326                        let next = table.next_auto_value(i).ok_or_else(|| {
3327                            EngineError::Unsupported(alloc::format!(
3328                                "AUTO_INCREMENT applies to integer columns only (column `{}`)",
3329                                col.name
3330                            ))
3331                        })?;
3332                        raw = Value::BigInt(next);
3333                    }
3334                    out.push(coerce_value(raw, col.ty, &col.name, i)?);
3335                }
3336                out
3337            } else {
3338                // 1-1 mapping fast path: single Vec alloc, no raw_tuple.
3339                let mut out = Vec::with_capacity(schema_cols_len);
3340                for (i, (col, expr)) in column_meta.iter().zip(tuple).enumerate() {
3341                    let mut raw = literal_expr_to_value(expr)?;
3342                    if col.auto_increment && raw.is_null() {
3343                        let next = table.next_auto_value(i).ok_or_else(|| {
3344                            EngineError::Unsupported(alloc::format!(
3345                                "AUTO_INCREMENT applies to integer columns only (column `{}`)",
3346                                col.name
3347                            ))
3348                        })?;
3349                        raw = Value::BigInt(next);
3350                    }
3351                    out.push(coerce_value(raw, col.ty, &col.name, i)?);
3352                }
3353                out
3354            };
3355            all_values.push(values);
3356        }
3357        // Stage 2 — FK enforcement on the immutable catalog.
3358        // Non-lexical lifetimes release the mutable borrow on
3359        // `table` here since stage 1 was the last use. The
3360        // parent-table lookup runs before any row is committed.
3361        let uniqueness = table.schema().uniqueness_constraints.clone();
3362        let _ = table;
3363        if !fks.is_empty() {
3364            enforce_fk_inserts(self.active_catalog(), &stmt.table, &fks, &all_values)?;
3365        }
3366        // v7.9.19 — composite UNIQUE / PRIMARY KEY enforcement.
3367        enforce_uniqueness_inserts(self.active_catalog(), &stmt.table, &uniqueness, &all_values)?;
3368        // v7.9.29 — CREATE UNIQUE INDEX [WHERE pred] enforcement.
3369        // Independent of table-level UniquenessConstraint (which
3370        // can't carry a predicate). Walks the table's indexes;
3371        // for each `is_unique` index, only rows whose
3372        // partial_predicate evaluates truthy are checked for
3373        // collision. mailrs K1.
3374        enforce_unique_index_inserts(self.active_catalog(), &stmt.table, &all_values)?;
3375        // v7.9.8 / v7.9.9 — ON CONFLICT handling.
3376        //   - `DO NOTHING` filters `all_values` to non-conflicting
3377        //     rows + drops within-batch duplicates.
3378        //   - `DO UPDATE SET …` ALSO filters, but for each
3379        //     conflicting row it queues an UPDATE on the existing
3380        //     row using the incoming row's values as `EXCLUDED.*`.
3381        let mut pending_updates: Vec<(usize, Vec<Value>)> = Vec::new();
3382        let mut skipped_count = 0usize;
3383        if let Some(clause) = &stmt.on_conflict {
3384            let conflict_cols = resolve_on_conflict_columns(
3385                self.active_catalog(),
3386                &stmt.table,
3387                clause.target_columns.as_slice(),
3388            )?;
3389            let mut kept: Vec<Vec<Value>> = Vec::with_capacity(all_values.len());
3390            let mut seen_keys: Vec<Vec<Value>> = Vec::new();
3391            for values in all_values {
3392                let key_tuple: Vec<&Value> = conflict_cols.iter().map(|&c| &values[c]).collect();
3393                // SQL spec: NULL in any conflict column means "no
3394                // conflict possible" (NULL ≠ NULL for uniqueness).
3395                let has_null_key = key_tuple.iter().any(|v| matches!(v, Value::Null));
3396                let collides_with_table = !has_null_key
3397                    && on_conflict_keys_exist(
3398                        self.active_catalog(),
3399                        &stmt.table,
3400                        &conflict_cols,
3401                        &key_tuple,
3402                    );
3403                let key_tuple_owned: Vec<Value> = key_tuple.iter().map(|v| (*v).clone()).collect();
3404                let collides_with_batch =
3405                    !has_null_key && seen_keys.iter().any(|k| k == &key_tuple_owned);
3406                let collides = collides_with_table || collides_with_batch;
3407                match (&clause.action, collides) {
3408                    (_, false) => {
3409                        seen_keys.push(key_tuple_owned);
3410                        kept.push(values);
3411                    }
3412                    (spg_sql::ast::OnConflictAction::Nothing, true) => {
3413                        skipped_count += 1;
3414                    }
3415                    (
3416                        spg_sql::ast::OnConflictAction::Update {
3417                            assignments,
3418                            where_,
3419                        },
3420                        true,
3421                    ) => {
3422                        if !collides_with_table {
3423                            skipped_count += 1;
3424                            continue;
3425                        }
3426                        let target_pos = lookup_row_position_by_keys(
3427                            self.active_catalog(),
3428                            &stmt.table,
3429                            &conflict_cols,
3430                            &key_tuple,
3431                        )
3432                        .ok_or_else(|| {
3433                            EngineError::Unsupported(
3434                                "ON CONFLICT DO UPDATE: conflict detected but row \
3435                                 position could not be resolved (cold-tier row?)"
3436                                    .into(),
3437                            )
3438                        })?;
3439                        let updated = apply_on_conflict_assignments(
3440                            self.active_catalog(),
3441                            &stmt.table,
3442                            target_pos,
3443                            &values,
3444                            assignments,
3445                            where_.as_ref(),
3446                        )?;
3447                        if let Some(new_row) = updated {
3448                            pending_updates.push((target_pos, new_row));
3449                        } else {
3450                            skipped_count += 1;
3451                        }
3452                    }
3453                }
3454            }
3455            all_values = kept;
3456        }
3457        // Stage 3 — insert all rows under a fresh mutable borrow.
3458        let table = self
3459            .active_catalog_mut()
3460            .get_mut(&stmt.table)
3461            .ok_or_else(|| {
3462                EngineError::Storage(StorageError::TableNotFound {
3463                    name: stmt.table.clone(),
3464                })
3465            })?;
3466        // v7.9.4 — keep RETURNING projection rows separate per
3467        // INSERT and per UPDATE branch so DO UPDATE pushes the new
3468        // post-update state, not the incoming-only values.
3469        let mut returning_rows: Vec<Vec<Value>> = Vec::new();
3470        for values in all_values {
3471            if stmt.returning.is_some() {
3472                returning_rows.push(values.clone());
3473            }
3474            table.insert(Row::new(values))?;
3475            affected += 1;
3476        }
3477        // v7.9.9 — apply ON CONFLICT DO UPDATE rewrites collected
3478        // in the conflict-resolution pass. update_row handles
3479        // index maintenance + body re-encoding.
3480        for (pos, new_row) in pending_updates {
3481            if stmt.returning.is_some() {
3482                returning_rows.push(new_row.clone());
3483            }
3484            table.update_row(pos, new_row)?;
3485            affected += 1;
3486        }
3487        let _ = skipped_count;
3488        // v7.9.4/v7.9.9 — RETURNING streams the rows that ended
3489        // up in the table after this statement (insert or
3490        // post-update on conflict).
3491        if let Some(items) = &stmt.returning {
3492            let _ = table;
3493            return self.build_returning_rows(&stmt.table, items, returning_rows);
3494        }
3495        // v6.2.1 — auto-analyze: track per-table modified-row
3496        // counter so the background sweep can decide when to
3497        // re-ANALYZE. Cheap path on the autocommit-wrap hot loop
3498        // — one BTreeMap entry update per INSERT batch.
3499        if !self.in_transaction() && affected > 0 {
3500            self.statistics
3501                .record_modifications(&stmt.table, affected as u64);
3502        }
3503        Ok(QueryResult::CommandOk {
3504            affected,
3505            modified_catalog: !self.in_transaction(),
3506        })
3507    }
3508
3509    /// v4.5: SELECT with cooperative cancellation. The token is
3510    /// honoured between UNION peers and inside the bare-SELECT row
3511    /// loop; HNSW kNN graph walks and the aggregate executor don't
3512    /// honour it yet (deferred — those paths bound their work
3513    /// internally by `LIMIT k` and `GROUP BY` cardinality).
3514    /// v6.10.2 — cold-tier time-travel scan. Resolves the segment
3515    /// by id, decodes each row body against the table's current
3516    /// schema, applies the SELECT's projection + optional WHERE +
3517    /// optional LIMIT, returns a `Rows` result. JOINs / aggregates
3518    /// / ORDER BY are unsupported on this path (STABILITY carve-
3519    /// out); operators wanting them should restore the segment
3520    /// into a regular table first.
3521    fn exec_select_as_of_segment(
3522        &self,
3523        stmt: &SelectStatement,
3524        from: &spg_sql::ast::FromClause,
3525        segment_id: u32,
3526    ) -> Result<QueryResult, EngineError> {
3527        // v6.10.2 scope: no joins, no aggregates, no ORDER BY,
3528        // no GROUP BY / HAVING / UNION / OFFSET / DISTINCT.
3529        if !from.joins.is_empty()
3530            || stmt.group_by.is_some()
3531            || stmt.having.is_some()
3532            || !stmt.unions.is_empty()
3533            || !stmt.order_by.is_empty()
3534            || stmt.offset.is_some()
3535            || stmt.distinct
3536            || aggregate::uses_aggregate(stmt)
3537        {
3538            return Err(EngineError::Unsupported(
3539                "AS OF SEGMENT supports SELECT projection + WHERE + LIMIT only \
3540                 (joins / aggregates / ORDER BY are STABILITY § \"Out of v6.10\")"
3541                    .into(),
3542            ));
3543        }
3544        let table = self
3545            .active_catalog()
3546            .get(&from.primary.name)
3547            .ok_or_else(|| StorageError::TableNotFound {
3548                name: from.primary.name.clone(),
3549            })?;
3550        let schema = table.schema().clone();
3551        let schema_cols = &schema.columns;
3552        let alias = from
3553            .primary
3554            .alias
3555            .as_deref()
3556            .unwrap_or(from.primary.name.as_str());
3557        let ctx = EvalContext::new(schema_cols, Some(alias));
3558        let seg = self
3559            .active_catalog()
3560            .cold_segment(segment_id)
3561            .ok_or_else(|| {
3562                EngineError::Unsupported(alloc::format!(
3563                    "AS OF SEGMENT: cold segment {segment_id} not registered"
3564                ))
3565            })?;
3566        let mut out_rows: Vec<Row> = Vec::new();
3567        let mut limit_remaining: Option<usize> =
3568            stmt.limit_literal().and_then(|n| usize::try_from(n).ok());
3569        for (_key, body) in seg.scan() {
3570            let (row, _consumed) =
3571                spg_storage::decode_row_body_dense(&body, &schema).map_err(EngineError::Storage)?;
3572            if let Some(where_expr) = &stmt.where_ {
3573                let cond = self.eval_expr_simple(where_expr, &row, &ctx)?;
3574                if !matches!(cond, Value::Bool(true)) {
3575                    continue;
3576                }
3577            }
3578            // Projection.
3579            let projected = self.project_row_simple(&row, &stmt.items, schema_cols, alias)?;
3580            out_rows.push(projected);
3581            if let Some(rem) = limit_remaining.as_mut() {
3582                if *rem == 0 {
3583                    out_rows.pop();
3584                    break;
3585                }
3586                *rem -= 1;
3587            }
3588        }
3589        // Output column schema: derive from SELECT items.
3590        let columns = self.derive_output_columns(&stmt.items, schema_cols, alias);
3591        Ok(QueryResult::Rows {
3592            columns,
3593            rows: out_rows,
3594        })
3595    }
3596
3597    /// v6.10.2 — simple-path WHERE eval that doesn't go through
3598    /// the correlated-subquery / Memoize machinery. AS OF SEGMENT
3599    /// scan paths predicate against a snapshot frozen segment, no
3600    /// cross-row state.
3601    fn eval_expr_simple(
3602        &self,
3603        expr: &Expr,
3604        row: &Row,
3605        ctx: &EvalContext,
3606    ) -> Result<Value, EngineError> {
3607        let cancel = CancelToken::none();
3608        self.eval_expr_with_correlated(expr, row, ctx, cancel, None)
3609    }
3610
3611    /// v7.9.4 — INSERT / UPDATE / DELETE RETURNING projector.
3612    /// Given the table name, the user-supplied projection items,
3613    /// and the mutated rows (post-insert / post-update values, or
3614    /// pre-delete snapshot), build a `QueryResult::Rows` whose
3615    /// schema describes the projected columns. Mailrs migration
3616    /// blocker #1.
3617    fn build_returning_rows(
3618        &self,
3619        table_name: &str,
3620        items: &[SelectItem],
3621        mutated_rows: Vec<Vec<Value>>,
3622    ) -> Result<QueryResult, EngineError> {
3623        let table = self.active_catalog().get(table_name).ok_or_else(|| {
3624            EngineError::Storage(StorageError::TableNotFound {
3625                name: table_name.into(),
3626            })
3627        })?;
3628        let schema_cols = table.schema().columns.clone();
3629        let columns = self.derive_output_columns(items, &schema_cols, table_name);
3630        let mut out_rows: Vec<Row> = Vec::with_capacity(mutated_rows.len());
3631        for values in mutated_rows {
3632            let row = Row::new(values);
3633            let projected = self.project_row_simple(&row, items, &schema_cols, table_name)?;
3634            out_rows.push(projected);
3635        }
3636        Ok(QueryResult::Rows {
3637            columns,
3638            rows: out_rows,
3639        })
3640    }
3641
3642    /// v6.10.2 — projection for AS OF SEGMENT. Resolves
3643    /// `SelectItem::Wildcard` to all schema columns and
3644    /// `SelectItem::Expr` via the regular eval path.
3645    fn project_row_simple(
3646        &self,
3647        row: &Row,
3648        items: &[SelectItem],
3649        schema_cols: &[ColumnSchema],
3650        alias: &str,
3651    ) -> Result<Row, EngineError> {
3652        let ctx = EvalContext::new(schema_cols, Some(alias));
3653        let cancel = CancelToken::none();
3654        let mut out_vals = Vec::new();
3655        for item in items {
3656            match item {
3657                SelectItem::Wildcard => {
3658                    out_vals.extend(row.values.iter().cloned());
3659                }
3660                SelectItem::Expr { expr, .. } => {
3661                    let v = self.eval_expr_with_correlated(expr, row, &ctx, cancel, None)?;
3662                    out_vals.push(v);
3663                }
3664            }
3665        }
3666        Ok(Row::new(out_vals))
3667    }
3668
3669    /// v6.10.2 — derive the output `ColumnSchema` list for an
3670    /// AS OF SEGMENT projection. Wildcards take the full schema;
3671    /// expressions take the alias if present or a synthetic
3672    /// `?column?` (PG convention) otherwise.
3673    fn derive_output_columns(
3674        &self,
3675        items: &[SelectItem],
3676        schema_cols: &[ColumnSchema],
3677        _alias: &str,
3678    ) -> Vec<ColumnSchema> {
3679        let mut out = Vec::new();
3680        for item in items {
3681            match item {
3682                SelectItem::Wildcard => {
3683                    out.extend(schema_cols.iter().cloned());
3684                }
3685                SelectItem::Expr { alias, .. } => {
3686                    let name = alias.clone().unwrap_or_else(|| "?column?".to_string());
3687                    // Default to Text; the caller's row values
3688                    // carry the actual type. v6.10.2 scope.
3689                    out.push(ColumnSchema::new(name, DataType::Text, true));
3690                }
3691            }
3692        }
3693        out
3694    }
3695
3696    fn exec_select_cancel(
3697        &self,
3698        stmt: &SelectStatement,
3699        cancel: CancelToken<'_>,
3700    ) -> Result<QueryResult, EngineError> {
3701        cancel.check()?;
3702        // v6.10.2 — cold-tier time-travel short-circuit. When the
3703        // primary TableRef carries `AS OF SEGMENT '<id>'`, run a
3704        // dedicated cold-segment scan instead of the regular
3705        // hot+index path. The scope is intentionally narrow for
3706        // v6.10.2 — bare `SELECT * FROM <t> AS OF SEGMENT 'id'`,
3707        // optionally with a single-column-equality WHERE. JOINs /
3708        // aggregates / ORDER BY / subqueries on top of a time-
3709        // travelled scan are STABILITY § "Out of v6.10".
3710        if let Some(from) = &stmt.from
3711            && let Some(seg_id) = from.primary.as_of_segment
3712        {
3713            return self.exec_select_as_of_segment(stmt, from, seg_id);
3714        }
3715        // v6.2.0 / v6.5.0 — virtual-table short-circuits. Detected
3716        // pre-CTE because they don't read from the catalog and
3717        // shouldn't participate in regular FROM resolution.
3718        if let Some(from) = &stmt.from
3719            && from.joins.is_empty()
3720            && stmt.where_.is_none()
3721            && stmt.group_by.is_none()
3722            && stmt.having.is_none()
3723            && stmt.unions.is_empty()
3724            && stmt.order_by.is_empty()
3725            && stmt.limit.is_none()
3726            && stmt.offset.is_none()
3727            && !stmt.distinct
3728            && stmt.items.iter().all(|i| matches!(i, SelectItem::Wildcard))
3729        {
3730            let lower = from.primary.name.to_ascii_lowercase();
3731            match lower.as_str() {
3732                "spg_statistic" => return Ok(self.exec_spg_statistic()),
3733                // v6.5.0 — observability v2 virtual tables.
3734                "spg_stat_replication" => return Ok(self.exec_spg_stat_replication()),
3735                "spg_stat_segment" => return Ok(self.exec_spg_stat_segment()),
3736                "spg_stat_query" => return Ok(self.exec_spg_stat_query()),
3737                "spg_stat_activity" => return Ok(self.exec_spg_stat_activity()),
3738                "spg_audit_chain" => return Ok(self.exec_spg_audit_chain()),
3739                "spg_audit_verify" => return Ok(self.exec_spg_audit_verify()),
3740                "spg_table_ddl" => return Ok(self.exec_spg_table_ddl()),
3741                "spg_role_ddl" => return Ok(self.exec_spg_role_ddl()),
3742                "spg_database_ddl" => return Ok(self.exec_spg_database_ddl()),
3743                _ => {}
3744            }
3745        }
3746        // v4.11: CTEs materialise into a temporary enriched catalog
3747        // *before* anything else — the body SELECT can then refer
3748        // to CTE names via the regular FROM-clause resolution.
3749        // Uncorrelated only: each CTE body runs once against the
3750        // current catalog, not against later CTEs' results (left-
3751        // to-right materialisation would relax this, but we keep
3752        // it simple for v4.11 MVP).
3753        if !stmt.ctes.is_empty() {
3754            return self.exec_with_ctes(stmt, cancel);
3755        }
3756        // v4.10: subqueries (uncorrelated) are resolved here, before
3757        // the executor sees the row loop. We clone the statement so
3758        // we can mutate without disturbing the caller's AST — most
3759        // queries pass through with no subquery nodes and the clone
3760        // is cheap; with subqueries the materialisation cost
3761        // dominates anyway.
3762        let mut stmt_owned;
3763        let stmt_ref: &SelectStatement = if expr_tree_has_subquery(stmt) {
3764            stmt_owned = stmt.clone();
3765            self.resolve_select_subqueries(&mut stmt_owned, cancel)?;
3766            &stmt_owned
3767        } else {
3768            stmt
3769        };
3770        if stmt_ref.unions.is_empty() {
3771            return self.exec_bare_select_cancel(stmt_ref, cancel);
3772        }
3773        // UNION path: clone-strip the head into a bare block (its own
3774        // DISTINCT and any inner ORDER BY are dropped by parser rule —
3775        // the wrapper SelectStatement carries them), execute, then chain
3776        // peers with left-associative dedup semantics.
3777        let mut head = stmt_ref.clone();
3778        head.unions = Vec::new();
3779        head.order_by = Vec::new();
3780        head.limit = None;
3781        let QueryResult::Rows { columns, mut rows } =
3782            self.exec_bare_select_cancel(&head, cancel)?
3783        else {
3784            unreachable!("bare SELECT cannot return CommandOk")
3785        };
3786        for (kind, peer) in &stmt_ref.unions {
3787            let QueryResult::Rows {
3788                columns: peer_cols,
3789                rows: peer_rows,
3790            } = self.exec_bare_select_cancel(peer, cancel)?
3791            else {
3792                unreachable!("bare SELECT cannot return CommandOk")
3793            };
3794            if peer_cols.len() != columns.len() {
3795                return Err(EngineError::Unsupported(alloc::format!(
3796                    "UNION arity mismatch: head has {} columns, peer has {}",
3797                    columns.len(),
3798                    peer_cols.len()
3799                )));
3800            }
3801            rows.extend(peer_rows);
3802            if matches!(kind, UnionKind::Distinct) {
3803                rows = dedup_rows(rows);
3804            }
3805        }
3806        // ORDER BY at the top of a UNION applies to the combined result.
3807        // Eval against the projected schema (NOT the source table).
3808        if !stmt.order_by.is_empty() {
3809            let synth_ctx = EvalContext::new(&columns, None);
3810            let descs: Vec<bool> = stmt.order_by.iter().map(|o| o.desc).collect();
3811            let mut tagged: Vec<(Vec<f64>, Row)> = Vec::with_capacity(rows.len());
3812            for r in rows {
3813                let keys = build_order_keys(&stmt.order_by, &r, &synth_ctx)?;
3814                tagged.push((keys, r));
3815            }
3816            sort_by_keys(&mut tagged, &descs);
3817            rows = tagged.into_iter().map(|(_, r)| r).collect();
3818        }
3819        apply_offset_and_limit(&mut rows, stmt.offset_literal(), stmt.limit_literal());
3820        Ok(QueryResult::Rows { columns, rows })
3821    }
3822
3823    #[allow(clippy::too_many_lines)]
3824    #[allow(clippy::too_many_lines)] // huge match — splitting fragments the planner
3825    /// v7.11.7 — execute `SELECT … FROM unnest(expr) [AS] alias …`.
3826    /// Synthesises a single-column virtual table whose column type
3827    /// is TEXT and whose rows are the array elements. Routes
3828    /// through the regular projection / WHERE / ORDER BY / LIMIT
3829    /// machinery so set-returning UNNEST composes naturally with
3830    /// the rest of the SELECT surface.
3831    fn exec_select_unnest(
3832        &self,
3833        stmt: &SelectStatement,
3834        primary: &TableRef,
3835        cancel: CancelToken<'_>,
3836    ) -> Result<QueryResult, EngineError> {
3837        let expr = primary
3838            .unnest_expr
3839            .as_deref()
3840            .expect("caller guards unnest_expr.is_some()");
3841        // Evaluate the array expression once. Empty schema / empty
3842        // row — uncorrelated UNNEST cannot reference outer columns.
3843        let empty_schema: alloc::vec::Vec<ColumnSchema> = alloc::vec::Vec::new();
3844        let ctx = EvalContext::new(&empty_schema, None);
3845        let dummy_row = Row::new(alloc::vec::Vec::new());
3846        // v7.11.13 — unnest dispatches per array element type so
3847        // INT[] / BIGINT[] surface their PG types in projection.
3848        let (elem_dtype, rows): (DataType, alloc::vec::Vec<Row>) =
3849            match eval::eval_expr(expr, &dummy_row, &ctx).map_err(EngineError::Eval)? {
3850                Value::Null => (DataType::Text, alloc::vec::Vec::new()),
3851                Value::TextArray(items) => {
3852                    let rows = items
3853                        .into_iter()
3854                        .map(|item| {
3855                            Row::new(alloc::vec![match item {
3856                                Some(s) => Value::Text(s),
3857                                None => Value::Null,
3858                            }])
3859                        })
3860                        .collect();
3861                    (DataType::Text, rows)
3862                }
3863                Value::IntArray(items) => {
3864                    let rows = items
3865                        .into_iter()
3866                        .map(|item| {
3867                            Row::new(alloc::vec![match item {
3868                                Some(n) => Value::Int(n),
3869                                None => Value::Null,
3870                            }])
3871                        })
3872                        .collect();
3873                    (DataType::Int, rows)
3874                }
3875                Value::BigIntArray(items) => {
3876                    let rows = items
3877                        .into_iter()
3878                        .map(|item| {
3879                            Row::new(alloc::vec![match item {
3880                                Some(n) => Value::BigInt(n),
3881                                None => Value::Null,
3882                            }])
3883                        })
3884                        .collect();
3885                    (DataType::BigInt, rows)
3886                }
3887                other => {
3888                    return Err(EngineError::Unsupported(alloc::format!(
3889                        "unnest() expects an array argument, got {:?}",
3890                        other.data_type()
3891                    )));
3892                }
3893            };
3894        let alias = primary
3895            .alias
3896            .clone()
3897            .unwrap_or_else(|| "unnest".to_string());
3898        let col_schema = ColumnSchema::new(alias.clone(), elem_dtype, true);
3899        let schema_cols = alloc::vec![col_schema.clone()];
3900        let scan_ctx = EvalContext::new(&schema_cols, Some(&alias));
3901        // Apply WHERE.
3902        let filtered: alloc::vec::Vec<Row> = if let Some(w) = &stmt.where_ {
3903            let mut out = alloc::vec::Vec::with_capacity(rows.len());
3904            for row in rows {
3905                cancel.check()?;
3906                let v = eval::eval_expr(w, &row, &scan_ctx).map_err(EngineError::Eval)?;
3907                if matches!(v, Value::Bool(true)) {
3908                    out.push(row);
3909                }
3910            }
3911            out
3912        } else {
3913            rows
3914        };
3915        // Projection.
3916        let projection = build_projection(&stmt.items, &schema_cols, &alias)?;
3917        let mut projected_rows: alloc::vec::Vec<Row> =
3918            alloc::vec::Vec::with_capacity(filtered.len());
3919        for row in &filtered {
3920            let mut vals = alloc::vec::Vec::with_capacity(projection.len());
3921            for p in &projection {
3922                vals.push(eval::eval_expr(&p.expr, row, &scan_ctx).map_err(EngineError::Eval)?);
3923            }
3924            projected_rows.push(Row::new(vals));
3925        }
3926        // ORDER BY / LIMIT — apply on the projected rows (cheap;
3927        // unnest result sets are small by design).
3928        let columns: alloc::vec::Vec<ColumnSchema> = projection
3929            .iter()
3930            .map(|p| ColumnSchema::new(p.output_name.clone(), p.ty, p.nullable))
3931            .collect();
3932        // Re-evaluate ORDER BY against the source schema (pre-projection
3933        // so col refs by name still resolve through `scan_ctx`).
3934        if !stmt.order_by.is_empty() {
3935            let mut indexed: alloc::vec::Vec<(usize, Vec<Value>)> = filtered
3936                .iter()
3937                .enumerate()
3938                .map(|(i, r)| -> Result<_, EngineError> {
3939                    let keys: Result<Vec<Value>, EngineError> = stmt
3940                        .order_by
3941                        .iter()
3942                        .map(|ob| {
3943                            eval::eval_expr(&ob.expr, r, &scan_ctx).map_err(EngineError::Eval)
3944                        })
3945                        .collect();
3946                    Ok((i, keys?))
3947                })
3948                .collect::<Result<_, _>>()?;
3949            indexed.sort_by(|a, b| {
3950                for (idx, (ka, kb)) in a.1.iter().zip(b.1.iter()).enumerate() {
3951                    let mut cmp = value_cmp(ka, kb);
3952                    if stmt.order_by[idx].desc {
3953                        cmp = cmp.reverse();
3954                    }
3955                    if cmp != core::cmp::Ordering::Equal {
3956                        return cmp;
3957                    }
3958                }
3959                core::cmp::Ordering::Equal
3960            });
3961            projected_rows = indexed
3962                .into_iter()
3963                .map(|(i, _)| projected_rows[i].clone())
3964                .collect();
3965        }
3966        // LIMIT / OFFSET — apply at the tail.
3967        if let Some(offset) = stmt.offset_literal() {
3968            let off = (offset as usize).min(projected_rows.len());
3969            projected_rows.drain(..off);
3970        }
3971        if let Some(limit) = stmt.limit_literal() {
3972            projected_rows.truncate(limit as usize);
3973        }
3974        Ok(QueryResult::Rows {
3975            columns,
3976            rows: projected_rows,
3977        })
3978    }
3979
3980    fn exec_bare_select_cancel(
3981        &self,
3982        stmt: &SelectStatement,
3983        cancel: CancelToken<'_>,
3984    ) -> Result<QueryResult, EngineError> {
3985        // v4.12: window-function path. When the projection contains
3986        // any `name(args) OVER (...)` we route to the dedicated
3987        // executor — partition + sort + per-row window value before
3988        // the regular projection.
3989        if select_has_window(stmt) {
3990            return self.exec_select_with_window(stmt, cancel);
3991        }
3992        // Constant SELECT (no FROM) — evaluate each item once against an
3993        // empty dummy row. Useful for `SELECT 1`, `SELECT coalesce(...)`,
3994        // `SELECT '7'::INT`. Column references will surface as
3995        // ColumnNotFound on eval since the schema is empty.
3996        let Some(from) = &stmt.from else {
3997            let empty_schema: Vec<ColumnSchema> = Vec::new();
3998            let ctx = EvalContext::new(&empty_schema, None);
3999            let projection = build_projection(&stmt.items, &empty_schema, "")?;
4000            let dummy_row = Row::new(Vec::new());
4001            let mut values = Vec::with_capacity(projection.len());
4002            for p in &projection {
4003                values.push(eval::eval_expr(&p.expr, &dummy_row, &ctx)?);
4004            }
4005            let columns: Vec<ColumnSchema> = projection
4006                .into_iter()
4007                .map(|p| ColumnSchema::new(p.output_name, p.ty, p.nullable))
4008                .collect();
4009            return Ok(QueryResult::Rows {
4010                columns,
4011                rows: alloc::vec![Row::new(values)],
4012            });
4013        };
4014        // Multi-table FROM (one or more joined peers) goes through the
4015        // nested-loop join executor. Single-table FROM stays on the
4016        // existing scan + index-seek path.
4017        if !from.joins.is_empty() {
4018            return self.exec_joined_select(stmt, from);
4019        }
4020        // v7.11.7 — `FROM unnest(<expr>) [AS] <alias>`. Synthesise a
4021        // single-column table at SELECT entry by evaluating the
4022        // expression once against the empty row (UNNEST is
4023        // uncorrelated in v7.11; correlated / LATERAL unnest is a
4024        // v7.12 carve-out). Build a virtual `Table` in a heap-only
4025        // catalog, then route to the regular scan path.
4026        if from.primary.unnest_expr.is_some() {
4027            return self.exec_select_unnest(stmt, &from.primary, cancel);
4028        }
4029        let primary = &from.primary;
4030        let table = self.active_catalog().get(&primary.name).ok_or_else(|| {
4031            StorageError::TableNotFound {
4032                name: primary.name.clone(),
4033            }
4034        })?;
4035        let schema_cols = &table.schema().columns;
4036        // The qualifier accepted on column refs is the alias (if any) else the
4037        // bare table name.
4038        let alias = primary.alias.as_deref().unwrap_or(primary.name.as_str());
4039        let ctx = EvalContext::new(schema_cols, Some(alias));
4040
4041        // NSW kNN planner: `ORDER BY col <-> literal LIMIT k` with no
4042        // WHERE and an NSW index on `col` skips the full scan. The
4043        // walk returns rows already in ascending-distance order, so
4044        // ORDER BY / LIMIT are honoured implicitly.
4045        if let Some(nsw_rows) = try_nsw_knn(stmt, table, schema_cols, alias) {
4046            return materialise_in_order(stmt, table, schema_cols, alias, &nsw_rows);
4047        }
4048
4049        // Index seek: if WHERE is `col = literal` (or commuted) and the
4050        // referenced column has an index, dispatch each locator through
4051        // the catalog (hot tier → borrow, cold tier → page-read +
4052        // decode) and iterate just those rows. Otherwise fall back to a
4053        // full scan over the hot tier (cold-tier rows are only reached
4054        // via index seek in v5.1 — full table scans against cold-tier
4055        // data ship in v5.2 with the freezer's per-segment scan API).
4056        let indexed_rows: Option<Vec<Cow<'_, Row>>> = stmt
4057            .where_
4058            .as_ref()
4059            .and_then(|w| try_index_seek(w, schema_cols, self.active_catalog(), table, alias));
4060
4061        // Aggregate path: filter rows first, then hand off to the
4062        // aggregate executor which does its own projection + ORDER BY.
4063        if aggregate::uses_aggregate(stmt) {
4064            let mut filtered: Vec<&Row> = Vec::new();
4065            // v6.2.6 — Memoize: per-query LRU cache for correlated
4066            // scalar subqueries. Fresh per row-loop entry so each
4067            // SELECT execution gets an isolated cache.
4068            let mut memo = memoize::MemoizeCache::new();
4069            if let Some(rows) = &indexed_rows {
4070                for cow in rows {
4071                    let row = cow.as_ref();
4072                    if let Some(where_expr) = &stmt.where_ {
4073                        let cond = self.eval_expr_with_correlated(
4074                            where_expr,
4075                            row,
4076                            &ctx,
4077                            cancel,
4078                            Some(&mut memo),
4079                        )?;
4080                        if !matches!(cond, Value::Bool(true)) {
4081                            continue;
4082                        }
4083                    }
4084                    filtered.push(row);
4085                }
4086            } else {
4087                for i in 0..table.row_count() {
4088                    let row = &table.rows()[i];
4089                    if let Some(where_expr) = &stmt.where_ {
4090                        let cond = self.eval_expr_with_correlated(
4091                            where_expr,
4092                            row,
4093                            &ctx,
4094                            cancel,
4095                            Some(&mut memo),
4096                        )?;
4097                        if !matches!(cond, Value::Bool(true)) {
4098                            continue;
4099                        }
4100                    }
4101                    filtered.push(row);
4102                }
4103            }
4104            let mut agg = aggregate::run(stmt, &filtered, schema_cols, Some(alias))?;
4105            apply_offset_and_limit(&mut agg.rows, stmt.offset_literal(), stmt.limit_literal());
4106            return Ok(QueryResult::Rows {
4107                columns: agg.columns,
4108                rows: agg.rows,
4109            });
4110        }
4111
4112        let projection = build_projection(&stmt.items, schema_cols, alias)?;
4113
4114        // Materialise the filter pass into `(order_key, projected_row)`
4115        // tuples. The order key is `None` when there's no ORDER BY clause.
4116        let mut tagged: Vec<(Vec<f64>, Row)> = Vec::new();
4117        // v6.2.6 — Memoize per-row WHERE eval shares one cache.
4118        let mut memo = memoize::MemoizeCache::new();
4119        // Inline the per-row work in a closure so the indexed and full-
4120        // scan branches share the body.
4121        let mut process_row = |row: &Row, loop_idx: usize| -> Result<(), EngineError> {
4122            if loop_idx.is_multiple_of(256) {
4123                cancel.check()?;
4124            }
4125            if let Some(where_expr) = &stmt.where_ {
4126                let cond =
4127                    self.eval_expr_with_correlated(where_expr, row, &ctx, cancel, Some(&mut memo))?;
4128                if !matches!(cond, Value::Bool(true)) {
4129                    return Ok(());
4130                }
4131            }
4132            let mut values = Vec::with_capacity(projection.len());
4133            for p in &projection {
4134                values.push(eval::eval_expr(&p.expr, row, &ctx)?);
4135            }
4136            let order_keys = if stmt.order_by.is_empty() {
4137                Vec::new()
4138            } else {
4139                build_order_keys(&stmt.order_by, row, &ctx)?
4140            };
4141            tagged.push((order_keys, Row::new(values)));
4142            Ok(())
4143        };
4144        if let Some(rows) = &indexed_rows {
4145            for (loop_idx, cow) in rows.iter().enumerate() {
4146                process_row(cow.as_ref(), loop_idx)?;
4147            }
4148        } else {
4149            for i in 0..table.row_count() {
4150                process_row(&table.rows()[i], i)?;
4151            }
4152        }
4153
4154        if !stmt.order_by.is_empty() {
4155            // Partial-sort fast path: when LIMIT is small relative to
4156            // the row count, select_nth_unstable + sort just the
4157            // prefix is O(n + k log k) instead of O(n log n). DISTINCT
4158            // requires the full sort because de-dup happens after.
4159            let keep = if stmt.distinct {
4160                None
4161            } else {
4162                stmt.limit_literal()
4163                    .map(|l| l as usize + stmt.offset_literal().map_or(0, |o| o as usize))
4164            };
4165            let descs: Vec<bool> = stmt.order_by.iter().map(|o| o.desc).collect();
4166            partial_sort_tagged(&mut tagged, keep, &descs);
4167        }
4168
4169        let mut output_rows: Vec<Row> = tagged.into_iter().map(|(_, r)| r).collect();
4170        if stmt.distinct {
4171            output_rows = dedup_rows(output_rows);
4172        }
4173        apply_offset_and_limit(
4174            &mut output_rows,
4175            stmt.offset_literal(),
4176            stmt.limit_literal(),
4177        );
4178
4179        let columns: Vec<ColumnSchema> = projection
4180            .into_iter()
4181            .map(|p| ColumnSchema::new(p.output_name, p.ty, p.nullable))
4182            .collect();
4183
4184        Ok(QueryResult::Rows {
4185            columns,
4186            rows: output_rows,
4187        })
4188    }
4189
4190    /// Multi-table SELECT executor (one or more JOIN peers).
4191    ///
4192    /// v1.10 builds the joined row set up-front via nested-loop joins,
4193    /// then runs WHERE + projection + ORDER BY against the combined
4194    /// rows. No index seek. Aggregates and DISTINCT still work because
4195    /// the executor delegates projection through the same shared paths.
4196    #[allow(clippy::too_many_lines)]
4197    fn exec_joined_select(
4198        &self,
4199        stmt: &SelectStatement,
4200        from: &FromClause,
4201    ) -> Result<QueryResult, EngineError> {
4202        // Resolve every table reference up front so we surface
4203        // TableNotFound before we start the cartesian work.
4204        let primary_table = self
4205            .active_catalog()
4206            .get(&from.primary.name)
4207            .ok_or_else(|| StorageError::TableNotFound {
4208                name: from.primary.name.clone(),
4209            })?;
4210        let primary_alias = from
4211            .primary
4212            .alias
4213            .as_deref()
4214            .unwrap_or(from.primary.name.as_str())
4215            .to_string();
4216        let mut joined_tables: Vec<(&Table, String, JoinKind, Option<&Expr>)> = Vec::new();
4217        for j in &from.joins {
4218            let t = self.active_catalog().get(&j.table.name).ok_or_else(|| {
4219                StorageError::TableNotFound {
4220                    name: j.table.name.clone(),
4221                }
4222            })?;
4223            let a = j
4224                .table
4225                .alias
4226                .as_deref()
4227                .unwrap_or(j.table.name.as_str())
4228                .to_string();
4229            joined_tables.push((t, a, j.kind, j.on.as_ref()));
4230        }
4231
4232        // Build the combined schema: composite "alias.col" names so the
4233        // qualified-column resolver can find anything by exact match.
4234        let mut combined_schema: Vec<ColumnSchema> = Vec::new();
4235        for col in &primary_table.schema().columns {
4236            combined_schema.push(ColumnSchema::new(
4237                alloc::format!("{primary_alias}.{}", col.name),
4238                col.ty,
4239                col.nullable,
4240            ));
4241        }
4242        for (t, a, _, _) in &joined_tables {
4243            for col in &t.schema().columns {
4244                combined_schema.push(ColumnSchema::new(
4245                    alloc::format!("{a}.{}", col.name),
4246                    col.ty,
4247                    col.nullable,
4248                ));
4249            }
4250        }
4251        let ctx = EvalContext::new(&combined_schema, None);
4252
4253        // Nested-loop join. Starting set: every primary row, padded with
4254        // (no joined columns yet).
4255        let mut working: Vec<Row> = primary_table.rows().iter().cloned().collect();
4256        let mut produced_len = primary_table.schema().columns.len();
4257        for (t, _, kind, on) in &joined_tables {
4258            let right_arity = t.schema().columns.len();
4259            let mut next: Vec<Row> = Vec::new();
4260            for left in &working {
4261                let mut left_matched = false;
4262                for right in t.rows() {
4263                    let mut combined_vals = left.values.clone();
4264                    combined_vals.extend(right.values.iter().cloned());
4265                    // Pad combined to the eventual full width so the
4266                    // partial schema still matches positions used by ON.
4267                    let combined = Row::new(combined_vals);
4268                    let keep = if let Some(on_expr) = on {
4269                        let cond = eval::eval_expr(on_expr, &combined, &ctx)?;
4270                        matches!(cond, Value::Bool(true))
4271                    } else {
4272                        // CROSS / comma-list: every pair survives.
4273                        true
4274                    };
4275                    if keep {
4276                        next.push(combined);
4277                        left_matched = true;
4278                    }
4279                }
4280                if !left_matched && matches!(kind, JoinKind::Left) {
4281                    // LEFT OUTER JOIN: emit the left row with NULLs on
4282                    // the right side when no peer matched.
4283                    let mut combined_vals = left.values.clone();
4284                    for _ in 0..right_arity {
4285                        combined_vals.push(Value::Null);
4286                    }
4287                    next.push(Row::new(combined_vals));
4288                }
4289            }
4290            working = next;
4291            produced_len += right_arity;
4292            debug_assert!(produced_len <= combined_schema.len());
4293        }
4294
4295        // WHERE filter against combined rows.
4296        let mut filtered: Vec<Row> = Vec::new();
4297        for row in working {
4298            if let Some(where_expr) = &stmt.where_ {
4299                let cond = eval::eval_expr(where_expr, &row, &ctx)?;
4300                if !matches!(cond, Value::Bool(true)) {
4301                    continue;
4302                }
4303            }
4304            filtered.push(row);
4305        }
4306
4307        // Aggregate path: handle GROUP BY / aggregate calls over the
4308        // joined+filtered rows.
4309        if aggregate::uses_aggregate(stmt) {
4310            let refs: Vec<&Row> = filtered.iter().collect();
4311            let mut agg = aggregate::run(stmt, &refs, &combined_schema, None)?;
4312            apply_offset_and_limit(&mut agg.rows, stmt.offset_literal(), stmt.limit_literal());
4313            return Ok(QueryResult::Rows {
4314                columns: agg.columns,
4315                rows: agg.rows,
4316            });
4317        }
4318
4319        let projection = build_projection(&stmt.items, &combined_schema, "")?;
4320        let mut tagged: Vec<(Vec<f64>, Row)> = Vec::new();
4321        for row in &filtered {
4322            let mut values = Vec::with_capacity(projection.len());
4323            for p in &projection {
4324                values.push(eval::eval_expr(&p.expr, row, &ctx)?);
4325            }
4326            let order_keys = if stmt.order_by.is_empty() {
4327                Vec::new()
4328            } else {
4329                build_order_keys(&stmt.order_by, row, &ctx)?
4330            };
4331            tagged.push((order_keys, Row::new(values)));
4332        }
4333        if !stmt.order_by.is_empty() {
4334            let keep = if stmt.distinct {
4335                None
4336            } else {
4337                stmt.limit_literal()
4338                    .map(|l| l as usize + stmt.offset_literal().map_or(0, |o| o as usize))
4339            };
4340            let descs: Vec<bool> = stmt.order_by.iter().map(|o| o.desc).collect();
4341            partial_sort_tagged(&mut tagged, keep, &descs);
4342        }
4343        let mut output_rows: Vec<Row> = tagged.into_iter().map(|(_, r)| r).collect();
4344        if stmt.distinct {
4345            output_rows = dedup_rows(output_rows);
4346        }
4347        apply_offset_and_limit(
4348            &mut output_rows,
4349            stmt.offset_literal(),
4350            stmt.limit_literal(),
4351        );
4352        let columns: Vec<ColumnSchema> = projection
4353            .into_iter()
4354            .map(|p| ColumnSchema::new(p.output_name, p.ty, p.nullable))
4355            .collect();
4356        Ok(QueryResult::Rows {
4357            columns,
4358            rows: output_rows,
4359        })
4360    }
4361}
4362
4363/// One row-producing projection: an expression to evaluate, the resulting
4364/// column's user-visible name, its inferred type, and nullability.
4365#[derive(Debug, Clone)]
4366struct ProjectedItem {
4367    expr: Expr,
4368    output_name: String,
4369    ty: DataType,
4370    nullable: bool,
4371}
4372
4373/// Dedupe a row set, preserving first-seen order. `Row`'s `PartialEq` is
4374/// structural (`Vec<Value>` ⇒ pairwise `Value` equality), which gives SQL
4375/// `NULL = NULL → TRUE` and `NaN = NaN → FALSE`. The first agrees with
4376/// the spec's "two NULLs are not distinct"; the second is a tolerated
4377/// quirk for v1 (no NaN literals are reachable from the SQL surface).
4378fn dedup_rows(rows: Vec<Row>) -> Vec<Row> {
4379    let mut out: Vec<Row> = Vec::with_capacity(rows.len());
4380    for r in rows {
4381        if !out.iter().any(|seen| seen == &r) {
4382            out.push(r);
4383        }
4384    }
4385    out
4386}
4387
4388/// Coerce a `Value` to an `f64` sort key for ORDER BY. Numbers map directly;
4389/// NULL sorts last (treated as `+∞`); booleans are 0.0 / 1.0; text uses lex
4390/// order via the byte values; vectors are not sortable.
4391fn value_to_order_key(v: &Value) -> Result<f64, EngineError> {
4392    match v {
4393        Value::Null => Ok(f64::INFINITY),
4394        Value::SmallInt(n) => Ok(f64::from(*n)),
4395        Value::Int(n) => Ok(f64::from(*n)),
4396        Value::Date(d) => Ok(f64::from(*d)),
4397        #[allow(clippy::cast_precision_loss)]
4398        Value::Timestamp(t) => Ok(*t as f64),
4399        #[allow(clippy::cast_precision_loss)]
4400        Value::Numeric { scaled, scale } => {
4401            // Scaled integer / 10^scale, computed via f64 for sort
4402            // ordering only. Precision losses here only matter for
4403            // ORDER BY tie-breaks well past 15 significant digits.
4404            // `f64::powi` lives in std; we hand-roll the loop so the
4405            // no_std engine crate doesn't need it.
4406            let mut divisor = 1.0_f64;
4407            for _ in 0..*scale {
4408                divisor *= 10.0;
4409            }
4410            Ok((*scaled as f64) / divisor)
4411        }
4412        #[allow(clippy::cast_precision_loss)]
4413        Value::BigInt(n) => Ok(*n as f64),
4414        Value::Float(x) => Ok(*x),
4415        Value::Bool(b) => Ok(if *b { 1.0 } else { 0.0 }),
4416        Value::Text(s) => {
4417            // Lex order by codepoints — good enough for ORDER BY name.
4418            // Map first 8 bytes packed into u64 as a coarse key; ties fall to
4419            // partial_cmp Equal. v1.x can swap in a real string comparator.
4420            let mut key: u64 = 0;
4421            for &b in s.as_bytes().iter().take(8) {
4422                key = (key << 8) | u64::from(b);
4423            }
4424            #[allow(clippy::cast_precision_loss)]
4425            Ok(key as f64)
4426        }
4427        Value::Vector(_) | Value::Sq8Vector(_) | Value::HalfVector(_) => {
4428            Err(EngineError::Unsupported(
4429                "ORDER BY of a raw vector column is not meaningful — use `<->`".into(),
4430            ))
4431        }
4432        Value::Interval { .. } => Err(EngineError::Unsupported(
4433            "ORDER BY of an INTERVAL is not supported in v2.11 \
4434             (months vs micros has no single canonical ordering)"
4435                .into(),
4436        )),
4437        Value::Json(_) => Err(EngineError::Unsupported(
4438            "ORDER BY of a JSON value is not supported — cast the document to text first".into(),
4439        )),
4440        // v7.5.0 — Value is #[non_exhaustive]; future variants need
4441        // an explicit ORDER BY mapping. Surface as Unsupported until
4442        // engine support is added.
4443        _ => Err(EngineError::Unsupported(
4444            "ORDER BY of this value type is not supported".into(),
4445        )),
4446    }
4447}
4448
4449/// Try to plan a WHERE clause as an equality lookup against an existing
4450/// index. Returns the candidate row indices on success; `None` means the
4451/// caller should fall back to a full scan.
4452///
4453/// v0.8 recognises a single top-level `col = literal` (in either operand
4454/// order). AND chains and range scans land in later milestones.
4455/// Look for `ORDER BY col <dist-op> literal LIMIT k` against an
4456/// NSW-indexed vector column. Recognised distance ops: `<->` (L2),
4457/// `<#>` (inner product), `<=>` (cosine). When a WHERE clause is
4458/// present, the planner does an "over-fetch and filter" pass — it
4459/// asks the graph for `k * over_fetch` candidates, evaluates WHERE
4460/// against each, and trims back to `k`. Returns the row indices in
4461/// ascending-distance order when the plan applies.
4462fn try_nsw_knn(
4463    stmt: &SelectStatement,
4464    table: &Table,
4465    schema_cols: &[ColumnSchema],
4466    table_alias: &str,
4467) -> Option<Vec<usize>> {
4468    if stmt.distinct {
4469        return None;
4470    }
4471    let limit = usize::try_from(stmt.limit_literal()?).ok()?;
4472    if limit == 0 {
4473        return None;
4474    }
4475    // v6.4.0 — NSW kNN dispatch needs a single ORDER BY key on the
4476    // distance metric. Multi-key ORDER BY falls through to the
4477    // generic sort path.
4478    if stmt.order_by.len() != 1 {
4479        return None;
4480    }
4481    let order = &stmt.order_by[0];
4482    // NSW kNN returns rows ascending by distance — DESC inverts the
4483    // natural order, so the planner can't handle it without a sort
4484    // pass. Fall back to the generic ORDER BY path.
4485    if order.desc {
4486        return None;
4487    }
4488    let Expr::Binary { lhs, op, rhs } = &order.expr else {
4489        return None;
4490    };
4491    let metric = match op {
4492        BinOp::L2Distance => spg_storage::NswMetric::L2,
4493        BinOp::InnerProduct => spg_storage::NswMetric::InnerProduct,
4494        BinOp::CosineDistance => spg_storage::NswMetric::Cosine,
4495        _ => return None,
4496    };
4497    // Accept both `col <op> literal` and `literal <op> col`.
4498    let ((Expr::Column(col), literal) | (literal, Expr::Column(col))) =
4499        (lhs.as_ref(), rhs.as_ref())
4500    else {
4501        return None;
4502    };
4503    if let Some(q) = &col.qualifier
4504        && q != table_alias
4505    {
4506        return None;
4507    }
4508    let col_pos = schema_cols.iter().position(|s| s.name == col.name)?;
4509    let query = literal_to_vector(literal)?;
4510    let idx = spg_storage::nsw_index_on(table, col_pos)?;
4511    if let Some(where_expr) = &stmt.where_ {
4512        // Over-fetch and filter. The factor (10×) is a heuristic that
4513        // covers typical selectivity for the corpus tests; v2.x will
4514        // make it configurable.
4515        let over_fetch = limit.saturating_mul(10).max(NSW_OVER_FETCH_FLOOR);
4516        let candidates = spg_storage::nsw_query(table, &idx.name, &query, over_fetch, metric);
4517        let ctx = EvalContext::new(schema_cols, Some(table_alias));
4518        let mut kept: Vec<usize> = Vec::with_capacity(limit);
4519        for i in candidates {
4520            let row = &table.rows()[i];
4521            let cond = eval::eval_expr(where_expr, row, &ctx).ok()?;
4522            if matches!(cond, Value::Bool(true)) {
4523                kept.push(i);
4524                if kept.len() >= limit {
4525                    break;
4526                }
4527            }
4528        }
4529        Some(kept)
4530    } else {
4531        Some(spg_storage::nsw_query(
4532            table, &idx.name, &query, limit, metric,
4533        ))
4534    }
4535}
4536
4537/// Lower bound on the over-fetch pool when WHERE is present — even
4538/// for tiny `LIMIT 1` queries we keep enough candidates to absorb a
4539/// few WHERE rejections.
4540const NSW_OVER_FETCH_FLOOR: usize = 32;
4541
4542/// Pull a `Vec<f32>` out of a literal-or-cast expression. Returns
4543/// `None` for anything we can't fold at plan time.
4544fn literal_to_vector(e: &Expr) -> Option<Vec<f32>> {
4545    match e {
4546        Expr::Literal(Literal::Vector(v)) => Some(v.clone()),
4547        Expr::Cast { expr, .. } => literal_to_vector(expr),
4548        _ => None,
4549    }
4550}
4551
4552/// Materialise rows in a planner-supplied order (used by the NSW path)
4553/// without re-running ORDER BY. The projection + LIMIT slot mirror the
4554/// equivalent block in `exec_bare_select`.
4555fn materialise_in_order(
4556    stmt: &SelectStatement,
4557    table: &Table,
4558    schema_cols: &[ColumnSchema],
4559    table_alias: &str,
4560    ordered_rows: &[usize],
4561) -> Result<QueryResult, EngineError> {
4562    let ctx = EvalContext::new(schema_cols, Some(table_alias));
4563    let projection = build_projection(&stmt.items, schema_cols, table_alias)?;
4564    let mut output_rows: Vec<Row> = Vec::with_capacity(ordered_rows.len());
4565    for &i in ordered_rows {
4566        let row = &table.rows()[i];
4567        let mut values = Vec::with_capacity(projection.len());
4568        for p in &projection {
4569            values.push(eval::eval_expr(&p.expr, row, &ctx)?);
4570        }
4571        output_rows.push(Row::new(values));
4572    }
4573    apply_offset_and_limit(
4574        &mut output_rows,
4575        stmt.offset_literal(),
4576        stmt.limit_literal(),
4577    );
4578    let columns: Vec<ColumnSchema> = projection
4579        .into_iter()
4580        .map(|p| ColumnSchema::new(p.output_name, p.ty, p.nullable))
4581        .collect();
4582    Ok(QueryResult::Rows {
4583        columns,
4584        rows: output_rows,
4585    })
4586}
4587
4588fn try_index_seek<'a>(
4589    where_expr: &Expr,
4590    schema_cols: &[ColumnSchema],
4591    catalog: &'a Catalog,
4592    table: &'a Table,
4593    table_alias: &str,
4594) -> Option<Vec<Cow<'a, Row>>> {
4595    let Expr::Binary {
4596        lhs,
4597        op: BinOp::Eq,
4598        rhs,
4599    } = where_expr
4600    else {
4601        return None;
4602    };
4603    let (col_pos, value) = resolve_col_literal_pair(lhs, rhs, schema_cols, table_alias)
4604        .or_else(|| resolve_col_literal_pair(rhs, lhs, schema_cols, table_alias))?;
4605    let idx = table.index_on(col_pos)?;
4606    let key = IndexKey::from_value(&value)?;
4607    let locators = idx.lookup_eq(&key);
4608    let table_name = table.schema().name.as_str();
4609    // v5.1: each locator dispatches to either the hot tier (zero-
4610    // copy borrow of `table.rows()[i]`) or a cold-tier segment
4611    // (one page read + dense row decode, ~µs scale). Cold rows are
4612    // returned as `Cow::Owned` so the caller's `&Row` iteration
4613    // doesn't see a tier distinction; pre-freezer (no cold
4614    // segments loaded) every locator is `Hot` and every entry is
4615    // `Cow::Borrowed` — identical cost to the pre-v5.1 path.
4616    let mut out: Vec<Cow<'a, Row>> = Vec::with_capacity(locators.len());
4617    for loc in locators {
4618        match *loc {
4619            spg_storage::RowLocator::Hot(i) => {
4620                if let Some(row) = table.rows().get(i) {
4621                    out.push(Cow::Borrowed(row));
4622                }
4623            }
4624            spg_storage::RowLocator::Cold { segment_id, .. } => {
4625                if let Some(row) = catalog.resolve_cold_locator(table_name, segment_id, &key) {
4626                    out.push(Cow::Owned(row));
4627                }
4628            }
4629        }
4630    }
4631    Some(out)
4632}
4633
4634/// v5.2.3: extract `(column_position, IndexKey)` when `where_expr`
4635/// is a simple `col = literal` predicate suitable for a `BTree` index
4636/// seek. Used by `exec_update_cancel` / `exec_delete_cancel` to
4637/// decide whether a write touches a cold-tier row (which requires
4638/// promote-on-write / shadow-on-delete) before falling through to
4639/// the hot-tier row walk.
4640///
4641/// Returns `None` for any predicate shape the planner can't push
4642/// down to an index seek — complex WHERE clauses always take the
4643/// hot-only path (cold rows are immutable to non-indexed writes
4644/// until a future scan-fanout sub-version).
4645fn try_pk_predicate(
4646    where_expr: &Expr,
4647    schema_cols: &[ColumnSchema],
4648    table_alias: &str,
4649) -> Option<(usize, IndexKey)> {
4650    let Expr::Binary {
4651        lhs,
4652        op: BinOp::Eq,
4653        rhs,
4654    } = where_expr
4655    else {
4656        return None;
4657    };
4658    let (col_pos, value) = resolve_col_literal_pair(lhs, rhs, schema_cols, table_alias)
4659        .or_else(|| resolve_col_literal_pair(rhs, lhs, schema_cols, table_alias))?;
4660    let key = IndexKey::from_value(&value)?;
4661    Some((col_pos, key))
4662}
4663
4664fn resolve_col_literal_pair(
4665    col_side: &Expr,
4666    lit_side: &Expr,
4667    schema_cols: &[ColumnSchema],
4668    table_alias: &str,
4669) -> Option<(usize, Value)> {
4670    let Expr::Column(c) = col_side else {
4671        return None;
4672    };
4673    if let Some(q) = &c.qualifier
4674        && q != table_alias
4675    {
4676        return None;
4677    }
4678    let pos = schema_cols.iter().position(|s| s.name == c.name)?;
4679    let Expr::Literal(l) = lit_side else {
4680        return None;
4681    };
4682    let v = match l {
4683        Literal::Integer(n) => {
4684            if let Ok(small) = i32::try_from(*n) {
4685                Value::Int(small)
4686            } else {
4687                Value::BigInt(*n)
4688            }
4689        }
4690        Literal::Float(x) => Value::Float(*x),
4691        Literal::String(s) => Value::Text(s.clone()),
4692        Literal::Bool(b) => Value::Bool(*b),
4693        Literal::Null => Value::Null,
4694        // Vector and Interval literals can't be used as B-tree index keys.
4695        // Tell the planner to fall back to full-scan.
4696        Literal::Vector(_) | Literal::Interval { .. } => return None,
4697    };
4698    Some((pos, v))
4699}
4700
4701/// Find the schema entry that a SELECT-list `Expr::Column` refers to.
4702/// Mirrors `resolve_column` in `eval.rs`, but returns a proper
4703/// `EngineError` so the projection-build path keeps `UnknownQualifier`
4704/// vs `ColumnNotFound` distinct.
4705fn resolve_projection_column<'a>(
4706    c: &ColumnName,
4707    schema_cols: &'a [ColumnSchema],
4708    table_alias: &str,
4709) -> Result<&'a ColumnSchema, EngineError> {
4710    if let Some(q) = &c.qualifier {
4711        let composite = alloc::format!("{q}.{name}", name = c.name);
4712        if let Some(s) = schema_cols.iter().find(|s| s.name == composite) {
4713            return Ok(s);
4714        }
4715        // Single-table case: the qualifier may equal the active alias —
4716        // then look for the bare column name.
4717        if q == table_alias
4718            && let Some(s) = schema_cols.iter().find(|s| s.name == c.name)
4719        {
4720            return Ok(s);
4721        }
4722        // For multi-table schemas the qualifier is unknown only if no
4723        // column bears the "<q>." prefix. For single-table, the alias
4724        // mismatch alone is enough.
4725        let prefix = alloc::format!("{q}.");
4726        let qualifier_known =
4727            q == table_alias || schema_cols.iter().any(|s| s.name.starts_with(&prefix));
4728        if !qualifier_known {
4729            return Err(EngineError::Eval(EvalError::UnknownQualifier {
4730                qualifier: q.clone(),
4731            }));
4732        }
4733        return Err(EngineError::Eval(EvalError::ColumnNotFound {
4734            name: c.name.clone(),
4735        }));
4736    }
4737    if let Some(s) = schema_cols.iter().find(|s| s.name == c.name) {
4738        return Ok(s);
4739    }
4740    let suffix = alloc::format!(".{name}", name = c.name);
4741    let mut matches = schema_cols.iter().filter(|s| s.name.ends_with(&suffix));
4742    let first = matches.next();
4743    let extra = matches.next();
4744    match (first, extra) {
4745        (Some(s), None) => Ok(s),
4746        (Some(_), Some(_)) => Err(EngineError::Eval(EvalError::TypeMismatch {
4747            detail: alloc::format!("ambiguous column reference: {}", c.name),
4748        })),
4749        _ => Err(EngineError::Eval(EvalError::ColumnNotFound {
4750            name: c.name.clone(),
4751        })),
4752    }
4753}
4754
4755fn build_projection(
4756    items: &[SelectItem],
4757    schema_cols: &[ColumnSchema],
4758    table_alias: &str,
4759) -> Result<Vec<ProjectedItem>, EngineError> {
4760    let mut out = Vec::new();
4761    for item in items {
4762        match item {
4763            SelectItem::Wildcard => {
4764                for col in schema_cols {
4765                    out.push(ProjectedItem {
4766                        expr: Expr::Column(ColumnName {
4767                            qualifier: None,
4768                            name: col.name.clone(),
4769                        }),
4770                        output_name: col.name.clone(),
4771                        ty: col.ty,
4772                        nullable: col.nullable,
4773                    });
4774                }
4775            }
4776            SelectItem::Expr { expr, alias } => {
4777                // Plain column ref keeps full schema info (real type +
4778                // nullability). Compound expressions evaluate fine but have
4779                // no static type — surface them as nullable TEXT, which is
4780                // what most clients render anyway.
4781                if let Expr::Column(c) = expr {
4782                    let sch = resolve_projection_column(c, schema_cols, table_alias)?;
4783                    let output_name = alias.clone().unwrap_or_else(|| c.name.clone());
4784                    out.push(ProjectedItem {
4785                        expr: expr.clone(),
4786                        output_name,
4787                        ty: sch.ty,
4788                        nullable: sch.nullable,
4789                    });
4790                } else {
4791                    let output_name = alias.clone().unwrap_or_else(|| expr.to_string());
4792                    out.push(ProjectedItem {
4793                        expr: expr.clone(),
4794                        output_name,
4795                        ty: DataType::Text,
4796                        nullable: true,
4797                    });
4798                }
4799            }
4800        }
4801    }
4802    Ok(out)
4803}
4804
4805/// Promote an integer to a NUMERIC value at the requested scale.
4806/// Rejects values that, after scaling, would overflow the column's
4807/// precision budget.
4808fn numeric_from_integer(
4809    n: i128,
4810    precision: u8,
4811    scale: u8,
4812    col_name: &str,
4813) -> Result<Value, EngineError> {
4814    let factor = pow10_i128(scale);
4815    let scaled = n.checked_mul(factor).ok_or_else(|| {
4816        EngineError::Unsupported(alloc::format!(
4817            "integer overflow scaling value for column `{col_name}` to scale {scale}"
4818        ))
4819    })?;
4820    check_precision(scaled, precision, col_name)?;
4821    Ok(Value::Numeric { scaled, scale })
4822}
4823
4824/// Float → NUMERIC. Uses round-half-away-from-zero on `x * 10^scale`,
4825/// then verifies the result fits the column's precision.
4826#[allow(clippy::cast_precision_loss, clippy::cast_possible_truncation)]
4827fn numeric_from_float(
4828    x: f64,
4829    precision: u8,
4830    scale: u8,
4831    col_name: &str,
4832) -> Result<Value, EngineError> {
4833    if !x.is_finite() {
4834        return Err(EngineError::Unsupported(alloc::format!(
4835            "cannot store non-finite float in NUMERIC column `{col_name}`"
4836        )));
4837    }
4838    let mut factor = 1.0_f64;
4839    for _ in 0..scale {
4840        factor *= 10.0;
4841    }
4842    // Round half-away-from-zero by biasing then casting (`as i128`
4843    // truncates toward zero, so the bias + truncation gives the
4844    // desired rounding). `f64::floor` / `ceil` live in std; we don't
4845    // need them — the cast handles the truncation step.
4846    let shifted = x * factor;
4847    let biased = if shifted >= 0.0 {
4848        shifted + 0.5
4849    } else {
4850        shifted - 0.5
4851    };
4852    // Range-check before casting back to i128 — the cast itself is
4853    // saturating in Rust, which would silently truncate huge inputs.
4854    if !(-1e38..=1e38).contains(&biased) {
4855        return Err(EngineError::Unsupported(alloc::format!(
4856            "value {x} overflows NUMERIC range for column `{col_name}`"
4857        )));
4858    }
4859    let scaled = biased as i128;
4860    check_precision(scaled, precision, col_name)?;
4861    Ok(Value::Numeric { scaled, scale })
4862}
4863
4864/// Move a Numeric value from `src_scale` to `dst_scale`. Going up
4865/// multiplies by 10; going down rounds half-away-from-zero.
4866fn numeric_rescale(
4867    scaled: i128,
4868    src_scale: u8,
4869    precision: u8,
4870    dst_scale: u8,
4871    col_name: &str,
4872) -> Result<Value, EngineError> {
4873    let new_scaled = if dst_scale >= src_scale {
4874        let bump = pow10_i128(dst_scale - src_scale);
4875        scaled.checked_mul(bump).ok_or_else(|| {
4876            EngineError::Unsupported(alloc::format!(
4877                "overflow rescaling NUMERIC for column `{col_name}`"
4878            ))
4879        })?
4880    } else {
4881        let drop = pow10_i128(src_scale - dst_scale);
4882        let half = drop / 2;
4883        if scaled >= 0 {
4884            (scaled + half) / drop
4885        } else {
4886            (scaled - half) / drop
4887        }
4888    };
4889    check_precision(new_scaled, precision, col_name)?;
4890    Ok(Value::Numeric {
4891        scaled: new_scaled,
4892        scale: dst_scale,
4893    })
4894}
4895
4896/// Drop the fractional part of a scaled integer, returning the integer
4897/// portion (toward zero). Used for NUMERIC → INT casts.
4898const fn numeric_truncate_to_integer(scaled: i128, scale: u8) -> i128 {
4899    if scale == 0 {
4900        return scaled;
4901    }
4902    let factor = pow10_i128_const(scale);
4903    scaled / factor
4904}
4905
4906/// Verify a scaled NUMERIC value fits the column's declared precision.
4907/// `precision == 0` is the "unconstrained" form (bare `NUMERIC`); we
4908/// skip the check there.
4909fn check_precision(scaled: i128, precision: u8, col_name: &str) -> Result<(), EngineError> {
4910    if precision == 0 {
4911        return Ok(());
4912    }
4913    let limit = pow10_i128(precision);
4914    if scaled.unsigned_abs() >= limit.unsigned_abs() {
4915        return Err(EngineError::Unsupported(alloc::format!(
4916            "NUMERIC value exceeds precision {precision} for column `{col_name}`"
4917        )));
4918    }
4919    Ok(())
4920}
4921
4922const fn pow10_i128_const(p: u8) -> i128 {
4923    let mut acc: i128 = 1;
4924    let mut i = 0;
4925    while i < p {
4926        acc *= 10;
4927        i += 1;
4928    }
4929    acc
4930}
4931
4932fn pow10_i128(p: u8) -> i128 {
4933    pow10_i128_const(p)
4934}
4935
4936/// Walk a parsed `Statement`, swapping any `NOW()` /
4937/// `CURRENT_TIMESTAMP()` / `CURRENT_DATE()` function calls for a
4938/// literal cast that wraps the engine's per-statement clock reading.
4939/// When `now_micros` is `None`, calls stay as-is and surface as
4940/// `unknown function` at eval time — keeps the error path explicit.
4941/// v4.10: pre-walk the WHERE / projection / etc. of a SELECT and
4942/// replace every subquery node with a materialised literal. SPG
4943/// only supports uncorrelated subqueries — the inner SELECT does
4944/// not see outer-row columns, so the result is the same for every
4945/// outer row and can be evaluated once.
4946///
4947/// Returns the rewritten statement; the caller passes this to the
4948/// regular row-loop executor which no longer sees Subquery nodes
4949/// in its tree.
4950impl Engine {
4951    /// v4.12 window executor. Implements `ROW_NUMBER` / `RANK` /
4952    /// `DENSE_RANK` and the partition-aware aggregates `SUM` /
4953    /// `AVG` / `COUNT` / `MIN` / `MAX`. The plan is:
4954    /// 1. Apply the WHERE filter.
4955    /// 2. For each unique `WindowFunction` node in the projection,
4956    ///    partition + sort, compute the per-row value.
4957    /// 3. Append the window values as synthetic columns (`__win_N`)
4958    ///    to the row schema.
4959    /// 4. Rewrite the projection to read those columns.
4960    /// 5. Hand off to the regular project / ORDER BY / LIMIT pipe.
4961    #[allow(
4962        clippy::too_many_lines,
4963        clippy::type_complexity,
4964        clippy::needless_range_loop
4965    )] // window-eval is one cohesive pipe; splitting fragments
4966    fn exec_select_with_window(
4967        &self,
4968        stmt: &SelectStatement,
4969        cancel: CancelToken<'_>,
4970    ) -> Result<QueryResult, EngineError> {
4971        let from = stmt.from.as_ref().ok_or_else(|| {
4972            EngineError::Unsupported("window functions require a FROM clause".into())
4973        })?;
4974        // For v4.12 we only support a single-table FROM. Joins +
4975        // windows is queued for v5.x.
4976        if !from.joins.is_empty() {
4977            return Err(EngineError::Unsupported(
4978                "JOIN with window functions not yet supported".into(),
4979            ));
4980        }
4981        let primary = &from.primary;
4982        let table = self.active_catalog().get(&primary.name).ok_or_else(|| {
4983            StorageError::TableNotFound {
4984                name: primary.name.clone(),
4985            }
4986        })?;
4987        let alias = primary.alias.as_deref().unwrap_or(primary.name.as_str());
4988        let schema_cols = &table.schema().columns;
4989        let ctx = EvalContext::new(schema_cols, Some(alias));
4990
4991        // 1) Filter pass.
4992        let mut filtered: Vec<&Row> = Vec::new();
4993        for (i, row) in table.rows().iter().enumerate() {
4994            if i.is_multiple_of(256) {
4995                cancel.check()?;
4996            }
4997            if let Some(w) = &stmt.where_ {
4998                let cond = eval::eval_expr(w, row, &ctx)?;
4999                if !matches!(cond, Value::Bool(true)) {
5000                    continue;
5001                }
5002            }
5003            filtered.push(row);
5004        }
5005        let n_rows = filtered.len();
5006
5007        // 2) Collect unique window function nodes from projection.
5008        let mut window_nodes: Vec<Expr> = Vec::new();
5009        for item in &stmt.items {
5010            if let SelectItem::Expr { expr, .. } = item {
5011                collect_window_nodes(expr, &mut window_nodes);
5012            }
5013        }
5014
5015        // 3) For each window, compute per-row value.
5016        // Index: same order as window_nodes; for row i, win_vals[w][i].
5017        let mut win_vals: Vec<Vec<Value>> = Vec::with_capacity(window_nodes.len());
5018        for wnode in &window_nodes {
5019            let Expr::WindowFunction {
5020                name,
5021                args,
5022                partition_by,
5023                order_by,
5024                frame,
5025                null_treatment,
5026            } = wnode
5027            else {
5028                unreachable!("collect_window_nodes pushes only WindowFunction");
5029            };
5030            // Compute (partition_key, order_key, original_index) for each row.
5031            let mut indexed: Vec<(Vec<Value>, Vec<(Value, bool)>, usize)> =
5032                Vec::with_capacity(n_rows);
5033            for (i, row) in filtered.iter().enumerate() {
5034                let pkey: Vec<Value> = partition_by
5035                    .iter()
5036                    .map(|p| eval::eval_expr(p, row, &ctx))
5037                    .collect::<Result<_, _>>()?;
5038                let okey: Vec<(Value, bool)> = order_by
5039                    .iter()
5040                    .map(|(e, desc)| eval::eval_expr(e, row, &ctx).map(|v| (v, *desc)))
5041                    .collect::<Result<_, _>>()?;
5042                indexed.push((pkey, okey, i));
5043            }
5044            // Sort by (partition_key, order_key). Partition key uses
5045            // a stable encoded form; order key respects ASC/DESC.
5046            indexed.sort_by(|a, b| {
5047                let p_cmp = partition_key_cmp(&a.0, &b.0);
5048                if p_cmp != core::cmp::Ordering::Equal {
5049                    return p_cmp;
5050                }
5051                order_key_cmp(&a.1, &b.1)
5052            });
5053            // Per-partition compute.
5054            let mut out_vals: Vec<Value> = alloc::vec![Value::Null; n_rows];
5055            let mut p_start = 0;
5056            while p_start < indexed.len() {
5057                let mut p_end = p_start + 1;
5058                while p_end < indexed.len()
5059                    && partition_key_cmp(&indexed[p_start].0, &indexed[p_end].0)
5060                        == core::cmp::Ordering::Equal
5061                {
5062                    p_end += 1;
5063                }
5064                // Compute the function within this partition slice.
5065                compute_window_partition(
5066                    name,
5067                    args,
5068                    !order_by.is_empty(),
5069                    frame.as_ref(),
5070                    *null_treatment,
5071                    &indexed[p_start..p_end],
5072                    &filtered,
5073                    &ctx,
5074                    &mut out_vals,
5075                )?;
5076                p_start = p_end;
5077            }
5078            win_vals.push(out_vals);
5079        }
5080
5081        // 4) Build extended schema: original columns + synthetic.
5082        let mut ext_cols = schema_cols.clone();
5083        for i in 0..window_nodes.len() {
5084            ext_cols.push(ColumnSchema::new(
5085                alloc::format!("__win_{i}"),
5086                DataType::Text, // type doesn't matter for projection eval
5087                true,
5088            ));
5089        }
5090        // 5) Build extended rows: each row gets its window values appended.
5091        let mut ext_rows: Vec<Row> = Vec::with_capacity(n_rows);
5092        for i in 0..n_rows {
5093            let mut values = filtered[i].values.clone();
5094            for w in 0..window_nodes.len() {
5095                values.push(win_vals[w][i].clone());
5096            }
5097            ext_rows.push(Row::new(values));
5098        }
5099        // 6) Rewrite the projection: WindowFunction nodes → Column(__win_N).
5100        let mut rewritten_items: Vec<SelectItem> = Vec::with_capacity(stmt.items.len());
5101        for item in &stmt.items {
5102            let new_item = match item {
5103                SelectItem::Wildcard => SelectItem::Wildcard,
5104                SelectItem::Expr { expr, alias } => {
5105                    let mut e = expr.clone();
5106                    rewrite_window_to_columns(&mut e, &window_nodes);
5107                    SelectItem::Expr {
5108                        expr: e,
5109                        alias: alias.clone(),
5110                    }
5111                }
5112            };
5113            rewritten_items.push(new_item);
5114        }
5115
5116        // 7) Project into final rows.
5117        let ext_ctx = EvalContext::new(&ext_cols, Some(alias));
5118        let projection = build_projection(&rewritten_items, &ext_cols, alias)?;
5119        let mut tagged: Vec<(Vec<f64>, Row)> = Vec::with_capacity(n_rows);
5120        for (i, row) in ext_rows.iter().enumerate() {
5121            if i.is_multiple_of(256) {
5122                cancel.check()?;
5123            }
5124            let mut values = Vec::with_capacity(projection.len());
5125            for p in &projection {
5126                values.push(eval::eval_expr(&p.expr, row, &ext_ctx)?);
5127            }
5128            let order_keys = if stmt.order_by.is_empty() {
5129                Vec::new()
5130            } else {
5131                let mut keys = Vec::with_capacity(stmt.order_by.len());
5132                for o in &stmt.order_by {
5133                    let mut e = o.expr.clone();
5134                    rewrite_window_to_columns(&mut e, &window_nodes);
5135                    let key = eval::eval_expr(&e, row, &ext_ctx)?;
5136                    keys.push(value_to_order_key(&key)?);
5137                }
5138                keys
5139            };
5140            tagged.push((order_keys, Row::new(values)));
5141        }
5142        // ORDER BY + LIMIT/OFFSET on the projected rows.
5143        if !stmt.order_by.is_empty() {
5144            let descs: Vec<bool> = stmt.order_by.iter().map(|o| o.desc).collect();
5145            sort_by_keys(&mut tagged, &descs);
5146        }
5147        let mut out_rows: Vec<Row> = tagged.into_iter().map(|(_, r)| r).collect();
5148        apply_offset_and_limit(&mut out_rows, stmt.offset_literal(), stmt.limit_literal());
5149        let final_cols: Vec<ColumnSchema> = projection
5150            .into_iter()
5151            .map(|p| ColumnSchema::new(p.output_name, p.ty, p.nullable))
5152            .collect();
5153        Ok(QueryResult::Rows {
5154            columns: final_cols,
5155            rows: out_rows,
5156        })
5157    }
5158
5159    /// v4.11: materialise each CTE into a temp table inside a
5160    /// cloned catalog, then run the body SELECT against a fresh
5161    /// engine instance that owns the enriched catalog. The clone
5162    /// is moderately expensive — only paid by CTE-bearing queries.
5163    /// Subqueries inside CTE bodies / the main body resolve as
5164    /// usual; `clock_fn` is propagated so `NOW()` lines up.
5165    fn exec_with_ctes(
5166        &self,
5167        stmt: &SelectStatement,
5168        cancel: CancelToken<'_>,
5169    ) -> Result<QueryResult, EngineError> {
5170        cancel.check()?;
5171        let mut catalog = self.active_catalog().clone();
5172        for cte in &stmt.ctes {
5173            if catalog.get(&cte.name).is_some() {
5174                return Err(EngineError::Unsupported(alloc::format!(
5175                    "CTE name {:?} shadows an existing table; rename the CTE",
5176                    cte.name
5177                )));
5178            }
5179            let (columns, rows) = if cte.recursive {
5180                self.materialise_recursive_cte(cte, &catalog, cancel)?
5181            } else {
5182                let body_result = self.exec_select_cancel(&cte.body, cancel)?;
5183                let QueryResult::Rows { columns, rows } = body_result else {
5184                    return Err(EngineError::Unsupported(alloc::format!(
5185                        "CTE {:?} body did not return rows",
5186                        cte.name
5187                    )));
5188                };
5189                (columns, rows)
5190            };
5191            // v4.22: the projection builder labels any non-column
5192            // expression as Text — including literal SELECT 1.
5193            // Promote each column's type to whatever the rows
5194            // actually carry so the CTE storage table accepts them.
5195            let inferred = infer_column_types(&columns, &rows);
5196            let mut columns = inferred;
5197            // v4.22: apply optional `WITH name(a, b, c)` overrides.
5198            if !cte.column_overrides.is_empty() {
5199                if cte.column_overrides.len() != columns.len() {
5200                    return Err(EngineError::Unsupported(alloc::format!(
5201                        "CTE {:?} column list has {} names but body returns {} columns",
5202                        cte.name,
5203                        cte.column_overrides.len(),
5204                        columns.len()
5205                    )));
5206                }
5207                for (col, name) in columns.iter_mut().zip(cte.column_overrides.iter()) {
5208                    col.name.clone_from(name);
5209                }
5210            }
5211            let schema = TableSchema::new(cte.name.clone(), columns);
5212            catalog.create_table(schema).map_err(EngineError::Storage)?;
5213            let table = catalog
5214                .get_mut(&cte.name)
5215                .expect("just-created CTE table must exist");
5216            for row in rows {
5217                table.insert(row).map_err(EngineError::Storage)?;
5218            }
5219        }
5220        // Strip CTEs from the body before running on the temp engine
5221        // so we don't recurse forever.
5222        let mut body = stmt.clone();
5223        body.ctes = Vec::new();
5224        let mut temp = Engine::restore(catalog);
5225        if let Some(c) = self.clock {
5226            temp = temp.with_clock(c);
5227        }
5228        if let Some(f) = self.salt_fn {
5229            temp = temp.with_salt_fn(f);
5230        }
5231        temp.exec_select_cancel(&body, cancel)
5232    }
5233
5234    /// v4.22: materialise a WITH RECURSIVE CTE. The body must be a
5235    /// UNION (or UNION ALL) of an anchor that does not reference
5236    /// the CTE name, and one or more recursive terms that do. The
5237    /// anchor runs first; each subsequent iteration runs the
5238    /// recursive term against a temp catalog where the CTE name is
5239    /// bound to the *previous* iteration's output. Iteration stops
5240    /// when the recursive term yields no rows; UNION (DISTINCT)
5241    /// deduplicates against the accumulated result, UNION ALL does
5242    /// not. A hard cap on total rows prevents runaway queries.
5243    #[allow(clippy::too_many_lines)]
5244    fn materialise_recursive_cte(
5245        &self,
5246        cte: &spg_sql::ast::Cte,
5247        base_catalog: &Catalog,
5248        cancel: CancelToken<'_>,
5249    ) -> Result<(Vec<ColumnSchema>, Vec<Row>), EngineError> {
5250        const MAX_TOTAL_ROWS: usize = 1_000_000;
5251        const MAX_ITERATIONS: usize = 100_000;
5252        cancel.check()?;
5253        if cte.body.unions.is_empty() {
5254            return Err(EngineError::Unsupported(alloc::format!(
5255                "WITH RECURSIVE {:?} body must be a UNION of an anchor and a recursive term",
5256                cte.name
5257            )));
5258        }
5259        // Anchor: the body's leading SELECT, with unions stripped.
5260        let mut anchor = cte.body.clone();
5261        let union_terms = core::mem::take(&mut anchor.unions);
5262        anchor.ctes = Vec::new();
5263        // Anchor must not reference the CTE name.
5264        if select_refers_to(&anchor, &cte.name) {
5265            return Err(EngineError::Unsupported(alloc::format!(
5266                "WITH RECURSIVE {:?}: the anchor must not reference the CTE itself",
5267                cte.name
5268            )));
5269        }
5270        let anchor_result = self.exec_select_cancel(&anchor, cancel)?;
5271        let QueryResult::Rows {
5272            columns: anchor_cols,
5273            rows: anchor_rows,
5274        } = anchor_result
5275        else {
5276            return Err(EngineError::Unsupported(alloc::format!(
5277                "WITH RECURSIVE {:?}: anchor did not return rows",
5278                cte.name
5279            )));
5280        };
5281        // The projection builder labels non-column expressions Text;
5282        // refine column types from the anchor's actual values so the
5283        // intermediate iter-catalog tables accept them.
5284        let mut columns = infer_column_types(&anchor_cols, &anchor_rows);
5285        if !cte.column_overrides.is_empty() {
5286            if cte.column_overrides.len() != columns.len() {
5287                return Err(EngineError::Unsupported(alloc::format!(
5288                    "CTE {:?} column list has {} names but anchor returns {} columns",
5289                    cte.name,
5290                    cte.column_overrides.len(),
5291                    columns.len()
5292                )));
5293            }
5294            for (col, name) in columns.iter_mut().zip(cte.column_overrides.iter()) {
5295                col.name.clone_from(name);
5296            }
5297        }
5298        let mut all_rows: Vec<Row> = anchor_rows.clone();
5299        let mut working_set: Vec<Row> = anchor_rows;
5300        let mut seen: alloc::collections::BTreeSet<Vec<u8>> = alloc::collections::BTreeSet::new();
5301        // Track at least one "all UNION ALL" flag — if every union
5302        // kind is ALL we skip the dedup step (faster + matches PG).
5303        let all_union_all = union_terms.iter().all(|(k, _)| matches!(k, UnionKind::All));
5304        if !all_union_all {
5305            for r in &all_rows {
5306                seen.insert(encode_row_key(r));
5307            }
5308        }
5309        for iter in 0..MAX_ITERATIONS {
5310            cancel.check()?;
5311            if working_set.is_empty() {
5312                break;
5313            }
5314            // Build a fresh catalog: base + CTE bound to working_set.
5315            let mut iter_catalog = base_catalog.clone();
5316            let schema = TableSchema::new(cte.name.clone(), columns.clone());
5317            iter_catalog
5318                .create_table(schema)
5319                .map_err(EngineError::Storage)?;
5320            {
5321                let table = iter_catalog.get_mut(&cte.name).expect("just-created");
5322                for row in &working_set {
5323                    table.insert(row.clone()).map_err(EngineError::Storage)?;
5324                }
5325            }
5326            let mut iter_engine = Engine::restore(iter_catalog);
5327            if let Some(c) = self.clock {
5328                iter_engine = iter_engine.with_clock(c);
5329            }
5330            if let Some(f) = self.salt_fn {
5331                iter_engine = iter_engine.with_salt_fn(f);
5332            }
5333            // Run each recursive term in sequence and collect new rows.
5334            let mut next_set: Vec<Row> = Vec::new();
5335            for (_, term) in &union_terms {
5336                let mut term = term.clone();
5337                term.ctes = Vec::new();
5338                let r = iter_engine.exec_select_cancel(&term, cancel)?;
5339                let QueryResult::Rows {
5340                    columns: rc,
5341                    rows: rs,
5342                } = r
5343                else {
5344                    return Err(EngineError::Unsupported(alloc::format!(
5345                        "WITH RECURSIVE {:?}: recursive term did not return rows",
5346                        cte.name
5347                    )));
5348                };
5349                if rc.len() != columns.len() {
5350                    return Err(EngineError::Unsupported(alloc::format!(
5351                        "WITH RECURSIVE {:?}: column count of recursive term ({}) does not match anchor ({})",
5352                        cte.name,
5353                        rc.len(),
5354                        columns.len()
5355                    )));
5356                }
5357                for row in rs {
5358                    if !all_union_all {
5359                        let key = encode_row_key(&row);
5360                        if !seen.insert(key) {
5361                            continue;
5362                        }
5363                    }
5364                    next_set.push(row);
5365                }
5366            }
5367            if next_set.is_empty() {
5368                break;
5369            }
5370            all_rows.extend(next_set.iter().cloned());
5371            working_set = next_set;
5372            if all_rows.len() > MAX_TOTAL_ROWS {
5373                return Err(EngineError::Unsupported(alloc::format!(
5374                    "WITH RECURSIVE {:?}: produced more than {MAX_TOTAL_ROWS} rows — likely runaway recursion",
5375                    cte.name
5376                )));
5377            }
5378            if iter + 1 == MAX_ITERATIONS {
5379                return Err(EngineError::Unsupported(alloc::format!(
5380                    "WITH RECURSIVE {:?}: exceeded {MAX_ITERATIONS} iterations",
5381                    cte.name
5382                )));
5383            }
5384        }
5385        Ok((columns, all_rows))
5386    }
5387
5388    fn resolve_select_subqueries(
5389        &self,
5390        stmt: &mut SelectStatement,
5391        cancel: CancelToken<'_>,
5392    ) -> Result<(), EngineError> {
5393        for item in &mut stmt.items {
5394            if let SelectItem::Expr { expr, .. } = item {
5395                self.resolve_expr_subqueries(expr, cancel)?;
5396            }
5397        }
5398        if let Some(w) = &mut stmt.where_ {
5399            self.resolve_expr_subqueries(w, cancel)?;
5400        }
5401        if let Some(gs) = &mut stmt.group_by {
5402            for g in gs {
5403                self.resolve_expr_subqueries(g, cancel)?;
5404            }
5405        }
5406        if let Some(h) = &mut stmt.having {
5407            self.resolve_expr_subqueries(h, cancel)?;
5408        }
5409        for o in &mut stmt.order_by {
5410            self.resolve_expr_subqueries(&mut o.expr, cancel)?;
5411        }
5412        for (_, peer) in &mut stmt.unions {
5413            self.resolve_select_subqueries(peer, cancel)?;
5414        }
5415        Ok(())
5416    }
5417
5418    #[allow(clippy::only_used_in_recursion)] // engine handle reads aren't really pure
5419    fn resolve_expr_subqueries(
5420        &self,
5421        e: &mut Expr,
5422        cancel: CancelToken<'_>,
5423    ) -> Result<(), EngineError> {
5424        // Replace-on-this-node cases first.
5425        if let Some(replacement) = self.subquery_replacement(e, cancel)? {
5426            *e = replacement;
5427            return Ok(());
5428        }
5429        match e {
5430            Expr::Binary { lhs, rhs, .. } => {
5431                self.resolve_expr_subqueries(lhs, cancel)?;
5432                self.resolve_expr_subqueries(rhs, cancel)?;
5433            }
5434            Expr::Unary { expr, .. } | Expr::Cast { expr, .. } | Expr::IsNull { expr, .. } => {
5435                self.resolve_expr_subqueries(expr, cancel)?;
5436            }
5437            Expr::FunctionCall { args, .. } => {
5438                for a in args {
5439                    self.resolve_expr_subqueries(a, cancel)?;
5440                }
5441            }
5442            Expr::Like { expr, pattern, .. } => {
5443                self.resolve_expr_subqueries(expr, cancel)?;
5444                self.resolve_expr_subqueries(pattern, cancel)?;
5445            }
5446            Expr::Extract { source, .. } => self.resolve_expr_subqueries(source, cancel)?,
5447            // v4.12 window functions — recurse into args + ORDER BY
5448            // + PARTITION BY in case they carry inner subqueries.
5449            Expr::WindowFunction {
5450                args,
5451                partition_by,
5452                order_by,
5453                ..
5454            } => {
5455                for a in args {
5456                    self.resolve_expr_subqueries(a, cancel)?;
5457                }
5458                for p in partition_by {
5459                    self.resolve_expr_subqueries(p, cancel)?;
5460                }
5461                for (e, _) in order_by {
5462                    self.resolve_expr_subqueries(e, cancel)?;
5463                }
5464            }
5465            // Subquery nodes are handled in subquery_replacement
5466            // (which returned None — defensive no-op); Literal /
5467            // Column are leaves.
5468            Expr::ScalarSubquery(_)
5469            | Expr::Exists { .. }
5470            | Expr::InSubquery { .. }
5471            | Expr::Literal(_)
5472            | Expr::Placeholder(_)
5473            | Expr::Column(_) => {}
5474            // v7.10.10 — recurse children.
5475            Expr::Array(items) => {
5476                for elem in items {
5477                    self.resolve_expr_subqueries(elem, cancel)?;
5478                }
5479            }
5480            Expr::ArraySubscript { target, index } => {
5481                self.resolve_expr_subqueries(target, cancel)?;
5482                self.resolve_expr_subqueries(index, cancel)?;
5483            }
5484            Expr::AnyAll { expr, array, .. } => {
5485                self.resolve_expr_subqueries(expr, cancel)?;
5486                self.resolve_expr_subqueries(array, cancel)?;
5487            }
5488        }
5489        Ok(())
5490    }
5491
5492    /// v4.23: per-row eval that handles correlated subqueries.
5493    /// Equivalent to `eval::eval_expr` when the expression has no
5494    /// subqueries; otherwise clones the expression, substitutes
5495    /// outer-row columns into each surviving subquery node, runs
5496    /// the inner SELECT, and replaces the node with the literal
5497    /// result. Only the WHERE-filter call sites use this path so
5498    /// the uncorrelated fast path is preserved everywhere else.
5499    fn eval_expr_with_correlated(
5500        &self,
5501        expr: &Expr,
5502        row: &Row,
5503        ctx: &EvalContext<'_>,
5504        cancel: CancelToken<'_>,
5505        memo: Option<&mut memoize::MemoizeCache>,
5506    ) -> Result<Value, EngineError> {
5507        if !expr_has_subquery(expr) {
5508            return eval::eval_expr(expr, row, ctx).map_err(EngineError::Eval);
5509        }
5510        let mut e = expr.clone();
5511        self.resolve_correlated_in_expr(&mut e, row, ctx, cancel, memo)?;
5512        eval::eval_expr(&e, row, ctx).map_err(EngineError::Eval)
5513    }
5514
5515    fn resolve_correlated_in_expr(
5516        &self,
5517        e: &mut Expr,
5518        row: &Row,
5519        ctx: &EvalContext<'_>,
5520        cancel: CancelToken<'_>,
5521        mut memo: Option<&mut memoize::MemoizeCache>,
5522    ) -> Result<(), EngineError> {
5523        match e {
5524            Expr::ScalarSubquery(inner) => {
5525                // v6.2.6 — Memoize: build the cache key from the
5526                // pre-substitution subquery repr + the outer row's
5527                // values. Two outer rows with identical correlated
5528                // values hit the same entry.
5529                let cache_key = memo.as_ref().map(|_| memoize::CacheKey {
5530                    subquery_repr: alloc::format!("{}", **inner),
5531                    outer_values: row.values.clone(),
5532                });
5533                if let (Some(cache), Some(k)) = (memo.as_deref_mut(), cache_key.as_ref())
5534                    && let Some(cached) = cache.get(k)
5535                {
5536                    *e = value_to_literal_expr(cached)?;
5537                    return Ok(());
5538                }
5539                let mut s = (**inner).clone();
5540                substitute_outer_columns(&mut s, row, ctx);
5541                let r = self.exec_select_cancel(&s, cancel)?;
5542                let QueryResult::Rows { rows, .. } = r else {
5543                    return Err(EngineError::Unsupported(
5544                        "scalar subquery: inner did not return rows".into(),
5545                    ));
5546                };
5547                let value = match rows.as_slice() {
5548                    [] => Value::Null,
5549                    [r0] => r0.values.first().cloned().unwrap_or(Value::Null),
5550                    _ => {
5551                        return Err(EngineError::Unsupported(alloc::format!(
5552                            "scalar subquery returned {} rows; expected 0 or 1",
5553                            rows.len()
5554                        )));
5555                    }
5556                };
5557                if let (Some(cache), Some(k)) = (memo.as_deref_mut(), cache_key) {
5558                    cache.insert(k, value.clone());
5559                }
5560                *e = value_to_literal_expr(value)?;
5561            }
5562            Expr::Exists { subquery, negated } => {
5563                let mut s = (**subquery).clone();
5564                substitute_outer_columns(&mut s, row, ctx);
5565                let r = self.exec_select_cancel(&s, cancel)?;
5566                let exists = matches!(r, QueryResult::Rows { rows, .. } if !rows.is_empty());
5567                let bit = if *negated { !exists } else { exists };
5568                *e = Expr::Literal(Literal::Bool(bit));
5569            }
5570            Expr::InSubquery {
5571                expr: lhs,
5572                subquery,
5573                negated,
5574            } => {
5575                self.resolve_correlated_in_expr(lhs, row, ctx, cancel, memo.as_deref_mut())?;
5576                let lhs_val = eval::eval_expr(lhs, row, ctx).map_err(EngineError::Eval)?;
5577                let mut s = (**subquery).clone();
5578                substitute_outer_columns(&mut s, row, ctx);
5579                let r = self.exec_select_cancel(&s, cancel)?;
5580                let QueryResult::Rows { columns, rows, .. } = r else {
5581                    return Err(EngineError::Unsupported(
5582                        "IN-subquery: inner did not return rows".into(),
5583                    ));
5584                };
5585                if columns.len() != 1 {
5586                    return Err(EngineError::Unsupported(alloc::format!(
5587                        "IN-subquery must project exactly one column; got {}",
5588                        columns.len()
5589                    )));
5590                }
5591                let mut found = false;
5592                let mut any_null = false;
5593                for r0 in rows {
5594                    let v = r0.values.into_iter().next().unwrap_or(Value::Null);
5595                    if v.is_null() {
5596                        any_null = true;
5597                        continue;
5598                    }
5599                    if value_cmp(&v, &lhs_val) == core::cmp::Ordering::Equal {
5600                        found = true;
5601                        break;
5602                    }
5603                }
5604                let bit = if found {
5605                    !*negated
5606                } else if any_null {
5607                    return Err(EngineError::Unsupported(
5608                        "IN-subquery with NULL in result and no match: NULL semantics not yet implemented".into(),
5609                    ));
5610                } else {
5611                    *negated
5612                };
5613                *e = Expr::Literal(Literal::Bool(bit));
5614            }
5615            Expr::Binary { lhs, rhs, .. } => {
5616                self.resolve_correlated_in_expr(lhs, row, ctx, cancel, memo.as_deref_mut())?;
5617                self.resolve_correlated_in_expr(rhs, row, ctx, cancel, memo.as_deref_mut())?;
5618            }
5619            Expr::Unary { expr, .. } | Expr::Cast { expr, .. } | Expr::IsNull { expr, .. } => {
5620                self.resolve_correlated_in_expr(expr, row, ctx, cancel, memo.as_deref_mut())?;
5621            }
5622            Expr::Like { expr, pattern, .. } => {
5623                self.resolve_correlated_in_expr(expr, row, ctx, cancel, memo.as_deref_mut())?;
5624                self.resolve_correlated_in_expr(pattern, row, ctx, cancel, memo.as_deref_mut())?;
5625            }
5626            Expr::FunctionCall { args, .. } => {
5627                for a in args {
5628                    self.resolve_correlated_in_expr(a, row, ctx, cancel, memo.as_deref_mut())?;
5629                }
5630            }
5631            Expr::Extract { source, .. } => {
5632                self.resolve_correlated_in_expr(source, row, ctx, cancel, memo.as_deref_mut())?;
5633            }
5634            Expr::WindowFunction { .. }
5635            | Expr::Literal(_)
5636            | Expr::Placeholder(_)
5637            | Expr::Column(_) => {}
5638            // v7.10.10 — recurse children.
5639            Expr::Array(items) => {
5640                for elem in items {
5641                    self.resolve_correlated_in_expr(elem, row, ctx, cancel, memo.as_deref_mut())?;
5642                }
5643            }
5644            Expr::ArraySubscript { target, index } => {
5645                self.resolve_correlated_in_expr(target, row, ctx, cancel, memo.as_deref_mut())?;
5646                self.resolve_correlated_in_expr(index, row, ctx, cancel, memo.as_deref_mut())?;
5647            }
5648            Expr::AnyAll { expr, array, .. } => {
5649                self.resolve_correlated_in_expr(expr, row, ctx, cancel, memo.as_deref_mut())?;
5650                self.resolve_correlated_in_expr(array, row, ctx, cancel, memo.as_deref_mut())?;
5651            }
5652        }
5653        Ok(())
5654    }
5655
5656    fn subquery_replacement(
5657        &self,
5658        e: &Expr,
5659        cancel: CancelToken<'_>,
5660    ) -> Result<Option<Expr>, EngineError> {
5661        match e {
5662            Expr::ScalarSubquery(inner) => {
5663                let mut s = (**inner).clone();
5664                // Recurse into the inner SELECT first so nested
5665                // subqueries materialise bottom-up.
5666                self.resolve_select_subqueries(&mut s, cancel)?;
5667                let r = match self.exec_bare_select_cancel(&s, cancel) {
5668                    Ok(r) => r,
5669                    Err(e) if is_correlation_error(&e) => return Ok(None),
5670                    Err(e) => return Err(e),
5671                };
5672                let QueryResult::Rows { rows, .. } = r else {
5673                    return Err(EngineError::Unsupported(
5674                        "scalar subquery: inner statement did not return rows".into(),
5675                    ));
5676                };
5677                let value = match rows.as_slice() {
5678                    [] => Value::Null,
5679                    [row] => row.values.first().cloned().unwrap_or(Value::Null),
5680                    _ => {
5681                        return Err(EngineError::Unsupported(alloc::format!(
5682                            "scalar subquery returned {} rows; expected 0 or 1",
5683                            rows.len()
5684                        )));
5685                    }
5686                };
5687                Ok(Some(value_to_literal_expr(value)?))
5688            }
5689            Expr::Exists { subquery, negated } => {
5690                let mut s = (**subquery).clone();
5691                self.resolve_select_subqueries(&mut s, cancel)?;
5692                let r = match self.exec_bare_select_cancel(&s, cancel) {
5693                    Ok(r) => r,
5694                    Err(e) if is_correlation_error(&e) => return Ok(None),
5695                    Err(e) => return Err(e),
5696                };
5697                let exists = match r {
5698                    QueryResult::Rows { rows, .. } => !rows.is_empty(),
5699                    QueryResult::CommandOk { .. } => false,
5700                };
5701                let bit = if *negated { !exists } else { exists };
5702                Ok(Some(Expr::Literal(Literal::Bool(bit))))
5703            }
5704            Expr::InSubquery {
5705                expr,
5706                subquery,
5707                negated,
5708            } => {
5709                let mut s = (**subquery).clone();
5710                self.resolve_select_subqueries(&mut s, cancel)?;
5711                let r = match self.exec_bare_select_cancel(&s, cancel) {
5712                    Ok(r) => r,
5713                    Err(e) if is_correlation_error(&e) => return Ok(None),
5714                    Err(e) => return Err(e),
5715                };
5716                let QueryResult::Rows { columns, rows, .. } = r else {
5717                    return Err(EngineError::Unsupported(
5718                        "IN-subquery: inner statement did not return rows".into(),
5719                    ));
5720                };
5721                if columns.len() != 1 {
5722                    return Err(EngineError::Unsupported(alloc::format!(
5723                        "IN-subquery must project exactly one column; got {}",
5724                        columns.len()
5725                    )));
5726                }
5727                // Build the same OR-Eq chain the parse-time literal-list
5728                // path constructs, with each value lifted into a Literal.
5729                let mut acc: Option<Expr> = None;
5730                for row in rows {
5731                    let v = row.values.into_iter().next().unwrap_or(Value::Null);
5732                    let lit = value_to_literal_expr(v)?;
5733                    let cmp = Expr::Binary {
5734                        lhs: expr.clone(),
5735                        op: BinOp::Eq,
5736                        rhs: Box::new(lit),
5737                    };
5738                    acc = Some(match acc {
5739                        None => cmp,
5740                        Some(prev) => Expr::Binary {
5741                            lhs: Box::new(prev),
5742                            op: BinOp::Or,
5743                            rhs: Box::new(cmp),
5744                        },
5745                    });
5746                }
5747                let combined = acc.unwrap_or(Expr::Literal(Literal::Bool(false)));
5748                let final_expr = if *negated {
5749                    Expr::Unary {
5750                        op: UnOp::Not,
5751                        expr: Box::new(combined),
5752                    }
5753                } else {
5754                    combined
5755                };
5756                Ok(Some(final_expr))
5757            }
5758            _ => Ok(None),
5759        }
5760    }
5761}
5762
5763// ---- v4.12 window-function helpers ----
5764// The (partition-key, order-key, original-index) tuple shape used
5765// across these helpers is intrinsic to the planner. Factoring it
5766// into a typedef adds indirection without making the code clearer,
5767// so several lints are allowed inline on the affected functions
5768// rather than module-wide.
5769
5770/// v4.22: cheap structural scan for `FROM <name>` (qualified or
5771/// not) inside a SELECT — used to verify the anchor of a WITH
5772/// RECURSIVE CTE doesn't recurse into itself. Conservative: walks
5773/// FROM joins, subqueries, and unions.
5774fn select_refers_to(stmt: &SelectStatement, target: &str) -> bool {
5775    if let Some(from) = &stmt.from
5776        && from_refers_to(from, target)
5777    {
5778        return true;
5779    }
5780    for (_, peer) in &stmt.unions {
5781        if select_refers_to(peer, target) {
5782            return true;
5783        }
5784    }
5785    for item in &stmt.items {
5786        if let SelectItem::Expr { expr, .. } = item
5787            && expr_refers_to(expr, target)
5788        {
5789            return true;
5790        }
5791    }
5792    if let Some(w) = &stmt.where_
5793        && expr_refers_to(w, target)
5794    {
5795        return true;
5796    }
5797    false
5798}
5799
5800fn from_refers_to(from: &FromClause, target: &str) -> bool {
5801    if from.primary.name.eq_ignore_ascii_case(target) {
5802        return true;
5803    }
5804    from.joins
5805        .iter()
5806        .any(|j| j.table.name.eq_ignore_ascii_case(target))
5807}
5808
5809fn expr_refers_to(e: &Expr, target: &str) -> bool {
5810    match e {
5811        Expr::ScalarSubquery(s) => select_refers_to(s, target),
5812        Expr::Exists { subquery, .. } | Expr::InSubquery { subquery, .. } => {
5813            select_refers_to(subquery, target)
5814        }
5815        Expr::Binary { lhs, rhs, .. } => expr_refers_to(lhs, target) || expr_refers_to(rhs, target),
5816        Expr::Unary { expr, .. } | Expr::Cast { expr, .. } | Expr::IsNull { expr, .. } => {
5817            expr_refers_to(expr, target)
5818        }
5819        Expr::Like { expr, pattern, .. } => {
5820            expr_refers_to(expr, target) || expr_refers_to(pattern, target)
5821        }
5822        Expr::FunctionCall { args, .. } => args.iter().any(|a| expr_refers_to(a, target)),
5823        Expr::Extract { source, .. } => expr_refers_to(source, target),
5824        Expr::WindowFunction {
5825            args,
5826            partition_by,
5827            order_by,
5828            ..
5829        } => {
5830            args.iter().any(|a| expr_refers_to(a, target))
5831                || partition_by.iter().any(|p| expr_refers_to(p, target))
5832                || order_by.iter().any(|(o, _)| expr_refers_to(o, target))
5833        }
5834        Expr::Literal(_) | Expr::Placeholder(_) | Expr::Column(_) => false,
5835        Expr::Array(items) => items.iter().any(|e| expr_refers_to(e, target)),
5836        Expr::ArraySubscript { target: t, index } => {
5837            expr_refers_to(t, target) || expr_refers_to(index, target)
5838        }
5839        Expr::AnyAll { expr, array, .. } => {
5840            expr_refers_to(expr, target) || expr_refers_to(array, target)
5841        }
5842    }
5843}
5844
5845/// v4.22: pick more specific column types from observed rows when
5846/// the projection builder defaulted to Text (the v1.x behavior for
5847/// non-column expressions). Lets `WITH t(n) AS (SELECT 1 ...)`
5848/// land an Int column in the CTE storage table rather than failing
5849/// the insert with "expected TEXT, got INT".
5850fn infer_column_types(columns: &[ColumnSchema], rows: &[Row]) -> Vec<ColumnSchema> {
5851    let mut out = columns.to_vec();
5852    for (col_idx, col) in out.iter_mut().enumerate() {
5853        if col.ty != DataType::Text {
5854            continue;
5855        }
5856        let mut inferred: Option<DataType> = None;
5857        let mut all_null = true;
5858        for row in rows {
5859            let Some(v) = row.values.get(col_idx) else {
5860                continue;
5861            };
5862            let ty = match v {
5863                Value::Null => continue,
5864                Value::SmallInt(_) => DataType::SmallInt,
5865                Value::Int(_) => DataType::Int,
5866                Value::BigInt(_) => DataType::BigInt,
5867                Value::Float(_) => DataType::Float,
5868                Value::Bool(_) => DataType::Bool,
5869                Value::Vector(_) => DataType::Vector {
5870                    dim: 0,
5871                    encoding: VecEncoding::F32,
5872                },
5873                _ => DataType::Text,
5874            };
5875            all_null = false;
5876            inferred = Some(match inferred {
5877                None => ty,
5878                Some(prev) if prev == ty => prev,
5879                Some(_) => DataType::Text,
5880            });
5881        }
5882        if let Some(t) = inferred {
5883            col.ty = t;
5884            col.nullable = true;
5885        } else if all_null {
5886            col.nullable = true;
5887        }
5888    }
5889    out
5890}
5891
5892/// v4.26: render a human-readable plan tree for `EXPLAIN <select>`.
5893/// Lines are pushed into `out`; `depth` controls indentation. We
5894/// describe the rewritten SELECT — what the executor *would* do —
5895/// using the engine handle to spot indexed lookups and table shapes.
5896#[allow(clippy::too_many_lines, clippy::format_push_string)]
5897/// v6.2.4 — Walk every line of the rendered plan tree and append
5898/// per-operator stats. Lines that name a known operator get
5899/// `(rows=N)` (`actual_rows` of the top-level operator equals the
5900/// final result row count; scans report their catalog row count
5901/// as the rows-considered metric). Other lines — Filter / Join /
5902/// GroupBy / OrderBy etc. — are marked `(—)` so the surface is
5903/// complete-by-construction; v6.2.5 fills these in via inline
5904/// executor counters.
5905/// v6.8.3 — surface "CREATE INDEX …" suggestions for every
5906/// `(table, column)` pair the query touches via WHERE / JOIN
5907/// that doesn't already have an index on the owning table.
5908/// Walks the SELECT's FROM clauses + WHERE expression tree;
5909/// returns one line per missing index. Deterministic order:
5910/// FROM-clause iteration order, then column-reference walk
5911/// order inside each WHERE. Each suggestion is a copy-pastable
5912/// DDL string.
5913fn build_index_suggestions(stmt: &SelectStatement, engine: &Engine) -> Vec<String> {
5914    use alloc::collections::BTreeSet;
5915    let mut seen: BTreeSet<(String, String)> = BTreeSet::new();
5916    let mut out: Vec<String> = Vec::new();
5917    let cat = engine.active_catalog();
5918    // Build a (table, qualifier-or-alias) list from the FROM clause
5919    // so unqualified column refs in WHERE resolve to the correct
5920    // table.
5921    let Some(from) = &stmt.from else {
5922        return out;
5923    };
5924    let mut tables: Vec<String> = Vec::new();
5925    tables.push(from.primary.name.clone());
5926    for j in &from.joins {
5927        tables.push(j.table.name.clone());
5928    }
5929    // Collect column refs from the WHERE expression. JOIN ON
5930    // predicates also feed in.
5931    let mut col_refs: Vec<spg_sql::ast::ColumnName> = Vec::new();
5932    if let Some(w) = &stmt.where_ {
5933        collect_column_refs(w, &mut col_refs);
5934    }
5935    for j in &from.joins {
5936        if let Some(on) = &j.on {
5937            collect_column_refs(on, &mut col_refs);
5938        }
5939    }
5940    for cn in &col_refs {
5941        // Resolve owner table: explicit qualifier first, else
5942        // first table in FROM that has a column of this name.
5943        let owner: Option<String> = if let Some(q) = &cn.qualifier {
5944            tables.iter().find(|t| t == &q).cloned()
5945        } else {
5946            tables.iter().find_map(|t| {
5947                cat.get(t).and_then(|tbl| {
5948                    if tbl.schema().column_position(&cn.name).is_some() {
5949                        Some(t.clone())
5950                    } else {
5951                        None
5952                    }
5953                })
5954            })
5955        };
5956        let Some(owner) = owner else {
5957            continue;
5958        };
5959        let Some(tbl) = cat.get(&owner) else {
5960            continue;
5961        };
5962        let Some(col_pos) = tbl.schema().column_position(&cn.name) else {
5963            continue;
5964        };
5965        // Skip if any BTree index already covers this column as
5966        // its key.
5967        let already_indexed = tbl.indices().iter().any(|i| {
5968            matches!(i.kind, spg_storage::IndexKind::BTree(_))
5969                && i.column_position == col_pos
5970                && i.expression.is_none()
5971                && i.partial_predicate.is_none()
5972        });
5973        if already_indexed {
5974            continue;
5975        }
5976        if seen.insert((owner.clone(), cn.name.clone())) {
5977            out.push(alloc::format!(
5978                "SUGGEST: CREATE INDEX ix_{}_{} ON {} ({})",
5979                owner,
5980                cn.name,
5981                owner,
5982                cn.name
5983            ));
5984        }
5985    }
5986    out
5987}
5988
5989/// Walks an `Expr` and pushes every `ColumnName` it references.
5990/// Order is depth-first, left-to-right.
5991fn collect_column_refs(expr: &Expr, out: &mut Vec<spg_sql::ast::ColumnName>) {
5992    match expr {
5993        Expr::Column(cn) => out.push(cn.clone()),
5994        Expr::FunctionCall { args, .. } => {
5995            for a in args {
5996                collect_column_refs(a, out);
5997            }
5998        }
5999        Expr::Binary { lhs, rhs, .. } => {
6000            collect_column_refs(lhs, out);
6001            collect_column_refs(rhs, out);
6002        }
6003        Expr::Unary { expr: e, .. } => collect_column_refs(e, out),
6004        _ => {}
6005    }
6006}
6007
6008fn annotate_explain_lines(lines: &mut [String], total_rows: usize, engine: &Engine) {
6009    let catalog = engine.active_catalog();
6010    let cold_ids = catalog.cold_segment_ids_global();
6011    let any_cold = !cold_ids.is_empty();
6012    let cold_ids_repr = if any_cold {
6013        let mut s = alloc::string::String::from("[");
6014        for (i, id) in cold_ids.iter().enumerate() {
6015            if i > 0 {
6016                s.push(',');
6017            }
6018            s.push_str(&alloc::format!("{id}"));
6019        }
6020        s.push(']');
6021        s
6022    } else {
6023        alloc::string::String::new()
6024    };
6025    for (idx, line) in lines.iter_mut().enumerate() {
6026        let trimmed = line.trim_start();
6027        let is_top_level = idx == 0;
6028        if is_top_level {
6029            line.push_str(&alloc::format!(" (rows={total_rows})"));
6030            continue;
6031        }
6032        if let Some(rest) = trimmed.strip_prefix("From: ") {
6033            let (name, scan_kind) = match rest.split_once(" [") {
6034                Some((n, k)) => (n.trim(), k.trim_end_matches(']')),
6035                None => (rest.trim(), ""),
6036            };
6037            let bare = name.split_whitespace().next().unwrap_or(name);
6038            let hot = catalog.get(bare).map(|t| t.rows().len());
6039            // v6.2.7 — `cold_segments=[id0,id1,…]` enumerates every
6040            // cold-tier segment the scan COULD have walked. v6.2.x
6041            // can tighten to per-table by walking the table's
6042            // BTree-index cold locators.
6043            let annot = match (hot, scan_kind) {
6044                (Some(h), "full scan") => {
6045                    let mut s = alloc::format!(" (hot_rows={h}");
6046                    if any_cold {
6047                        s.push_str(&alloc::format!(
6048                            ", cold_tier=present, cold_segments={cold_ids_repr}"
6049                        ));
6050                    }
6051                    s.push(')');
6052                    s
6053                }
6054                (Some(h), "index seek") => {
6055                    let mut s = alloc::format!(" (hot_rows≤{h}");
6056                    if any_cold {
6057                        s.push_str(&alloc::format!(
6058                            ", cold_tier=present, cold_segments={cold_ids_repr}"
6059                        ));
6060                    }
6061                    s.push(')');
6062                    s
6063                }
6064                _ => " (rows=—)".to_string(),
6065            };
6066            line.push_str(&annot);
6067            continue;
6068        }
6069        // Filter / GroupBy / Having / OrderBy / Limit / Join etc.
6070        line.push_str(" (rows=—)");
6071    }
6072}
6073
6074fn explain_select(stmt: &SelectStatement, engine: &Engine, depth: usize, out: &mut Vec<String>) {
6075    let pad = "  ".repeat(depth);
6076    // 1) Top-level operator label.
6077    let top = if !stmt.ctes.is_empty() {
6078        if stmt.ctes.iter().any(|c| c.recursive) {
6079            "CTEScan (WITH RECURSIVE)"
6080        } else {
6081            "CTEScan (WITH)"
6082        }
6083    } else if !stmt.unions.is_empty() {
6084        "UnionScan"
6085    } else if select_has_window(stmt) {
6086        "WindowAgg"
6087    } else if aggregate::uses_aggregate(stmt) {
6088        "Aggregate"
6089    } else if stmt.distinct {
6090        "Distinct"
6091    } else if stmt.from.is_some() {
6092        "TableScan"
6093    } else {
6094        "Result"
6095    };
6096    out.push(alloc::format!("{pad}{top}"));
6097    let child = "  ".repeat(depth + 1);
6098    // 2) CTE bodies.
6099    for cte in &stmt.ctes {
6100        let head = if cte.recursive {
6101            alloc::format!("{child}CTE (recursive): {}", cte.name)
6102        } else {
6103            alloc::format!("{child}CTE: {}", cte.name)
6104        };
6105        out.push(head);
6106        explain_select(&cte.body, engine, depth + 2, out);
6107    }
6108    // 3) FROM details — primary table + joins, index hits.
6109    if let Some(from) = &stmt.from {
6110        let mut tag = alloc::format!("{child}From: {}", from.primary.name);
6111        if let Some(alias) = &from.primary.alias {
6112            tag.push_str(&alloc::format!(" AS {alias}"));
6113        }
6114        // Try to detect an index-seek opportunity on WHERE against
6115        // the primary table — same heuristic the executor uses.
6116        if let Some(w) = &stmt.where_
6117            && let Some(table) = engine.active_catalog().get(&from.primary.name)
6118        {
6119            let alias = from.primary.alias.as_deref().unwrap_or(&from.primary.name);
6120            let cols = &table.schema().columns;
6121            if try_index_seek(w, cols, engine.active_catalog(), table, alias).is_some() {
6122                tag.push_str(" [index seek]");
6123            } else {
6124                tag.push_str(" [full scan]");
6125            }
6126        } else {
6127            tag.push_str(" [full scan]");
6128        }
6129        out.push(tag);
6130        for j in &from.joins {
6131            let kind = match j.kind {
6132                spg_sql::ast::JoinKind::Inner => "INNER JOIN",
6133                spg_sql::ast::JoinKind::Left => "LEFT JOIN",
6134                spg_sql::ast::JoinKind::Cross => "CROSS JOIN",
6135            };
6136            let mut s = alloc::format!("{child}{kind}: {}", j.table.name);
6137            if let Some(alias) = &j.table.alias {
6138                s.push_str(&alloc::format!(" AS {alias}"));
6139            }
6140            if j.on.is_some() {
6141                s.push_str(" (ON …)");
6142            }
6143            out.push(s);
6144        }
6145    }
6146    // 4) WHERE / GROUP BY / HAVING / ORDER BY / LIMIT / OFFSET.
6147    if let Some(w) = &stmt.where_ {
6148        let mut s = alloc::format!("{child}Filter: {w}");
6149        if expr_has_subquery(w) {
6150            s.push_str(" [subquery]");
6151        }
6152        out.push(s);
6153    }
6154    if let Some(gs) = &stmt.group_by {
6155        let mut parts = Vec::new();
6156        for g in gs {
6157            parts.push(alloc::format!("{g}"));
6158        }
6159        out.push(alloc::format!("{child}GroupBy: {}", parts.join(", ")));
6160    }
6161    if let Some(h) = &stmt.having {
6162        out.push(alloc::format!("{child}Having: {h}"));
6163    }
6164    for o in &stmt.order_by {
6165        let dir = if o.desc { "DESC" } else { "ASC" };
6166        out.push(alloc::format!("{child}OrderBy: {} {dir}", o.expr));
6167    }
6168    if let Some(lim) = stmt.limit {
6169        out.push(alloc::format!("{child}Limit: {lim}"));
6170    }
6171    if let Some(off) = stmt.offset {
6172        out.push(alloc::format!("{child}Offset: {off}"));
6173    }
6174    // 5) Projection — collapse Wildcard or render N items.
6175    if stmt
6176        .items
6177        .iter()
6178        .any(|it| matches!(it, SelectItem::Wildcard))
6179    {
6180        out.push(alloc::format!("{child}Project: *"));
6181    } else {
6182        out.push(alloc::format!(
6183            "{child}Project: {} item(s)",
6184            stmt.items.len()
6185        ));
6186    }
6187    // 6) Recurse into UNION peers.
6188    for (kind, peer) in &stmt.unions {
6189        let label = match kind {
6190            UnionKind::All => "UNION ALL",
6191            UnionKind::Distinct => "UNION",
6192        };
6193        out.push(alloc::format!("{child}{label}"));
6194        explain_select(peer, engine, depth + 2, out);
6195    }
6196}
6197
6198/// v4.23: recognise the engine errors that indicate the inner
6199/// SELECT couldn't be evaluated in isolation because it references
6200/// an outer column — used by `subquery_replacement` to skip
6201/// materialisation and let row-eval handle it instead.
6202fn is_correlation_error(e: &EngineError) -> bool {
6203    matches!(
6204        e,
6205        EngineError::Eval(
6206            eval::EvalError::ColumnNotFound { .. } | eval::EvalError::UnknownQualifier { .. }
6207        )
6208    )
6209}
6210
6211/// v4.23: walk every Expr in `stmt` and replace each Column ref
6212/// that targets the outer scope (qualifier matches the outer
6213/// table alias) with a Literal carrying the outer row's value.
6214/// Conservative: only qualified refs are substituted, so the user
6215/// must write `outer_alias.col` to reference an outer column. This
6216/// matches PG's lexical scoping for correlated subqueries and
6217/// avoids accidentally rebinding inner columns of the same name.
6218fn substitute_outer_columns(stmt: &mut SelectStatement, row: &Row, ctx: &EvalContext<'_>) {
6219    let Some(outer_alias) = ctx.table_alias else {
6220        return;
6221    };
6222    substitute_in_select(stmt, row, ctx, outer_alias);
6223}
6224
6225fn substitute_in_select(
6226    stmt: &mut SelectStatement,
6227    row: &Row,
6228    ctx: &EvalContext<'_>,
6229    outer_alias: &str,
6230) {
6231    for item in &mut stmt.items {
6232        if let SelectItem::Expr { expr, .. } = item {
6233            substitute_in_expr(expr, row, ctx, outer_alias);
6234        }
6235    }
6236    if let Some(w) = &mut stmt.where_ {
6237        substitute_in_expr(w, row, ctx, outer_alias);
6238    }
6239    if let Some(gs) = &mut stmt.group_by {
6240        for g in gs {
6241            substitute_in_expr(g, row, ctx, outer_alias);
6242        }
6243    }
6244    if let Some(h) = &mut stmt.having {
6245        substitute_in_expr(h, row, ctx, outer_alias);
6246    }
6247    for o in &mut stmt.order_by {
6248        substitute_in_expr(&mut o.expr, row, ctx, outer_alias);
6249    }
6250    for (_, peer) in &mut stmt.unions {
6251        substitute_in_select(peer, row, ctx, outer_alias);
6252    }
6253}
6254
6255fn substitute_in_expr(e: &mut Expr, row: &Row, ctx: &EvalContext<'_>, outer_alias: &str) {
6256    if let Expr::Column(c) = e
6257        && let Some(qual) = &c.qualifier
6258        && qual.eq_ignore_ascii_case(outer_alias)
6259    {
6260        // Look up the column's index in the outer schema.
6261        if let Some(idx) = ctx
6262            .columns
6263            .iter()
6264            .position(|sc| sc.name.eq_ignore_ascii_case(&c.name))
6265        {
6266            let v = row.values.get(idx).cloned().unwrap_or(Value::Null);
6267            if let Ok(lit) = value_to_literal_expr(v) {
6268                *e = lit;
6269                return;
6270            }
6271        }
6272    }
6273    match e {
6274        Expr::Binary { lhs, rhs, .. } => {
6275            substitute_in_expr(lhs, row, ctx, outer_alias);
6276            substitute_in_expr(rhs, row, ctx, outer_alias);
6277        }
6278        Expr::Unary { expr, .. } | Expr::Cast { expr, .. } | Expr::IsNull { expr, .. } => {
6279            substitute_in_expr(expr, row, ctx, outer_alias);
6280        }
6281        Expr::Like { expr, pattern, .. } => {
6282            substitute_in_expr(expr, row, ctx, outer_alias);
6283            substitute_in_expr(pattern, row, ctx, outer_alias);
6284        }
6285        Expr::FunctionCall { args, .. } => {
6286            for a in args {
6287                substitute_in_expr(a, row, ctx, outer_alias);
6288            }
6289        }
6290        Expr::Extract { source, .. } => substitute_in_expr(source, row, ctx, outer_alias),
6291        Expr::WindowFunction {
6292            args,
6293            partition_by,
6294            order_by,
6295            ..
6296        } => {
6297            for a in args {
6298                substitute_in_expr(a, row, ctx, outer_alias);
6299            }
6300            for p in partition_by {
6301                substitute_in_expr(p, row, ctx, outer_alias);
6302            }
6303            for (o, _) in order_by {
6304                substitute_in_expr(o, row, ctx, outer_alias);
6305            }
6306        }
6307        Expr::ScalarSubquery(s) => substitute_in_select(s, row, ctx, outer_alias),
6308        Expr::Exists { subquery, .. } | Expr::InSubquery { subquery, .. } => {
6309            substitute_in_select(subquery, row, ctx, outer_alias);
6310        }
6311        Expr::Literal(_) | Expr::Placeholder(_) | Expr::Column(_) => {}
6312        Expr::Array(items) => {
6313            for elem in items {
6314                substitute_in_expr(elem, row, ctx, outer_alias);
6315            }
6316        }
6317        Expr::ArraySubscript { target, index } => {
6318            substitute_in_expr(target, row, ctx, outer_alias);
6319            substitute_in_expr(index, row, ctx, outer_alias);
6320        }
6321        Expr::AnyAll { expr, array, .. } => {
6322            substitute_in_expr(expr, row, ctx, outer_alias);
6323            substitute_in_expr(array, row, ctx, outer_alias);
6324        }
6325    }
6326}
6327
6328/// v4.22: encode a Row to a comparable byte key for UNION-DISTINCT
6329/// dedup inside the recursive iteration. Crude but deterministic
6330/// — Debug prints embed type discriminants so NULL ≠ "" ≠ 0.
6331fn encode_row_key(row: &Row) -> Vec<u8> {
6332    let mut out = Vec::new();
6333    for v in &row.values {
6334        let s = alloc::format!("{v:?}|");
6335        out.extend_from_slice(s.as_bytes());
6336    }
6337    out
6338}
6339
6340fn select_has_window(stmt: &SelectStatement) -> bool {
6341    for item in &stmt.items {
6342        if let SelectItem::Expr { expr, .. } = item
6343            && expr_has_window(expr)
6344        {
6345            return true;
6346        }
6347    }
6348    false
6349}
6350
6351fn expr_has_window(e: &Expr) -> bool {
6352    match e {
6353        Expr::WindowFunction { .. } => true,
6354        Expr::Binary { lhs, rhs, .. } => expr_has_window(lhs) || expr_has_window(rhs),
6355        Expr::Unary { expr, .. } | Expr::Cast { expr, .. } | Expr::IsNull { expr, .. } => {
6356            expr_has_window(expr)
6357        }
6358        Expr::FunctionCall { args, .. } => args.iter().any(expr_has_window),
6359        Expr::Like { expr, pattern, .. } => expr_has_window(expr) || expr_has_window(pattern),
6360        Expr::Extract { source, .. } => expr_has_window(source),
6361        Expr::ScalarSubquery(_)
6362        | Expr::Exists { .. }
6363        | Expr::InSubquery { .. }
6364        | Expr::Literal(_)
6365        | Expr::Placeholder(_)
6366        | Expr::Column(_) => false,
6367        Expr::Array(items) => items.iter().any(expr_has_window),
6368        Expr::ArraySubscript { target, index } => expr_has_window(target) || expr_has_window(index),
6369        Expr::AnyAll { expr, array, .. } => expr_has_window(expr) || expr_has_window(array),
6370    }
6371}
6372
6373fn collect_window_nodes(e: &Expr, out: &mut Vec<Expr>) {
6374    if let Expr::WindowFunction { .. } = e {
6375        // Deduplicate by structural equality on the expression
6376        // (cheap because window args + partition + order are
6377        // small). Without dedup we'd recompute identical windows
6378        // once per occurrence in the projection.
6379        if !out.iter().any(|x| x == e) {
6380            out.push(e.clone());
6381        }
6382        return;
6383    }
6384    match e {
6385        // Already handled by the early-return at the top.
6386        Expr::WindowFunction { .. } => unreachable!(),
6387        Expr::Binary { lhs, rhs, .. } => {
6388            collect_window_nodes(lhs, out);
6389            collect_window_nodes(rhs, out);
6390        }
6391        Expr::Unary { expr, .. } | Expr::Cast { expr, .. } | Expr::IsNull { expr, .. } => {
6392            collect_window_nodes(expr, out);
6393        }
6394        Expr::FunctionCall { args, .. } => {
6395            for a in args {
6396                collect_window_nodes(a, out);
6397            }
6398        }
6399        Expr::Like { expr, pattern, .. } => {
6400            collect_window_nodes(expr, out);
6401            collect_window_nodes(pattern, out);
6402        }
6403        Expr::Extract { source, .. } => collect_window_nodes(source, out),
6404        _ => {}
6405    }
6406}
6407
6408fn rewrite_window_to_columns(e: &mut Expr, window_nodes: &[Expr]) {
6409    if let Expr::WindowFunction { .. } = e
6410        && let Some(idx) = window_nodes.iter().position(|w| w == e)
6411    {
6412        *e = Expr::Column(spg_sql::ast::ColumnName {
6413            qualifier: None,
6414            name: alloc::format!("__win_{idx}"),
6415        });
6416        return;
6417    }
6418    match e {
6419        Expr::Binary { lhs, rhs, .. } => {
6420            rewrite_window_to_columns(lhs, window_nodes);
6421            rewrite_window_to_columns(rhs, window_nodes);
6422        }
6423        Expr::Unary { expr, .. } | Expr::Cast { expr, .. } | Expr::IsNull { expr, .. } => {
6424            rewrite_window_to_columns(expr, window_nodes);
6425        }
6426        Expr::FunctionCall { args, .. } => {
6427            for a in args {
6428                rewrite_window_to_columns(a, window_nodes);
6429            }
6430        }
6431        Expr::Like { expr, pattern, .. } => {
6432            rewrite_window_to_columns(expr, window_nodes);
6433            rewrite_window_to_columns(pattern, window_nodes);
6434        }
6435        Expr::Extract { source, .. } => rewrite_window_to_columns(source, window_nodes),
6436        _ => {}
6437    }
6438}
6439
6440/// Total order over partition-key tuples. NULL sorts as the
6441/// lowest value (matches the `<` partial order's NULL-last
6442/// behaviour with `INFINITY` flipped).
6443fn partition_key_cmp(a: &[Value], b: &[Value]) -> core::cmp::Ordering {
6444    for (x, y) in a.iter().zip(b.iter()) {
6445        let c = value_cmp(x, y);
6446        if c != core::cmp::Ordering::Equal {
6447            return c;
6448        }
6449    }
6450    a.len().cmp(&b.len())
6451}
6452
6453fn order_key_cmp(a: &[(Value, bool)], b: &[(Value, bool)]) -> core::cmp::Ordering {
6454    for ((va, desc), (vb, _)) in a.iter().zip(b.iter()) {
6455        let c = value_cmp(va, vb);
6456        let c = if *desc { c.reverse() } else { c };
6457        if c != core::cmp::Ordering::Equal {
6458            return c;
6459        }
6460    }
6461    a.len().cmp(&b.len())
6462}
6463
6464#[allow(clippy::match_same_arms)] // explicit arms per type document the supported pairs
6465fn value_cmp(a: &Value, b: &Value) -> core::cmp::Ordering {
6466    use core::cmp::Ordering;
6467    match (a, b) {
6468        (Value::Null, Value::Null) => Ordering::Equal,
6469        (Value::Null, _) => Ordering::Less,
6470        (_, Value::Null) => Ordering::Greater,
6471        (Value::Int(x), Value::Int(y)) => x.cmp(y),
6472        (Value::BigInt(x), Value::BigInt(y)) => x.cmp(y),
6473        (Value::SmallInt(x), Value::SmallInt(y)) => x.cmp(y),
6474        (Value::Text(x), Value::Text(y)) => x.cmp(y),
6475        (Value::Bool(x), Value::Bool(y)) => x.cmp(y),
6476        (Value::Float(x), Value::Float(y)) => x.partial_cmp(y).unwrap_or(Ordering::Equal),
6477        (Value::Date(x), Value::Date(y)) => x.cmp(y),
6478        (Value::Timestamp(x), Value::Timestamp(y)) => x.cmp(y),
6479        // Cross-type compare: fall back to the debug rendering —
6480        // same-partition is the goal, exact order is irrelevant.
6481        _ => alloc::format!("{a:?}").cmp(&alloc::format!("{b:?}")),
6482    }
6483}
6484
6485/// Compute the window function's per-row output for one partition.
6486/// `slice` has (partition key, order key, original-row-index)
6487/// tuples already sorted by order key. `filtered_rows` is the
6488/// full row list indexed by original-row-index. `out_vals` is
6489/// the destination, also indexed by original-row-index.
6490#[allow(
6491    clippy::too_many_arguments,
6492    clippy::cast_possible_truncation,
6493    clippy::cast_possible_wrap,
6494    clippy::cast_precision_loss,
6495    clippy::cast_sign_loss,
6496    clippy::doc_markdown,
6497    clippy::too_many_lines,
6498    clippy::type_complexity,
6499    clippy::match_same_arms
6500)]
6501fn compute_window_partition(
6502    name: &str,
6503    args: &[Expr],
6504    ordered: bool,
6505    frame: Option<&WindowFrame>,
6506    null_treatment: spg_sql::ast::NullTreatment,
6507    slice: &[(Vec<Value>, Vec<(Value, bool)>, usize)],
6508    filtered_rows: &[&Row],
6509    ctx: &EvalContext<'_>,
6510    out_vals: &mut [Value],
6511) -> Result<(), EngineError> {
6512    let ignore_nulls = matches!(null_treatment, spg_sql::ast::NullTreatment::Ignore);
6513    let lower = name.to_ascii_lowercase();
6514    match lower.as_str() {
6515        "row_number" => {
6516            for (rank, (_, _, idx)) in slice.iter().enumerate() {
6517                out_vals[*idx] = Value::BigInt((rank + 1) as i64);
6518            }
6519            Ok(())
6520        }
6521        "rank" => {
6522            let mut prev_key: Option<&[(Value, bool)]> = None;
6523            let mut current_rank: i64 = 1;
6524            for (i, (_, okey, idx)) in slice.iter().enumerate() {
6525                if let Some(p) = prev_key
6526                    && order_key_cmp(p, okey) != core::cmp::Ordering::Equal
6527                {
6528                    current_rank = (i + 1) as i64;
6529                }
6530                if prev_key.is_none() {
6531                    current_rank = 1;
6532                }
6533                out_vals[*idx] = Value::BigInt(current_rank);
6534                prev_key = Some(okey.as_slice());
6535            }
6536            Ok(())
6537        }
6538        "dense_rank" => {
6539            let mut prev_key: Option<&[(Value, bool)]> = None;
6540            let mut current_rank: i64 = 0;
6541            for (_, okey, idx) in slice {
6542                if prev_key.is_none_or(|p| order_key_cmp(p, okey) != core::cmp::Ordering::Equal) {
6543                    current_rank += 1;
6544                }
6545                out_vals[*idx] = Value::BigInt(current_rank);
6546                prev_key = Some(okey.as_slice());
6547            }
6548            Ok(())
6549        }
6550        "sum" | "avg" | "min" | "max" | "count" | "count_star" => {
6551            // Pre-evaluate the function arg per row in the slice
6552            // (count_star has no arg).
6553            let arg_values: Vec<Value> = if lower == "count_star" || args.is_empty() {
6554                slice.iter().map(|_| Value::Null).collect()
6555            } else {
6556                slice
6557                    .iter()
6558                    .map(|(_, _, idx)| eval::eval_expr(&args[0], filtered_rows[*idx], ctx))
6559                    .collect::<Result<_, _>>()
6560                    .map_err(EngineError::Eval)?
6561            };
6562            // v4.20: pick the effective frame. Explicit frame
6563            // overrides the implicit default (running for ordered,
6564            // whole-partition for unordered).
6565            let eff = effective_frame(frame, ordered)?;
6566            #[allow(clippy::needless_range_loop)]
6567            for i in 0..slice.len() {
6568                let (lo, hi) = frame_bounds_for_row(&eff, i, slice);
6569                let mut sum: f64 = 0.0;
6570                let mut count: i64 = 0;
6571                let mut min_v: Option<f64> = None;
6572                let mut max_v: Option<f64> = None;
6573                let mut row_count: i64 = 0;
6574                if lo <= hi {
6575                    for j in lo..=hi {
6576                        let v = &arg_values[j];
6577                        match lower.as_str() {
6578                            "count_star" => row_count += 1,
6579                            "count" => {
6580                                if !v.is_null() {
6581                                    count += 1;
6582                                }
6583                            }
6584                            _ => {
6585                                if let Some(x) = value_to_f64(v) {
6586                                    sum += x;
6587                                    count += 1;
6588                                    min_v = Some(min_v.map_or(x, |m| m.min(x)));
6589                                    max_v = Some(max_v.map_or(x, |m| m.max(x)));
6590                                }
6591                            }
6592                        }
6593                    }
6594                }
6595                let value = match lower.as_str() {
6596                    "count_star" => Value::BigInt(row_count),
6597                    "count" => Value::BigInt(count),
6598                    "sum" => Value::Float(sum),
6599                    "avg" => {
6600                        if count == 0 {
6601                            Value::Null
6602                        } else {
6603                            Value::Float(sum / count as f64)
6604                        }
6605                    }
6606                    "min" => min_v.map_or(Value::Null, Value::Float),
6607                    "max" => max_v.map_or(Value::Null, Value::Float),
6608                    _ => unreachable!(),
6609                };
6610                let (_, _, idx) = &slice[i];
6611                out_vals[*idx] = value;
6612            }
6613            Ok(())
6614        }
6615        "lag" | "lead" => {
6616            // lag(expr [, offset [, default]])
6617            // lead(expr [, offset [, default]])
6618            if args.is_empty() {
6619                return Err(EngineError::Unsupported(alloc::format!(
6620                    "{lower}() requires at least one argument"
6621                )));
6622            }
6623            let offset: i64 = if args.len() >= 2 {
6624                let v = eval::eval_expr(&args[1], filtered_rows[slice[0].2], ctx)
6625                    .map_err(EngineError::Eval)?;
6626                match v {
6627                    Value::SmallInt(n) => i64::from(n),
6628                    Value::Int(n) => i64::from(n),
6629                    Value::BigInt(n) => n,
6630                    _ => {
6631                        return Err(EngineError::Unsupported(alloc::format!(
6632                            "{lower}() offset must be integer"
6633                        )));
6634                    }
6635                }
6636            } else {
6637                1
6638            };
6639            let default: Value = if args.len() >= 3 {
6640                eval::eval_expr(&args[2], filtered_rows[slice[0].2], ctx)
6641                    .map_err(EngineError::Eval)?
6642            } else {
6643                Value::Null
6644            };
6645            let values: Vec<Value> = slice
6646                .iter()
6647                .map(|(_, _, idx)| eval::eval_expr(&args[0], filtered_rows[*idx], ctx))
6648                .collect::<Result<_, _>>()
6649                .map_err(EngineError::Eval)?;
6650            let n = slice.len();
6651            for (i, (_, _, idx)) in slice.iter().enumerate() {
6652                let signed_offset = if lower == "lag" { -offset } else { offset };
6653                let v = if ignore_nulls {
6654                    // v6.4.2 — IGNORE NULLS: walk in the offset direction
6655                    // skipping NULL values; the `offset`-th non-NULL
6656                    // encountered is the result.
6657                    let step: i64 = if signed_offset >= 0 { 1 } else { -1 };
6658                    let needed: i64 = signed_offset.abs();
6659                    if needed == 0 {
6660                        values[i].clone()
6661                    } else {
6662                        let mut j: i64 = i as i64;
6663                        let mut hits: i64 = 0;
6664                        let mut found: Option<Value> = None;
6665                        loop {
6666                            j += step;
6667                            if j < 0 || j >= n as i64 {
6668                                break;
6669                            }
6670                            #[allow(clippy::cast_sign_loss)]
6671                            let v = &values[j as usize];
6672                            if !v.is_null() {
6673                                hits += 1;
6674                                if hits == needed {
6675                                    found = Some(v.clone());
6676                                    break;
6677                                }
6678                            }
6679                        }
6680                        found.unwrap_or_else(|| default.clone())
6681                    }
6682                } else {
6683                    let target_signed = i64::try_from(i).unwrap_or(i64::MAX) + signed_offset;
6684                    if target_signed < 0 || target_signed >= i64::try_from(n).unwrap_or(i64::MAX) {
6685                        default.clone()
6686                    } else {
6687                        #[allow(clippy::cast_sign_loss)]
6688                        {
6689                            values[target_signed as usize].clone()
6690                        }
6691                    }
6692                };
6693                out_vals[*idx] = v;
6694            }
6695            Ok(())
6696        }
6697        "first_value" | "last_value" | "nth_value" => {
6698            if args.is_empty() {
6699                return Err(EngineError::Unsupported(alloc::format!(
6700                    "{lower}() requires at least one argument"
6701                )));
6702            }
6703            let values: Vec<Value> = slice
6704                .iter()
6705                .map(|(_, _, idx)| eval::eval_expr(&args[0], filtered_rows[*idx], ctx))
6706                .collect::<Result<_, _>>()
6707                .map_err(EngineError::Eval)?;
6708            let nth: usize = if lower == "nth_value" {
6709                if args.len() < 2 {
6710                    return Err(EngineError::Unsupported(
6711                        "nth_value() requires (expr, n)".into(),
6712                    ));
6713                }
6714                let v = eval::eval_expr(&args[1], filtered_rows[slice[0].2], ctx)
6715                    .map_err(EngineError::Eval)?;
6716                let raw = match v {
6717                    Value::SmallInt(n) => i64::from(n),
6718                    Value::Int(n) => i64::from(n),
6719                    Value::BigInt(n) => n,
6720                    _ => {
6721                        return Err(EngineError::Unsupported(
6722                            "nth_value() n must be integer".into(),
6723                        ));
6724                    }
6725                };
6726                if raw < 1 {
6727                    return Err(EngineError::Unsupported(
6728                        "nth_value() n must be >= 1".into(),
6729                    ));
6730                }
6731                #[allow(clippy::cast_sign_loss)]
6732                {
6733                    raw as usize
6734                }
6735            } else {
6736                0
6737            };
6738            let eff = effective_frame(frame, ordered)?;
6739            for i in 0..slice.len() {
6740                let (lo, hi) = frame_bounds_for_row(&eff, i, slice);
6741                let (_, _, idx) = &slice[i];
6742                let v = if lo > hi {
6743                    Value::Null
6744                } else if ignore_nulls && matches!(lower.as_str(), "first_value" | "last_value") {
6745                    // v6.4.2 — IGNORE NULLS: skip NULL cells when
6746                    // selecting the boundary value within the frame.
6747                    if lower == "first_value" {
6748                        (lo..=hi)
6749                            .find_map(|j| {
6750                                let v = &values[j];
6751                                (!v.is_null()).then(|| v.clone())
6752                            })
6753                            .unwrap_or(Value::Null)
6754                    } else {
6755                        (lo..=hi)
6756                            .rev()
6757                            .find_map(|j| {
6758                                let v = &values[j];
6759                                (!v.is_null()).then(|| v.clone())
6760                            })
6761                            .unwrap_or(Value::Null)
6762                    }
6763                } else {
6764                    match lower.as_str() {
6765                        "first_value" => values[lo].clone(),
6766                        "last_value" => values[hi].clone(),
6767                        "nth_value" => {
6768                            let pos = lo + nth - 1;
6769                            if pos > hi {
6770                                Value::Null
6771                            } else {
6772                                values[pos].clone()
6773                            }
6774                        }
6775                        _ => unreachable!(),
6776                    }
6777                };
6778                out_vals[*idx] = v;
6779            }
6780            Ok(())
6781        }
6782        "ntile" => {
6783            if args.is_empty() {
6784                return Err(EngineError::Unsupported(
6785                    "ntile(n) requires an integer argument".into(),
6786                ));
6787            }
6788            let v = eval::eval_expr(&args[0], filtered_rows[slice[0].2], ctx)
6789                .map_err(EngineError::Eval)?;
6790            let bucket_count: i64 = match v {
6791                Value::SmallInt(n) => i64::from(n),
6792                Value::Int(n) => i64::from(n),
6793                Value::BigInt(n) => n,
6794                _ => {
6795                    return Err(EngineError::Unsupported(
6796                        "ntile() argument must be integer".into(),
6797                    ));
6798                }
6799            };
6800            if bucket_count < 1 {
6801                return Err(EngineError::Unsupported(
6802                    "ntile() argument must be >= 1".into(),
6803                ));
6804            }
6805            #[allow(clippy::cast_sign_loss)]
6806            let buckets = bucket_count as usize;
6807            let n = slice.len();
6808            // Each bucket gets `base` rows; the first `extras` buckets
6809            // get one extra. PG semantics.
6810            let base = n / buckets;
6811            let extras = n % buckets;
6812            let mut bucket: usize = 1;
6813            let mut remaining_in_bucket = if extras > 0 { base + 1 } else { base };
6814            let mut buckets_with_extra_remaining = extras;
6815            for (_, _, idx) in slice {
6816                if remaining_in_bucket == 0 {
6817                    bucket += 1;
6818                    buckets_with_extra_remaining = buckets_with_extra_remaining.saturating_sub(1);
6819                    remaining_in_bucket = if buckets_with_extra_remaining > 0 {
6820                        base + 1
6821                    } else {
6822                        base
6823                    };
6824                    // Edge: if base==0 and extras==0, all rows fit;
6825                    // shouldn't reach here, but guard anyway.
6826                    if remaining_in_bucket == 0 {
6827                        remaining_in_bucket = 1;
6828                    }
6829                }
6830                out_vals[*idx] = Value::BigInt(i64::try_from(bucket).unwrap_or(i64::MAX));
6831                remaining_in_bucket -= 1;
6832            }
6833            Ok(())
6834        }
6835        "percent_rank" => {
6836            // (rank - 1) / (n - 1) where rank is the standard RANK().
6837            // Single-row partitions get 0.
6838            let n = slice.len();
6839            let mut prev_key: Option<&[(Value, bool)]> = None;
6840            let mut current_rank: i64 = 1;
6841            for (i, (_, okey, idx)) in slice.iter().enumerate() {
6842                if let Some(p) = prev_key
6843                    && order_key_cmp(p, okey) != core::cmp::Ordering::Equal
6844                {
6845                    current_rank = i64::try_from(i + 1).unwrap_or(i64::MAX);
6846                }
6847                if prev_key.is_none() {
6848                    current_rank = 1;
6849                }
6850                #[allow(clippy::cast_precision_loss)]
6851                let pr = if n <= 1 {
6852                    0.0
6853                } else {
6854                    (current_rank - 1) as f64 / (n - 1) as f64
6855                };
6856                out_vals[*idx] = Value::Float(pr);
6857                prev_key = Some(okey.as_slice());
6858            }
6859            Ok(())
6860        }
6861        "cume_dist" => {
6862            // # rows up to and including this row's peer group / n.
6863            let n = slice.len();
6864            // First pass: find peer-group-end rank for each row.
6865            for i in 0..slice.len() {
6866                let peer_end = peer_group_end(slice, i);
6867                #[allow(clippy::cast_precision_loss)]
6868                let cd = (peer_end + 1) as f64 / n as f64;
6869                let (_, _, idx) = &slice[i];
6870                out_vals[*idx] = Value::Float(cd);
6871            }
6872            Ok(())
6873        }
6874        other => Err(EngineError::Unsupported(alloc::format!(
6875            "window function {other:?} not supported (v4.21: row_number/rank/dense_rank/sum/avg/count/min/max/lag/lead/first_value/last_value/nth_value/ntile/percent_rank/cume_dist)"
6876        ))),
6877    }
6878}
6879
6880/// v4.20: resolve the user-provided frame down to a normalised
6881/// `(kind, start, end)`. `None` means default — derive from
6882/// `ordered`: ordered ⇒ RANGE UNBOUNDED PRECEDING AND CURRENT ROW,
6883/// unordered ⇒ ROWS UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING.
6884/// Single-bound shorthand (e.g. `ROWS 5 PRECEDING`) normalises
6885/// end → CURRENT ROW per the PG spec.
6886fn effective_frame(
6887    frame: Option<&WindowFrame>,
6888    ordered: bool,
6889) -> Result<(FrameKind, FrameBound, FrameBound), EngineError> {
6890    match frame {
6891        None => {
6892            if ordered {
6893                Ok((
6894                    FrameKind::Range,
6895                    FrameBound::UnboundedPreceding,
6896                    FrameBound::CurrentRow,
6897                ))
6898            } else {
6899                Ok((
6900                    FrameKind::Rows,
6901                    FrameBound::UnboundedPreceding,
6902                    FrameBound::UnboundedFollowing,
6903                ))
6904            }
6905        }
6906        Some(fr) => {
6907            let end = fr.end.clone().unwrap_or(FrameBound::CurrentRow);
6908            // Reject start > end (a few impossible combinations).
6909            if matches!(fr.start, FrameBound::UnboundedFollowing)
6910                || matches!(end, FrameBound::UnboundedPreceding)
6911            {
6912                return Err(EngineError::Unsupported(alloc::format!(
6913                    "invalid frame: start={:?} end={:?}",
6914                    fr.start,
6915                    end
6916                )));
6917            }
6918            // RANGE OFFSET PRECEDING / FOLLOWING needs value-typed
6919            // arithmetic on the ORDER BY key (e.g. `RANGE BETWEEN
6920            // INTERVAL '1 day' PRECEDING AND CURRENT ROW`). Not
6921            // implemented in v4.20.
6922            if fr.kind == FrameKind::Range
6923                && (matches!(
6924                    fr.start,
6925                    FrameBound::OffsetPreceding(_) | FrameBound::OffsetFollowing(_)
6926                ) || matches!(
6927                    end,
6928                    FrameBound::OffsetPreceding(_) | FrameBound::OffsetFollowing(_)
6929                ))
6930            {
6931                return Err(EngineError::Unsupported(
6932                    "RANGE with explicit offset bounds is not supported (v4.20: only UNBOUNDED / CURRENT ROW for RANGE)".into(),
6933                ));
6934            }
6935            Ok((fr.kind, fr.start.clone(), end))
6936        }
6937    }
6938}
6939
6940/// Compute `(lo, hi)` row-index bounds inside the partition slice
6941/// for the row at position `i`. Inclusive, clamped to
6942/// `[0, slice.len()-1]`. Empty result if `lo > hi`.
6943#[allow(clippy::type_complexity)]
6944fn frame_bounds_for_row(
6945    eff: &(FrameKind, FrameBound, FrameBound),
6946    i: usize,
6947    slice: &[(Vec<Value>, Vec<(Value, bool)>, usize)],
6948) -> (usize, usize) {
6949    let (kind, start, end) = eff;
6950    let n = slice.len();
6951    let last = n.saturating_sub(1);
6952    let (mut lo, mut hi) = match kind {
6953        FrameKind::Rows => {
6954            let lo = match start {
6955                FrameBound::UnboundedPreceding => 0,
6956                FrameBound::OffsetPreceding(k) => {
6957                    let k = usize::try_from(*k).unwrap_or(usize::MAX);
6958                    i.saturating_sub(k)
6959                }
6960                FrameBound::CurrentRow => i,
6961                FrameBound::OffsetFollowing(k) => {
6962                    let k = usize::try_from(*k).unwrap_or(usize::MAX);
6963                    i.saturating_add(k).min(last)
6964                }
6965                FrameBound::UnboundedFollowing => last,
6966            };
6967            let hi = match end {
6968                FrameBound::UnboundedPreceding => 0,
6969                FrameBound::OffsetPreceding(k) => {
6970                    let k = usize::try_from(*k).unwrap_or(usize::MAX);
6971                    i.saturating_sub(k)
6972                }
6973                FrameBound::CurrentRow => i,
6974                FrameBound::OffsetFollowing(k) => {
6975                    let k = usize::try_from(*k).unwrap_or(usize::MAX);
6976                    i.saturating_add(k).min(last)
6977                }
6978                FrameBound::UnboundedFollowing => last,
6979            };
6980            (lo, hi)
6981        }
6982        FrameKind::Range => {
6983            // RANGE bounds are peer-aware. With only UNBOUNDED and
6984            // CURRENT ROW supported (rejected at effective_frame for
6985            // explicit offsets), the start/end map to the
6986            // partition's full extent at the same-order-key peer
6987            // group boundary.
6988            let lo = match start {
6989                FrameBound::UnboundedPreceding => 0,
6990                FrameBound::CurrentRow => peer_group_start(slice, i),
6991                FrameBound::UnboundedFollowing => last,
6992                _ => unreachable!("offset bounds rejected for RANGE"),
6993            };
6994            let hi = match end {
6995                FrameBound::UnboundedPreceding => 0,
6996                FrameBound::CurrentRow => peer_group_end(slice, i),
6997                FrameBound::UnboundedFollowing => last,
6998                _ => unreachable!("offset bounds rejected for RANGE"),
6999            };
7000            (lo, hi)
7001        }
7002    };
7003    if hi >= n {
7004        hi = last;
7005    }
7006    if lo >= n {
7007        lo = last;
7008    }
7009    (lo, hi)
7010}
7011
7012/// Find the inclusive index of the first row with the same ORDER
7013/// BY key as `slice[i]`. Slice is already sorted by partition then
7014/// order, so peers are contiguous.
7015#[allow(clippy::type_complexity)]
7016fn peer_group_start(slice: &[(Vec<Value>, Vec<(Value, bool)>, usize)], i: usize) -> usize {
7017    let key = &slice[i].1;
7018    let mut j = i;
7019    while j > 0 && order_key_cmp(&slice[j - 1].1, key) == core::cmp::Ordering::Equal {
7020        j -= 1;
7021    }
7022    j
7023}
7024
7025/// Find the inclusive index of the last row with the same ORDER
7026/// BY key as `slice[i]`.
7027#[allow(clippy::type_complexity)]
7028fn peer_group_end(slice: &[(Vec<Value>, Vec<(Value, bool)>, usize)], i: usize) -> usize {
7029    let key = &slice[i].1;
7030    let mut j = i;
7031    while j + 1 < slice.len() && order_key_cmp(&slice[j + 1].1, key) == core::cmp::Ordering::Equal {
7032        j += 1;
7033    }
7034    j
7035}
7036
7037fn value_to_f64(v: &Value) -> Option<f64> {
7038    match v {
7039        Value::SmallInt(n) => Some(f64::from(*n)),
7040        Value::Int(n) => Some(f64::from(*n)),
7041        #[allow(clippy::cast_precision_loss)]
7042        Value::BigInt(n) => Some(*n as f64),
7043        Value::Float(x) => Some(*x),
7044        _ => None,
7045    }
7046}
7047
7048/// Quick scan for any subquery-bearing node in a SELECT's WHERE /
7049/// projection / `order_by` — saves cloning the AST when there are
7050/// none (the common case).
7051fn expr_tree_has_subquery(stmt: &SelectStatement) -> bool {
7052    let mut any = false;
7053    for item in &stmt.items {
7054        if let SelectItem::Expr { expr, .. } = item {
7055            any = any || expr_has_subquery(expr);
7056        }
7057    }
7058    if let Some(w) = &stmt.where_ {
7059        any = any || expr_has_subquery(w);
7060    }
7061    if let Some(h) = &stmt.having {
7062        any = any || expr_has_subquery(h);
7063    }
7064    for o in &stmt.order_by {
7065        any = any || expr_has_subquery(&o.expr);
7066    }
7067    for (_, peer) in &stmt.unions {
7068        any = any || expr_tree_has_subquery(peer);
7069    }
7070    any
7071}
7072
7073fn expr_has_subquery(e: &Expr) -> bool {
7074    match e {
7075        Expr::ScalarSubquery(_) | Expr::Exists { .. } | Expr::InSubquery { .. } => true,
7076        Expr::Binary { lhs, rhs, .. } => expr_has_subquery(lhs) || expr_has_subquery(rhs),
7077        Expr::Unary { expr, .. } | Expr::Cast { expr, .. } | Expr::IsNull { expr, .. } => {
7078            expr_has_subquery(expr)
7079        }
7080        Expr::FunctionCall { args, .. } => args.iter().any(expr_has_subquery),
7081        Expr::Like { expr, pattern, .. } => expr_has_subquery(expr) || expr_has_subquery(pattern),
7082        Expr::Extract { source, .. } => expr_has_subquery(source),
7083        Expr::WindowFunction {
7084            args,
7085            partition_by,
7086            order_by,
7087            ..
7088        } => {
7089            args.iter().any(expr_has_subquery)
7090                || partition_by.iter().any(expr_has_subquery)
7091                || order_by.iter().any(|(e, _)| expr_has_subquery(e))
7092        }
7093        Expr::Literal(_) | Expr::Placeholder(_) | Expr::Column(_) => false,
7094        Expr::Array(items) => items.iter().any(expr_has_subquery),
7095        Expr::ArraySubscript { target, index } => {
7096            expr_has_subquery(target) || expr_has_subquery(index)
7097        }
7098        Expr::AnyAll { expr, array, .. } => expr_has_subquery(expr) || expr_has_subquery(array),
7099    }
7100}
7101
7102/// v4.10 helper: materialise a runtime `Value` back into an AST
7103/// `Expr::Literal` for the subquery-rewrite path. Supports the
7104/// types `Literal` can represent (Integer / Float / Text / Bool /
7105/// Null). Date / Timestamp / Numeric / Vector / Interval / JSON
7106/// would lose precision through Literal and aren't supported in
7107/// uncorrelated-subquery results; they error with a clear hint.
7108fn value_to_literal_expr(v: Value) -> Result<Expr, EngineError> {
7109    let lit = match v {
7110        Value::Null => Literal::Null,
7111        Value::SmallInt(n) => Literal::Integer(i64::from(n)),
7112        Value::Int(n) => Literal::Integer(i64::from(n)),
7113        Value::BigInt(n) => Literal::Integer(n),
7114        Value::Float(x) => Literal::Float(x),
7115        Value::Text(s) | Value::Json(s) => Literal::String(s),
7116        Value::Bool(b) => Literal::Bool(b),
7117        other => {
7118            return Err(EngineError::Unsupported(alloc::format!(
7119                "subquery result type {:?} not yet materialisable; cast to text or integer in the inner SELECT",
7120                other.data_type()
7121            )));
7122        }
7123    };
7124    Ok(Expr::Literal(lit))
7125}
7126
7127/// v6.1.1 — walk the prepared `Statement` AST and replace every
7128/// `Expr::Placeholder(n)` with `Expr::Literal(value_to_literal(
7129/// params[n-1]))`. The dispatch downstream sees a `Statement`
7130/// indistinguishable from a simple-query parse, so the exec path
7131/// stays unchanged.
7132///
7133/// Errors fall into one shape: a `$N` references past the bound
7134/// `params.len()`. Out-of-range happens when the Bind didn't
7135/// supply enough values; pgwire surfaces this as a protocol error
7136/// to the client.
7137fn substitute_placeholders(stmt: &mut Statement, params: &[Value]) -> Result<(), EngineError> {
7138    match stmt {
7139        Statement::Select(s) => substitute_select(s, params)?,
7140        Statement::Insert(ins) => {
7141            for row in &mut ins.rows {
7142                for e in row {
7143                    substitute_expr(e, params)?;
7144                }
7145            }
7146        }
7147        Statement::Update(u) => {
7148            for (_, e) in &mut u.assignments {
7149                substitute_expr(e, params)?;
7150            }
7151            if let Some(w) = &mut u.where_ {
7152                substitute_expr(w, params)?;
7153            }
7154        }
7155        Statement::Delete(d) => {
7156            if let Some(w) = &mut d.where_ {
7157                substitute_expr(w, params)?;
7158            }
7159        }
7160        Statement::Explain(e) => substitute_select(&mut e.inner, params)?,
7161        // Other statements (CREATE / BEGIN / SHOW / …) have no
7162        // expression slots; no walk needed.
7163        _ => {}
7164    }
7165    Ok(())
7166}
7167
7168fn substitute_select(s: &mut SelectStatement, params: &[Value]) -> Result<(), EngineError> {
7169    for item in &mut s.items {
7170        if let SelectItem::Expr { expr, .. } = item {
7171            substitute_expr(expr, params)?;
7172        }
7173    }
7174    if let Some(w) = &mut s.where_ {
7175        substitute_expr(w, params)?;
7176    }
7177    if let Some(gs) = &mut s.group_by {
7178        for g in gs {
7179            substitute_expr(g, params)?;
7180        }
7181    }
7182    if let Some(h) = &mut s.having {
7183        substitute_expr(h, params)?;
7184    }
7185    for o in &mut s.order_by {
7186        substitute_expr(&mut o.expr, params)?;
7187    }
7188    for (_, peer) in &mut s.unions {
7189        substitute_select(peer, params)?;
7190    }
7191    // v7.9.24 — LIMIT $N / OFFSET $N placeholder resolution.
7192    // mailrs H2. After this pass each LIMIT/OFFSET that was a
7193    // Placeholder is rewritten to Literal so the existing
7194    // `LimitExpr::as_literal` path consumes a concrete u32.
7195    if let Some(le) = s.limit {
7196        s.limit = Some(resolve_limit_placeholder(le, params)?);
7197    }
7198    if let Some(le) = s.offset {
7199        s.offset = Some(resolve_limit_placeholder(le, params)?);
7200    }
7201    Ok(())
7202}
7203
7204fn resolve_limit_placeholder(
7205    le: spg_sql::ast::LimitExpr,
7206    params: &[Value],
7207) -> Result<spg_sql::ast::LimitExpr, EngineError> {
7208    use spg_sql::ast::LimitExpr;
7209    match le {
7210        LimitExpr::Literal(_) => Ok(le),
7211        LimitExpr::Placeholder(n) => {
7212            let idx = usize::from(n).saturating_sub(1);
7213            let v = params.get(idx).ok_or_else(|| {
7214                EngineError::Eval(EvalError::PlaceholderOutOfRange {
7215                    n,
7216                    bound: u16::try_from(params.len()).unwrap_or(u16::MAX),
7217                })
7218            })?;
7219            let int = match v {
7220                Value::SmallInt(x) => Some(i64::from(*x)),
7221                Value::Int(x) => Some(i64::from(*x)),
7222                Value::BigInt(x) => Some(*x),
7223                _ => None,
7224            }
7225            .ok_or_else(|| {
7226                EngineError::Unsupported(alloc::format!(
7227                    "LIMIT/OFFSET ${n} bound to non-integer {v:?}"
7228                ))
7229            })?;
7230            if int < 0 {
7231                return Err(EngineError::Unsupported(alloc::format!(
7232                    "LIMIT/OFFSET ${n} bound to negative value {int}"
7233                )));
7234            }
7235            let bounded = u32::try_from(int).map_err(|_| {
7236                EngineError::Unsupported(alloc::format!(
7237                    "LIMIT/OFFSET ${n} value {int} exceeds u32 range"
7238                ))
7239            })?;
7240            Ok(LimitExpr::Literal(bounded))
7241        }
7242    }
7243}
7244
7245fn substitute_expr(e: &mut Expr, params: &[Value]) -> Result<(), EngineError> {
7246    if let Expr::Placeholder(n) = e {
7247        let idx = usize::from(*n).saturating_sub(1);
7248        let v = params.get(idx).ok_or_else(|| {
7249            EngineError::Eval(EvalError::PlaceholderOutOfRange {
7250                n: *n,
7251                bound: u16::try_from(params.len()).unwrap_or(u16::MAX),
7252            })
7253        })?;
7254        *e = Expr::Literal(value_to_literal(v.clone()));
7255        return Ok(());
7256    }
7257    match e {
7258        Expr::Binary { lhs, rhs, .. } => {
7259            substitute_expr(lhs, params)?;
7260            substitute_expr(rhs, params)?;
7261        }
7262        Expr::Unary { expr, .. } | Expr::Cast { expr, .. } | Expr::IsNull { expr, .. } => {
7263            substitute_expr(expr, params)?;
7264        }
7265        Expr::FunctionCall { args, .. } => {
7266            for a in args {
7267                substitute_expr(a, params)?;
7268            }
7269        }
7270        Expr::Like { expr, pattern, .. } => {
7271            substitute_expr(expr, params)?;
7272            substitute_expr(pattern, params)?;
7273        }
7274        Expr::Extract { source, .. } => substitute_expr(source, params)?,
7275        Expr::ScalarSubquery(s) => substitute_select(s, params)?,
7276        Expr::Exists { subquery, .. } => substitute_select(subquery, params)?,
7277        Expr::InSubquery { expr, subquery, .. } => {
7278            substitute_expr(expr, params)?;
7279            substitute_select(subquery, params)?;
7280        }
7281        Expr::WindowFunction {
7282            args,
7283            partition_by,
7284            order_by,
7285            ..
7286        } => {
7287            for a in args {
7288                substitute_expr(a, params)?;
7289            }
7290            for p in partition_by {
7291                substitute_expr(p, params)?;
7292            }
7293            for (e, _) in order_by {
7294                substitute_expr(e, params)?;
7295            }
7296        }
7297        Expr::Literal(_) | Expr::Column(_) => {}
7298        // Already handled above.
7299        Expr::Placeholder(_) => unreachable!("Placeholder handled at top of fn"),
7300        Expr::Array(items) => {
7301            for elem in items {
7302                substitute_expr(elem, params)?;
7303            }
7304        }
7305        Expr::ArraySubscript { target, index } => {
7306            substitute_expr(target, params)?;
7307            substitute_expr(index, params)?;
7308        }
7309        Expr::AnyAll { expr, array, .. } => {
7310            substitute_expr(expr, params)?;
7311            substitute_expr(array, params)?;
7312        }
7313    }
7314    Ok(())
7315}
7316
7317/// v6.1.1 — convert a runtime `Value` into the closest matching
7318/// `Literal` for the substitute walker. Lossless for the simple
7319/// scalars (Int / Float / Text / Bool); Numeric / Date / Timestamp
7320/// / Json / Interval render as their canonical text form so the
7321/// downstream coerce_value can re-parse against the target column
7322/// type. SQ8 / HalfVector cells are NOT expected as bind params;
7323/// pgwire's Bind decodes vector params to the f32 representation
7324/// before they reach this helper.
7325/// v6.2.0 — total ordering on `Value`s used by ANALYZE to sort a
7326/// column's non-NULL sample before histogram building. Cross-type
7327/// pairs (Int vs Float, Date vs Timestamp, …) compare via the
7328/// same widening the eval-side `compare` operator uses; everything
7329/// else (the genuinely-incompatible pairs) falls back to ordering
7330/// by canonical string form so the sort is still total + stable.
7331/// Vector / SQ8 / Half / Json / Numeric / Interval values reach
7332/// here only via the string-fallback path because vector columns
7333/// are filtered out upstream.
7334fn sort_values_for_histogram(a: &Value, b: &Value) -> core::cmp::Ordering {
7335    use core::cmp::Ordering;
7336    match (a, b) {
7337        (Value::SmallInt(a), Value::SmallInt(b)) => a.cmp(b),
7338        (Value::Int(a), Value::Int(b)) => a.cmp(b),
7339        (Value::BigInt(a), Value::BigInt(b)) => a.cmp(b),
7340        (Value::SmallInt(a), Value::Int(b)) => i32::from(*a).cmp(b),
7341        (Value::Int(a), Value::SmallInt(b)) => a.cmp(&i32::from(*b)),
7342        (Value::Int(a), Value::BigInt(b)) => i64::from(*a).cmp(b),
7343        (Value::BigInt(a), Value::Int(b)) => a.cmp(&i64::from(*b)),
7344        (Value::SmallInt(a), Value::BigInt(b)) => i64::from(*a).cmp(b),
7345        (Value::BigInt(a), Value::SmallInt(b)) => a.cmp(&i64::from(*b)),
7346        (Value::Float(a), Value::Float(b)) => a.partial_cmp(b).unwrap_or(Ordering::Equal),
7347        (Value::Text(a), Value::Text(b)) | (Value::Json(a), Value::Json(b)) => a.cmp(b),
7348        (Value::Bool(a), Value::Bool(b)) => a.cmp(b),
7349        (Value::Date(a), Value::Date(b)) => a.cmp(b),
7350        (Value::Timestamp(a), Value::Timestamp(b)) => a.cmp(b),
7351        // Mixed numeric/float — widen to f64 and compare.
7352        (Value::SmallInt(n), Value::Float(x)) => {
7353            (f64::from(*n)).partial_cmp(x).unwrap_or(Ordering::Equal)
7354        }
7355        (Value::Float(x), Value::SmallInt(n)) => {
7356            x.partial_cmp(&f64::from(*n)).unwrap_or(Ordering::Equal)
7357        }
7358        (Value::Int(n), Value::Float(x)) => {
7359            (f64::from(*n)).partial_cmp(x).unwrap_or(Ordering::Equal)
7360        }
7361        (Value::Float(x), Value::Int(n)) => {
7362            x.partial_cmp(&f64::from(*n)).unwrap_or(Ordering::Equal)
7363        }
7364        (Value::BigInt(n), Value::Float(x)) => {
7365            #[allow(clippy::cast_precision_loss)]
7366            let nf = *n as f64;
7367            nf.partial_cmp(x).unwrap_or(Ordering::Equal)
7368        }
7369        (Value::Float(x), Value::BigInt(n)) => {
7370            #[allow(clippy::cast_precision_loss)]
7371            let nf = *n as f64;
7372            x.partial_cmp(&nf).unwrap_or(Ordering::Equal)
7373        }
7374        // Cross-type fallback: lexicographic on canonical form.
7375        // Total + stable so the sort is well-defined.
7376        _ => canonical_value_repr(a).cmp(&canonical_value_repr(b)),
7377    }
7378}
7379
7380/// v6.2.0 — render the histogram bounds list as a `[v0, v1, ...]`
7381/// string for the `spg_statistic.histogram_bounds` column. Values
7382/// containing `,` or `[` / `]` are JSON-style escaped so the
7383/// rendering round-trips through a future parser; v6.2.0 only
7384/// uses the rendered form for human consumption, so the escaping
7385/// is conservative.
7386fn render_histogram_bounds(bounds: &[alloc::string::String]) -> alloc::string::String {
7387    let mut out = alloc::string::String::with_capacity(bounds.len() * 8 + 2);
7388    out.push('[');
7389    for (i, b) in bounds.iter().enumerate() {
7390        if i > 0 {
7391            out.push_str(", ");
7392        }
7393        let needs_quote = b.contains([',', '[', ']', '"']) || b.is_empty();
7394        if needs_quote {
7395            out.push('"');
7396            for ch in b.chars() {
7397                if ch == '"' || ch == '\\' {
7398                    out.push('\\');
7399                }
7400                out.push(ch);
7401            }
7402            out.push('"');
7403        } else {
7404            out.push_str(b);
7405        }
7406    }
7407    out.push(']');
7408    out
7409}
7410
7411/// v6.2.0 — canonical textual form of a `Value` for histogram
7412/// bound storage. Strings used by ANALYZE for sort + bound output.
7413/// INT / BIGINT → decimal; FLOAT → shortest-round-trip via
7414/// `{:?}`; TEXT pass-through; BOOL → `t` / `f`; DATE / TIMESTAMP →
7415/// the same form `format_date` / `format_timestamp` produce for
7416/// SQL Display. Vector / SQ8 / Half / Json / Numeric / Interval
7417/// reach this only via a non-Vector column (vector columns are
7418/// skipped upstream); they fall back to a Debug-derived form so
7419/// stats still serialise without crashing.
7420pub(crate) fn canonical_value_repr(v: &Value) -> alloc::string::String {
7421    match v {
7422        Value::Null => "NULL".to_string(),
7423        Value::SmallInt(n) => alloc::format!("{n}"),
7424        Value::Int(n) => alloc::format!("{n}"),
7425        Value::BigInt(n) => alloc::format!("{n}"),
7426        Value::Float(x) => alloc::format!("{x:?}"),
7427        Value::Text(s) | Value::Json(s) => s.clone(),
7428        Value::Bool(b) => if *b { "t" } else { "f" }.to_string(),
7429        Value::Date(d) => eval::format_date(*d),
7430        Value::Timestamp(t) => eval::format_timestamp(*t),
7431        Value::Interval { months, micros } => eval::format_interval(*months, *micros),
7432        Value::Numeric { scaled, scale } => eval::format_numeric(*scaled, *scale),
7433        Value::Vector(_) | Value::Sq8Vector(_) | Value::HalfVector(_) => {
7434            // Unreachable in practice (vector columns are filtered
7435            // out before this). Defensive fallback so a future
7436            // vector-stats path doesn't crash.
7437            alloc::format!("{v:?}")
7438        }
7439        // v7.5.0 — Value is #[non_exhaustive] for downstream
7440        // forward-compat. Future variants fall through to Debug
7441        // form here (same shape as the vector fallback above).
7442        _ => alloc::format!("{v:?}"),
7443    }
7444}
7445
7446/// v6.2.0 — true for engine-managed catalog tables that the bare
7447/// `ANALYZE` (no target) should skip. v6.2.0 has no internal
7448/// tables yet (publications / subscriptions / users / statistics
7449/// all live as engine fields, not catalog tables), so this is a
7450/// reserved future-proofing hook — every existing user table is
7451/// analysed.
7452const fn is_internal_table_name(_name: &str) -> bool {
7453    false
7454}
7455
7456fn value_to_literal(v: Value) -> Literal {
7457    match v {
7458        Value::Null => Literal::Null,
7459        Value::SmallInt(n) => Literal::Integer(i64::from(n)),
7460        Value::Int(n) => Literal::Integer(i64::from(n)),
7461        Value::BigInt(n) => Literal::Integer(n),
7462        Value::Float(x) => Literal::Float(x),
7463        Value::Text(s) | Value::Json(s) => Literal::String(s),
7464        Value::Bool(b) => Literal::Bool(b),
7465        Value::Vector(v) => Literal::Vector(v),
7466        Value::Numeric { scaled, scale } => Literal::String(eval::format_numeric(scaled, scale)),
7467        Value::Date(d) => Literal::String(eval::format_date(d)),
7468        Value::Timestamp(t) => Literal::String(eval::format_timestamp(t)),
7469        Value::Interval { months, micros } => Literal::Interval {
7470            months,
7471            micros,
7472            text: eval::format_interval(months, micros),
7473        },
7474        // SQ8 / halfvec cells dequantise to f32 before reaching the
7475        // substitute walker; pgwire's Bind path handles that.
7476        Value::Sq8Vector(q) => Literal::Vector(spg_storage::quantize::dequantize(&q)),
7477        Value::HalfVector(h) => Literal::Vector(h.to_f32_vec()),
7478        // v7.5.0 — Value is #[non_exhaustive]; future variants
7479        // render as Debug-form String literal until explicit
7480        // mapping is added.
7481        v => Literal::String(alloc::format!("{v:?}")),
7482    }
7483}
7484
7485fn rewrite_clock_calls(stmt: &mut Statement, now_micros: Option<i64>) {
7486    let Some(now) = now_micros else {
7487        return;
7488    };
7489    match stmt {
7490        Statement::Select(s) => rewrite_select_clock(s, now),
7491        Statement::Insert(ins) => {
7492            for row in &mut ins.rows {
7493                for e in row {
7494                    rewrite_expr_clock(e, now);
7495                }
7496            }
7497        }
7498        _ => {}
7499    }
7500}
7501
7502fn rewrite_select_clock(s: &mut SelectStatement, now: i64) {
7503    for item in &mut s.items {
7504        if let SelectItem::Expr { expr, .. } = item {
7505            rewrite_expr_clock(expr, now);
7506        }
7507    }
7508    if let Some(w) = &mut s.where_ {
7509        rewrite_expr_clock(w, now);
7510    }
7511    if let Some(gs) = &mut s.group_by {
7512        for g in gs {
7513            rewrite_expr_clock(g, now);
7514        }
7515    }
7516    if let Some(h) = &mut s.having {
7517        rewrite_expr_clock(h, now);
7518    }
7519    for o in &mut s.order_by {
7520        rewrite_expr_clock(&mut o.expr, now);
7521    }
7522    for (_, peer) in &mut s.unions {
7523        rewrite_select_clock(peer, now);
7524    }
7525}
7526
7527/// v3.0.3 hot path: every recursion lands in exactly one `match` arm.
7528/// Literal / Column-with-qualifier (the dominant cases on a typical
7529/// AST) take a single pattern dispatch and exit. The clock-rewrite
7530/// targets (zero-arg `NOW` / `CURRENT_TIMESTAMP` / `CURRENT_DATE`
7531/// functions, and bare `CURRENT_TIMESTAMP` / `CURRENT_DATE` column
7532/// refs) sit on their own arms with match guards so the fall-through
7533/// to the recursive arms is unambiguous.
7534fn rewrite_expr_clock(e: &mut Expr, now: i64) {
7535    // Fast-path test on the no-recursion shapes first. We can't fold
7536    // them into the big match below because they need to *replace* `e`
7537    // outright; the recursive arms below match on its sub-fields.
7538    if let Some(replacement) = clock_replacement_for(e, now) {
7539        *e = replacement;
7540        return;
7541    }
7542    match e {
7543        Expr::Binary { lhs, rhs, .. } => {
7544            rewrite_expr_clock(lhs, now);
7545            rewrite_expr_clock(rhs, now);
7546        }
7547        Expr::Unary { expr, .. } | Expr::Cast { expr, .. } | Expr::IsNull { expr, .. } => {
7548            rewrite_expr_clock(expr, now);
7549        }
7550        Expr::FunctionCall { args, .. } => {
7551            for a in args {
7552                rewrite_expr_clock(a, now);
7553            }
7554        }
7555        Expr::Like { expr, pattern, .. } => {
7556            rewrite_expr_clock(expr, now);
7557            rewrite_expr_clock(pattern, now);
7558        }
7559        Expr::Extract { source, .. } => rewrite_expr_clock(source, now),
7560        // v4.10 subquery nodes — recurse into the inner SELECT's
7561        // expression slots so e.g. SELECT NOW() in a scalar
7562        // subquery picks up the same instant as the outer query.
7563        Expr::ScalarSubquery(s) => rewrite_select_clock(s, now),
7564        Expr::Exists { subquery, .. } => rewrite_select_clock(subquery, now),
7565        Expr::InSubquery { expr, subquery, .. } => {
7566            rewrite_expr_clock(expr, now);
7567            rewrite_select_clock(subquery, now);
7568        }
7569        // v4.12 window functions — args + PARTITION BY + ORDER BY
7570        // may all reference clock literals.
7571        Expr::WindowFunction {
7572            args,
7573            partition_by,
7574            order_by,
7575            ..
7576        } => {
7577            for a in args {
7578                rewrite_expr_clock(a, now);
7579            }
7580            for p in partition_by {
7581                rewrite_expr_clock(p, now);
7582            }
7583            for (e, _) in order_by {
7584                rewrite_expr_clock(e, now);
7585            }
7586        }
7587        Expr::Literal(_) | Expr::Placeholder(_) | Expr::Column(_) => {}
7588        Expr::Array(items) => {
7589            for elem in items {
7590                rewrite_expr_clock(elem, now);
7591            }
7592        }
7593        Expr::ArraySubscript { target, index } => {
7594            rewrite_expr_clock(target, now);
7595            rewrite_expr_clock(index, now);
7596        }
7597        Expr::AnyAll { expr, array, .. } => {
7598            rewrite_expr_clock(expr, now);
7599            rewrite_expr_clock(array, now);
7600        }
7601    }
7602}
7603
7604/// Returns `Some(Expr)` when `e` is one of the clock-call shapes that
7605/// must be rewritten; otherwise `None` so the caller falls through to
7606/// the recursive walk. Identifies both function-call forms (`NOW()` /
7607/// `CURRENT_TIMESTAMP()` / `CURRENT_DATE()`) and bare-identifier forms
7608/// (`CURRENT_TIMESTAMP` / `CURRENT_DATE` as unqualified column refs,
7609/// which is how PG accepts them without parens).
7610fn clock_replacement_for(e: &Expr, now: i64) -> Option<Expr> {
7611    let (kind, name) = match e {
7612        Expr::FunctionCall { name, args } if args.is_empty() => (ClockSite::Fn, name.as_str()),
7613        Expr::Column(c) if c.qualifier.is_none() => (ClockSite::BareIdent, c.name.as_str()),
7614        _ => return None,
7615    };
7616    // ASCII case-insensitive name match. Limited to the three keywords
7617    // that actually need rewriting.
7618    let matched = match name.len() {
7619        3 if kind == ClockSite::Fn && name.eq_ignore_ascii_case("now") => Some(true),
7620        12 if name.eq_ignore_ascii_case("current_date") => Some(false),
7621        17 if name.eq_ignore_ascii_case("current_timestamp") => Some(true),
7622        _ => None,
7623    };
7624    let is_timestamp = matched?;
7625    let payload = if is_timestamp {
7626        now
7627    } else {
7628        now.div_euclid(86_400_000_000)
7629    };
7630    let target = if is_timestamp {
7631        spg_sql::ast::CastTarget::Timestamp
7632    } else {
7633        spg_sql::ast::CastTarget::Date
7634    };
7635    Some(Expr::Cast {
7636        expr: alloc::boxed::Box::new(Expr::Literal(spg_sql::ast::Literal::Integer(payload))),
7637        target,
7638    })
7639}
7640
7641#[derive(Debug, Clone, Copy, PartialEq, Eq)]
7642enum ClockSite {
7643    Fn,
7644    BareIdent,
7645}
7646
7647/// `ORDER BY <integer>` references the N-th SELECT item (1-based).
7648/// Swap the integer literal for the matching item's expression so the
7649/// executor doesn't need a special-case branch. Recurses into UNION
7650/// peers because each peer keeps its own SELECT list.
7651/// v6.4.1 — expand `GROUP BY ALL` to every non-aggregate SELECT-list
7652/// item. Mirrors DuckDB / PG 19 semantics. Wildcards (`SELECT * …`)
7653/// are NOT expanded by GROUP BY ALL (PG 19 leaves the wildcard intact
7654/// and groups by whatever explicit non-aggregates remain — none in
7655/// the wildcard-only case, which still works for non-aggregate
7656/// queries).
7657fn expand_group_by_all(s: &mut SelectStatement) {
7658    if !s.group_by_all {
7659        for (_, peer) in &mut s.unions {
7660            expand_group_by_all(peer);
7661        }
7662        return;
7663    }
7664    let mut groups: Vec<Expr> = Vec::new();
7665    for item in &s.items {
7666        if let SelectItem::Expr { expr, .. } = item
7667            && !aggregate::contains_aggregate(expr)
7668        {
7669            groups.push(expr.clone());
7670        }
7671    }
7672    s.group_by = Some(groups);
7673    s.group_by_all = false;
7674    for (_, peer) in &mut s.unions {
7675        expand_group_by_all(peer);
7676    }
7677}
7678
7679fn resolve_order_by_position(s: &mut SelectStatement) {
7680    // v6.4.0 — iterate every ORDER BY key. Position references
7681    // (`ORDER BY 2`) bind to the 1-based projection index;
7682    // identifier references that match a SELECT-list alias bind to
7683    // the projected expression (Step 4 of L3a).
7684    for order in &mut s.order_by {
7685        match &order.expr {
7686            Expr::Literal(Literal::Integer(n)) if *n >= 1 => {
7687                if let Ok(idx_one_based) = usize::try_from(*n) {
7688                    let idx = idx_one_based - 1;
7689                    if idx < s.items.len()
7690                        && let SelectItem::Expr { expr, .. } = &s.items[idx]
7691                    {
7692                        order.expr = expr.clone();
7693                    }
7694                }
7695            }
7696            Expr::Column(c) if c.qualifier.is_none() => {
7697                // Alias-in-ORDER-BY lookup.
7698                for item in &s.items {
7699                    if let SelectItem::Expr {
7700                        expr,
7701                        alias: Some(a),
7702                    } = item
7703                        && a == &c.name
7704                    {
7705                        order.expr = expr.clone();
7706                        break;
7707                    }
7708                }
7709            }
7710            _ => {}
7711        }
7712    }
7713    for (_, peer) in &mut s.unions {
7714        resolve_order_by_position(peer);
7715    }
7716}
7717
7718/// Sort `tagged` by `f64` key, reversing the comparator under DESC.
7719/// Used by the UNION ORDER BY path; per-block paths inline the same
7720/// comparator because they already hold `&OrderBy` directly.
7721/// v3.1.1: partial-sort helper. When `keep` (= offset + limit) is
7722/// strictly less than `tagged.len()`, run `select_nth_unstable_by` to
7723/// partition the prefix in O(n), then sort just that prefix in O(k
7724/// log k). Total O(n + k log k), vs O(n log n) for a full sort. The
7725/// caller decides what `keep` is; passing `None` (no LIMIT) keeps the
7726/// full-sort behaviour.
7727///
7728/// `tagged` holds `(Option<f64>, Row)` (the SELECT path) — `None` keys
7729/// sort last in ascending order, mirroring NULL-sorts-last in SQL.
7730fn partial_sort_tagged(tagged: &mut Vec<(Vec<f64>, Row)>, keep: Option<usize>, descs: &[bool]) {
7731    let cmp = |a: &(Vec<f64>, Row), b: &(Vec<f64>, Row)| cmp_multi_key(&a.0, &b.0, descs);
7732    match keep {
7733        Some(k) if k < tagged.len() && k > 0 => {
7734            let pivot = k - 1;
7735            tagged.select_nth_unstable_by(pivot, cmp);
7736            tagged[..k].sort_by(cmp);
7737            tagged.truncate(k);
7738        }
7739        _ => {
7740            tagged.sort_by(cmp);
7741        }
7742    }
7743}
7744
7745fn sort_by_keys(tagged: &mut [(Vec<f64>, Row)], descs: &[bool]) {
7746    tagged.sort_by(|a, b| cmp_multi_key(&a.0, &b.0, descs));
7747}
7748
7749/// v6.4.0 — multi-key ORDER BY comparator. Each key's per-key DESC
7750/// flag is honored independently. NULL is encoded as `f64::INFINITY`
7751/// so it sorts last in ASC and first in DESC (matches PG default).
7752fn cmp_multi_key(a: &[f64], b: &[f64], descs: &[bool]) -> core::cmp::Ordering {
7753    use core::cmp::Ordering;
7754    for (i, (ka, kb)) in a.iter().zip(b.iter()).enumerate() {
7755        let ord = ka.partial_cmp(kb).unwrap_or(Ordering::Equal);
7756        let ord = if descs.get(i).copied().unwrap_or(false) {
7757            ord.reverse()
7758        } else {
7759            ord
7760        };
7761        if ord != Ordering::Equal {
7762            return ord;
7763        }
7764    }
7765    Ordering::Equal
7766}
7767
7768/// v6.4.0 — eval every ORDER BY expression for a row and pack the
7769/// resulting keys into a `Vec<f64>`. NULL → `f64::INFINITY`.
7770fn build_order_keys(
7771    order_by: &[OrderBy],
7772    row: &Row,
7773    ctx: &EvalContext,
7774) -> Result<Vec<f64>, EngineError> {
7775    let mut keys = Vec::with_capacity(order_by.len());
7776    for o in order_by {
7777        let v = eval::eval_expr(&o.expr, row, ctx)?;
7778        keys.push(value_to_order_key(&v)?);
7779    }
7780    Ok(keys)
7781}
7782
7783/// Drop the first `offset` rows then truncate to `limit`. PG / `MySQL`
7784/// agree: OFFSET applies *after* ORDER BY but *before* LIMIT (so
7785/// `LIMIT 10 OFFSET 5` keeps rows 6..=15).
7786fn apply_offset_and_limit(rows: &mut Vec<Row>, offset: Option<u32>, limit: Option<u32>) {
7787    if let Some(off) = offset {
7788        let off = off as usize;
7789        if off >= rows.len() {
7790            rows.clear();
7791        } else {
7792            rows.drain(..off);
7793        }
7794    }
7795    if let Some(n) = limit {
7796        rows.truncate(n as usize);
7797    }
7798}
7799
7800/// v7.6.1 — resolve a parser-level `ForeignKeyConstraint` (column
7801/// names + parent table name) into the storage-layer shape (column
7802/// indices + same parent table). Validates everything the engine
7803/// needs to know about the FK at CREATE TABLE time:
7804///
7805///   - parent table exists (catalog lookup, unless self-referencing)
7806///   - parent columns exist on the parent table
7807///   - parent column list matches the local arity (defaults to the
7808///     parent's primary index column when omitted)
7809///   - parent columns are covered by a `BTree` UNIQUE-class index
7810///     (SPG's stand-in for `PRIMARY KEY`/`UNIQUE`) — required so
7811///     the v7.6.2 INSERT path can do an O(log n) parent lookup
7812///   - local columns exist on the table being created
7813fn resolve_foreign_key(
7814    local_table_name: &str,
7815    local_cols: &[ColumnSchema],
7816    fk: spg_sql::ast::ForeignKeyConstraint,
7817    catalog: &Catalog,
7818) -> Result<spg_storage::ForeignKeyConstraint, EngineError> {
7819    // Resolve local columns.
7820    let mut local_columns = Vec::with_capacity(fk.columns.len());
7821    for name in &fk.columns {
7822        let pos = local_cols
7823            .iter()
7824            .position(|c| c.name == *name)
7825            .ok_or_else(|| {
7826                EngineError::Unsupported(alloc::format!(
7827                    "FOREIGN KEY references unknown local column {name:?}"
7828                ))
7829            })?;
7830        local_columns.push(pos);
7831    }
7832    // Self-referencing FK: parent table is the one we're creating.
7833    // The parent column resolution uses the local column list since
7834    // the catalog doesn't have this table yet.
7835    let is_self_ref = fk.parent_table == local_table_name;
7836    let (parent_cols_for_lookup, parent_table_str): (&[ColumnSchema], &str) = if is_self_ref {
7837        (local_cols, local_table_name)
7838    } else {
7839        let parent_table = catalog.get(&fk.parent_table).ok_or_else(|| {
7840            EngineError::Storage(StorageError::TableNotFound {
7841                name: fk.parent_table.clone(),
7842            })
7843        })?;
7844        (
7845            parent_table.schema().columns.as_slice(),
7846            fk.parent_table.as_str(),
7847        )
7848    };
7849    // Resolve parent column names → positions. If the FK omitted the
7850    // parent column list, fall back to the parent's primary index
7851    // column (single-column only — composite default is rejected
7852    // because there's no unambiguous "PK" in SPG's index list).
7853    let parent_columns: Vec<usize> = if fk.parent_columns.is_empty() {
7854        if fk.columns.len() != 1 {
7855            return Err(EngineError::Unsupported(
7856                "composite FOREIGN KEY without explicit parent column list is not supported \
7857                 — list the parent columns explicitly"
7858                    .into(),
7859            ));
7860        }
7861        // Find a single BTree index on the parent and use its column.
7862        let pos = pick_pk_index_column(catalog, parent_table_str, is_self_ref, local_cols)
7863            .ok_or_else(|| {
7864                EngineError::Unsupported(alloc::format!(
7865                    "parent table {parent_table_str:?} has no PRIMARY-key / UNIQUE BTree index \
7866                     to default the FOREIGN KEY against"
7867                ))
7868            })?;
7869        alloc::vec![pos]
7870    } else {
7871        let mut out = Vec::with_capacity(fk.parent_columns.len());
7872        for name in &fk.parent_columns {
7873            let pos = parent_cols_for_lookup
7874                .iter()
7875                .position(|c| c.name == *name)
7876                .ok_or_else(|| {
7877                    EngineError::Unsupported(alloc::format!(
7878                        "FOREIGN KEY references unknown parent column \
7879                         {name:?} on table {parent_table_str:?}"
7880                    ))
7881                })?;
7882            out.push(pos);
7883        }
7884        out
7885    };
7886    if parent_columns.len() != local_columns.len() {
7887        return Err(EngineError::Unsupported(alloc::format!(
7888            "FOREIGN KEY arity mismatch: {} local columns vs {} parent columns",
7889            local_columns.len(),
7890            parent_columns.len()
7891        )));
7892    }
7893    // For non-self-referencing FKs, verify the parent column set is
7894    // covered by a BTree index. SPG doesn't have a `PRIMARY KEY`
7895    // declaration; the convention is "the parent column for FK
7896    // purposes must have a BTree index" — which the user creates via
7897    // `CREATE INDEX ... USING btree (col)` (the default). We accept
7898    // any single-column BTree index that covers a parent column;
7899    // composite parent column lists require an index whose `column_position`
7900    // matches the first parent column (multi-column BTree indices
7901    // are not in the v7.x roadmap).
7902    if !is_self_ref {
7903        let parent_table = catalog.get(&fk.parent_table).expect("checked above");
7904        let primary_parent_col = parent_columns[0];
7905        let has_btree = parent_table
7906            .schema()
7907            .columns
7908            .get(primary_parent_col)
7909            .is_some()
7910            && parent_table.indices().iter().any(|idx| {
7911                matches!(idx.kind, spg_storage::IndexKind::BTree(_))
7912                    && idx.column_position == primary_parent_col
7913                    && idx.partial_predicate.is_none()
7914            });
7915        if !has_btree {
7916            return Err(EngineError::Unsupported(alloc::format!(
7917                "FOREIGN KEY parent column on {:?} is not covered by an unconditional BTree \
7918                 index — create one with `CREATE INDEX ... ON {} ({})` first",
7919                parent_table_str,
7920                parent_table_str,
7921                parent_table.schema().columns[primary_parent_col].name,
7922            )));
7923        }
7924    }
7925    let on_delete = fk_action_sql_to_storage(fk.on_delete);
7926    let on_update = fk_action_sql_to_storage(fk.on_update);
7927    Ok(spg_storage::ForeignKeyConstraint {
7928        name: fk.name,
7929        local_columns,
7930        parent_table: fk.parent_table,
7931        parent_columns,
7932        on_delete,
7933        on_update,
7934    })
7935}
7936
7937/// v7.6.1 — pick a sentinel "primary key" column from the parent
7938/// table when the FK didn't name parent columns. Picks the first
7939/// single-column unconditional BTree index — that's the closest
7940/// thing SPG has to a PRIMARY KEY today. Self-referencing FKs use
7941/// `local_cols` as the column source.
7942fn pick_pk_index_column(
7943    catalog: &Catalog,
7944    parent_name: &str,
7945    is_self_ref: bool,
7946    local_cols: &[ColumnSchema],
7947) -> Option<usize> {
7948    if is_self_ref {
7949        // Self-ref FK omitted parent columns: pick column 0 by
7950        // convention (no catalog entry yet). Engine will widen this
7951        // when v7.6.7 lands; v7.6.1 only handles the explicit form.
7952        let _ = local_cols;
7953        return Some(0);
7954    }
7955    let parent = catalog.get(parent_name)?;
7956    parent.indices().iter().find_map(|idx| {
7957        if matches!(idx.kind, spg_storage::IndexKind::BTree(_))
7958            && idx.partial_predicate.is_none()
7959            && idx.included_columns.is_empty()
7960            && idx.expression.is_none()
7961        {
7962            Some(idx.column_position)
7963        } else {
7964            None
7965        }
7966    })
7967}
7968
7969/// v7.9.8 / v7.9.10 — resolve the column positions that
7970/// identify a conflict for ON CONFLICT. Returns a Vec of
7971/// column positions (1 element for single-column form, N for
7972/// composite). When the user wrote bare `ON CONFLICT DO …`,
7973/// falls back to the table's first unconditional BTree index
7974/// (always single-column today).
7975fn resolve_on_conflict_columns(
7976    catalog: &Catalog,
7977    table_name: &str,
7978    target: &[String],
7979) -> Result<Vec<usize>, EngineError> {
7980    let table = catalog.get(table_name).ok_or_else(|| {
7981        EngineError::Storage(StorageError::TableNotFound {
7982            name: table_name.into(),
7983        })
7984    })?;
7985    if target.is_empty() {
7986        let pos = table
7987            .indices()
7988            .iter()
7989            .find_map(|idx| {
7990                if matches!(idx.kind, spg_storage::IndexKind::BTree(_))
7991                    && idx.partial_predicate.is_none()
7992                    && idx.included_columns.is_empty()
7993                    && idx.expression.is_none()
7994                {
7995                    Some(idx.column_position)
7996                } else {
7997                    None
7998                }
7999            })
8000            .ok_or_else(|| {
8001                EngineError::Unsupported(alloc::format!(
8002                    "ON CONFLICT without target requires a UNIQUE BTree index on {table_name:?}"
8003                ))
8004            })?;
8005        return Ok(alloc::vec![pos]);
8006    }
8007    let mut out = Vec::with_capacity(target.len());
8008    for name in target {
8009        let pos = table
8010            .schema()
8011            .columns
8012            .iter()
8013            .position(|c| c.name == *name)
8014            .ok_or_else(|| {
8015                EngineError::Unsupported(alloc::format!(
8016                    "ON CONFLICT target column {name:?} not found on {table_name:?}"
8017                ))
8018            })?;
8019        out.push(pos);
8020    }
8021    Ok(out)
8022}
8023
8024/// v7.9.8 — check whether the BTree index on `column_pos` of
8025/// `table_name` already has a row with this key.
8026fn on_conflict_key_exists(
8027    catalog: &Catalog,
8028    table_name: &str,
8029    column_pos: usize,
8030    key: &Value,
8031) -> bool {
8032    let Some(table) = catalog.get(table_name) else {
8033        return false;
8034    };
8035    let Some(idx_key) = spg_storage::IndexKey::from_value(key) else {
8036        return false;
8037    };
8038    table.indices().iter().any(|idx| {
8039        matches!(idx.kind, spg_storage::IndexKind::BTree(_))
8040            && idx.column_position == column_pos
8041            && idx.partial_predicate.is_none()
8042            && !idx.lookup_eq(&idx_key).is_empty()
8043    })
8044}
8045
8046/// v7.9.9 / v7.9.10 — look up an existing row's position by
8047/// matching all `column_positions` against the incoming `key`
8048/// tuple. Single-column shape (one column) reduces to the
8049/// canonical PK lookup; composite shapes scan linearly until
8050/// every position matches.
8051fn lookup_row_position_by_keys(
8052    catalog: &Catalog,
8053    table_name: &str,
8054    column_positions: &[usize],
8055    key: &[&Value],
8056) -> Option<usize> {
8057    let table = catalog.get(table_name)?;
8058    table.rows().iter().position(|r| {
8059        column_positions
8060            .iter()
8061            .enumerate()
8062            .all(|(i, &pos)| r.values.get(pos) == Some(key[i]))
8063    })
8064}
8065
8066/// v7.9.10 — does the table already contain a row whose
8067/// `column_positions` tuple equals `key`? Single-column shape
8068/// uses the existing BTree fast path; composite shapes fall
8069/// back to a row scan.
8070fn on_conflict_keys_exist(
8071    catalog: &Catalog,
8072    table_name: &str,
8073    column_positions: &[usize],
8074    key: &[&Value],
8075) -> bool {
8076    if column_positions.len() == 1 {
8077        return on_conflict_key_exists(catalog, table_name, column_positions[0], key[0]);
8078    }
8079    let Some(table) = catalog.get(table_name) else {
8080        return false;
8081    };
8082    table.rows().iter().any(|r| {
8083        column_positions
8084            .iter()
8085            .enumerate()
8086            .all(|(i, &pos)| r.values.get(pos) == Some(key[i]))
8087    })
8088}
8089
8090/// v7.9.9 — apply ON CONFLICT DO UPDATE SET assignments to an
8091/// existing row.
8092///
8093/// `incoming` is the rejected INSERT row (used to resolve
8094/// `EXCLUDED.col` references in the assignment exprs);
8095/// `target_pos` is the position of the existing row in the table.
8096/// Each assignment substitutes `EXCLUDED.col` with the matching
8097/// incoming value, evaluates the resulting expression against
8098/// the existing row, and writes the new value into the
8099/// corresponding column of the returned `Vec<Value>`. If
8100/// `where_` evaluates falsy, returns Ok(None) — PG behaviour:
8101/// the conflicting row is silently kept unchanged.
8102fn apply_on_conflict_assignments(
8103    catalog: &Catalog,
8104    table_name: &str,
8105    target_pos: usize,
8106    incoming: &[Value],
8107    assignments: &[(String, Expr)],
8108    where_: Option<&Expr>,
8109) -> Result<Option<Vec<Value>>, EngineError> {
8110    let table = catalog.get(table_name).ok_or_else(|| {
8111        EngineError::Storage(StorageError::TableNotFound {
8112            name: table_name.into(),
8113        })
8114    })?;
8115    let schema_cols = table.schema().columns.clone();
8116    let existing = table
8117        .rows()
8118        .get(target_pos)
8119        .ok_or_else(|| {
8120            EngineError::Unsupported(alloc::format!(
8121                "ON CONFLICT DO UPDATE: row position {target_pos} out of bounds on {table_name:?}"
8122            ))
8123        })?
8124        .clone();
8125    let ctx = eval::EvalContext::new(&schema_cols, Some(table_name));
8126    // Optional WHERE filter on the conflict row.
8127    if let Some(w) = where_ {
8128        let pred = w.clone();
8129        let pred = substitute_excluded_refs(pred, &schema_cols, incoming);
8130        let v = eval::eval_expr(&pred, &existing, &ctx)?;
8131        if !matches!(v, Value::Bool(true)) {
8132            return Ok(None);
8133        }
8134    }
8135    let mut new_values = existing.values.clone();
8136    for (col_name, expr) in assignments {
8137        let target_idx = schema_cols
8138            .iter()
8139            .position(|c| c.name == *col_name)
8140            .ok_or_else(|| {
8141                EngineError::Eval(EvalError::ColumnNotFound {
8142                    name: col_name.clone(),
8143                })
8144            })?;
8145        let sub = substitute_excluded_refs(expr.clone(), &schema_cols, incoming);
8146        let v = eval::eval_expr(&sub, &existing, &ctx)?;
8147        new_values[target_idx] = coerce_value(v, schema_cols[target_idx].ty, col_name, target_idx)?;
8148    }
8149    Ok(Some(new_values))
8150}
8151
8152/// v7.9.9 — walk an `Expr` tree replacing any `Column { qualifier:
8153/// "EXCLUDED", name }` reference with a `Literal` of the matching
8154/// value from the incoming-row vec. Resolution against the
8155/// child-table column list (by name).
8156fn substitute_excluded_refs(expr: Expr, schema_cols: &[ColumnSchema], incoming: &[Value]) -> Expr {
8157    use spg_sql::ast::ColumnName;
8158    match expr {
8159        Expr::Column(ColumnName { qualifier, name })
8160            if qualifier
8161                .as_deref()
8162                .is_some_and(|q| q.eq_ignore_ascii_case("excluded")) =>
8163        {
8164            let pos = schema_cols.iter().position(|c| c.name == name);
8165            match pos {
8166                Some(p) => {
8167                    let v = incoming.get(p).cloned().unwrap_or(Value::Null);
8168                    value_to_literal_expr(v)
8169                        .unwrap_or_else(|_| Expr::Literal(spg_sql::ast::Literal::Null))
8170                }
8171                None => Expr::Column(ColumnName { qualifier, name }),
8172            }
8173        }
8174        Expr::Binary { op, lhs, rhs } => Expr::Binary {
8175            op,
8176            lhs: Box::new(substitute_excluded_refs(*lhs, schema_cols, incoming)),
8177            rhs: Box::new(substitute_excluded_refs(*rhs, schema_cols, incoming)),
8178        },
8179        Expr::Unary { op, expr } => Expr::Unary {
8180            op,
8181            expr: Box::new(substitute_excluded_refs(*expr, schema_cols, incoming)),
8182        },
8183        Expr::FunctionCall { name, args } => Expr::FunctionCall {
8184            name,
8185            args: args
8186                .into_iter()
8187                .map(|a| substitute_excluded_refs(a, schema_cols, incoming))
8188                .collect(),
8189        },
8190        other => other,
8191    }
8192}
8193
8194/// v7.6.2 / v7.6.7 — INSERT-side FK enforcement. For every row
8195/// about to be inserted into `child_table`, every FK declared on
8196/// that table is checked: the row's FK columns must either be
8197/// NULL (SQL spec skip) or match an existing parent row via the
8198/// parent's BTree PK / UNIQUE index.
8199///
8200/// Returns `EngineError::Unsupported` with a `FOREIGN KEY violation`
8201/// payload on first failure.
8202///
8203/// **Self-referencing FKs (v7.6.7 widening):** when `fk.parent_table
8204/// == child_table`, the parent rows visible to this check are
8205///  (a) rows already committed to the table, plus
8206///  (b) earlier rows from the *same* `rows` batch.
8207/// This makes `INSERT INTO tree VALUES (1, NULL), (2, 1), (3, 2)`
8208/// work in a single statement — common pattern for bulk-loading
8209/// hierarchies.
8210/// v7.9.19 — enforce table-level UNIQUE / PRIMARY KEY tuple
8211/// constraints at INSERT time. For each constraint declared on
8212/// the target table, check that no existing row + no earlier row
8213/// in the same batch has the same full-column tuple. NULL in
8214/// any column lifts the row out of the check (SQL spec: NULL
8215/// ≠ NULL for uniqueness). mailrs G1 + G6.
8216fn enforce_uniqueness_inserts(
8217    catalog: &Catalog,
8218    child_table: &str,
8219    constraints: &[spg_storage::UniquenessConstraint],
8220    rows: &[Vec<Value>],
8221) -> Result<(), EngineError> {
8222    if constraints.is_empty() {
8223        return Ok(());
8224    }
8225    let table = catalog.get(child_table).ok_or_else(|| {
8226        EngineError::Storage(StorageError::TableNotFound {
8227            name: child_table.into(),
8228        })
8229    })?;
8230    for uc in constraints {
8231        for (batch_idx, row_values) in rows.iter().enumerate() {
8232            let key: Vec<&Value> = uc.columns.iter().map(|&i| &row_values[i]).collect();
8233            let has_null = key.iter().any(|v| matches!(v, Value::Null));
8234            if has_null {
8235                continue;
8236            }
8237            // Table-side collision: scan existing rows.
8238            let collides_in_table = table.rows().iter().any(|prow| {
8239                uc.columns
8240                    .iter()
8241                    .enumerate()
8242                    .all(|(i, &p)| prow.values.get(p) == Some(key[i]))
8243            });
8244            // Batch-side collision: earlier rows in the same INSERT.
8245            let collides_in_batch = rows[..batch_idx].iter().any(|earlier| {
8246                uc.columns
8247                    .iter()
8248                    .enumerate()
8249                    .all(|(i, &p)| earlier.get(p) == Some(key[i]))
8250            });
8251            if collides_in_table || collides_in_batch {
8252                let kind = if uc.is_primary_key {
8253                    "PRIMARY KEY"
8254                } else {
8255                    "UNIQUE"
8256                };
8257                let col_names: Vec<String> = uc
8258                    .columns
8259                    .iter()
8260                    .map(|&i| table.schema().columns[i].name.clone())
8261                    .collect();
8262                return Err(EngineError::Unsupported(alloc::format!(
8263                    "{kind} violation on {child_table:?} columns {col_names:?}: \
8264                     row #{batch_idx} duplicates an existing key"
8265                )));
8266            }
8267        }
8268    }
8269    Ok(())
8270}
8271
8272/// v7.9.29 — `true` iff `v` counts as a truthy SQL value for a
8273/// WHERE-style predicate. NULL → false (three-valued logic
8274/// collapses to "skip this row" for index inclusion). Numeric
8275/// non-zero, BIGINT non-zero, TINYINT non-zero, BOOLEAN true → true.
8276/// Everything else (strings, vectors, JSON, …) is not a valid
8277/// predicate result and surfaces as `false` so a malformed
8278/// predicate degrades to "row not in index" rather than panicking.
8279fn predicate_truthy(v: &spg_storage::Value) -> bool {
8280    use spg_storage::Value as V;
8281    match v {
8282        V::Bool(b) => *b,
8283        V::Int(n) => *n != 0,
8284        V::BigInt(n) => *n != 0,
8285        V::SmallInt(n) => *n != 0,
8286        _ => false,
8287    }
8288}
8289
8290/// v7.9.29 — at CREATE UNIQUE INDEX time, scan the table's
8291/// committed rows for pre-existing duplicates. If any pair of rows
8292/// matches the predicate AND has the same index key, refuse to
8293/// create the index so the user fixes the data before retrying.
8294fn check_existing_unique_violation(
8295    idx: &spg_storage::Index,
8296    schema: &spg_storage::TableSchema,
8297    rows: &[spg_storage::Row],
8298) -> Result<(), EngineError> {
8299    let predicate_expr = match idx.partial_predicate.as_deref() {
8300        Some(s) => Some(spg_sql::parser::parse_expression(s).map_err(|e| {
8301            EngineError::Unsupported(alloc::format!(
8302                "stored partial predicate {s:?} failed to re-parse: {e:?}"
8303            ))
8304        })?),
8305        None => None,
8306    };
8307    let ctx = eval::EvalContext::new(&schema.columns, None);
8308    let key_positions = unique_key_positions(idx);
8309    let mut seen: alloc::vec::Vec<alloc::vec::Vec<spg_storage::Value>> = alloc::vec::Vec::new();
8310    for row in rows {
8311        if let Some(expr) = &predicate_expr {
8312            let v = eval::eval_expr(expr, row, &ctx).map_err(|e| {
8313                EngineError::Unsupported(alloc::format!(
8314                    "evaluating UNIQUE INDEX predicate against existing row: {e:?}"
8315                ))
8316            })?;
8317            if !predicate_truthy(&v) {
8318                continue;
8319            }
8320        }
8321        let key: alloc::vec::Vec<spg_storage::Value> = key_positions
8322            .iter()
8323            .map(|&p| {
8324                row.values
8325                    .get(p)
8326                    .cloned()
8327                    .unwrap_or(spg_storage::Value::Null)
8328            })
8329            .collect();
8330        if key.iter().any(|v| matches!(v, spg_storage::Value::Null)) {
8331            continue;
8332        }
8333        if seen.iter().any(|other| *other == key) {
8334            return Err(EngineError::Unsupported(alloc::format!(
8335                "CREATE UNIQUE INDEX {:?}: existing rows already violate the constraint",
8336                idx.name
8337            )));
8338        }
8339        seen.push(key);
8340    }
8341    Ok(())
8342}
8343
8344/// v7.9.29 — full key tuple for a UNIQUE INDEX (leading +
8345/// extra positions). For single-column indexes this is just
8346/// `[column_position]`.
8347fn unique_key_positions(idx: &spg_storage::Index) -> alloc::vec::Vec<usize> {
8348    let mut out = alloc::vec::Vec::with_capacity(1 + idx.extra_column_positions.len());
8349    out.push(idx.column_position);
8350    out.extend_from_slice(&idx.extra_column_positions);
8351    out
8352}
8353
8354/// v7.9.29 — at INSERT time, walk every `is_unique` index on the
8355/// target table. For each, eval the index's optional predicate
8356/// against (a) the candidate row and (b) every committed row plus
8357/// earlier batch rows; only rows where the predicate is truthy
8358/// participate. A duplicate key among predicate-matching rows is a
8359/// uniqueness violation. NULL keys lift the row out of the check
8360/// (matching PG's "UNIQUE allows multiple NULLs" semantics).
8361fn enforce_unique_index_inserts(
8362    catalog: &Catalog,
8363    table_name: &str,
8364    rows: &[alloc::vec::Vec<spg_storage::Value>],
8365) -> Result<(), EngineError> {
8366    let table = catalog.get(table_name).ok_or_else(|| {
8367        EngineError::Storage(StorageError::TableNotFound {
8368            name: table_name.into(),
8369        })
8370    })?;
8371    let schema = table.schema();
8372    let ctx = eval::EvalContext::new(&schema.columns, None);
8373    for idx in table.indices() {
8374        if !idx.is_unique {
8375            continue;
8376        }
8377        // Re-parse the predicate once per index per batch.
8378        let predicate_expr = match idx.partial_predicate.as_deref() {
8379            Some(s) => Some(spg_sql::parser::parse_expression(s).map_err(|e| {
8380                EngineError::Unsupported(alloc::format!(
8381                    "UNIQUE INDEX {:?} predicate {s:?} failed to re-parse: {e:?}",
8382                    idx.name
8383                ))
8384            })?),
8385            None => None,
8386        };
8387        let key_positions = unique_key_positions(idx);
8388        let key_of = |values: &[spg_storage::Value]| -> alloc::vec::Vec<spg_storage::Value> {
8389            key_positions
8390                .iter()
8391                .map(|&p| values.get(p).cloned().unwrap_or(spg_storage::Value::Null))
8392                .collect()
8393        };
8394        // Helper: does `values` participate in this index? (predicate
8395        // truthy when present.) Wraps `values` into a transient Row
8396        // because eval_expr requires &Row.
8397        let participates = |values: &[spg_storage::Value]| -> Result<bool, EngineError> {
8398            let Some(expr) = &predicate_expr else {
8399                return Ok(true);
8400            };
8401            let tmp_row = spg_storage::Row {
8402                values: values.to_vec(),
8403            };
8404            let v = eval::eval_expr(expr, &tmp_row, &ctx).map_err(|e| {
8405                EngineError::Unsupported(alloc::format!(
8406                    "UNIQUE INDEX {:?} predicate eval: {e:?}",
8407                    idx.name
8408                ))
8409            })?;
8410            Ok(predicate_truthy(&v))
8411        };
8412        for (batch_idx, row_values) in rows.iter().enumerate() {
8413            if !participates(row_values)? {
8414                continue;
8415            }
8416            let key = key_of(row_values);
8417            if key.iter().any(|v| matches!(v, spg_storage::Value::Null)) {
8418                continue;
8419            }
8420            // Committed-table collision.
8421            for prow in table.rows() {
8422                if !participates(&prow.values)? {
8423                    continue;
8424                }
8425                if key_of(&prow.values) == key {
8426                    return Err(EngineError::Unsupported(alloc::format!(
8427                        "UNIQUE INDEX {:?} violation on {table_name:?}: \
8428                         row #{batch_idx} duplicates an existing key",
8429                        idx.name
8430                    )));
8431                }
8432            }
8433            // Within-batch collision: earlier rows in the same INSERT.
8434            for earlier in &rows[..batch_idx] {
8435                if !participates(earlier)? {
8436                    continue;
8437                }
8438                if key_of(earlier) == key {
8439                    return Err(EngineError::Unsupported(alloc::format!(
8440                        "UNIQUE INDEX {:?} violation on {table_name:?}: \
8441                         row #{batch_idx} duplicates an earlier row in the same batch",
8442                        idx.name
8443                    )));
8444                }
8445            }
8446        }
8447    }
8448    Ok(())
8449}
8450
8451fn enforce_fk_inserts(
8452    catalog: &Catalog,
8453    child_table: &str,
8454    fks: &[spg_storage::ForeignKeyConstraint],
8455    rows: &[Vec<Value>],
8456) -> Result<(), EngineError> {
8457    for fk in fks {
8458        let parent_is_self = fk.parent_table == child_table;
8459        let parent = if parent_is_self {
8460            // Self-ref: read the current state of the same table.
8461            // The mut borrow on child has been dropped by the caller.
8462            catalog.get(child_table).ok_or_else(|| {
8463                EngineError::Storage(StorageError::TableNotFound {
8464                    name: child_table.into(),
8465                })
8466            })?
8467        } else {
8468            catalog.get(&fk.parent_table).ok_or_else(|| {
8469                EngineError::Storage(StorageError::TableNotFound {
8470                    name: fk.parent_table.clone(),
8471                })
8472            })?
8473        };
8474        for (batch_idx, row_values) in rows.iter().enumerate() {
8475            // Single-column FK fast path: try the parent's BTree
8476            // index for an O(log n) lookup. Composite FKs fall back
8477            // to a parent-row scan.
8478            if fk.local_columns.len() == 1 {
8479                let v = &row_values[fk.local_columns[0]];
8480                if matches!(v, Value::Null) {
8481                    continue;
8482                }
8483                let parent_col = fk.parent_columns[0];
8484                let key = spg_storage::IndexKey::from_value(v).ok_or_else(|| {
8485                    EngineError::Unsupported(alloc::format!(
8486                        "FOREIGN KEY column value of type {:?} is not index-eligible",
8487                        v.data_type()
8488                    ))
8489                })?;
8490                let present_committed = parent.indices().iter().any(|idx| {
8491                    matches!(idx.kind, spg_storage::IndexKind::BTree(_))
8492                        && idx.column_position == parent_col
8493                        && idx.partial_predicate.is_none()
8494                        && !idx.lookup_eq(&key).is_empty()
8495                });
8496                // v7.6.7 self-ref widening: also accept a match
8497                // against earlier rows in this same batch when the
8498                // FK points at the table being inserted into.
8499                let present_in_batch = parent_is_self
8500                    && rows[..batch_idx]
8501                        .iter()
8502                        .any(|earlier| earlier.get(parent_col) == Some(v));
8503                if !(present_committed || present_in_batch) {
8504                    return Err(EngineError::Unsupported(alloc::format!(
8505                        "FOREIGN KEY violation: no parent row in {:?} where {} = {:?}",
8506                        fk.parent_table,
8507                        parent
8508                            .schema()
8509                            .columns
8510                            .get(parent_col)
8511                            .map_or("?", |c| c.name.as_str()),
8512                        v,
8513                    )));
8514                }
8515            } else {
8516                // Composite FK: scan parent rows. v7.6.7 also
8517                // accepts a match against earlier rows in the same
8518                // batch (self-ref bulk-loading of hierarchies).
8519                if fk
8520                    .local_columns
8521                    .iter()
8522                    .all(|&i| matches!(row_values.get(i), Some(Value::Null)))
8523                {
8524                    continue;
8525                }
8526                let local: Vec<&Value> = fk.local_columns.iter().map(|&i| &row_values[i]).collect();
8527                let parent_match_committed = parent.rows().iter().any(|prow| {
8528                    fk.parent_columns
8529                        .iter()
8530                        .enumerate()
8531                        .all(|(i, &pi)| prow.values.get(pi) == Some(local[i]))
8532                });
8533                let parent_match_in_batch = parent_is_self
8534                    && rows[..batch_idx].iter().any(|earlier| {
8535                        fk.parent_columns
8536                            .iter()
8537                            .enumerate()
8538                            .all(|(i, &pi)| earlier.get(pi) == Some(local[i]))
8539                    });
8540                if !(parent_match_committed || parent_match_in_batch) {
8541                    return Err(EngineError::Unsupported(alloc::format!(
8542                        "FOREIGN KEY violation: no parent row in {:?} matching composite key",
8543                        fk.parent_table,
8544                    )));
8545                }
8546            }
8547        }
8548    }
8549    Ok(())
8550}
8551
8552/// v7.6.4 / v7.6.5 — one step of the FK action plan computed for a
8553/// DELETE on a parent. The plan is a list of these steps, stacked
8554/// across the FK graph by `plan_fk_parent_deletions`.
8555#[derive(Debug, Clone)]
8556struct FkChildStep {
8557    child_table: String,
8558    action: FkChildAction,
8559}
8560
8561#[derive(Debug, Clone)]
8562enum FkChildAction {
8563    /// CASCADE — remove these rows. Sorted, deduplicated positions.
8564    Delete { positions: Vec<usize> },
8565    /// SET NULL — for each (row, column) in the flat list, write
8566    /// NULL into that child cell. Multiple FKs on the same row may
8567    /// produce overlapping entries (deduped at plan time).
8568    SetNull {
8569        positions: Vec<usize>,
8570        columns: Vec<usize>,
8571    },
8572    /// SET DEFAULT — same shape as SetNull but writes the column's
8573    /// declared DEFAULT value (resolved at plan time). Columns
8574    /// without a DEFAULT raise an error during planning.
8575    SetDefault {
8576        positions: Vec<usize>,
8577        columns: Vec<usize>,
8578        defaults: Vec<Value>,
8579    },
8580}
8581
8582/// v7.6.3 → v7.6.5 — plan FK fallout for a DELETE on a parent table.
8583///
8584/// Walks every table in the catalog looking for FKs whose
8585/// `parent_table` is `parent_table_name`. For each such FK + each
8586/// to-be-deleted parent row:
8587///
8588///   - RESTRICT / NoAction → error, no plan returned
8589///   - CASCADE → child rows get scheduled for deletion; recursive
8590///   - SetNull → child FK column(s) scheduled to be NULL-ed.
8591///     Verified NULL-able at plan time.
8592///   - SetDefault → child FK column(s) scheduled to be reset to
8593///     their declared DEFAULT. Columns without a DEFAULT raise.
8594///
8595/// SET NULL / SET DEFAULT do NOT cascade further — the child row
8596/// stays; only one of its columns mutates.
8597fn plan_fk_parent_deletions(
8598    catalog: &Catalog,
8599    parent_table_name: &str,
8600    to_delete_positions: &[usize],
8601    to_delete_rows: &[Vec<Value>],
8602) -> Result<Vec<FkChildStep>, EngineError> {
8603    use alloc::collections::{BTreeMap, BTreeSet};
8604    if to_delete_rows.is_empty() {
8605        return Ok(Vec::new());
8606    }
8607    let mut delete_plan: BTreeMap<String, BTreeSet<usize>> = BTreeMap::new();
8608    // setnull / setdefault keyed by child_table → (row_idx, col_idx) → optional default
8609    let mut setnull_plan: BTreeMap<String, BTreeSet<(usize, usize)>> = BTreeMap::new();
8610    let mut setdefault_plan: BTreeMap<String, BTreeMap<(usize, usize), Value>> = BTreeMap::new();
8611    let mut visited: BTreeSet<(String, usize)> = BTreeSet::new();
8612    for &p in to_delete_positions {
8613        visited.insert((parent_table_name.to_string(), p));
8614    }
8615    let mut work: Vec<(String, Vec<Value>)> = to_delete_rows
8616        .iter()
8617        .map(|r| (parent_table_name.to_string(), r.clone()))
8618        .collect();
8619    while let Some((cur_parent, parent_row)) = work.pop() {
8620        for child_name in catalog.table_names() {
8621            let child = catalog
8622                .get(&child_name)
8623                .expect("table_names → catalog.get round-trip is total");
8624            for fk in &child.schema().foreign_keys {
8625                if fk.parent_table != cur_parent {
8626                    continue;
8627                }
8628                let parent_key: Vec<&Value> = fk
8629                    .parent_columns
8630                    .iter()
8631                    .map(|&pi| &parent_row[pi])
8632                    .collect();
8633                if parent_key.iter().any(|v| matches!(v, Value::Null)) {
8634                    continue;
8635                }
8636                for (child_row_idx, child_row) in child.rows().iter().enumerate() {
8637                    if child_name == cur_parent
8638                        && visited.contains(&(child_name.clone(), child_row_idx))
8639                    {
8640                        continue;
8641                    }
8642                    let matches_key = fk
8643                        .local_columns
8644                        .iter()
8645                        .enumerate()
8646                        .all(|(i, &li)| child_row.values.get(li) == Some(parent_key[i]));
8647                    if !matches_key {
8648                        continue;
8649                    }
8650                    match fk.on_delete {
8651                        spg_storage::FkAction::Restrict | spg_storage::FkAction::NoAction => {
8652                            return Err(EngineError::Unsupported(alloc::format!(
8653                                "FOREIGN KEY violation: DELETE on {cur_parent:?} is \
8654                                 restricted by FK from {child_name:?}.{:?}",
8655                                fk.local_columns,
8656                            )));
8657                        }
8658                        spg_storage::FkAction::Cascade => {
8659                            if visited.insert((child_name.clone(), child_row_idx)) {
8660                                delete_plan
8661                                    .entry(child_name.clone())
8662                                    .or_default()
8663                                    .insert(child_row_idx);
8664                                work.push((child_name.clone(), child_row.values.clone()));
8665                            }
8666                        }
8667                        spg_storage::FkAction::SetNull => {
8668                            // Verify every local FK column is NULL-able.
8669                            for &li in &fk.local_columns {
8670                                let col = child.schema().columns.get(li).ok_or_else(|| {
8671                                    EngineError::Unsupported(alloc::format!(
8672                                        "FK local column {li} missing in {child_name:?}"
8673                                    ))
8674                                })?;
8675                                if !col.nullable {
8676                                    return Err(EngineError::Unsupported(alloc::format!(
8677                                        "FOREIGN KEY ON DELETE SET NULL: column \
8678                                         {child_name:?}.{:?} is NOT NULL — cannot SET NULL",
8679                                        col.name,
8680                                    )));
8681                                }
8682                            }
8683                            let entry = setnull_plan.entry(child_name.clone()).or_default();
8684                            for &li in &fk.local_columns {
8685                                entry.insert((child_row_idx, li));
8686                            }
8687                        }
8688                        spg_storage::FkAction::SetDefault => {
8689                            // Resolve the DEFAULT for every local FK col.
8690                            let entry = setdefault_plan.entry(child_name.clone()).or_default();
8691                            for &li in &fk.local_columns {
8692                                let col = child.schema().columns.get(li).ok_or_else(|| {
8693                                    EngineError::Unsupported(alloc::format!(
8694                                        "FK local column {li} missing in {child_name:?}"
8695                                    ))
8696                                })?;
8697                                let default = col.default.clone().ok_or_else(|| {
8698                                    EngineError::Unsupported(alloc::format!(
8699                                        "FOREIGN KEY ON DELETE SET DEFAULT: column \
8700                                         {child_name:?}.{:?} has no DEFAULT declared",
8701                                        col.name,
8702                                    ))
8703                                })?;
8704                                entry.insert((child_row_idx, li), default);
8705                            }
8706                        }
8707                    }
8708                }
8709            }
8710        }
8711    }
8712    // Flatten the three plans into the ordered `FkChildStep` list.
8713    // Deletes are applied last per child (after any null/default
8714    // re-writes on the same child) so a child row that's both
8715    // re-written and then cascade-deleted only ends up deleted —
8716    // but in v7.6.5 SetNull/Cascade never overlap on the same row
8717    // (a single FK chooses exactly one action), so the order is
8718    // mostly a precaution.
8719    let mut steps: Vec<FkChildStep> = Vec::new();
8720    for (child_table, entries) in setnull_plan {
8721        let (positions, columns): (Vec<usize>, Vec<usize>) = entries.into_iter().unzip();
8722        steps.push(FkChildStep {
8723            child_table,
8724            action: FkChildAction::SetNull { positions, columns },
8725        });
8726    }
8727    for (child_table, entries) in setdefault_plan {
8728        let mut positions = Vec::with_capacity(entries.len());
8729        let mut columns = Vec::with_capacity(entries.len());
8730        let mut defaults = Vec::with_capacity(entries.len());
8731        for ((p, c), v) in entries {
8732            positions.push(p);
8733            columns.push(c);
8734            defaults.push(v);
8735        }
8736        steps.push(FkChildStep {
8737            child_table,
8738            action: FkChildAction::SetDefault {
8739                positions,
8740                columns,
8741                defaults,
8742            },
8743        });
8744    }
8745    for (child_table, positions) in delete_plan {
8746        steps.push(FkChildStep {
8747            child_table,
8748            action: FkChildAction::Delete {
8749                positions: positions.into_iter().collect(),
8750            },
8751        });
8752    }
8753    Ok(steps)
8754}
8755
8756/// v7.6.6 — plan FK fallout for an UPDATE that mutates parent-side
8757/// PK/UNIQUE columns. Walks every other table whose FK references
8758/// `parent_table_name`; for each FK whose parent_columns overlap a
8759/// mutated column, decides the action by `fk.on_update`.
8760///
8761///   - RESTRICT / NoAction → error if any child references the OLD
8762///     value
8763///   - CASCADE → child FK columns get rewritten to the NEW parent
8764///     value (a SetNull-style update step with the new value)
8765///   - SetNull → child FK columns set to NULL
8766///   - SetDefault → child FK columns set to declared default
8767///
8768/// `plan_with_old` is `(row_position, old_values, new_values)` so
8769/// the planner can detect "did this row's parent key actually
8770/// change?" — only rows where at least one referenced parent
8771/// column moved trigger inbound work.
8772fn plan_fk_parent_updates(
8773    catalog: &Catalog,
8774    parent_table_name: &str,
8775    plan_with_old: &[(usize, Vec<Value>, Vec<Value>)],
8776) -> Result<Vec<FkChildStep>, EngineError> {
8777    use alloc::collections::BTreeMap;
8778    if plan_with_old.is_empty() {
8779        return Ok(Vec::new());
8780    }
8781    // For each child table we may touch, build per-child step
8782    // lists. UPDATE never deletes children — `delete_plan` stays
8783    // empty here but is kept structurally aligned with
8784    // `plan_fk_parent_deletions` for future use.
8785    let delete_plan: BTreeMap<String, alloc::collections::BTreeSet<usize>> = BTreeMap::new();
8786    let mut setnull_plan: BTreeMap<String, alloc::collections::BTreeSet<(usize, usize)>> =
8787        BTreeMap::new();
8788    let mut setdefault_plan: BTreeMap<String, BTreeMap<(usize, usize), Value>> = BTreeMap::new();
8789    // Cascade-update plan: child_table → row_idx → col_idx → new_value
8790    let mut cascade_plan: BTreeMap<String, BTreeMap<(usize, usize), Value>> = BTreeMap::new();
8791
8792    for child_name in catalog.table_names() {
8793        let child = catalog
8794            .get(&child_name)
8795            .expect("table_names → catalog.get total");
8796        for fk in &child.schema().foreign_keys {
8797            if fk.parent_table != parent_table_name {
8798                continue;
8799            }
8800            for (_pos, old_row, new_row) in plan_with_old {
8801                // Did any parent FK column change?
8802                let key_changed = fk
8803                    .parent_columns
8804                    .iter()
8805                    .any(|&pi| old_row.get(pi) != new_row.get(pi));
8806                if !key_changed {
8807                    continue;
8808                }
8809                // The OLD parent key — used to find referring children.
8810                let old_key: Vec<&Value> =
8811                    fk.parent_columns.iter().map(|&pi| &old_row[pi]).collect();
8812                if old_key.iter().any(|v| matches!(v, Value::Null)) {
8813                    // NULL parent has no children — skip.
8814                    continue;
8815                }
8816                let new_key: Vec<&Value> =
8817                    fk.parent_columns.iter().map(|&pi| &new_row[pi]).collect();
8818                for (child_row_idx, child_row) in child.rows().iter().enumerate() {
8819                    // Self-ref same-row updates: a row updating its
8820                    // own PK doesn't restrict itself.
8821                    if child_name == parent_table_name
8822                        && plan_with_old.iter().any(|(p, _, _)| *p == child_row_idx)
8823                    {
8824                        continue;
8825                    }
8826                    let matches_key = fk
8827                        .local_columns
8828                        .iter()
8829                        .enumerate()
8830                        .all(|(i, &li)| child_row.values.get(li) == Some(old_key[i]));
8831                    if !matches_key {
8832                        continue;
8833                    }
8834                    match fk.on_update {
8835                        spg_storage::FkAction::Restrict | spg_storage::FkAction::NoAction => {
8836                            return Err(EngineError::Unsupported(alloc::format!(
8837                                "FOREIGN KEY violation: UPDATE on {parent_table_name:?} PK is \
8838                                 restricted by FK from {child_name:?}.{:?}",
8839                                fk.local_columns,
8840                            )));
8841                        }
8842                        spg_storage::FkAction::Cascade => {
8843                            // Rewrite child FK columns to new key.
8844                            let entry = cascade_plan.entry(child_name.clone()).or_default();
8845                            for (i, &li) in fk.local_columns.iter().enumerate() {
8846                                entry.insert((child_row_idx, li), new_key[i].clone());
8847                            }
8848                        }
8849                        spg_storage::FkAction::SetNull => {
8850                            for &li in &fk.local_columns {
8851                                let col = child.schema().columns.get(li).ok_or_else(|| {
8852                                    EngineError::Unsupported(alloc::format!(
8853                                        "FK local column {li} missing in {child_name:?}"
8854                                    ))
8855                                })?;
8856                                if !col.nullable {
8857                                    return Err(EngineError::Unsupported(alloc::format!(
8858                                        "FOREIGN KEY ON UPDATE SET NULL: column \
8859                                         {child_name:?}.{:?} is NOT NULL",
8860                                        col.name,
8861                                    )));
8862                                }
8863                            }
8864                            let entry = setnull_plan.entry(child_name.clone()).or_default();
8865                            for &li in &fk.local_columns {
8866                                entry.insert((child_row_idx, li));
8867                            }
8868                        }
8869                        spg_storage::FkAction::SetDefault => {
8870                            let entry = setdefault_plan.entry(child_name.clone()).or_default();
8871                            for &li in &fk.local_columns {
8872                                let col = child.schema().columns.get(li).ok_or_else(|| {
8873                                    EngineError::Unsupported(alloc::format!(
8874                                        "FK local column {li} missing in {child_name:?}"
8875                                    ))
8876                                })?;
8877                                let default = col.default.clone().ok_or_else(|| {
8878                                    EngineError::Unsupported(alloc::format!(
8879                                        "FOREIGN KEY ON UPDATE SET DEFAULT: column \
8880                                         {child_name:?}.{:?} has no DEFAULT",
8881                                        col.name,
8882                                    ))
8883                                })?;
8884                                entry.insert((child_row_idx, li), default);
8885                            }
8886                        }
8887                    }
8888                }
8889            }
8890        }
8891    }
8892    // Flatten into FkChildStep list. UPDATE doesn't produce
8893    // DeleteSteps (CASCADE on UPDATE just rewrites FK values).
8894    let mut steps: Vec<FkChildStep> = Vec::new();
8895    for (child_table, entries) in cascade_plan {
8896        let mut positions = Vec::with_capacity(entries.len());
8897        let mut columns = Vec::with_capacity(entries.len());
8898        let mut defaults = Vec::with_capacity(entries.len());
8899        for ((p, c), v) in entries {
8900            positions.push(p);
8901            columns.push(c);
8902            defaults.push(v);
8903        }
8904        // We reuse `FkChildAction::SetDefault` for cascade-update:
8905        // both shapes are "write a known value into specific cells"
8906        // — `apply_per_cell_writes` doesn't care whether the value
8907        // came from a DEFAULT declaration or a new parent key.
8908        steps.push(FkChildStep {
8909            child_table,
8910            action: FkChildAction::SetDefault {
8911                positions,
8912                columns,
8913                defaults,
8914            },
8915        });
8916    }
8917    for (child_table, entries) in setnull_plan {
8918        let (positions, columns): (Vec<usize>, Vec<usize>) = entries.into_iter().unzip();
8919        steps.push(FkChildStep {
8920            child_table,
8921            action: FkChildAction::SetNull { positions, columns },
8922        });
8923    }
8924    for (child_table, entries) in setdefault_plan {
8925        let mut positions = Vec::with_capacity(entries.len());
8926        let mut columns = Vec::with_capacity(entries.len());
8927        let mut defaults = Vec::with_capacity(entries.len());
8928        for ((p, c), v) in entries {
8929            positions.push(p);
8930            columns.push(c);
8931            defaults.push(v);
8932        }
8933        steps.push(FkChildStep {
8934            child_table,
8935            action: FkChildAction::SetDefault {
8936                positions,
8937                columns,
8938                defaults,
8939            },
8940        });
8941    }
8942    let _ = delete_plan; // UPDATE never deletes children.
8943    Ok(steps)
8944}
8945
8946/// v7.6.5 — apply one FK child step to the catalog. Encapsulates
8947/// the three action variants so the DELETE executor stays a
8948/// simple loop over the planned steps.
8949fn apply_fk_child_step(catalog: &mut Catalog, step: &FkChildStep) -> Result<(), EngineError> {
8950    let child = catalog.get_mut(&step.child_table).ok_or_else(|| {
8951        EngineError::Storage(StorageError::TableNotFound {
8952            name: step.child_table.clone(),
8953        })
8954    })?;
8955    match &step.action {
8956        FkChildAction::Delete { positions } => {
8957            let _ = child.delete_rows(positions);
8958        }
8959        FkChildAction::SetNull { positions, columns } => {
8960            apply_per_cell_writes(child, positions, columns, |_| Value::Null)?;
8961        }
8962        FkChildAction::SetDefault {
8963            positions,
8964            columns,
8965            defaults,
8966        } => {
8967            apply_per_cell_writes(child, positions, columns, |i| defaults[i].clone())?;
8968        }
8969    }
8970    Ok(())
8971}
8972
8973/// v7.6.5 — write new values into selected child cells via
8974/// `Table::update_row` (the catalog's existing UPDATE entry).
8975/// Groups writes by row position so multi-column updates on the
8976/// same row only call `update_row` once. `value_for(i)` produces
8977/// the new value for the i-th (position, column) entry.
8978fn apply_per_cell_writes(
8979    child: &mut spg_storage::Table,
8980    positions: &[usize],
8981    columns: &[usize],
8982    mut value_for: impl FnMut(usize) -> Value,
8983) -> Result<(), EngineError> {
8984    use alloc::collections::BTreeMap;
8985    let mut by_row: BTreeMap<usize, Vec<(usize, Value)>> = BTreeMap::new();
8986    for i in 0..positions.len() {
8987        by_row
8988            .entry(positions[i])
8989            .or_default()
8990            .push((columns[i], value_for(i)));
8991    }
8992    for (pos, mutations) in by_row {
8993        let mut new_values = child.rows()[pos].values.clone();
8994        for (col, v) in mutations {
8995            if let Some(slot) = new_values.get_mut(col) {
8996                *slot = v;
8997            }
8998        }
8999        child
9000            .update_row(pos, new_values)
9001            .map_err(EngineError::Storage)?;
9002    }
9003    Ok(())
9004}
9005
9006fn fk_action_sql_to_storage(a: spg_sql::ast::FkAction) -> spg_storage::FkAction {
9007    match a {
9008        spg_sql::ast::FkAction::Restrict => spg_storage::FkAction::Restrict,
9009        spg_sql::ast::FkAction::Cascade => spg_storage::FkAction::Cascade,
9010        spg_sql::ast::FkAction::SetNull => spg_storage::FkAction::SetNull,
9011        spg_sql::ast::FkAction::SetDefault => spg_storage::FkAction::SetDefault,
9012        spg_sql::ast::FkAction::NoAction => spg_storage::FkAction::NoAction,
9013    }
9014}
9015
9016/// v7.9.21 — resolve a column's DEFAULT for INSERT-time
9017/// default-fill. Free fn (rather than `&self`) so callers
9018/// with an active `&mut Table` borrow can still use it.
9019/// Literal defaults take the cached path (`col.default`);
9020/// runtime defaults hit `clock_fn` at each call. mailrs G4.
9021fn resolve_column_default_free(
9022    col: &ColumnSchema,
9023    clock_fn: Option<ClockFn>,
9024) -> Result<Value, EngineError> {
9025    if let Some(rt) = &col.runtime_default {
9026        return eval_runtime_default_free(rt, col.ty, clock_fn);
9027    }
9028    Ok(col.default.clone().unwrap_or(Value::Null))
9029}
9030
9031fn eval_runtime_default_free(
9032    rt: &str,
9033    ty: DataType,
9034    clock_fn: Option<ClockFn>,
9035) -> Result<Value, EngineError> {
9036    let s = rt.trim().to_ascii_lowercase();
9037    let canonical = s.trim_end_matches("()");
9038    let now_us = match clock_fn {
9039        Some(f) => f(),
9040        None => 0,
9041    };
9042    let v = match canonical {
9043        "now" | "current_timestamp" | "localtimestamp" => Value::Timestamp(now_us),
9044        "current_date" => Value::Date((now_us / 86_400_000_000) as i32),
9045        "current_time" | "localtime" => Value::Timestamp(now_us),
9046        other => {
9047            return Err(EngineError::Unsupported(alloc::format!(
9048                "runtime DEFAULT expression {other:?} not supported \
9049                 (v7.9.21 whitelist: now() / current_timestamp / \
9050                 current_date / current_time / localtimestamp / \
9051                 localtime)"
9052            )));
9053        }
9054    };
9055    coerce_value(v, ty, "DEFAULT", 0)
9056}
9057
9058/// v7.9.21 — true when a DEFAULT expression needs INSERT-time
9059/// evaluation rather than being cacheable as a literal Value.
9060/// FunctionCall is the immediate case (`now()`,
9061/// `current_timestamp`). Literal expressions and simple sign-
9062/// flipped numerics still take the static-cache path.
9063fn is_runtime_default_expr(expr: &Expr) -> bool {
9064    match expr {
9065        Expr::FunctionCall { .. } => true,
9066        Expr::Unary { expr, .. } => is_runtime_default_expr(expr),
9067        _ => false,
9068    }
9069}
9070
9071fn column_def_to_schema(c: ColumnDef) -> Result<ColumnSchema, EngineError> {
9072    let ty = column_type_to_data_type(c.ty);
9073    let mut schema = ColumnSchema::new(c.name.clone(), ty, c.nullable);
9074    if let Some(default_expr) = c.default {
9075        // v7.9.21 — distinguish literal defaults (evaluated once
9076        // at CREATE TABLE) from expression defaults (deferred to
9077        // INSERT). Function calls (`now()`, `current_timestamp`
9078        // — see v7.9.20 keyword promotion) take the runtime path.
9079        // Literals continue to cache. mailrs G4.
9080        if is_runtime_default_expr(&default_expr) {
9081            let display = alloc::format!("{default_expr}");
9082            schema = schema.with_runtime_default(display);
9083        } else {
9084            let raw = literal_expr_to_value(default_expr)?;
9085            let coerced = coerce_value(raw, ty, &c.name, 0)?;
9086            schema = schema.with_default(coerced);
9087        }
9088    }
9089    if c.auto_increment {
9090        // AUTO_INCREMENT only makes sense on integer-shaped columns.
9091        if !matches!(ty, DataType::SmallInt | DataType::Int | DataType::BigInt) {
9092            return Err(EngineError::Unsupported(alloc::format!(
9093                "AUTO_INCREMENT requires an integer column type, got {ty:?}"
9094            )));
9095        }
9096        schema = schema.with_auto_increment();
9097    }
9098    Ok(schema)
9099}
9100
9101/// v7.10.4 — decode a BYTEA literal. Accepts:
9102///   * `\xDEADBEEF` (case-insensitive hex; whitespace stripped)
9103///   * `Hello\000world` (backslash escape form; `\\` for literal backslash)
9104///   * Anything else → raw UTF-8 bytes of the input (PG accepts this too).
9105fn decode_bytea_literal(s: &str) -> Result<alloc::vec::Vec<u8>, &'static str> {
9106    let s = s.trim();
9107    if let Some(hex) = s.strip_prefix("\\x").or_else(|| s.strip_prefix("\\X")) {
9108        // Hex form. Each pair of hex digits → one byte.
9109        let cleaned: alloc::string::String = hex.chars().filter(|c| !c.is_whitespace()).collect();
9110        if cleaned.len() % 2 != 0 {
9111            return Err("odd-length hex literal");
9112        }
9113        let mut out = alloc::vec::Vec::with_capacity(cleaned.len() / 2);
9114        let cleaned_bytes = cleaned.as_bytes();
9115        for i in (0..cleaned_bytes.len()).step_by(2) {
9116            let hi = hex_nibble(cleaned_bytes[i])?;
9117            let lo = hex_nibble(cleaned_bytes[i + 1])?;
9118            out.push((hi << 4) | lo);
9119        }
9120        return Ok(out);
9121    }
9122    // Escape form or raw. Walk char-by-char; `\\` and `\NNN` octal
9123    // sequences decode; anything else is a literal byte.
9124    let bytes = s.as_bytes();
9125    let mut out = alloc::vec::Vec::with_capacity(bytes.len());
9126    let mut i = 0;
9127    while i < bytes.len() {
9128        let b = bytes[i];
9129        if b == b'\\' && i + 1 < bytes.len() {
9130            let n = bytes[i + 1];
9131            if n == b'\\' {
9132                out.push(b'\\');
9133                i += 2;
9134                continue;
9135            }
9136            if n.is_ascii_digit()
9137                && i + 3 < bytes.len()
9138                && bytes[i + 2].is_ascii_digit()
9139                && bytes[i + 3].is_ascii_digit()
9140            {
9141                let oct = |x: u8| (x - b'0') as u32;
9142                let v = oct(n) * 64 + oct(bytes[i + 2]) * 8 + oct(bytes[i + 3]);
9143                if v <= 0xFF {
9144                    out.push(v as u8);
9145                    i += 4;
9146                    continue;
9147                }
9148            }
9149        }
9150        out.push(b);
9151        i += 1;
9152    }
9153    Ok(out)
9154}
9155
9156fn hex_nibble(b: u8) -> Result<u8, &'static str> {
9157    match b {
9158        b'0'..=b'9' => Ok(b - b'0'),
9159        b'a'..=b'f' => Ok(b - b'a' + 10),
9160        b'A'..=b'F' => Ok(b - b'A' + 10),
9161        _ => Err("invalid hex digit"),
9162    }
9163}
9164
9165/// v7.10.11 — decode a PG TEXT[] external array form
9166/// (`{a,b,NULL}` with optional double-quoted elements). The
9167/// engine takes a leading/trailing `{`/`}` and splits at commas.
9168/// Quoted elements (`"hello, world"`) preserve embedded commas;
9169/// `\\` and `\"` decode to literal backslash / quote. Plain
9170/// unquoted `NULL` (case-insensitive) maps to `None`.
9171/// v7.11.13 — pick the array type for `ARRAY[lit, …]` from the
9172/// element values. Single-element-type rules:
9173///   - all NULL / all Text → TextArray
9174///   - all Int (or Int+NULL) → IntArray
9175///   - any BigInt without Text → BigIntArray (widening)
9176///   - any Text → TextArray (fallback; non-string elements
9177///     render as text)
9178fn array_literal_widen(items: alloc::vec::Vec<Value>) -> Value {
9179    let mut has_text = false;
9180    let mut has_bigint = false;
9181    let mut has_int = false;
9182    for v in &items {
9183        match v {
9184            Value::Null => {}
9185            Value::Text(_) | Value::Json(_) => has_text = true,
9186            Value::BigInt(_) => has_bigint = true,
9187            Value::Int(_) | Value::SmallInt(_) => has_int = true,
9188            _ => has_text = true,
9189        }
9190    }
9191    if has_text || (!has_bigint && !has_int) {
9192        let out: alloc::vec::Vec<Option<alloc::string::String>> = items
9193            .into_iter()
9194            .map(|v| match v {
9195                Value::Null => None,
9196                Value::Text(s) | Value::Json(s) => Some(s),
9197                other => Some(alloc::format!("{other:?}")),
9198            })
9199            .collect();
9200        return Value::TextArray(out);
9201    }
9202    if has_bigint {
9203        let out: alloc::vec::Vec<Option<i64>> = items
9204            .into_iter()
9205            .map(|v| match v {
9206                Value::Null => None,
9207                Value::Int(n) => Some(i64::from(n)),
9208                Value::SmallInt(n) => Some(i64::from(n)),
9209                Value::BigInt(n) => Some(n),
9210                _ => unreachable!("widen: unexpected non-integer in BigInt path"),
9211            })
9212            .collect();
9213        return Value::BigIntArray(out);
9214    }
9215    let out: alloc::vec::Vec<Option<i32>> = items
9216        .into_iter()
9217        .map(|v| match v {
9218            Value::Null => None,
9219            Value::Int(n) => Some(n),
9220            Value::SmallInt(n) => Some(i32::from(n)),
9221            _ => unreachable!("widen: unexpected non-i32-compatible in Int path"),
9222        })
9223        .collect();
9224    Value::IntArray(out)
9225}
9226
9227fn decode_text_array_literal(
9228    s: &str,
9229) -> Result<alloc::vec::Vec<Option<alloc::string::String>>, &'static str> {
9230    let trimmed = s.trim();
9231    let inner = trimmed
9232        .strip_prefix('{')
9233        .and_then(|x| x.strip_suffix('}'))
9234        .ok_or("TEXT[] literal must be enclosed in '{...}'")?;
9235    let mut out: alloc::vec::Vec<Option<alloc::string::String>> = alloc::vec::Vec::new();
9236    if inner.trim().is_empty() {
9237        return Ok(out);
9238    }
9239    let bytes = inner.as_bytes();
9240    let mut i = 0;
9241    while i <= bytes.len() {
9242        // Skip leading whitespace.
9243        while i < bytes.len() && (bytes[i] == b' ' || bytes[i] == b'\t') {
9244            i += 1;
9245        }
9246        // Quoted element.
9247        if i < bytes.len() && bytes[i] == b'"' {
9248            i += 1; // open quote
9249            let mut buf = alloc::string::String::new();
9250            while i < bytes.len() && bytes[i] != b'"' {
9251                if bytes[i] == b'\\' && i + 1 < bytes.len() {
9252                    buf.push(bytes[i + 1] as char);
9253                    i += 2;
9254                } else {
9255                    buf.push(bytes[i] as char);
9256                    i += 1;
9257                }
9258            }
9259            if i >= bytes.len() {
9260                return Err("unterminated quoted element");
9261            }
9262            i += 1; // close quote
9263            out.push(Some(buf));
9264        } else {
9265            // Unquoted element — read until next comma or end.
9266            let start = i;
9267            while i < bytes.len() && bytes[i] != b',' {
9268                i += 1;
9269            }
9270            let raw = inner[start..i].trim();
9271            if raw.eq_ignore_ascii_case("NULL") {
9272                out.push(None);
9273            } else {
9274                out.push(Some(alloc::string::ToString::to_string(raw)));
9275            }
9276        }
9277        // Skip whitespace, expect comma or end.
9278        while i < bytes.len() && (bytes[i] == b' ' || bytes[i] == b'\t') {
9279            i += 1;
9280        }
9281        if i >= bytes.len() {
9282            break;
9283        }
9284        if bytes[i] != b',' {
9285            return Err("expected ',' between TEXT[] elements");
9286        }
9287        i += 1;
9288    }
9289    Ok(out)
9290}
9291
9292/// v7.10.11 — encode a TEXT[] back into the PG external array
9293/// form. NULL elements become the literal `NULL`; elements
9294/// containing commas, quotes, backslashes, or braces are
9295/// double-quoted with `\\` / `\"` escapes.
9296fn encode_text_array(items: &[Option<alloc::string::String>]) -> alloc::string::String {
9297    let mut out = alloc::string::String::with_capacity(2 + items.len() * 8);
9298    out.push('{');
9299    for (i, item) in items.iter().enumerate() {
9300        if i > 0 {
9301            out.push(',');
9302        }
9303        match item {
9304            None => out.push_str("NULL"),
9305            Some(s) => {
9306                let needs_quote = s.is_empty()
9307                    || s.eq_ignore_ascii_case("NULL")
9308                    || s.chars()
9309                        .any(|c| matches!(c, ',' | '{' | '}' | '"' | '\\' | ' ' | '\t'));
9310                if needs_quote {
9311                    out.push('"');
9312                    for c in s.chars() {
9313                        if c == '"' || c == '\\' {
9314                            out.push('\\');
9315                        }
9316                        out.push(c);
9317                    }
9318                    out.push('"');
9319                } else {
9320                    out.push_str(s);
9321                }
9322            }
9323        }
9324    }
9325    out.push('}');
9326    out
9327}
9328
9329/// v7.10.4 — encode BYTEA bytes in PG hex output format
9330/// (`\x` prefix, lowercase hex pairs). Used by Text-side
9331/// round-trip + the wire layer's text-mode encoder.
9332fn encode_bytea_hex(b: &[u8]) -> alloc::string::String {
9333    let mut out = alloc::string::String::with_capacity(2 + 2 * b.len());
9334    out.push_str("\\x");
9335    for byte in b {
9336        let hi = byte >> 4;
9337        let lo = byte & 0x0F;
9338        out.push(hex_digit(hi));
9339        out.push(hex_digit(lo));
9340    }
9341    out
9342}
9343
9344const fn hex_digit(n: u8) -> char {
9345    match n {
9346        0..=9 => (b'0' + n) as char,
9347        10..=15 => (b'a' + n - 10) as char,
9348        _ => '?',
9349    }
9350}
9351
9352const fn column_type_to_data_type(t: ColumnTypeName) -> DataType {
9353    match t {
9354        ColumnTypeName::SmallInt => DataType::SmallInt,
9355        ColumnTypeName::Int => DataType::Int,
9356        ColumnTypeName::BigInt => DataType::BigInt,
9357        ColumnTypeName::Float => DataType::Float,
9358        ColumnTypeName::Text => DataType::Text,
9359        ColumnTypeName::Varchar(n) => DataType::Varchar(n),
9360        ColumnTypeName::Char(n) => DataType::Char(n),
9361        ColumnTypeName::Bool => DataType::Bool,
9362        ColumnTypeName::Vector { dim, encoding } => DataType::Vector {
9363            dim,
9364            encoding: match encoding {
9365                SqlVecEncoding::F32 => VecEncoding::F32,
9366                SqlVecEncoding::Sq8 => VecEncoding::Sq8,
9367                SqlVecEncoding::F16 => VecEncoding::F16,
9368            },
9369        },
9370        ColumnTypeName::Numeric(precision, scale) => DataType::Numeric { precision, scale },
9371        ColumnTypeName::Date => DataType::Date,
9372        ColumnTypeName::Timestamp => DataType::Timestamp,
9373        ColumnTypeName::Timestamptz => DataType::Timestamptz,
9374        ColumnTypeName::Json => DataType::Json,
9375        ColumnTypeName::Jsonb => DataType::Jsonb,
9376        ColumnTypeName::Bytes => DataType::Bytes,
9377        ColumnTypeName::TextArray => DataType::TextArray,
9378        ColumnTypeName::IntArray => DataType::IntArray,
9379        ColumnTypeName::BigIntArray => DataType::BigIntArray,
9380    }
9381}
9382
9383/// Convert an INSERT VALUES expression to a storage Value. Supports literal
9384/// expressions, unary-minus over numeric literals, and pgvector-style
9385/// `'[..]'::vector` cast (v1.2). Anything more complex returns `Unsupported`.
9386fn literal_expr_to_value(expr: Expr) -> Result<Value, EngineError> {
9387    match expr {
9388        Expr::Literal(l) => Ok(literal_to_value(l)),
9389        Expr::Cast { expr, target } => {
9390            let inner_value = literal_expr_to_value(*expr)?;
9391            crate::eval::cast_value(inner_value, target).map_err(EngineError::Eval)
9392        }
9393        Expr::Unary {
9394            op: UnOp::Neg,
9395            expr,
9396        } => match *expr {
9397            Expr::Literal(Literal::Integer(n)) => {
9398                // Fold to i32 if it fits, else BigInt. Parser emits Integer(i64)
9399                // — overflow on negate of i64::MIN is the one edge case.
9400                let neg = n.checked_neg().ok_or_else(|| {
9401                    EngineError::Unsupported("integer literal overflow on negation".into())
9402                })?;
9403                Ok(int_value_for(neg))
9404            }
9405            Expr::Literal(Literal::Float(x)) => Ok(Value::Float(-x)),
9406            other => Err(EngineError::Unsupported(alloc::format!(
9407                "unary minus over non-literal expression: {other:?}"
9408            ))),
9409        },
9410        // v7.10.10 — `ARRAY[lit, lit, …]` constructor accepted at
9411        // INSERT-time. Each element must reduce to a Value through
9412        // `literal_expr_to_value`; NULL elements become `None`.
9413        // v7.11.13 — deduce shape from element values: all Int →
9414        // IntArray; any BigInt → BigIntArray (widening); any Text
9415        // → TextArray. Cast targets (`ARRAY[]::INT[]`) flow through
9416        // the outer Cast arm before reaching here and re-coerce.
9417        Expr::Array(items) => {
9418            let mut materialised: alloc::vec::Vec<Value> = alloc::vec::Vec::with_capacity(items.len());
9419            for elem in items {
9420                materialised.push(literal_expr_to_value(elem)?);
9421            }
9422            Ok(array_literal_widen(materialised))
9423        }
9424        other => Err(EngineError::Unsupported(alloc::format!(
9425            "non-literal INSERT value expression: {other:?}"
9426        ))),
9427    }
9428}
9429
9430fn literal_to_value(l: Literal) -> Value {
9431    match l {
9432        Literal::Integer(n) => int_value_for(n),
9433        Literal::Float(x) => Value::Float(x),
9434        Literal::String(s) => Value::Text(s),
9435        Literal::Bool(b) => Value::Bool(b),
9436        Literal::Null => Value::Null,
9437        Literal::Vector(v) => Value::Vector(v),
9438        Literal::Interval { months, micros, .. } => Value::Interval { months, micros },
9439    }
9440}
9441
9442/// Pick `Int` (`i32`) when the literal fits, else `BigInt`. `INT` vs `BIGINT`
9443/// columns will still enforce the right tag downstream — this is just the
9444/// default we synthesise from an unannotated integer literal.
9445fn int_value_for(n: i64) -> Value {
9446    if let Ok(small) = i32::try_from(n) {
9447        Value::Int(small)
9448    } else {
9449        Value::BigInt(n)
9450    }
9451}
9452
9453/// Widen / narrow `v` to fit `expected`. Numerics permit safe widening
9454/// (`Int → BigInt`, `Int/BigInt → Float`) and best-effort narrowing
9455/// (`BigInt → Int` succeeds only when the value fits in `i32`). Everything
9456/// else returns `TypeMismatch` carrying the column name for caller diagnostics.
9457/// `NULL` is always permitted; the nullability check happens later in storage.
9458#[allow(clippy::too_many_lines)]
9459fn coerce_value(
9460    v: Value,
9461    expected: DataType,
9462    col_name: &str,
9463    position: usize,
9464) -> Result<Value, EngineError> {
9465    if v.is_null() {
9466        return Ok(Value::Null);
9467    }
9468    let actual = v.data_type().expect("non-null");
9469    if actual == expected {
9470        return Ok(v);
9471    }
9472    let coerced = match (v, expected) {
9473        (Value::Int(n), DataType::BigInt) => Some(Value::BigInt(i64::from(n))),
9474        (Value::Int(n), DataType::Float) => Some(Value::Float(f64::from(n))),
9475        (Value::Int(n), DataType::SmallInt) => i16::try_from(n).ok().map(Value::SmallInt),
9476        (Value::Int(n), DataType::Numeric { precision, scale }) => Some(numeric_from_integer(
9477            i128::from(n),
9478            precision,
9479            scale,
9480            col_name,
9481        )?),
9482        (Value::SmallInt(n), DataType::Int) => Some(Value::Int(i32::from(n))),
9483        (Value::SmallInt(n), DataType::BigInt) => Some(Value::BigInt(i64::from(n))),
9484        (Value::SmallInt(n), DataType::Float) => Some(Value::Float(f64::from(n))),
9485        (Value::SmallInt(n), DataType::Numeric { precision, scale }) => Some(numeric_from_integer(
9486            i128::from(n),
9487            precision,
9488            scale,
9489            col_name,
9490        )?),
9491        (Value::BigInt(n), DataType::Int) => i32::try_from(n).ok().map(Value::Int),
9492        (Value::BigInt(n), DataType::SmallInt) => i16::try_from(n).ok().map(Value::SmallInt),
9493        #[allow(clippy::cast_precision_loss)]
9494        (Value::BigInt(n), DataType::Float) => Some(Value::Float(n as f64)),
9495        (Value::BigInt(n), DataType::Numeric { precision, scale }) => Some(numeric_from_integer(
9496            i128::from(n),
9497            precision,
9498            scale,
9499            col_name,
9500        )?),
9501        (Value::Float(x), DataType::Numeric { precision, scale }) => {
9502            Some(numeric_from_float(x, precision, scale, col_name)?)
9503        }
9504        // Text → DATE / TIMESTAMP: parse canonical text forms.
9505        (Value::Text(s), DataType::Date) => {
9506            let d = eval::parse_date_literal(&s).ok_or_else(|| {
9507                EngineError::Eval(EvalError::TypeMismatch {
9508                    detail: alloc::format!("cannot parse {s:?} as DATE for column `{col_name}`"),
9509                })
9510            })?;
9511            Some(Value::Date(d))
9512        }
9513        // v4.9: Text ↔ JSON coercion. No structural validation —
9514        // any text literal is accepted; the responsibility for
9515        // valid JSON lies with the producer.
9516        (Value::Text(s), DataType::Json | DataType::Jsonb) => Some(Value::Json(s)),
9517        (Value::Json(s), DataType::Text) => Some(Value::Text(s)),
9518        // v7.10.4 — Text → BYTEA. Decode PG-style literal forms:
9519        //   - Hex:    `\x48656c6c6f`  (case-insensitive hex pairs)
9520        //   - Escape: `Hello\\000world`  (backslash + octal triples)
9521        //   - Plain:  any string → raw UTF-8 bytes (PG also accepts)
9522        // Errors surface as TypeMismatch so the operator gets a
9523        // clear "this literal isn't a bytea literal" hint.
9524        (Value::Text(s), DataType::Bytes) => {
9525            let bytes = decode_bytea_literal(&s).map_err(|e| {
9526                EngineError::Eval(EvalError::TypeMismatch {
9527                    detail: alloc::format!(
9528                        "cannot parse {s:?} as BYTEA for column `{col_name}`: {e}"
9529                    ),
9530                })
9531            })?;
9532            Some(Value::Bytes(bytes))
9533        }
9534        // v7.10.4 — BYTEA → Text round-trip uses the PG hex
9535        // output (lowercase, `\x` prefix). Important when a
9536        // SELECT pulls a bytea cell through a Text column path.
9537        (Value::Bytes(b), DataType::Text) => Some(Value::Text(encode_bytea_hex(&b))),
9538        // v7.10.11 — Text → TEXT[]. Decode PG's external array
9539        // form `'{a,b,NULL}'`. NULL element token (case-insensitive)
9540        // is the literal `NULL`; everything else is a quoted or
9541        // unquoted text element. mailrs `'{label1,label2}'::TEXT[]`.
9542        (Value::Text(s), DataType::TextArray) => {
9543            let arr = decode_text_array_literal(&s).map_err(|e| {
9544                EngineError::Eval(EvalError::TypeMismatch {
9545                    detail: alloc::format!(
9546                        "cannot parse {s:?} as TEXT[] for column `{col_name}`: {e}"
9547                    ),
9548                })
9549            })?;
9550            Some(Value::TextArray(arr))
9551        }
9552        // v7.10.11 — TEXT[] → Text round-trip uses PG's
9553        // external array form (`{a,b,NULL}`). Lets a SELECT
9554        // pull an array column through any Text-side codepath.
9555        (Value::TextArray(items), DataType::Text) => Some(Value::Text(encode_text_array(&items))),
9556        (Value::Text(s), DataType::Timestamp | DataType::Timestamptz) => {
9557            let t = eval::parse_timestamp_literal(&s).ok_or_else(|| {
9558                EngineError::Eval(EvalError::TypeMismatch {
9559                    detail: alloc::format!(
9560                        "cannot parse {s:?} as TIMESTAMP for column `{col_name}`"
9561                    ),
9562                })
9563            })?;
9564            Some(Value::Timestamp(t))
9565        }
9566        // DATE ↔ TIMESTAMP convertibility (DATE → midnight,
9567        // TIMESTAMP → day truncation).
9568        (Value::Date(d), DataType::Timestamp | DataType::Timestamptz) => {
9569            Some(Value::Timestamp(i64::from(d) * 86_400_000_000))
9570        }
9571        // v7.9.21 — Value::Timestamp lands in either Timestamp
9572        // or Timestamptz columns; the on-disk layout is the
9573        // same i64 microseconds UTC.
9574        (Value::Timestamp(t), DataType::Timestamptz) => Some(Value::Timestamp(t)),
9575        (Value::Timestamp(t), DataType::Date) => {
9576            let days = t.div_euclid(86_400_000_000);
9577            i32::try_from(days).ok().map(Value::Date)
9578        }
9579        (
9580            Value::Numeric {
9581                scaled,
9582                scale: src_scale,
9583            },
9584            DataType::Numeric { precision, scale },
9585        ) => Some(numeric_rescale(
9586            scaled, src_scale, precision, scale, col_name,
9587        )?),
9588        #[allow(clippy::cast_precision_loss)]
9589        (Value::Numeric { scaled, scale }, DataType::Float) => {
9590            let mut div = 1.0_f64;
9591            for _ in 0..scale {
9592                div *= 10.0;
9593            }
9594            Some(Value::Float((scaled as f64) / div))
9595        }
9596        (Value::Numeric { scaled, scale }, DataType::Int) => {
9597            let truncated = numeric_truncate_to_integer(scaled, scale);
9598            i32::try_from(truncated).ok().map(Value::Int)
9599        }
9600        (Value::Numeric { scaled, scale }, DataType::BigInt) => {
9601            let truncated = numeric_truncate_to_integer(scaled, scale);
9602            i64::try_from(truncated).ok().map(Value::BigInt)
9603        }
9604        (Value::Numeric { scaled, scale }, DataType::SmallInt) => {
9605            let truncated = numeric_truncate_to_integer(scaled, scale);
9606            i16::try_from(truncated).ok().map(Value::SmallInt)
9607        }
9608        // VARCHAR(n) enforces an upper bound on character count.
9609        (Value::Text(s), DataType::Varchar(max)) => {
9610            if u32::try_from(s.chars().count()).unwrap_or(u32::MAX) <= max {
9611                Some(Value::Text(s))
9612            } else {
9613                return Err(EngineError::Unsupported(alloc::format!(
9614                    "value for VARCHAR({max}) column `{col_name}` exceeds length: \
9615                     {} chars",
9616                    s.chars().count()
9617                )));
9618            }
9619        }
9620        // v6.0.1: f32 → SQ8 INSERT-time quantisation. Triggered
9621        // when the column declares `VECTOR(N) USING SQ8` and
9622        // the INSERT VALUES expression yields a raw f32 vector
9623        // (the normal pgvector-shape literal). Dim mismatch
9624        // falls through the `_ => None` arm and surfaces as
9625        // `TypeMismatch` with the expected SQ8 column type —
9626        // matching the F32 path's existing error.
9627        (
9628            Value::Vector(v),
9629            DataType::Vector {
9630                dim,
9631                encoding: VecEncoding::Sq8,
9632            },
9633        ) if v.len() == dim as usize => Some(Value::Sq8Vector(spg_storage::quantize::quantize(&v))),
9634        // v6.0.3: f32 → f16 INSERT-time conversion for HALF
9635        // columns. Bit-exact at the storage layer (modulo
9636        // half-precision rounding); no rerank pass needed at
9637        // search time.
9638        (
9639            Value::Vector(v),
9640            DataType::Vector {
9641                dim,
9642                encoding: VecEncoding::F16,
9643            },
9644        ) if v.len() == dim as usize => Some(Value::HalfVector(
9645            spg_storage::halfvec::HalfVector::from_f32_slice(&v),
9646        )),
9647        // CHAR(n) right-pads with U+0020 to exactly n chars; if the input
9648        // is already longer we reject (PG truncates trailing-space-only;
9649        // staying strict for v1).
9650        (Value::Text(s), DataType::Char(size)) => {
9651            let len = u32::try_from(s.chars().count()).unwrap_or(u32::MAX);
9652            if len > size {
9653                return Err(EngineError::Unsupported(alloc::format!(
9654                    "value for CHAR({size}) column `{col_name}` exceeds length: \
9655                     {len} chars"
9656                )));
9657            }
9658            let need = (size - len) as usize;
9659            let mut padded = s;
9660            padded.reserve(need);
9661            for _ in 0..need {
9662                padded.push(' ');
9663            }
9664            Some(Value::Text(padded))
9665        }
9666        _ => None,
9667    };
9668    coerced.ok_or(EngineError::Storage(StorageError::TypeMismatch {
9669        column: col_name.into(),
9670        expected,
9671        actual,
9672        position,
9673    }))
9674}
9675
9676#[cfg(test)]
9677mod tests {
9678    use super::*;
9679    use alloc::vec;
9680
9681    fn unwrap_command_ok(r: &QueryResult) -> usize {
9682        match r {
9683            QueryResult::CommandOk { affected, .. } => *affected,
9684            QueryResult::Rows { .. } => panic!("expected CommandOk, got Rows"),
9685        }
9686    }
9687
9688    #[test]
9689    fn create_table_registers_schema() {
9690        let mut e = Engine::new();
9691        e.execute("CREATE TABLE foo (a INT NOT NULL, b TEXT)")
9692            .unwrap();
9693        assert_eq!(e.catalog().table_count(), 1);
9694        let t = e.catalog().get("foo").unwrap();
9695        assert_eq!(t.schema().columns.len(), 2);
9696        assert_eq!(t.schema().columns[0].ty, DataType::Int);
9697        assert!(!t.schema().columns[0].nullable);
9698        assert_eq!(t.schema().columns[1].ty, DataType::Text);
9699    }
9700
9701    #[test]
9702    fn create_table_vector_default_is_f32_encoded() {
9703        let mut e = Engine::new();
9704        e.execute("CREATE TABLE t (v VECTOR(8))").unwrap();
9705        let t = e.catalog().get("t").unwrap();
9706        assert_eq!(
9707            t.schema().columns[0].ty,
9708            DataType::Vector {
9709                dim: 8,
9710                encoding: VecEncoding::F32,
9711            },
9712        );
9713    }
9714
9715    #[test]
9716    fn create_table_vector_using_sq8_succeeds() {
9717        // v6.0.1 step 3: the step-1 fence in `column_def_to_schema`
9718        // is lifted. CREATE TABLE persists an SQ8 column type in
9719        // the catalog; INSERT (next test) quantises raw f32 input.
9720        let mut e = Engine::new();
9721        e.execute("CREATE TABLE t (v VECTOR(8) USING SQ8)").unwrap();
9722        let t = e.catalog().get("t").unwrap();
9723        assert_eq!(
9724            t.schema().columns[0].ty,
9725            DataType::Vector {
9726                dim: 8,
9727                encoding: VecEncoding::Sq8,
9728            },
9729        );
9730    }
9731
9732    #[test]
9733    fn insert_into_sq8_column_quantises_f32_payload() {
9734        // v6.0.1 step 3: INSERT-time `coerce_value` rewrites a raw
9735        // `Value::Vector(Vec<f32>)` literal into the column's
9736        // quantised representation. The row that lands in the
9737        // catalog must therefore hold a `Value::Sq8Vector`, not the
9738        // original f32 buffer — that's the bit that delivers the
9739        // 4× compression target.
9740        let mut e = Engine::new();
9741        e.execute("CREATE TABLE t (v VECTOR(4) USING SQ8)").unwrap();
9742        e.execute("INSERT INTO t VALUES ([0.0, 0.25, 0.5, 1.0])")
9743            .unwrap();
9744        let t = e.catalog().get("t").unwrap();
9745        assert_eq!(t.rows().len(), 1);
9746        match &t.rows()[0].values[0] {
9747            Value::Sq8Vector(q) => {
9748                assert_eq!(q.bytes.len(), 4);
9749                // min/max are derived from the payload: min=0.0, max=1.0.
9750                assert!((q.min - 0.0).abs() < 1e-6);
9751                assert!((q.max - 1.0).abs() < 1e-6);
9752            }
9753            other => panic!("expected Sq8Vector cell, got {other:?}"),
9754        }
9755    }
9756
9757    #[test]
9758    fn create_table_vector_using_half_succeeds_and_insert_converts_to_f16() {
9759        // v6.0.3: CREATE TABLE accepts USING HALF; INSERT path
9760        // converts the incoming `Value::Vector(Vec<f32>)` cell
9761        // into `Value::HalfVector(HalfVector)` via the new
9762        // `coerce_value` arm. The dequantised round-trip is
9763        // bit-exact for f16-representable values, so 0.0 / 0.25
9764        // / 0.5 / 1.0 hit their grid points exactly.
9765        let mut e = Engine::new();
9766        e.execute("CREATE TABLE t (v VECTOR(4) USING HALF)")
9767            .unwrap();
9768        e.execute("INSERT INTO t VALUES ([0.0, 0.25, 0.5, 1.0])")
9769            .unwrap();
9770        let t = e.catalog().get("t").unwrap();
9771        assert_eq!(t.rows().len(), 1);
9772        match &t.rows()[0].values[0] {
9773            Value::HalfVector(h) => {
9774                assert_eq!(h.dim(), 4);
9775                let back = h.to_f32_vec();
9776                let expected = alloc::vec![0.0_f32, 0.25, 0.5, 1.0];
9777                for (g, e) in back.iter().zip(expected.iter()) {
9778                    assert!(
9779                        (g - e).abs() < 1e-6,
9780                        "{g} vs {e} should be exact on f16 grid"
9781                    );
9782                }
9783            }
9784            other => panic!("expected HalfVector cell, got {other:?}"),
9785        }
9786    }
9787
9788    #[test]
9789    fn alter_index_rebuild_in_place_succeeds() {
9790        // v6.0.4: bare REBUILD (no encoding switch) walks every
9791        // row again to rebuild the NSW graph. Verifies the engine
9792        // dispatch + storage helper plumbing without changing any
9793        // cell encoding.
9794        let mut e = Engine::new();
9795        e.execute("CREATE TABLE t (id INT NOT NULL, v VECTOR(3) NOT NULL)")
9796            .unwrap();
9797        for i in 0..8_i32 {
9798            #[allow(clippy::cast_precision_loss)]
9799            let base = (i as f32) * 0.1;
9800            e.execute(&alloc::format!(
9801                "INSERT INTO t VALUES ({i}, [{base}, {b1}, {b2}])",
9802                b1 = base + 0.01,
9803                b2 = base + 0.02,
9804            ))
9805            .unwrap();
9806        }
9807        e.execute("CREATE INDEX t_idx ON t USING hnsw (v)").unwrap();
9808        e.execute("ALTER INDEX t_idx REBUILD").unwrap();
9809        // Schema encoding stays F32 (no encoding clause).
9810        assert_eq!(
9811            e.catalog().get("t").unwrap().schema().columns[1].ty,
9812            DataType::Vector {
9813                dim: 3,
9814                encoding: VecEncoding::F32,
9815            },
9816        );
9817    }
9818
9819    #[test]
9820    fn alter_index_rebuild_with_encoding_switches_cell_type() {
9821        // v6.0.4: REBUILD WITH (encoding = SQ8) recodes every
9822        // stored cell from F32 → SQ8 + rebuilds the graph atop the
9823        // new encoding. Post-rebuild, cells must be Sq8Vector and
9824        // the schema must report encoding = Sq8.
9825        let mut e = Engine::new();
9826        e.execute("CREATE TABLE t (id INT NOT NULL, v VECTOR(4) NOT NULL)")
9827            .unwrap();
9828        e.execute("INSERT INTO t VALUES (1, [0.0, 0.25, 0.5, 1.0])")
9829            .unwrap();
9830        e.execute("CREATE INDEX t_idx ON t USING hnsw (v)").unwrap();
9831        e.execute("ALTER INDEX t_idx REBUILD WITH (encoding = SQ8)")
9832            .unwrap();
9833        let t = e.catalog().get("t").unwrap();
9834        assert_eq!(
9835            t.schema().columns[1].ty,
9836            DataType::Vector {
9837                dim: 4,
9838                encoding: VecEncoding::Sq8,
9839            },
9840        );
9841        assert!(matches!(t.rows()[0].values[1], Value::Sq8Vector(_)));
9842    }
9843
9844    #[test]
9845    fn alter_index_rebuild_unknown_index_errors() {
9846        let mut e = Engine::new();
9847        let err = e.execute("ALTER INDEX nope REBUILD").unwrap_err();
9848        assert!(
9849            matches!(
9850                &err,
9851                EngineError::Storage(StorageError::IndexNotFound { name }) if name == "nope"
9852            ),
9853            "got: {err}"
9854        );
9855    }
9856
9857    #[test]
9858    fn alter_index_rebuild_on_btree_index_errors() {
9859        // REBUILD on a B-tree index has no semantic meaning in
9860        // v6.0.4 — rejected at the storage layer with `Unsupported`.
9861        let mut e = Engine::new();
9862        e.execute("CREATE TABLE t (id INT NOT NULL)").unwrap();
9863        e.execute("INSERT INTO t VALUES (1)").unwrap();
9864        e.execute("CREATE INDEX t_idx ON t (id)").unwrap();
9865        let err = e.execute("ALTER INDEX t_idx REBUILD").unwrap_err();
9866        assert!(
9867            matches!(&err, EngineError::Storage(StorageError::Unsupported(_))),
9868            "got: {err}"
9869        );
9870    }
9871
9872    #[test]
9873    fn prepared_insert_substitutes_placeholders() {
9874        // v6.1.1: prepare() parses once; execute_prepared() walks the
9875        // AST and replaces $1/$2 with the param Values BEFORE the
9876        // dispatch sees them. Same logical result as a simple-query
9877        // INSERT, but parse happens once per *statement*, not per
9878        // execution.
9879        let mut e = Engine::new();
9880        e.execute("CREATE TABLE t (id INT NOT NULL, name TEXT NOT NULL)")
9881            .unwrap();
9882        let stmt = e.prepare("INSERT INTO t VALUES ($1, $2)").unwrap();
9883        for (id, name) in [(1, "alice"), (2, "bob"), (3, "carol")] {
9884            e.execute_prepared(stmt.clone(), &[Value::Int(id), Value::Text(name.into())])
9885                .unwrap();
9886        }
9887        // Read back via simple-query SELECT.
9888        let rows_result = e.execute("SELECT id, name FROM t").unwrap();
9889        let QueryResult::Rows { rows, .. } = rows_result else {
9890            panic!("expected Rows")
9891        };
9892        assert_eq!(rows.len(), 3);
9893    }
9894
9895    #[test]
9896    fn prepared_select_with_placeholder_filters_rows() {
9897        let mut e = Engine::new();
9898        e.execute("CREATE TABLE t (id INT NOT NULL, v INT NOT NULL)")
9899            .unwrap();
9900        for i in 0..10_i32 {
9901            e.execute(&alloc::format!("INSERT INTO t VALUES ({i}, {})", i * 7))
9902                .unwrap();
9903        }
9904        let stmt = e.prepare("SELECT id FROM t WHERE v = $1").unwrap();
9905        let QueryResult::Rows { rows, .. } = e.execute_prepared(stmt, &[Value::Int(35)]).unwrap()
9906        else {
9907            panic!("expected Rows")
9908        };
9909        // v = 35 means i*7 = 35 → i = 5.
9910        assert_eq!(rows.len(), 1);
9911        assert_eq!(rows[0].values[0], Value::Int(5));
9912    }
9913
9914    #[test]
9915    fn prepared_too_few_params_errors() {
9916        let mut e = Engine::new();
9917        e.execute("CREATE TABLE t (id INT NOT NULL)").unwrap();
9918        let stmt = e.prepare("INSERT INTO t VALUES ($1)").unwrap();
9919        let err = e.execute_prepared(stmt, &[]).unwrap_err();
9920        assert!(
9921            matches!(
9922                &err,
9923                EngineError::Eval(EvalError::PlaceholderOutOfRange { n: 1, bound: 0 })
9924            ),
9925            "got: {err}"
9926        );
9927    }
9928
9929    #[test]
9930    fn insert_into_half_column_dim_mismatch_errors() {
9931        let mut e = Engine::new();
9932        e.execute("CREATE TABLE t (v VECTOR(4) USING HALF)")
9933            .unwrap();
9934        let err = e.execute("INSERT INTO t VALUES ([1.0, 2.0])").unwrap_err();
9935        assert!(matches!(
9936            &err,
9937            EngineError::Storage(StorageError::TypeMismatch { .. })
9938        ));
9939    }
9940
9941    #[test]
9942    fn insert_into_sq8_column_dim_mismatch_errors() {
9943        // Dim mismatch falls through the `coerce_value` Vector→Sq8
9944        // arm's guard and surfaces as `TypeMismatch` — the same
9945        // error the F32 path produces today, so client error
9946        // handling stays uniform across encodings.
9947        let mut e = Engine::new();
9948        e.execute("CREATE TABLE t (v VECTOR(4) USING SQ8)").unwrap();
9949        let err = e.execute("INSERT INTO t VALUES ([1.0, 2.0])").unwrap_err();
9950        assert!(
9951            matches!(
9952                &err,
9953                EngineError::Storage(StorageError::TypeMismatch { .. })
9954            ),
9955            "got: {err}",
9956        );
9957    }
9958
9959    #[test]
9960    fn create_table_duplicate_errors() {
9961        let mut e = Engine::new();
9962        e.execute("CREATE TABLE foo (a INT)").unwrap();
9963        let err = e.execute("CREATE TABLE foo (a INT)").unwrap_err();
9964        assert!(matches!(
9965            err,
9966            EngineError::Storage(StorageError::DuplicateTable { ref name }) if name == "foo"
9967        ));
9968    }
9969
9970    #[test]
9971    fn insert_into_unknown_table_errors() {
9972        let mut e = Engine::new();
9973        let err = e.execute("INSERT INTO ghost VALUES (1)").unwrap_err();
9974        assert!(matches!(
9975            err,
9976            EngineError::Storage(StorageError::TableNotFound { ref name }) if name == "ghost"
9977        ));
9978    }
9979
9980    #[test]
9981    fn insert_happy_path_reports_one_affected() {
9982        let mut e = Engine::new();
9983        e.execute("CREATE TABLE foo (a INT NOT NULL)").unwrap();
9984        let r = e.execute("INSERT INTO foo VALUES (42)").unwrap();
9985        assert_eq!(unwrap_command_ok(&r), 1);
9986        assert_eq!(e.catalog().get("foo").unwrap().row_count(), 1);
9987    }
9988
9989    #[test]
9990    fn insert_arity_mismatch_propagates() {
9991        let mut e = Engine::new();
9992        e.execute("CREATE TABLE foo (a INT, b TEXT)").unwrap();
9993        let err = e.execute("INSERT INTO foo VALUES (1)").unwrap_err();
9994        assert!(matches!(
9995            err,
9996            EngineError::Storage(StorageError::ArityMismatch { .. })
9997        ));
9998    }
9999
10000    #[test]
10001    fn insert_negative_integer_via_unary_minus() {
10002        let mut e = Engine::new();
10003        e.execute("CREATE TABLE foo (a INT NOT NULL)").unwrap();
10004        e.execute("INSERT INTO foo VALUES (-7)").unwrap();
10005        let rows = e.catalog().get("foo").unwrap().rows();
10006        assert_eq!(rows[0].values[0], Value::Int(-7));
10007    }
10008
10009    #[test]
10010    fn insert_non_literal_expr_unsupported() {
10011        let mut e = Engine::new();
10012        e.execute("CREATE TABLE foo (a INT NOT NULL)").unwrap();
10013        let err = e.execute("INSERT INTO foo VALUES (1 + 2)").unwrap_err();
10014        assert!(matches!(err, EngineError::Unsupported(_)));
10015    }
10016
10017    #[test]
10018    fn select_star_returns_all_rows_in_insertion_order() {
10019        let mut e = Engine::new();
10020        e.execute("CREATE TABLE foo (a INT NOT NULL, b TEXT NOT NULL)")
10021            .unwrap();
10022        e.execute("INSERT INTO foo VALUES (1, 'one')").unwrap();
10023        e.execute("INSERT INTO foo VALUES (2, 'two')").unwrap();
10024        e.execute("INSERT INTO foo VALUES (3, 'three')").unwrap();
10025
10026        let r = e.execute("SELECT * FROM foo").unwrap();
10027        let QueryResult::Rows { columns, rows } = r else {
10028            panic!("expected Rows")
10029        };
10030        assert_eq!(columns.len(), 2);
10031        assert_eq!(columns[0].name, "a");
10032        assert_eq!(rows.len(), 3);
10033        assert_eq!(
10034            rows[1].values,
10035            vec![Value::Int(2), Value::Text("two".into())]
10036        );
10037    }
10038
10039    #[test]
10040    fn select_star_on_empty_table_returns_zero_rows() {
10041        let mut e = Engine::new();
10042        e.execute("CREATE TABLE foo (a INT)").unwrap();
10043        let r = e.execute("SELECT * FROM foo").unwrap();
10044        match r {
10045            QueryResult::Rows { rows, .. } => assert!(rows.is_empty()),
10046            QueryResult::CommandOk { .. } => panic!("expected Rows"),
10047        }
10048    }
10049
10050    // --- v0.4: WHERE + projection ------------------------------------------
10051
10052    fn make_three_row_users(e: &mut Engine) {
10053        e.execute("CREATE TABLE users (id INT NOT NULL, name TEXT NOT NULL, score INT)")
10054            .unwrap();
10055        e.execute("INSERT INTO users VALUES (1, 'alice', 90)")
10056            .unwrap();
10057        e.execute("INSERT INTO users VALUES (2, 'bob', NULL)")
10058            .unwrap();
10059        e.execute("INSERT INTO users VALUES (3, 'cara', 70)")
10060            .unwrap();
10061    }
10062
10063    fn unwrap_rows(r: QueryResult) -> (Vec<ColumnSchema>, Vec<Row>) {
10064        match r {
10065            QueryResult::Rows { columns, rows } => (columns, rows),
10066            QueryResult::CommandOk { .. } => panic!("expected Rows"),
10067        }
10068    }
10069
10070    #[test]
10071    fn where_filter_passes_only_true_rows() {
10072        let mut e = Engine::new();
10073        make_three_row_users(&mut e);
10074        let r = e.execute("SELECT * FROM users WHERE id > 1").unwrap();
10075        let (_, rows) = unwrap_rows(r);
10076        assert_eq!(rows.len(), 2);
10077        assert_eq!(rows[0].values[0], Value::Int(2));
10078        assert_eq!(rows[1].values[0], Value::Int(3));
10079    }
10080
10081    #[test]
10082    fn where_with_null_result_filters_out_row() {
10083        let mut e = Engine::new();
10084        make_three_row_users(&mut e);
10085        // score is NULL for bob → score > 80 is NULL → row excluded
10086        let r = e.execute("SELECT * FROM users WHERE score > 80").unwrap();
10087        let (_, rows) = unwrap_rows(r);
10088        assert_eq!(rows.len(), 1);
10089        assert_eq!(rows[0].values[1], Value::Text("alice".into()));
10090    }
10091
10092    #[test]
10093    fn projection_named_columns() {
10094        let mut e = Engine::new();
10095        make_three_row_users(&mut e);
10096        let r = e.execute("SELECT name, score FROM users").unwrap();
10097        let (cols, rows) = unwrap_rows(r);
10098        assert_eq!(cols.len(), 2);
10099        assert_eq!(cols[0].name, "name");
10100        assert_eq!(cols[1].name, "score");
10101        assert_eq!(rows.len(), 3);
10102        assert_eq!(
10103            rows[0].values,
10104            vec![Value::Text("alice".into()), Value::Int(90)]
10105        );
10106    }
10107
10108    #[test]
10109    fn projection_with_column_alias() {
10110        let mut e = Engine::new();
10111        make_three_row_users(&mut e);
10112        let r = e
10113            .execute("SELECT name AS who FROM users WHERE id = 1")
10114            .unwrap();
10115        let (cols, rows) = unwrap_rows(r);
10116        assert_eq!(cols[0].name, "who");
10117        assert_eq!(rows.len(), 1);
10118        assert_eq!(rows[0].values[0], Value::Text("alice".into()));
10119    }
10120
10121    #[test]
10122    fn qualified_column_with_table_alias_resolves() {
10123        let mut e = Engine::new();
10124        make_three_row_users(&mut e);
10125        let r = e
10126            .execute("SELECT u.id, u.name FROM users AS u WHERE u.id < 3")
10127            .unwrap();
10128        let (cols, rows) = unwrap_rows(r);
10129        assert_eq!(cols.len(), 2);
10130        assert_eq!(rows.len(), 2);
10131    }
10132
10133    #[test]
10134    fn qualified_column_with_wrong_alias_errors() {
10135        let mut e = Engine::new();
10136        make_three_row_users(&mut e);
10137        let err = e.execute("SELECT x.id FROM users AS u").unwrap_err();
10138        assert!(matches!(
10139            err,
10140            EngineError::Eval(EvalError::UnknownQualifier { ref qualifier }) if qualifier == "x"
10141        ));
10142    }
10143
10144    #[test]
10145    fn select_unknown_column_errors_in_projection() {
10146        let mut e = Engine::new();
10147        make_three_row_users(&mut e);
10148        let err = e.execute("SELECT ghost FROM users").unwrap_err();
10149        assert!(matches!(
10150            err,
10151            EngineError::Eval(EvalError::ColumnNotFound { ref name }) if name == "ghost"
10152        ));
10153    }
10154
10155    #[test]
10156    fn where_unknown_column_errors() {
10157        let mut e = Engine::new();
10158        make_three_row_users(&mut e);
10159        let err = e
10160            .execute("SELECT * FROM users WHERE ghost = 1")
10161            .unwrap_err();
10162        assert!(matches!(
10163            err,
10164            EngineError::Eval(EvalError::ColumnNotFound { .. })
10165        ));
10166    }
10167
10168    #[test]
10169    fn expression_projection_evaluates_and_renders() {
10170        // Compound expressions in the SELECT list are evaluated per row;
10171        // the output column is typed TEXT, name defaults to the expression.
10172        let mut e = Engine::new();
10173        e.execute("CREATE TABLE t (a INT NOT NULL)").unwrap();
10174        e.execute("INSERT INTO t VALUES (3)").unwrap();
10175        let (_, rows) = unwrap_rows(e.execute("SELECT 1 + 2 FROM t").unwrap());
10176        assert_eq!(rows.len(), 1);
10177        // The expression evaluates to integer 3; rendered as the cell value
10178        // (storage::Value::Int(3) since arithmetic kept ints).
10179        assert_eq!(rows[0].values[0], Value::Int(3));
10180    }
10181
10182    #[test]
10183    fn select_unknown_table_errors() {
10184        let mut e = Engine::new();
10185        let err = e.execute("SELECT * FROM ghost").unwrap_err();
10186        assert!(matches!(
10187            err,
10188            EngineError::Storage(StorageError::TableNotFound { .. })
10189        ));
10190    }
10191
10192    #[test]
10193    fn invalid_sql_returns_parse_error() {
10194        // v4.4: UPDATE is now real SQL, so use a true syntactic
10195        // garbage payload for the parse-error path.
10196        let mut e = Engine::new();
10197        let err = e.execute("THIS_IS_NOT_A_KEYWORD foo bar baz").unwrap_err();
10198        assert!(matches!(err, EngineError::Parse(_)));
10199    }
10200
10201    // --- v0.8 CREATE INDEX + index seek ------------------------------------
10202
10203    #[test]
10204    fn create_index_registers_on_table() {
10205        let mut e = Engine::new();
10206        make_three_row_users(&mut e);
10207        e.execute("CREATE INDEX by_name ON users (name)").unwrap();
10208        let t = e.catalog().get("users").unwrap();
10209        assert_eq!(t.indices().len(), 1);
10210        assert_eq!(t.indices()[0].name, "by_name");
10211    }
10212
10213    #[test]
10214    fn create_index_on_unknown_table_errors() {
10215        let mut e = Engine::new();
10216        let err = e.execute("CREATE INDEX i ON ghost (a)").unwrap_err();
10217        assert!(matches!(
10218            err,
10219            EngineError::Storage(StorageError::TableNotFound { .. })
10220        ));
10221    }
10222
10223    #[test]
10224    fn create_index_on_unknown_column_errors() {
10225        let mut e = Engine::new();
10226        make_three_row_users(&mut e);
10227        let err = e.execute("CREATE INDEX i ON users (ghost)").unwrap_err();
10228        assert!(matches!(
10229            err,
10230            EngineError::Storage(StorageError::ColumnNotFound { .. })
10231        ));
10232    }
10233
10234    #[test]
10235    fn select_eq_uses_index_returns_same_rows_as_scan() {
10236        // Build two engines: one with an index, one without. Same query →
10237        // same row set (index is a planner optimisation, not a semantic
10238        // change).
10239        let mut without = Engine::new();
10240        make_three_row_users(&mut without);
10241        let mut with = Engine::new();
10242        make_three_row_users(&mut with);
10243        with.execute("CREATE INDEX by_id ON users (id)").unwrap();
10244
10245        let q = "SELECT * FROM users WHERE id = 2";
10246        let (_, no_idx_rows) = unwrap_rows(without.execute(q).unwrap());
10247        let (_, idx_rows) = unwrap_rows(with.execute(q).unwrap());
10248        assert_eq!(no_idx_rows, idx_rows);
10249        assert_eq!(idx_rows.len(), 1);
10250    }
10251
10252    #[test]
10253    fn select_eq_with_no_matching_index_value_returns_empty() {
10254        let mut e = Engine::new();
10255        make_three_row_users(&mut e);
10256        e.execute("CREATE INDEX by_id ON users (id)").unwrap();
10257        let (_, rows) = unwrap_rows(e.execute("SELECT * FROM users WHERE id = 999").unwrap());
10258        assert_eq!(rows.len(), 0);
10259    }
10260
10261    // --- v0.9 transactions -------------------------------------------------
10262
10263    #[test]
10264    fn begin_sets_in_transaction_flag() {
10265        let mut e = Engine::new();
10266        assert!(!e.in_transaction());
10267        e.execute("BEGIN").unwrap();
10268        assert!(e.in_transaction());
10269    }
10270
10271    #[test]
10272    fn double_begin_errors() {
10273        let mut e = Engine::new();
10274        e.execute("BEGIN").unwrap();
10275        let err = e.execute("BEGIN").unwrap_err();
10276        assert_eq!(err, EngineError::TransactionAlreadyOpen);
10277    }
10278
10279    #[test]
10280    fn commit_without_begin_errors() {
10281        let mut e = Engine::new();
10282        let err = e.execute("COMMIT").unwrap_err();
10283        assert_eq!(err, EngineError::NoActiveTransaction);
10284    }
10285
10286    #[test]
10287    fn rollback_without_begin_errors() {
10288        let mut e = Engine::new();
10289        let err = e.execute("ROLLBACK").unwrap_err();
10290        assert_eq!(err, EngineError::NoActiveTransaction);
10291    }
10292
10293    #[test]
10294    fn commit_applies_shadow_to_committed_catalog() {
10295        let mut e = Engine::new();
10296        e.execute("CREATE TABLE t (v INT NOT NULL)").unwrap();
10297        e.execute("BEGIN").unwrap();
10298        e.execute("INSERT INTO t VALUES (1)").unwrap();
10299        e.execute("INSERT INTO t VALUES (2)").unwrap();
10300        e.execute("COMMIT").unwrap();
10301        assert!(!e.in_transaction());
10302        assert_eq!(e.catalog().get("t").unwrap().row_count(), 2);
10303    }
10304
10305    #[test]
10306    fn rollback_discards_shadow() {
10307        let mut e = Engine::new();
10308        e.execute("CREATE TABLE t (v INT NOT NULL)").unwrap();
10309        e.execute("BEGIN").unwrap();
10310        e.execute("INSERT INTO t VALUES (1)").unwrap();
10311        e.execute("INSERT INTO t VALUES (2)").unwrap();
10312        e.execute("ROLLBACK").unwrap();
10313        assert!(!e.in_transaction());
10314        assert_eq!(e.catalog().get("t").unwrap().row_count(), 0);
10315    }
10316
10317    #[test]
10318    fn select_during_tx_sees_uncommitted_writes_own_session() {
10319        // The shadow catalog is read by SELECTs while a TX is open — the
10320        // session can see its own pending writes.
10321        let mut e = Engine::new();
10322        e.execute("CREATE TABLE t (v INT NOT NULL)").unwrap();
10323        e.execute("BEGIN").unwrap();
10324        e.execute("INSERT INTO t VALUES (42)").unwrap();
10325        let (_, rows) = unwrap_rows(e.execute("SELECT * FROM t").unwrap());
10326        assert_eq!(rows.len(), 1);
10327        assert_eq!(rows[0].values[0], Value::Int(42));
10328    }
10329
10330    #[test]
10331    fn snapshot_with_no_users_is_bare_catalog_format() {
10332        let mut e = Engine::new();
10333        e.execute("CREATE TABLE t (id INT NOT NULL)").unwrap();
10334        let bytes = e.snapshot();
10335        assert_eq!(
10336            &bytes[..8],
10337            b"SPGDB001",
10338            "must be the bare v3.x catalog magic"
10339        );
10340        let e2 = Engine::restore_envelope(&bytes).unwrap();
10341        assert!(e2.users().is_empty());
10342        assert_eq!(e2.catalog().table_count(), 1);
10343    }
10344
10345    #[test]
10346    fn snapshot_with_users_round_trips_both_via_envelope() {
10347        let mut e = Engine::new();
10348        e.execute("CREATE TABLE t (id INT NOT NULL)").unwrap();
10349        e.create_user("alice", "pw1", Role::Admin, [9; 16]).unwrap();
10350        e.create_user("bob", "pw2", Role::ReadOnly, [5; 16])
10351            .unwrap();
10352        let bytes = e.snapshot();
10353        assert_eq!(&bytes[..8], b"SPGENV01", "must be the v4.1 envelope magic");
10354        let e2 = Engine::restore_envelope(&bytes).unwrap();
10355        assert_eq!(e2.users().len(), 2);
10356        assert_eq!(e2.verify_user("alice", "pw1"), Some(Role::Admin));
10357        assert_eq!(e2.verify_user("bob", "pw2"), Some(Role::ReadOnly));
10358        assert_eq!(e2.verify_user("alice", "wrong"), None);
10359        assert_eq!(e2.catalog().table_count(), 1);
10360    }
10361
10362    #[test]
10363    fn ddl_inside_tx_also_rolled_back() {
10364        let mut e = Engine::new();
10365        e.execute("BEGIN").unwrap();
10366        e.execute("CREATE TABLE t (v INT)").unwrap();
10367        // Visible inside the TX.
10368        e.execute("SELECT * FROM t").unwrap();
10369        e.execute("ROLLBACK").unwrap();
10370        // Gone after rollback.
10371        let err = e.execute("SELECT * FROM t").unwrap_err();
10372        assert!(matches!(
10373            err,
10374            EngineError::Storage(StorageError::TableNotFound { .. })
10375        ));
10376    }
10377
10378    // ── v6.1.2: CREATE / DROP PUBLICATION (engine-side) ──────
10379
10380    #[test]
10381    fn create_publication_lands_in_catalog() {
10382        let mut e = Engine::new();
10383        assert!(e.publications().is_empty());
10384        e.execute("CREATE PUBLICATION pub_a").unwrap();
10385        assert_eq!(e.publications().len(), 1);
10386        assert!(e.publications().contains("pub_a"));
10387    }
10388
10389    #[test]
10390    fn create_publication_duplicate_errors() {
10391        let mut e = Engine::new();
10392        e.execute("CREATE PUBLICATION pub_a").unwrap();
10393        let err = e.execute("CREATE PUBLICATION pub_a").unwrap_err();
10394        assert!(
10395            alloc::format!("{err:?}").contains("DuplicateName"),
10396            "got {err:?}"
10397        );
10398    }
10399
10400    #[test]
10401    fn drop_publication_silent_when_absent() {
10402        let mut e = Engine::new();
10403        // PG-compatible: DROP a publication that doesn't exist
10404        // succeeds (no-op) but reports zero affected.
10405        let r = e.execute("DROP PUBLICATION nope").unwrap();
10406        match r {
10407            QueryResult::CommandOk { affected, .. } => assert_eq!(affected, 0),
10408            other => panic!("expected CommandOk, got {other:?}"),
10409        }
10410    }
10411
10412    #[test]
10413    fn drop_publication_present_reports_one_affected() {
10414        let mut e = Engine::new();
10415        e.execute("CREATE PUBLICATION pub_a").unwrap();
10416        let r = e.execute("DROP PUBLICATION pub_a").unwrap();
10417        match r {
10418            QueryResult::CommandOk {
10419                affected,
10420                modified_catalog,
10421            } => {
10422                assert_eq!(affected, 1);
10423                assert!(modified_catalog);
10424            }
10425            other => panic!("expected CommandOk, got {other:?}"),
10426        }
10427        assert!(e.publications().is_empty());
10428    }
10429
10430    #[test]
10431    fn publications_persist_across_snapshot_restore() {
10432        // The persist-across-restart ship-gate at the engine layer —
10433        // snapshot → restore_envelope round trip must preserve the
10434        // publication catalog. The spg-server e2e covers the
10435        // process-restart variant.
10436        let mut e = Engine::new();
10437        e.execute("CREATE PUBLICATION pub_a").unwrap();
10438        e.execute("CREATE PUBLICATION pub_b FOR ALL TABLES")
10439            .unwrap();
10440        let snap = e.snapshot();
10441        let e2 = Engine::restore_envelope(&snap).unwrap();
10442        assert_eq!(e2.publications().len(), 2);
10443        assert!(e2.publications().contains("pub_a"));
10444        assert!(e2.publications().contains("pub_b"));
10445    }
10446
10447    #[test]
10448    fn create_publication_allowed_inside_transaction() {
10449        // v6.1.4 dropped the v6.1.2 in-TX guard — PG allows
10450        // CREATE PUBLICATION inside a TX and the auto-commit
10451        // wrap path needs the same allowance.
10452        let mut e = Engine::new();
10453        e.execute("BEGIN").unwrap();
10454        e.execute("CREATE PUBLICATION pub_a").unwrap();
10455        e.execute("COMMIT").unwrap();
10456        assert!(e.publications().contains("pub_a"));
10457    }
10458
10459    // ── v6.1.3: SHOW PUBLICATIONS + FOR-list variants ───────
10460
10461    #[test]
10462    fn create_publication_for_table_list_lands_with_scope() {
10463        let mut e = Engine::new();
10464        e.execute("CREATE TABLE t1 (id INT NOT NULL)").unwrap();
10465        e.execute("CREATE TABLE t2 (id INT NOT NULL)").unwrap();
10466        e.execute("CREATE PUBLICATION pub_a FOR TABLE t1, t2")
10467            .unwrap();
10468        let scope = e.publications().get("pub_a").cloned();
10469        let Some(spg_sql::ast::PublicationScope::ForTables(ts)) = scope else {
10470            panic!("expected ForTables scope, got {scope:?}")
10471        };
10472        assert_eq!(ts, alloc::vec!["t1".to_string(), "t2".to_string()]);
10473    }
10474
10475    #[test]
10476    fn create_publication_all_tables_except_lands_with_scope() {
10477        let mut e = Engine::new();
10478        e.execute("CREATE PUBLICATION pub_a FOR ALL TABLES EXCEPT t3")
10479            .unwrap();
10480        let scope = e.publications().get("pub_a").cloned();
10481        let Some(spg_sql::ast::PublicationScope::AllTablesExcept(ts)) = scope else {
10482            panic!("expected AllTablesExcept scope, got {scope:?}")
10483        };
10484        assert_eq!(ts, alloc::vec!["t3".to_string()]);
10485    }
10486
10487    #[test]
10488    fn show_publications_empty_returns_zero_rows() {
10489        let e = Engine::new();
10490        let r = e.execute_readonly("SHOW PUBLICATIONS").unwrap();
10491        let QueryResult::Rows { rows, columns } = r else {
10492            panic!()
10493        };
10494        assert!(rows.is_empty());
10495        assert_eq!(columns.len(), 3);
10496        assert_eq!(columns[0].name, "name");
10497        assert_eq!(columns[1].name, "scope");
10498        assert_eq!(columns[2].name, "table_count");
10499    }
10500
10501    #[test]
10502    fn show_publications_returns_one_row_per_publication_ordered_by_name() {
10503        let mut e = Engine::new();
10504        e.execute("CREATE PUBLICATION z_pub").unwrap();
10505        e.execute("CREATE PUBLICATION a_pub FOR TABLE t1, t2")
10506            .unwrap();
10507        e.execute("CREATE PUBLICATION m_pub FOR ALL TABLES EXCEPT bad")
10508            .unwrap();
10509        let r = e.execute_readonly("SHOW PUBLICATIONS").unwrap();
10510        let QueryResult::Rows { rows, .. } = r else {
10511            panic!()
10512        };
10513        assert_eq!(rows.len(), 3);
10514        // Alphabetical order: a_pub, m_pub, z_pub.
10515        let names: Vec<&str> = rows
10516            .iter()
10517            .map(|r| {
10518                if let Value::Text(s) = &r.values[0] {
10519                    s.as_str()
10520                } else {
10521                    panic!()
10522                }
10523            })
10524            .collect();
10525        assert_eq!(names, alloc::vec!["a_pub", "m_pub", "z_pub"]);
10526        // Row 0 — a_pub scope summary + table_count = 2.
10527        match &rows[0].values[1] {
10528            Value::Text(s) => assert_eq!(s, "FOR TABLE t1, t2"),
10529            other => panic!("expected Text, got {other:?}"),
10530        }
10531        assert_eq!(rows[0].values[2], Value::Int(2));
10532        // Row 1 — m_pub.
10533        match &rows[1].values[1] {
10534            Value::Text(s) => assert_eq!(s, "FOR ALL TABLES EXCEPT bad"),
10535            other => panic!("expected Text, got {other:?}"),
10536        }
10537        assert_eq!(rows[1].values[2], Value::Int(1));
10538        // Row 2 — z_pub (AllTables → NULL count).
10539        match &rows[2].values[1] {
10540            Value::Text(s) => assert_eq!(s, "FOR ALL TABLES"),
10541            other => panic!("expected Text, got {other:?}"),
10542        }
10543        assert_eq!(rows[2].values[2], Value::Null);
10544    }
10545
10546    #[test]
10547    fn for_list_scopes_persist_across_snapshot() {
10548        // The v6.1.2 envelope-v3 round-trip exercised AllTables;
10549        // v6.1.3 needs the scope-1 / scope-2 tags to survive too.
10550        let mut e = Engine::new();
10551        e.execute("CREATE PUBLICATION p1 FOR TABLE t1, t2").unwrap();
10552        e.execute("CREATE PUBLICATION p2 FOR ALL TABLES EXCEPT bad, worse")
10553            .unwrap();
10554        let snap = e.snapshot();
10555        let e2 = Engine::restore_envelope(&snap).unwrap();
10556        assert_eq!(e2.publications().len(), 2);
10557        let p1 = e2.publications().get("p1").cloned();
10558        let Some(spg_sql::ast::PublicationScope::ForTables(ts)) = p1 else {
10559            panic!("p1 scope lost: {p1:?}")
10560        };
10561        assert_eq!(ts, alloc::vec!["t1".to_string(), "t2".to_string()]);
10562        let p2 = e2.publications().get("p2").cloned();
10563        let Some(spg_sql::ast::PublicationScope::AllTablesExcept(ts)) = p2 else {
10564            panic!("p2 scope lost: {p2:?}")
10565        };
10566        assert_eq!(ts, alloc::vec!["bad".to_string(), "worse".to_string()]);
10567    }
10568
10569    // ── v6.1.4: CREATE / DROP SUBSCRIPTION + SHOW + envelope v4 ─
10570
10571    #[test]
10572    fn create_subscription_lands_in_catalog_with_defaults() {
10573        let mut e = Engine::new();
10574        e.execute(
10575            "CREATE SUBSCRIPTION sub_a CONNECTION 'host=127.0.0.1 port=20002' PUBLICATION pub_a",
10576        )
10577        .unwrap();
10578        let s = e.subscriptions().get("sub_a").cloned().expect("present");
10579        assert_eq!(s.conn_str, "host=127.0.0.1 port=20002");
10580        assert_eq!(s.publications, alloc::vec!["pub_a".to_string()]);
10581        assert!(s.enabled);
10582        assert_eq!(s.last_received_pos, 0);
10583    }
10584
10585    #[test]
10586    fn create_subscription_duplicate_name_errors() {
10587        let mut e = Engine::new();
10588        e.execute("CREATE SUBSCRIPTION s CONNECTION 'host=x' PUBLICATION p")
10589            .unwrap();
10590        let err = e
10591            .execute("CREATE SUBSCRIPTION s CONNECTION 'host=y' PUBLICATION p")
10592            .unwrap_err();
10593        assert!(
10594            alloc::format!("{err:?}").contains("DuplicateName"),
10595            "got {err:?}"
10596        );
10597    }
10598
10599    #[test]
10600    fn drop_subscription_silent_when_absent() {
10601        let mut e = Engine::new();
10602        let r = e.execute("DROP SUBSCRIPTION never").unwrap();
10603        match r {
10604            QueryResult::CommandOk { affected, .. } => assert_eq!(affected, 0),
10605            other => panic!("expected CommandOk, got {other:?}"),
10606        }
10607    }
10608
10609    #[test]
10610    fn subscription_advance_updates_last_pos_monotone() {
10611        let mut e = Engine::new();
10612        e.execute("CREATE SUBSCRIPTION s CONNECTION 'h=x' PUBLICATION p")
10613            .unwrap();
10614        assert!(e.subscription_advance("s", 100));
10615        assert_eq!(e.subscriptions().get("s").unwrap().last_received_pos, 100);
10616        assert!(e.subscription_advance("s", 50)); // stale → ignored
10617        assert_eq!(e.subscriptions().get("s").unwrap().last_received_pos, 100);
10618        assert!(e.subscription_advance("s", 200));
10619        assert_eq!(e.subscriptions().get("s").unwrap().last_received_pos, 200);
10620        assert!(!e.subscription_advance("missing", 1));
10621    }
10622
10623    #[test]
10624    fn show_subscriptions_returns_rows_ordered_by_name() {
10625        let mut e = Engine::new();
10626        e.execute("CREATE SUBSCRIPTION z_sub CONNECTION 'h=x' PUBLICATION p1, p2")
10627            .unwrap();
10628        e.execute("CREATE SUBSCRIPTION a_sub CONNECTION 'h=y' PUBLICATION p3")
10629            .unwrap();
10630        let r = e.execute_readonly("SHOW SUBSCRIPTIONS").unwrap();
10631        let QueryResult::Rows { rows, columns } = r else {
10632            panic!()
10633        };
10634        assert_eq!(rows.len(), 2);
10635        assert_eq!(columns.len(), 5);
10636        assert_eq!(columns[0].name, "name");
10637        assert_eq!(columns[4].name, "last_received_pos");
10638        // Alphabetical: a_sub, z_sub.
10639        let names: Vec<&str> = rows
10640            .iter()
10641            .map(|r| {
10642                if let Value::Text(s) = &r.values[0] {
10643                    s.as_str()
10644                } else {
10645                    panic!()
10646                }
10647            })
10648            .collect();
10649        assert_eq!(names, alloc::vec!["a_sub", "z_sub"]);
10650        // Row 0: a_sub
10651        assert_eq!(rows[0].values[1], Value::Text("h=y".to_string()));
10652        assert_eq!(rows[0].values[2], Value::Text("p3".to_string()));
10653        assert_eq!(rows[0].values[3], Value::Bool(true));
10654        assert_eq!(rows[0].values[4], Value::BigInt(0));
10655        // Row 1: z_sub — publications join with ", "
10656        assert_eq!(rows[1].values[2], Value::Text("p1, p2".to_string()));
10657    }
10658
10659    #[test]
10660    fn subscriptions_persist_across_snapshot_envelope_v4() {
10661        let mut e = Engine::new();
10662        e.execute("CREATE SUBSCRIPTION s1 CONNECTION 'h=A' PUBLICATION p1, p2")
10663            .unwrap();
10664        e.execute("CREATE SUBSCRIPTION s2 CONNECTION 'h=B' PUBLICATION p3")
10665            .unwrap();
10666        e.subscription_advance("s2", 42);
10667        let snap = e.snapshot();
10668        let e2 = Engine::restore_envelope(&snap).unwrap();
10669        assert_eq!(e2.subscriptions().len(), 2);
10670        let s1 = e2.subscriptions().get("s1").unwrap();
10671        assert_eq!(s1.conn_str, "h=A");
10672        assert_eq!(
10673            s1.publications,
10674            alloc::vec!["p1".to_string(), "p2".to_string()]
10675        );
10676        assert_eq!(s1.last_received_pos, 0);
10677        let s2 = e2.subscriptions().get("s2").unwrap();
10678        assert_eq!(s2.last_received_pos, 42);
10679    }
10680
10681    #[test]
10682    fn v3_envelope_loads_with_empty_subscriptions() {
10683        // v3 snapshot (publications-only). Forge it by hand so we
10684        // verify v6.1.4 readers don't panic — they must surface
10685        // empty subscriptions and a populated publication table.
10686        let mut e = Engine::new();
10687        e.execute("CREATE PUBLICATION pub_legacy").unwrap();
10688        let catalog = e.catalog.serialize();
10689        let users = crate::users::serialize_users(&e.users);
10690        let pubs = e.publications.serialize();
10691        let mut buf = Vec::new();
10692        buf.extend_from_slice(b"SPGENV01");
10693        buf.push(3u8); // v3
10694        buf.extend_from_slice(&u32::try_from(catalog.len()).unwrap().to_le_bytes());
10695        buf.extend_from_slice(&catalog);
10696        buf.extend_from_slice(&u32::try_from(users.len()).unwrap().to_le_bytes());
10697        buf.extend_from_slice(&users);
10698        buf.extend_from_slice(&u32::try_from(pubs.len()).unwrap().to_le_bytes());
10699        buf.extend_from_slice(&pubs);
10700        let crc = spg_crypto::crc32::crc32(&buf);
10701        buf.extend_from_slice(&crc.to_le_bytes());
10702
10703        let e2 = Engine::restore_envelope(&buf).expect("v3 envelope restores under v4 reader");
10704        assert!(e2.subscriptions().is_empty());
10705        assert!(e2.publications().contains("pub_legacy"));
10706    }
10707
10708    #[test]
10709    fn create_subscription_allowed_inside_transaction() {
10710        let mut e = Engine::new();
10711        e.execute("BEGIN").unwrap();
10712        e.execute("CREATE SUBSCRIPTION s CONNECTION 'h=x' PUBLICATION p")
10713            .unwrap();
10714        e.execute("COMMIT").unwrap();
10715        assert!(e.subscriptions().contains("s"));
10716    }
10717
10718    // ── v6.2.0: ANALYZE + spg_statistic + envelope v5 ──────────
10719    #[test]
10720    fn analyze_populates_histogram_bounds() {
10721        let mut e = Engine::new();
10722        e.execute("CREATE TABLE t (id INT NOT NULL, name TEXT)")
10723            .unwrap();
10724        for i in 0..50 {
10725            e.execute(&alloc::format!("INSERT INTO t VALUES ({i}, 'name{i}')"))
10726                .unwrap();
10727        }
10728        e.execute("ANALYZE t").unwrap();
10729        let stats = e.statistics();
10730        let id_stats = stats.get("t", "id").unwrap();
10731        assert!(id_stats.histogram_bounds.len() >= 2);
10732        assert_eq!(id_stats.histogram_bounds.first().unwrap(), "0");
10733        assert_eq!(id_stats.histogram_bounds.last().unwrap(), "49");
10734        assert!((id_stats.null_frac - 0.0).abs() < 1e-6);
10735        assert_eq!(id_stats.n_distinct, 50);
10736    }
10737
10738    #[test]
10739    fn reanalyze_overwrites_prior_stats() {
10740        let mut e = Engine::new();
10741        e.execute("CREATE TABLE t (id INT NOT NULL)").unwrap();
10742        for i in 0..10 {
10743            e.execute(&alloc::format!("INSERT INTO t VALUES ({i})"))
10744                .unwrap();
10745        }
10746        e.execute("ANALYZE t").unwrap();
10747        let n1 = e.statistics().get("t", "id").unwrap().n_distinct;
10748        assert_eq!(n1, 10);
10749        for i in 10..30 {
10750            e.execute(&alloc::format!("INSERT INTO t VALUES ({i})"))
10751                .unwrap();
10752        }
10753        e.execute("ANALYZE t").unwrap();
10754        let n2 = e.statistics().get("t", "id").unwrap().n_distinct;
10755        assert_eq!(n2, 30);
10756    }
10757
10758    #[test]
10759    fn analyze_unknown_table_errors() {
10760        let mut e = Engine::new();
10761        let err = e.execute("ANALYZE nonexistent").unwrap_err();
10762        assert!(matches!(
10763            err,
10764            EngineError::Storage(StorageError::TableNotFound { .. })
10765        ));
10766    }
10767
10768    #[test]
10769    fn bare_analyze_covers_all_user_tables() {
10770        let mut e = Engine::new();
10771        e.execute("CREATE TABLE t1 (id INT NOT NULL)").unwrap();
10772        e.execute("CREATE TABLE t2 (name TEXT NOT NULL)").unwrap();
10773        e.execute("INSERT INTO t1 VALUES (1)").unwrap();
10774        e.execute("INSERT INTO t2 VALUES ('alice')").unwrap();
10775        let r = e.execute("ANALYZE").unwrap();
10776        match r {
10777            QueryResult::CommandOk {
10778                affected,
10779                modified_catalog,
10780            } => {
10781                assert_eq!(affected, 2);
10782                assert!(modified_catalog);
10783            }
10784            other => panic!("expected CommandOk, got {other:?}"),
10785        }
10786        assert!(e.statistics().get("t1", "id").is_some());
10787        assert!(e.statistics().get("t2", "name").is_some());
10788    }
10789
10790    #[test]
10791    fn select_from_spg_statistic_returns_rows_per_column() {
10792        let mut e = Engine::new();
10793        e.execute("CREATE TABLE t (id INT NOT NULL, label TEXT)")
10794            .unwrap();
10795        e.execute("INSERT INTO t VALUES (1, 'a')").unwrap();
10796        e.execute("INSERT INTO t VALUES (2, 'b')").unwrap();
10797        e.execute("ANALYZE t").unwrap();
10798        let r = e.execute_readonly("SELECT * FROM spg_statistic").unwrap();
10799        let QueryResult::Rows { rows, columns } = r else {
10800            panic!()
10801        };
10802        // v6.7.0 — spg_statistic gained a `cold_row_count` column.
10803        assert_eq!(columns.len(), 6);
10804        assert_eq!(columns[0].name, "table_name");
10805        assert_eq!(columns[4].name, "histogram_bounds");
10806        assert_eq!(columns[5].name, "cold_row_count");
10807        assert_eq!(rows.len(), 2, "one row per column of t");
10808        // Sorted by (table_name, column_name).
10809        match (&rows[0].values[0], &rows[0].values[1]) {
10810            (Value::Text(t), Value::Text(c)) => {
10811                assert_eq!(t, "t");
10812                // BTreeMap orders (table, column); columns "id" < "label".
10813                assert_eq!(c, "id");
10814            }
10815            _ => panic!(),
10816        }
10817    }
10818
10819    #[test]
10820    fn analyze_skips_vector_columns() {
10821        // Vector columns have their own stats shape (HNSW graph);
10822        // ANALYZE leaves them out of spg_statistic.
10823        let mut e = Engine::new();
10824        e.execute("CREATE TABLE t (id INT NOT NULL, v VECTOR(3) NOT NULL)")
10825            .unwrap();
10826        e.execute("INSERT INTO t VALUES (1, [1, 2, 3])").unwrap();
10827        e.execute("ANALYZE t").unwrap();
10828        assert!(e.statistics().get("t", "id").is_some());
10829        assert!(e.statistics().get("t", "v").is_none());
10830    }
10831
10832    #[test]
10833    fn statistics_persist_across_envelope_v5_round_trip() {
10834        let mut e = Engine::new();
10835        e.execute("CREATE TABLE t (id INT NOT NULL)").unwrap();
10836        for i in 0..20 {
10837            e.execute(&alloc::format!("INSERT INTO t VALUES ({i})"))
10838                .unwrap();
10839        }
10840        e.execute("ANALYZE").unwrap();
10841        let snap = e.snapshot();
10842        let e2 = Engine::restore_envelope(&snap).unwrap();
10843        let s = e2.statistics().get("t", "id").unwrap();
10844        assert_eq!(s.n_distinct, 20);
10845    }
10846
10847    // ── v6.2.1 auto-analyze threshold ───────────────────────────
10848
10849    #[test]
10850    fn auto_analyze_threshold_fires_after_10pct_of_min_rows_on_small_table() {
10851        // For a table with 0 rows then 10 inserts → modified=10,
10852        // row_count=10. Threshold = 0.1 × max(10, 100) = 10. So
10853        // after the 10th INSERT the threshold is met.
10854        let mut e = Engine::new();
10855        e.execute("CREATE TABLE t (id INT NOT NULL)").unwrap();
10856        for i in 0..9 {
10857            e.execute(&alloc::format!("INSERT INTO t VALUES ({i})"))
10858                .unwrap();
10859        }
10860        assert!(e.tables_needing_analyze().is_empty(), "9 < threshold");
10861        e.execute("INSERT INTO t VALUES (9)").unwrap();
10862        let needs = e.tables_needing_analyze();
10863        assert_eq!(needs, alloc::vec!["t".to_string()]);
10864    }
10865
10866    #[test]
10867    fn auto_analyze_threshold_uses_10pct_of_row_count_for_large_tables() {
10868        // After ANALYZE on 1000 rows, threshold = 0.1 × row_count.
10869        // Each new INSERT bumps both modified and row_count, so to
10870        // trigger from N=1000 we need modifications ≥ 0.1 × (1000+M),
10871        // i.e. M ≥ 112. The test inserts 50 (no fire), then 150
10872        // more (200 total mods, row_count=1200, threshold=120 → fire).
10873        let mut e = Engine::new();
10874        e.execute("CREATE TABLE t (id INT NOT NULL)").unwrap();
10875        for i in 0..1000 {
10876            e.execute(&alloc::format!("INSERT INTO t VALUES ({i})"))
10877                .unwrap();
10878        }
10879        e.execute("ANALYZE t").unwrap();
10880        assert!(e.tables_needing_analyze().is_empty(), "fresh ANALYZE");
10881        for i in 1000..1050 {
10882            e.execute(&alloc::format!("INSERT INTO t VALUES ({i})"))
10883                .unwrap();
10884        }
10885        assert!(
10886            e.tables_needing_analyze().is_empty(),
10887            "50 inserts < threshold of ~105"
10888        );
10889        for i in 1050..1200 {
10890            e.execute(&alloc::format!("INSERT INTO t VALUES ({i})"))
10891                .unwrap();
10892        }
10893        assert_eq!(
10894            e.tables_needing_analyze(),
10895            alloc::vec!["t".to_string()],
10896            "200 inserts > 0.1 × 1200 threshold"
10897        );
10898    }
10899
10900    #[test]
10901    fn auto_analyze_threshold_resets_after_analyze() {
10902        let mut e = Engine::new();
10903        e.execute("CREATE TABLE t (id INT NOT NULL)").unwrap();
10904        for i in 0..200 {
10905            e.execute(&alloc::format!("INSERT INTO t VALUES ({i})"))
10906                .unwrap();
10907        }
10908        assert!(!e.tables_needing_analyze().is_empty());
10909        e.execute("ANALYZE").unwrap();
10910        assert!(
10911            e.tables_needing_analyze().is_empty(),
10912            "ANALYZE must reset the counter"
10913        );
10914    }
10915
10916    #[test]
10917    fn auto_analyze_threshold_tracks_updates_and_deletes() {
10918        let mut e = Engine::new();
10919        e.execute("CREATE TABLE t (id INT NOT NULL, label TEXT)")
10920            .unwrap();
10921        for i in 0..50 {
10922            e.execute(&alloc::format!("INSERT INTO t VALUES ({i}, 'x')"))
10923                .unwrap();
10924        }
10925        e.execute("ANALYZE t").unwrap();
10926        // UPDATE 20 rows + DELETE 5 → modified=25. Threshold = 0.1
10927        // × max(50, 100) = 10. So 25 >= 10 → trigger.
10928        e.execute("UPDATE t SET label = 'y' WHERE id < 20").unwrap();
10929        e.execute("DELETE FROM t WHERE id >= 45").unwrap();
10930        assert_eq!(e.tables_needing_analyze(), alloc::vec!["t".to_string()]);
10931    }
10932
10933    #[test]
10934    fn v4_envelope_loads_with_empty_statistics() {
10935        // Forge a v4 envelope by hand: catalog + users + pubs +
10936        // subs trailer, no statistics. A v6.2.0 reader must accept
10937        // it and surface an empty Statistics.
10938        let mut e = Engine::new();
10939        e.create_user("alice", "secret", crate::users::Role::ReadOnly, [0u8; 16])
10940            .unwrap();
10941        let catalog = e.catalog.serialize();
10942        let users = crate::users::serialize_users(&e.users);
10943        let pubs = e.publications.serialize();
10944        let subs = e.subscriptions.serialize();
10945        let mut buf = Vec::new();
10946        buf.extend_from_slice(b"SPGENV01");
10947        buf.push(4u8);
10948        buf.extend_from_slice(&u32::try_from(catalog.len()).unwrap().to_le_bytes());
10949        buf.extend_from_slice(&catalog);
10950        buf.extend_from_slice(&u32::try_from(users.len()).unwrap().to_le_bytes());
10951        buf.extend_from_slice(&users);
10952        buf.extend_from_slice(&u32::try_from(pubs.len()).unwrap().to_le_bytes());
10953        buf.extend_from_slice(&pubs);
10954        buf.extend_from_slice(&u32::try_from(subs.len()).unwrap().to_le_bytes());
10955        buf.extend_from_slice(&subs);
10956        let crc = spg_crypto::crc32::crc32(&buf);
10957        buf.extend_from_slice(&crc.to_le_bytes());
10958        let e2 = Engine::restore_envelope(&buf).expect("v4 envelope restores");
10959        assert!(e2.statistics().is_empty());
10960    }
10961
10962    #[test]
10963    fn v1_v2_envelope_loads_with_empty_publications() {
10964        // A snapshot taken before v6.1.2 (no publication trailer,
10965        // envelope v2) must still deserialise — and the resulting
10966        // engine must report zero publications. Use the engine's own
10967        // round-trip with no publications: that emits v3 but with an
10968        // empty pubs block. Then forge a v2 envelope by hand to lock
10969        // the back-compat path.
10970        let mut e = Engine::new();
10971        // Force users to be non-empty so the snapshot takes the
10972        // envelope path rather than the bare-catalog fallback.
10973        e.create_user("alice", "secret", crate::users::Role::ReadOnly, [0u8; 16])
10974            .unwrap();
10975
10976        // Forge an envelope v2: same shape as v3 but no pubs trailer.
10977        let catalog = e.catalog.serialize();
10978        let users = crate::users::serialize_users(&e.users);
10979        let mut buf = Vec::new();
10980        buf.extend_from_slice(b"SPGENV01");
10981        buf.push(2u8); // v2
10982        buf.extend_from_slice(&u32::try_from(catalog.len()).unwrap().to_le_bytes());
10983        buf.extend_from_slice(&catalog);
10984        buf.extend_from_slice(&u32::try_from(users.len()).unwrap().to_le_bytes());
10985        buf.extend_from_slice(&users);
10986        let crc = spg_crypto::crc32::crc32(&buf);
10987        buf.extend_from_slice(&crc.to_le_bytes());
10988
10989        let e2 = Engine::restore_envelope(&buf).expect("v2 envelope restores");
10990        assert!(e2.publications().is_empty());
10991    }
10992}