Skip to main content

spg_engine/
execute.rs

1//! Statement execution + prepared-statement dispatch, split out of
2//! `lib.rs` (lib.rs split 17). The public `execute` / `execute_in` /
3//! `execute_with_cancel` entry points, the `prepare` / `prepare_cached`
4//! / `describe_prepared` / `execute_prepared` prepared-statement path,
5//! and the internal pipeline (`execute_inner_with_cancel` →
6//! `execute_stmt_with_cancel`) that pre-resolves clock / sequence /
7//! placeholder rewrites and routes each parsed Statement to its domain
8//! handler (DDL / DML / SELECT / transaction / SHOW / …). Whole
9//! `impl Engine` methods reached via the Engine type, so the public
10//! surface is unchanged; `execute_stmt_with_cancel` is pub(crate) for
11//! the plpgsql + trigger re-entry paths.
12
13use alloc::string::String;
14use alloc::vec::Vec;
15
16use spg_sql::ast::Statement;
17use spg_sql::parser::{self, ParseError};
18use spg_storage::{ColumnSchema, Value};
19
20use crate::describe;
21use crate::{
22    CancelToken, Engine, EngineError, IMPLICIT_TX, QueryResult, TxId, expand_group_by_all,
23    plan_cache, reorder, resolve_order_by_position, rewrite_clock_calls, substitute_placeholders,
24};
25
26/// v7.38 Epic P — turn a caught panic payload into an
27/// [`EngineError::Internal`]. Recovers a human-readable detail from the
28/// common payload shapes (`&str` / `String`, and the injection framework's
29/// typed `InjectedError`) so the wire layer sends a clean message; falls
30/// back to a generic string when the payload type is opaque.
31// r1051 — a stray `#[cfg(feature = "std")]` sat here (misattached
32// between two doc comments) and gated this core/alloc-only function
33// out of the no_std build while its two call sites stayed: no_std had
34// not compiled since the GUC round, and nothing in the gate builds
35// no_std, so nothing said so. The suite's first no_std probe did.
36/// v7.38 (read01 P3.17) — reject a clearly-invalid value for a handful of
37/// well-known typed GUCs (boolean / memory-size / duration), so a typo
38/// like `SET work_mem = 'bogus'` errors like PG instead of silently
39/// storing junk. Conservative: only GUCs whose type is unambiguous are
40/// checked; every other name is accepted so pg_dump preambles and
41/// unknown settings still load.
42fn validate_known_guc(name: &str, value: &str) -> Result<(), EngineError> {
43    let key = name.to_ascii_lowercase();
44    let bad = || {
45        EngineError::Unsupported(alloc::format!(
46            "invalid value for parameter \"{name}\": \"{value}\""
47        ))
48    };
49    let is_bool = matches!(
50        value.trim().to_ascii_lowercase().as_str(),
51        "on" | "off" | "true" | "false" | "yes" | "no" | "1" | "0"
52    );
53    // Split a `<number><unit>` GUC value into its numeric head + unit tail.
54    let split_unit = |s: &str| -> (String, String) {
55        let st = s.trim();
56        let cut = st
57            .find(|c: char| c.is_ascii_alphabetic())
58            .unwrap_or(st.len());
59        (
60            String::from(st[..cut].trim()),
61            st[cut..].trim().to_ascii_lowercase(),
62        )
63    };
64    let (num, unit) = split_unit(value);
65    let is_size =
66        num.parse::<f64>().is_ok() && matches!(unit.as_str(), "" | "b" | "kb" | "mb" | "gb" | "tb");
67    let is_duration = num.parse::<i64>().is_ok()
68        && matches!(unit.as_str(), "" | "us" | "ms" | "s" | "min" | "h" | "d");
69    match key.as_str() {
70        "enable_seqscan"
71        | "enable_indexscan"
72        | "enable_bitmapscan"
73        | "enable_indexonlyscan"
74        | "enable_hashjoin"
75        | "enable_mergejoin"
76        | "enable_nestloop"
77        | "autovacuum"
78        | "fsync"
79        | "full_page_writes" => {
80            if !is_bool {
81                return Err(bad());
82            }
83        }
84        "work_mem"
85        | "maintenance_work_mem"
86        | "shared_buffers"
87        | "temp_buffers"
88        | "effective_cache_size"
89        | "wal_buffers" => {
90            if !is_size {
91                return Err(bad());
92            }
93        }
94        "statement_timeout" | "lock_timeout" | "idle_in_transaction_session_timeout" => {
95            if !is_duration {
96                return Err(bad());
97            }
98        }
99        // v7.39 (round 171) — synchronous_commit is a real, session-level
100        // durability control now (the embedded execute path gates its
101        // WAL-fsync wait on it); validate PG's value domain.
102        "synchronous_commit" => {
103            if !matches!(
104                value.to_ascii_lowercase().as_str(),
105                "on" | "off"
106                    | "local"
107                    | "remote_write"
108                    | "remote_apply"
109                    | "true"
110                    | "false"
111                    | "0"
112                    | "1"
113            ) {
114                return Err(bad());
115            }
116        }
117        // v7.39 (round 204) — enum GUCs reject an out-of-domain value
118        // like PG (`SET client_min_messages = bogus` errors). PG's
119        // message quotes the value with a trailing hint listing the
120        // valid set; we match the leading, stable clause.
121        "client_min_messages" => {
122            if !matches!(
123                value.trim().to_ascii_lowercase().as_str(),
124                "debug5"
125                    | "debug4"
126                    | "debug3"
127                    | "debug2"
128                    | "debug1"
129                    | "log"
130                    | "notice"
131                    | "warning"
132                    | "error"
133                    | "fatal"
134                    | "panic"
135            ) {
136                return Err(bad());
137            }
138        }
139        // v7.39 (GUC knife 3) — the render GUCs reject invalid values
140        // with PG's own texts (canonical-caps parameter names).
141        "datestyle" => {
142            if crate::session::parse_datestyle_parts(value, crate::eval::RenderStyle::default())
143                .is_none()
144            {
145                return Err(EngineError::Unsupported(alloc::format!(
146                    "invalid value for parameter \"DateStyle\": \"{value}\""
147                )));
148            }
149        }
150        "intervalstyle" => {
151            if crate::session::parse_intervalstyle(value).is_none() {
152                return Err(EngineError::Unsupported(alloc::format!(
153                    "invalid value for parameter \"IntervalStyle\": \"{value}\""
154                )));
155            }
156        }
157        "extra_float_digits" => match value.trim().parse::<i64>() {
158            Ok(n) if (-15..=3).contains(&n) => {}
159            Ok(n) => {
160                return Err(EngineError::Unsupported(alloc::format!(
161                    "{n} is outside the valid range for parameter \
162                         \"extra_float_digits\" (-15 .. 3)"
163                )));
164            }
165            Err(_) => return Err(bad()),
166        },
167        _ => {}
168    }
169    Ok(())
170}
171
172fn panic_payload_to_engine_error(payload: &(dyn core::any::Any + Send)) -> EngineError {
173    // The injection framework panics with a typed error; surface its
174    // message so tests get a deterministic, informative string.
175    #[cfg(feature = "injection-points")]
176    if let Some(inj) = payload.downcast_ref::<crate::testkit::injection::InjectedError>() {
177        return EngineError::Internal(alloc::format!("query aborted by internal error: {inj}"));
178    }
179    let detail = payload
180        .downcast_ref::<&'static str>()
181        .map(|s| String::from(*s))
182        .or_else(|| payload.downcast_ref::<String>().cloned());
183    match detail {
184        Some(d) => EngineError::Internal(alloc::format!("query aborted by internal error: {d}")),
185        None => EngineError::Internal(String::from("query aborted by internal error")),
186    }
187}
188
189impl Engine {
190    pub fn execute(&mut self, sql: &str) -> Result<QueryResult, EngineError> {
191        self.execute_in_with_cancel(sql, IMPLICIT_TX, CancelToken::none())
192    }
193
194    /// v7.38 (read01 P3.20) — handle a bare `SELECT set_config(name, value,
195    /// is_local)` by writing the GUC to the same session store `SET` uses
196    /// (honouring `is_local` via the transaction undo log), so set_config,
197    /// SHOW, current_setting, and pg_settings all agree. Returns `None`
198    /// (fall through to the ordinary read-only path) unless the statement is
199    /// exactly that shape — set_config buried in a FROM/WHERE/CTE, or over a
200    /// non-text name, keeps the old value-returning behaviour.
201    fn try_exec_set_config(
202        &mut self,
203        s: &spg_sql::ast::SelectStatement,
204    ) -> Result<Option<QueryResult>, EngineError> {
205        use spg_sql::ast::{Expr, SelectItem};
206        if s.from.is_some() || s.where_.is_some() || !s.ctes.is_empty() || s.items.len() != 1 {
207            return Ok(None);
208        }
209        let SelectItem::Expr { expr, .. } = &s.items[0] else {
210            return Ok(None);
211        };
212        let Expr::FunctionCall { name, args } = expr else {
213            return Ok(None);
214        };
215        if !(name.eq_ignore_ascii_case("set_config")
216            || name.eq_ignore_ascii_case("pg_catalog.set_config"))
217            || !(args.len() == 2 || args.len() == 3)
218        {
219            return Ok(None);
220        }
221        // Evaluate the arguments against an empty row.
222        let empty: Vec<ColumnSchema> = Vec::new();
223        let (name_v, value_v, local_v);
224        {
225            let ctx = self.ev_ctx(&empty, None);
226            let dummy = spg_storage::Row::new(Vec::new());
227            name_v = crate::eval::eval_expr(&args[0], &dummy, &ctx).map_err(EngineError::Eval)?;
228            value_v = crate::eval::eval_expr(&args[1], &dummy, &ctx).map_err(EngineError::Eval)?;
229            local_v = if args.len() == 3 {
230                crate::eval::eval_expr(&args[2], &dummy, &ctx).map_err(EngineError::Eval)?
231            } else {
232                Value::Bool(false)
233            };
234        }
235        let single = |v: Value<'static>| QueryResult::Rows {
236            columns: alloc::vec![ColumnSchema::new(
237                "set_config",
238                spg_storage::DataType::Text,
239                true
240            )],
241            rows: alloc::vec![spg_storage::Row::new(alloc::vec![v])],
242        };
243        let pname = match name_v {
244            Value::Text(s) => s.into_owned(),
245            // set_config(NULL, …) is a no-op returning NULL (PG).
246            Value::Null => return Ok(Some(single(Value::Null))),
247            _ => return Ok(None),
248        };
249        let is_local = matches!(local_v, Value::Bool(true));
250        // A NULL value resets the GUC to its default (PG), returning NULL.
251        let pval = match value_v {
252            Value::Text(s) => s.into_owned(),
253            Value::Null => {
254                self.session_params.remove(&pname.to_ascii_lowercase());
255                self.refresh_render_style();
256                return Ok(Some(single(Value::Null)));
257            }
258            _ => return Ok(None),
259        };
260        validate_known_guc(&pname, &pval)?;
261        if is_local {
262            if self.in_transaction() {
263                let prior = self.session_param(&pname).map(String::from);
264                self.local_guc_saves.push((pname.clone(), prior));
265                self.set_session_param(pname, spg_sql::ast::SetValue::String(pval.clone()));
266            }
267        } else {
268            self.set_session_param(pname, spg_sql::ast::SetValue::String(pval.clone()));
269        }
270        Ok(Some(single(Value::text(pval))))
271    }
272
273    /// v4.5 — write path with cooperative cancellation. Same dispatch
274    /// as `execute_in_with_cancel(sql, IMPLICIT_TX, cancel)`. Kept as
275    /// a separate entry point for backward-compat with the v4.5
276    /// public API.
277    pub fn execute_with_cancel(
278        &mut self,
279        sql: &str,
280        cancel: CancelToken<'_>,
281    ) -> Result<QueryResult, EngineError> {
282        self.execute_in_with_cancel(sql, IMPLICIT_TX, cancel)
283    }
284
285    /// v4.41.1 multi-slot write entry. Routes `sql` through the TX
286    /// slot identified by `tx_id` so spg-server dispatch can scope
287    /// each implicit-wrap BEGIN..stmt..COMMIT to its own slot in
288    /// `tx_catalogs`. `IMPLICIT_TX` is the legacy single-slot path
289    /// every other caller (engine self-tests, replay, spg-embedded)
290    /// implicitly takes via `execute()` / `execute_with_cancel()`.
291    pub fn execute_in(&mut self, sql: &str, tx_id: TxId) -> Result<QueryResult, EngineError> {
292        self.execute_in_with_cancel(sql, tx_id, CancelToken::none())
293    }
294
295    /// v4.41.1 write path with cooperative cancellation + explicit TX
296    /// scope. Sets `self.current_tx` for the duration of the call so
297    /// every `exec_*` helper transparently sees its TX's shadow
298    /// catalog and savepoint stack; restores on exit so the field is
299    /// only valid mid-call (no leakage across calls).
300    pub fn execute_in_with_cancel(
301        &mut self,
302        sql: &str,
303        tx_id: TxId,
304        cancel: CancelToken<'_>,
305    ) -> Result<QueryResult, EngineError> {
306        // v7.38 P0 元机制 A — establish the per-engine injection
307        // scope for the duration of this execute. The guard pops
308        // the store on drop so nested or sibling engines don't see
309        // ours. No-op in release builds (feature off).
310        let _inj = self.enter_injection_scope();
311        // v7.39 (read01 round 46) — NOTICEs are per-statement: clear the
312        // buffer here so one statement's "…, skipping" can never leak into
313        // the next one's NoticeResponse batch.
314        self.pending_notices.clear();
315        let saved = self.current_tx;
316        self.current_tx = Some(tx_id);
317        // v7.37.15 (Epic W slice 2) — memoized autocommit writer version
318        // is scoped to one statement. Save + reset like `current_tx` so
319        // a re-entrant execute (e.g. deferred trigger SQL) can't leak its
320        // version into ours, and ours never leaks to the next statement.
321        let saved_stmt_wv = self.stmt_writer_version;
322        self.stmt_writer_version = None;
323        // v7.34 (crash-recovery P0 #2) — row-level redo capture. Arm the
324        // active catalog before dispatch; on success drain the physical
325        // changes into `last_redo` for the embedding layer's WAL, on
326        // failure discard them (a failed statement leaves no redo; the
327        // drain clears the tables' capture buffers either way).
328        // v7.39 (round 736, S14/B3) — a delta-maintainable materialized
329        // view needs the same physical change stream the WAL reads, so
330        // its presence enables capture too (the fan-out below copies;
331        // `last_redo` stays the embedding layer's alone).
332        let matview_capture = !self.matview_maintainable.is_empty();
333        if self.redo_capture || matview_capture {
334            self.active_catalog_mut().enable_redo_all();
335        }
336        // v7.38 Epic P (panic isolation) — run statement execution
337        // behind a catch_unwind firewall so a panic in query
338        // processing surfaces as an ordinary `EngineError` (after
339        // rolling the in-flight tx back) instead of unwinding through
340        // the server's engine `RwLock` write guard (which would poison
341        // it) or aborting the process. NO-OP under the release
342        // `panic = "abort"` profile — the process aborts before any
343        // unwind reaches here; active in dev/test (`panic = "unwind"`)
344        // and once a later slice flips the release profile.
345        let pre_in_tx = self.in_transaction();
346        let result = self.execute_inner_catching(sql, cancel);
347        // v7.39 (round 426) — MySQL's ROW_COUNT() reads what the LAST
348        // statement did. Measured on MariaDB 11: a DML statement leaves the
349        // number of rows it changed (0 when it matched none), a
350        // row-returning statement leaves -1, and DDL leaves 0. One place,
351        // because every statement funnels through here — and it must be
352        // AFTER the dispatch, so ROW_COUNT()'s own SELECT is what sets -1
353        // for the call after it (as MariaDB does).
354        //
355        // A failed statement leaves the previous value alone: MariaDB keeps
356        // the last successful statement's count through an error.
357        if let Ok(res) = &result {
358            self.row_count = match res {
359                QueryResult::CommandOk { affected, .. } => i64::try_from(*affected).unwrap_or(-1),
360                QueryResult::Rows { .. } => -1,
361            };
362        }
363        // v7.39 (pg_stat knife A) — PG counts every statement outside a
364        // transaction block as one implicit xact (commit on success,
365        // rollback on error). Statements INSIDE a block are counted
366        // once, by exec_commit / exec_rollback; BEGIN itself (state
367        // flips outside -> inside) and the block-closers (inside ->
368        // outside, counted in their exec fns) are skipped here.
369        if !pre_in_tx && !self.in_transaction() {
370            let ctr = if result.is_ok() {
371                &self.xact_commit
372            } else {
373                &self.xact_rollback
374            };
375            ctr.fetch_add(1, core::sync::atomic::Ordering::Relaxed);
376        }
377        // r196 — a statement that did NOT run inside its own open tx
378        // slot (autocommit, or a COMMIT/ROLLBACK that just closed its
379        // slot) may have moved the committed base; bump the epoch so
380        // OTHER open txs know their next RC rebase is real. The test
381        // must be per-statement (`tx_catalogs` membership of THIS
382        // call's tx_id), not the global `in_transaction()` — a
383        // concurrent autocommit while some tx is open is exactly the
384        // case the rebase exists for (the first cut used the global
385        // check and 10 isolation pins caught the missed bumps).
386        // Deliberately over-approximate (reads bump too — an extra
387        // rebase is only slower, never wrong).
388        if !self.tx_catalogs.contains_key(&tx_id) {
389            self.commit_epoch = self.commit_epoch.wrapping_add(1);
390            // v7.39 (round 306) — large-object descriptors live only as
391            // long as the transaction that opened them, so this is
392            // exactly where they die: an autocommit statement (the
393            // implicit transaction just ended) or the COMMIT / ROLLBACK
394            // that closed the slot. Numbering restarts from 0, as PG's
395            // does. Same per-slot witness as the epoch bump above —
396            // another connection's open transaction must not keep this
397            // one's descriptors alive.
398            self.lo_descriptors.clear();
399            self.lo_next_fd = 0;
400        }
401        if self.redo_capture || matview_capture {
402            let mut drained = self.active_catalog_mut().drain_redo();
403            if result.is_ok() {
404                if matview_capture {
405                    self.fan_out_matview_deltas(&drained);
406                }
407                // v7.37.15 (Epic W slice 2) — stamp the real committing
408                // writer version onto every change this statement
409                // produced. All changes from one statement share the one
410                // version (the statement's xmin/xmax): in autocommit it's
411                // the memoized value the writes already used; inside an
412                // explicit tx it's the deterministic tx entry. Purely
413                // additive metadata — replay still resolves by physical
414                // position and ignores `writer_version` (later slice).
415                if !drained.is_empty() {
416                    let v = self.writer_version_for_current_stmt();
417                    for change in &mut drained {
418                        change.set_writer_version(v);
419                    }
420                }
421                if self.redo_capture {
422                    self.last_redo = drained;
423                }
424            }
425        }
426        self.current_tx = saved;
427        self.stmt_writer_version = saved_stmt_wv;
428        result
429    }
430
431    /// v6.1.1 — parse and pre-process a SQL string ONCE so the
432    /// resulting [`Statement`] can be cached and re-executed via
433    /// [`Engine::execute_prepared`]. Returns the same `Statement`
434    /// the simple-query path would synthesise internally (clock
435    /// rewrites + ORDER BY position-ref resolution applied at
436    /// prepare time, since both are session-independent). The
437    /// `$N` placeholders in the SQL stay as `Expr::Placeholder(n)`
438    /// nodes; they're resolved to concrete values per-call by
439    /// `execute_prepared`'s substitution walk.
440    ///
441    /// Pgwire's `Parse` (P) message lands here.
442    pub fn prepare(&self, sql: &str) -> Result<Statement, ParseError> {
443        let mut stmt = parser::parse_statement_with(sql, self.backslash_escapes)?;
444        self.preprocess(&mut stmt);
445        Ok(stmt)
446    }
447
448    /// r1043 — every pre-pass a parsed statement gets before execution,
449    /// in one place.
450    ///
451    /// There were two copies. `prepare` had clock rewrites, `GROUP BY
452    /// ALL` expansion, ORDER BY position resolution and the JOIN reorder;
453    /// `execute_readonly_with_cancel` — the path EVERY autocommit SELECT
454    /// takes over the wire — had the same list minus the `GROUP BY ALL`
455    /// expansion, and then r1042 added constant folding to one of them.
456    ///
457    /// The result was a plan that `EXPLAIN` described and the wire did not
458    /// run: `WHERE b = decode(lpad(to_hex(7),16,'0'),'hex')` planned as an
459    /// index scan and took 194 ms, against 0.009 ms for the same statement
460    /// through the embedded API, on the same build and the same 400,000
461    /// rows. EXPLAIN went through `prepare`; the query did not.
462    ///
463    /// One function, both callers. A pass added here reaches every route
464    /// by construction rather than by remembering.
465    pub(crate) fn preprocess(&self, stmt: &mut Statement) {
466        let now_micros = self.clock.map(|f| f());
467        rewrite_clock_calls(
468            stmt,
469            now_micros,
470            self.backslash_escapes,
471            now_micros.map_or(0, |n| self.session_tz_offset_at(n)),
472        );
473        // r1042 — evaluate the constant parts of every predicate once,
474        // here, instead of once per row. A cast on a literal is the
475        // common case and it was costing an index seek: `WHERE id = 7`
476        // sought and `WHERE id = 7::int` scanned, 23x apart at 400k rows.
477        crate::constfold::fold_statement(stmt);
478        if let Statement::Select(s) = stmt {
479            // v6.4.1 — expand `GROUP BY ALL` to every non-aggregate
480            // SELECT-list item BEFORE position / alias resolution so
481            // downstream passes see the explicit list.
482            expand_group_by_all(s);
483            resolve_order_by_position(s);
484            // v6.2.3 — cost-based JOIN reorder. No-op for
485            // single-table FROMs or any non-INNER join shape.
486            // v7.38 元机制 D — `SPG_TEST_PLAN_DETERMINISTIC=1` gates
487            // this so regression tests pin a stable join order.
488            reorder::reorder_joins_with(
489                s,
490                &self.catalog,
491                &self.statistics,
492                self.env_cfg.plan_deterministic,
493            );
494        }
495    }
496
497    /// v6.3.0 — cached prepare. Returns a cloned `Statement` from
498    /// the plan cache on hit, runs the full `prepare()` path on miss
499    /// and inserts the resulting plan before returning. Skipping the
500    /// parse + JOIN-reorder pipeline on hit is the dominant win for
501    /// JDBC / sqlx / pgx clients that reuse the same SQL string.
502    ///
503    /// Returns a cloned `Statement` (not a borrow) because the
504    /// pgwire layer owns its `PreparedStmt` map per-session and the
505    /// engine-level cache must stay available for other sessions.
506    /// Clone cost on a 5-table JOIN AST is well under the parse cost
507    /// it replaces.
508    /// v7.39 (round 192) — bump the engine-side per-table DML
509    /// counters (pg_stat_user_tables n_tup_*). Non-transactional by
510    /// design, like PG's stats collector.
511    pub(crate) fn note_table_write(&mut self, table: &str, ins: u64, upd: u64, del: u64) {
512        let e = self
513            .table_write_stats
514            .entry(alloc::string::String::from(table))
515            .or_insert((0, 0, 0));
516        e.0 = e.0.saturating_add(ins);
517        e.1 = e.1.saturating_add(upd);
518        e.2 = e.2.saturating_add(del);
519    }
520
521    pub fn prepare_cached(&mut self, sql: &str) -> Result<Statement, ParseError> {
522        // v7.39 (round 200) — don't cache LARGE statements. A 24 KB
523        // multi-row VALUES INSERT paid a full AST deep-clone (~640 µs)
524        // just to enter the plan cache, where a unique bulk statement
525        // is never reused — and at that size a cache hit would only
526        // save the ~190 µs re-parse anyway. The threshold keeps every
527        // ORM-shaped statement (small, repeated) on the cached path.
528        const PLAN_CACHE_MAX_SQL_BYTES: usize = 4096;
529        if sql.len() > PLAN_CACHE_MAX_SQL_BYTES {
530            return self.prepare(sql);
531        }
532        // v6.3.1 — version-aware lookup. If the cached plan was
533        // prepared before the most recent ANALYZE, evict and replan.
534        let current_version = self.statistics.version();
535        if let Some(plan) = self.plan_cache.get(sql) {
536            if plan.statistics_version == current_version {
537                return Ok(plan.stmt.clone());
538            }
539            // Stale entry — fall through to evict + re-prepare.
540        }
541        self.plan_cache.evict(sql);
542        let stmt = self.prepare(sql)?;
543        let source_tables = plan_cache::collect_source_tables(&stmt);
544        let plan = plan_cache::PreparedPlan {
545            stmt: stmt.clone(),
546            statistics_version: current_version,
547            source_tables,
548            describe_columns: alloc::vec::Vec::new(),
549        };
550        self.plan_cache.insert(String::from(sql), plan);
551        Ok(stmt)
552    }
553
554    /// v6.3.0 — read-only accessor for tests and v6.3.1 invalidation.
555    pub fn plan_cache(&self) -> &plan_cache::PlanCache {
556        &self.plan_cache
557    }
558
559    /// v7.38 (mailrs prod 7.35 pool-exhaustion incident) — boot-time
560    /// plan-IR cache warm-up. Walks `sqls`, calls `prepare_cached`
561    /// on each one. Each successful prepare leaves the parsed +
562    /// reordered + clock-rewritten `Statement` in the engine-wide
563    /// plan cache; subsequent `Engine::execute` / `execute_prepared`
564    /// for the same SQL skips parse + JOIN reorder. Returns the
565    /// count of successfully cached statements.
566    ///
567    /// The mailrs `Database::new` boot path is the expected caller:
568    /// pre-warm the top-N query shapes (inbox listing, contacts
569    /// search, stats) so the first user-facing request doesn't
570    /// pay the 2-3 s first-fire cost on the readonly-blocking
571    /// sqlx pool — which (under prod concurrency) exhausts the
572    /// pool and stalls the whole UI.
573    pub fn warm_up_plan_cache(&mut self, sqls: &[&str]) -> usize {
574        let mut warmed = 0;
575        for sql in sqls {
576            if self.prepare_cached(sql).is_ok() {
577                warmed += 1;
578            }
579        }
580        warmed
581    }
582
583    /// v7.38 (mailrs prod 7.35 pool-exhaustion incident) — boot-time
584    /// cold-tier OS page-cache warm-up. Walks every table in the
585    /// active catalog, iterates the cold rows via the existing
586    /// BTree-driven `iter_cold_rows_of_table`, drops the rows on
587    /// the floor. The walk's side effect is that every cold
588    /// segment file gets mmap-read once — the OS page cache then
589    /// serves subsequent queries without disk I/O.
590    ///
591    /// Returns the total cold rows touched across all tables.
592    /// On a hot-only catalog (no `cold_segments` populated) the
593    /// call is a near-no-op.
594    pub fn warm_up_cold_tier(&self) -> usize {
595        let catalog = self.active_catalog();
596        let mut total = 0;
597        for name in catalog.table_names() {
598            if let Some(table) = catalog.get(&name) {
599                let rows = self.iter_cold_rows_of_table(table);
600                total += rows.len();
601            }
602        }
603        total
604    }
605
606    /// v6.3.0 — mutable accessor for v6.3.1 invalidation hooks.
607    pub fn plan_cache_mut(&mut self) -> &mut plan_cache::PlanCache {
608        &mut self.plan_cache
609    }
610
611    /// v6.3.3 — Describe a prepared `Statement` without executing.
612    /// Returns `(parameter_oids, output_columns)`. Empty
613    /// `output_columns` means the statement has no row-producing shape
614    /// we could resolve here — the pgwire layer maps that to `NoData`.
615    ///
616    /// v7.39 (round 462) — a SELECT over a system catalog view resolves
617    /// against the same materialised catalog execution builds, so the
618    /// two paths cannot disagree about what a system view looks like.
619    pub fn describe_prepared(&self, stmt: &Statement) -> (Vec<u32>, Vec<ColumnSchema>) {
620        if let Statement::Select(s) = stmt {
621            if crate::system_catalog::select_references_meta_view(s)
622                && let Ok(catalog) = self.meta_view_catalog(s)
623            {
624                return describe::describe_prepared(stmt, &catalog);
625            }
626            if let Some(catalog) = self.admin_view_catalog(s) {
627                return describe::describe_prepared(stmt, &catalog);
628            }
629        }
630        describe::describe_prepared(stmt, self.active_catalog())
631    }
632
633    /// v6.1.1 — execute a [`Statement`] previously returned by
634    /// [`Engine::prepare`], substituting `Expr::Placeholder(n)`
635    /// nodes for the corresponding [`Value`] in `params` (1-based
636    /// per PG: `$1` → `params[0]`). Bind-time string parameters
637    /// are decoded into typed `Value`s by the pgwire layer before
638    /// this call so the resulting AST hits the same execution
639    /// path as a simple query — no SQL re-parse.
640    ///
641    /// Pgwire's `Execute` (E) message after a `Bind` (B) lands here.
642    pub fn execute_prepared(
643        &mut self,
644        stmt: Statement,
645        params: &[Value<'static>],
646    ) -> Result<QueryResult, EngineError> {
647        self.execute_prepared_with_cancel(stmt, params, CancelToken::none())
648    }
649
650    /// v7.37 (SPGS small-query bar) — borrow-based SELECT entry for
651    /// the pgwire `Execute` hot path when the portal has no bound
652    /// parameters. Skips both the AST clone the prepared path used
653    /// to do at the pgwire call site AND the `substitute_
654    /// placeholders` walk (a no-op when params are empty). Caller
655    /// must already hold the engine write lock — read would be
656    /// cleaner, but `current_tx` mutation keeps it `&mut`.
657    pub fn execute_prepared_select_no_params(
658        &mut self,
659        stmt: &spg_sql::ast::SelectStatement,
660        cancel: CancelToken<'_>,
661    ) -> Result<QueryResult, EngineError> {
662        let saved = self.current_tx;
663        self.current_tx = Some(IMPLICIT_TX);
664        // v7.38 Epic P (panic isolation) — Slice 3: route this read-only
665        // prepared-SELECT hot path (pgwire `Execute` with no bound params)
666        // through the SAME `catch_unwind` firewall as the write paths. A
667        // panic in `exec_select_cancel` is caught inside the engine and
668        // returned as `EngineError::Internal`, so it never unwinds through
669        // the caller's engine `RwLock` write guard (poisoning it) or aborts
670        // the process. This path is read-only, so the firewall's
671        // `discard_tx_on_panic` is a no-op (no shadow / writer version to
672        // drop) — exactly right: nothing to roll back, just catch + survive.
673        // `exec_select_cancel` materialises its `QueryResult` synchronously,
674        // so the whole result is produced inside the catch (statement
675        // boundary only — no per-row cost).
676        #[cfg(feature = "std")]
677        let result = self.catch_stmt_panic(|s| s.exec_select_cancel(stmt, cancel));
678        #[cfg(not(feature = "std"))]
679        let result = self.exec_select_cancel(stmt, cancel);
680        self.current_tx = saved;
681        result
682    }
683
684    /// v7.37.17 — `SHOW <name>` / `SHOW ALL`. Extracted (r1058) so the
685    /// READ-ONLY dispatcher can serve it too: the wire routes SHOW as a
686    /// read, and its fallthrough (unknown-to-the-wire names) landed on
687    /// `WriteRequired` instead of this answer.
688    pub(crate) fn exec_show_parameter(
689        &self,
690        name: alloc::string::String,
691    ) -> Result<QueryResult, EngineError> {
692        use spg_storage::{ColumnSchema, DataType, Row, Value};
693        // v7.37.17 (17.6 sibling) — `SHOW ALL` returns a
694        // (name, setting, description) triple for every
695        // parameter SPG knows about. PG's shape is the same.
696        // Emitting a fixed curated inventory here keeps the
697        // client shape stable without wire-tapping every
698        // per-session parameter.
699        // v7.38 (read01 P3.20/P3.23) — SHOW reads the same canonical
700        // GUC inventory as pg_settings, so `SHOW <name>` / `SHOW ALL`
701        // and pg_settings never disagree on which params exist.
702        let canon = crate::system_catalog::canonical_gucs();
703        let effective = |n: &str, boot: &str| -> alloc::string::String {
704            self.session_params
705                .iter()
706                .find(|(k, _)| k.eq_ignore_ascii_case(n))
707                .map(|(_, v)| v.clone())
708                .unwrap_or_else(|| boot.into())
709        };
710        if name.eq_ignore_ascii_case("all") {
711            let cols = alloc::vec![
712                ColumnSchema::new("name", DataType::Text, false),
713                ColumnSchema::new("setting", DataType::Text, false),
714                ColumnSchema::new("description", DataType::Text, false),
715            ];
716            let mut rows: Vec<Row> = Vec::new();
717            // Dynamic params outside the static canonical table.
718            rows.push(Row::new(alloc::vec![
719                Value::text(alloc::string::String::from("transaction_isolation")),
720                Value::text(alloc::string::String::from(
721                    self.current_isolation_level.as_pg_str(),
722                )),
723                Value::text(alloc::string::String::from(
724                    "Shows the current transaction's isolation level.",
725                )),
726            ]));
727            // v7.38.18 (C5) — `is_superuser` is deliberately NOT here.
728            // PG 18.4 answers `SHOW is_superuser` with `on` and has no
729            // row for it in `pg_settings`, so `SHOW ALL` does not list
730            // it either — measured, and the single reason SPG returned
731            // 399 rows against PG's 398 after this list was completed.
732            // `SHOW is_superuser` still answers, below, exactly as PG's
733            // does.
734            // v7.38.18 (C5) — every parameter PG 18.4 has, and PG's own
735            // one-line description in the third column. It used to be
736            // thirty-three rows carrying the CATEGORY under a heading
737            // that says `description`, which is neither PG's count nor
738            // PG's content. SPG's own list wins where the two overlap,
739            // because its value for `work_mem` is the real one.
740            for (n, boot, cat, _, _) in canon {
741                let d = crate::guc_catalog::guc_short_desc(n).unwrap_or(*cat);
742                rows.push(Row::new(alloc::vec![
743                    Value::text(alloc::string::String::from(*n)),
744                    Value::text(effective(n, boot)),
745                    Value::text(alloc::string::String::from(d)),
746                ]));
747            }
748            for &(n, _, human, _, _, _, _, d) in crate::guc_catalog::PG_GUC_CONTEXTS {
749                if canon.iter().any(|(c, ..)| (*c).eq_ignore_ascii_case(n)) {
750                    continue;
751                }
752                // ...nor the two pushed above with live values. PG has
753                // rows for both, so without this `SHOW ALL` returned 400
754                // where PG returns 398, with two names twice.
755                if rows
756                    .iter()
757                    .take(1)
758                    .any(|r| matches!(&r.values[0], Value::Text(t) if t.eq_ignore_ascii_case(n)))
759                {
760                    continue;
761                }
762                rows.push(Row::new(alloc::vec![
763                    Value::text(alloc::string::String::from(n)),
764                    Value::text(effective(n, human)),
765                    Value::text(alloc::string::String::from(d)),
766                ]));
767            }
768            // PG lists them in name order and a client reading `SHOW ALL`
769            // as a table sees that order; the two lists above are each
770            // sorted but interleave.
771            rows.sort_by_key(|r| match &r.values[0] {
772                Value::Text(t) => alloc::string::String::from(t.as_ref()),
773                other => alloc::format!("{other:?}"),
774            });
775            return Ok(QueryResult::Rows {
776                columns: cols,
777                rows,
778            });
779        }
780        // v7.38.18 (C12) — `SHOW WARNINGS`, MySQL's diagnostics area.
781        //
782        // Non-strict `sql_mode` bends a value that would not fit — the
783        // bending has been byte-for-byte MySQL's since v7.39 round 470
784        // — and MySQL TELLS you it did. Until now SPG bent the value
785        // silently, so an application that checks after an insert had
786        // no way to learn its data had been changed.
787        //
788        // Three columns, named and ordered as MySQL returns them.
789        // Reading does not clear: only the next warning-generating
790        // statement does.
791        // MySQL-only. PostgreSQL 18.4 answers `ERROR: unrecognized
792        // configuration parameter "warnings"`, and a PG session must
793        // keep getting that: a compatibility surface that leaks into
794        // the other dialect is a divergence of its own, and I put one
795        // there for a few minutes before checking.
796        // v7.38.18 (C12) — `SHOW COUNT(*) WARNINGS`, the size of that
797        // same diagnostics area. MySQL 9 answers it with one row of one
798        // column NAMED `@@session.warning_count`, which is the name a
799        // client library keys on; the parser folds the whole phrase to
800        // this one sentinel so no GUC can collide with it. Same dialect
801        // gate as `SHOW WARNINGS` above, for the same reason.
802        if self.backslash_escapes && name.eq_ignore_ascii_case("count(*) warnings") {
803            let cols = alloc::vec![ColumnSchema::new(
804                alloc::string::String::from("@@session.warning_count"),
805                spg_storage::DataType::BigInt,
806                false
807            )];
808            let n = i64::try_from(self.mysql_warnings.len()).unwrap_or(i64::MAX);
809            return Ok(QueryResult::Rows {
810                columns: cols,
811                rows: alloc::vec![Row::new(alloc::vec![Value::BigInt(n)])],
812            });
813        }
814
815        if self.backslash_escapes && name.eq_ignore_ascii_case("warnings") {
816            let cols = alloc::vec![
817                ColumnSchema::new(
818                    alloc::string::String::from("Level"),
819                    spg_storage::DataType::Text,
820                    false
821                ),
822                ColumnSchema::new(
823                    alloc::string::String::from("Code"),
824                    spg_storage::DataType::Int,
825                    false
826                ),
827                ColumnSchema::new(
828                    alloc::string::String::from("Message"),
829                    spg_storage::DataType::Text,
830                    false
831                ),
832            ];
833            let rows: Vec<Row> = self
834                .mysql_warnings
835                .iter()
836                .map(|w| {
837                    Row::new(alloc::vec![
838                        Value::text(w.level),
839                        Value::Int(i32::from(w.code)),
840                        Value::text(w.message.clone()),
841                    ])
842                })
843                .collect();
844            return Ok(QueryResult::Rows {
845                columns: cols,
846                rows,
847            });
848        }
849
850        let value: alloc::string::String = match name.to_ascii_lowercase().as_str() {
851            // v7.39 — the FOURTH surface, and the one my own count of
852            // this defect missed: `SHOW transaction_isolation` read the
853            // raw field, which outside a transaction is whatever the
854            // last one left rather than the session default. The pin
855            // found it, which is the argument for pinning agreement
856            // between surfaces instead of any one value.
857            "transaction_isolation" => {
858                alloc::string::String::from(self.current_isolation_level().as_pg_str())
859            }
860            // v7.39 — measured on PG 18.6: `off` by default, `on` inside
861            // `BEGIN READ ONLY`, `on` outside any transaction once
862            // `default_transaction_read_only` is set, and `off` again
863            // after. Both report surfaces are wired in the same change;
864            // wiring one and leaving its sibling is the shape this
865            // version keeps finding.
866            "transaction_read_only" => {
867                alloc::string::String::from(if self.transaction_read_only() {
868                    "on"
869                } else {
870                    "off"
871                })
872            }
873            "is_superuser" => alloc::string::String::from("on"),
874            _ => {
875                // Canonical GUC? report the session override or its
876                // boot default. Otherwise a user-set custom GUC, or a
877                // recognised-name error pointing at pg_settings.
878                if let Some((_, boot, ..)) =
879                    canon.iter().find(|(n, ..)| n.eq_ignore_ascii_case(&name))
880                {
881                    effective(&name, boot)
882                } else if let Some(v) = self.session_param(&name) {
883                    alloc::string::String::from(v)
884                } else if let Some(boot) = crate::guc_catalog::guc_boot_value(&name) {
885                    // v7.39 (round 534) — a parameter PG18 knows but
886                    // SPG does not model reports its compiled-in
887                    // default. `SHOW random_page_cost` printed
888                    // nothing at all before, and `SHOW fsync` with
889                    // it.
890                    alloc::string::String::from(boot)
891                } else {
892                    return Err(EngineError::Unsupported(alloc::format!(
893                        "SHOW {name:?}: parameter not recognised; \
894                             see `SELECT name, setting FROM pg_settings` for \
895                             the full inventory"
896                    )));
897                }
898            }
899        };
900        Ok(QueryResult::Rows {
901            columns: alloc::vec![ColumnSchema::new(name, DataType::Text, false)],
902            rows: alloc::vec![Row::new(alloc::vec![Value::text(value)])],
903        })
904    }
905
906    /// v7.37 — streaming SELECT for the pgwire `Execute` hot path.
907    /// Emits one `StreamItem::Header(cols)` then one
908    /// `StreamItem::Row(&[&Value])` per surviving row. Returns the
909    /// total row count for the `CommandComplete` tag.
910    ///
911    /// For shapes where the engine can stream directly (non-aggregate
912    /// join projection of bound columns, no ORDER BY / DISTINCT / etc.)
913    /// no `Vec<Row<'static>>` is materialised — cell references come straight
914    /// out of the source tables. For non-streamable shapes the engine
915    /// runs the full `exec_select_cancel`, then walks the materialised
916    /// `Vec<Row<'static>>` driving the same emit callback (no engine-side win,
917    /// but pgwire dispatches every Execute through one path).
918    pub fn execute_prepared_select_streaming<F>(
919        &mut self,
920        stmt: &spg_sql::ast::SelectStatement,
921        cancel: CancelToken<'_>,
922        mut emit: F,
923    ) -> Result<usize, EngineError>
924    where
925        F: FnMut(StreamItem<'_>) -> Result<(), EngineError>,
926    {
927        let saved = self.current_tx;
928        self.current_tx = Some(IMPLICIT_TX);
929        // v7.38 Epic P (panic isolation) — Slice 3: route the streaming
930        // read-only SELECT hot path through the SAME `catch_unwind` firewall.
931        //
932        // Catch SCOPE (verified): `exec_select_streaming` uses a *push*
933        // model — it drives the caller's `emit` callback synchronously via
934        // `?` for the header and every row (both the true-streaming
935        // `try_exec_joined_streaming` fast path and the materialising
936        // fall-back), and only returns once the whole result has been
937        // emitted. It does NOT hand a lazy iterator back to the wire layer to
938        // pull rows from later. Therefore a panic in the per-row streaming
939        // phase unwinds *inside* this call and IS caught by wrapping the one
940        // `exec_select_streaming` call — the entire streaming phase is
941        // covered, not just setup. This is a single statement-boundary catch
942        // (the `catch_unwind` landing pad is armed once, the whole emit loop
943        // runs inside it) — NOT a per-row catch, so there is no hot-path cost.
944        // Read-only, so `discard_tx_on_panic` is a no-op (correct: nothing to
945        // roll back). A panic caught mid-stream (after some rows were encoded
946        // into the wire buffer) leaves the same partial-`wbuf` + `Err` state
947        // the wire layer already handles when `emit` itself returns `Err`
948        // mid-stream, so no new torn-state concern is introduced.
949        #[cfg(feature = "std")]
950        let inner = self.catch_stmt_panic(|s| s.exec_select_streaming(stmt, cancel, &mut emit));
951        #[cfg(not(feature = "std"))]
952        let inner = self.exec_select_streaming(stmt, cancel, &mut emit);
953        self.current_tx = saved;
954        inner
955    }
956
957    /// v7.37 — internal streaming dispatcher. Phase 1: fall-back path
958    /// only — runs the materialising `exec_select_cancel`, then drives
959    /// the emit callback from the resulting `Vec<Row<'static>>`. Phase 2 will
960    /// add a true streaming path for the joined-projection shape.
961    fn exec_select_streaming<F>(
962        &mut self,
963        stmt: &spg_sql::ast::SelectStatement,
964        cancel: CancelToken<'_>,
965        emit: &mut F,
966    ) -> Result<usize, EngineError>
967    where
968        F: FnMut(StreamItem<'_>) -> Result<(), EngineError>,
969    {
970        // v7.37 — true-streaming fast path for joined-non-aggregate
971        // projection of bound columns. Skips `Vec<Row<'static>>` + per-cell
972        // `.cloned()` (about 4 ms saved on the 25 k-row PROJ shape).
973        // Unresolved subqueries / pull-up shapes / non-streamable
974        // structure (ORDER BY, DISTINCT, …) fall through to the
975        // materialising path.
976        if !crate::subquery::expr_tree_has_subquery(stmt) {
977            if let Some(n) = self.try_exec_joined_streaming(stmt, cancel, emit)? {
978                return Ok(n);
979            }
980        }
981        // Fall-back: materialise then iterate.
982        let QueryResult::Rows { columns, rows } = self.exec_select_cancel(stmt, cancel)? else {
983            return Err(EngineError::Unsupported(alloc::string::String::from(
984                "streaming SELECT got a non-Rows result",
985            )));
986        };
987        emit_materialised(&columns, &rows, cancel, emit)
988    }
989}
990
991/// Hand an already-materialised result to a streaming consumer: one
992/// `Header`, then every row, checking for cancellation as it goes.
993///
994/// v7.37 (round 824) — this loop existed three times, in
995/// `exec_select_streaming` and twice in the read-only entry points, and
996/// none of the three checked cancellation. A `statement_timeout` — and
997/// `CancelRequest`, which shares the token — therefore did not bound any
998/// shape the streaming path declines: arithmetic and function
999/// projections, `ORDER BY`, `DISTINCT`. Measured over 200k rows of 200
1000/// bytes under a 120ms timeout, every one of them ran to completion,
1001/// all 200000 rows, no error.
1002///
1003/// The loop reads like the cheap half of the work, since the rows
1004/// already exist. It is not: handing them to `emit` is what encodes them
1005/// and pushes them at the socket, and that is most of the elapsed time
1006/// (first row out at 30ms of 400ms). So the interruption a client asked
1007/// for never happened, and it never happened for the shapes most likely
1008/// to need it.
1009///
1010/// It is one function now so that the next copy cannot go missing the
1011/// check — which is how all three came to be missing it.
1012pub(crate) fn emit_materialised<F>(
1013    columns: &[ColumnSchema],
1014    rows: &[spg_storage::Row<'static>],
1015    cancel: CancelToken<'_>,
1016    emit: &mut F,
1017) -> Result<usize, EngineError>
1018where
1019    F: FnMut(StreamItem<'_>) -> Result<(), EngineError>,
1020{
1021    emit(StreamItem::Header(columns))?;
1022    let mut cell_refs: Vec<&Value> = Vec::with_capacity(columns.len());
1023    for (i, row) in rows.iter().enumerate() {
1024        // Same cadence as the streaming path's own check.
1025        if i.is_multiple_of(256) {
1026            cancel.check()?;
1027        }
1028        cell_refs.clear();
1029        for v in &row.values {
1030            cell_refs.push(v);
1031        }
1032        emit(StreamItem::Row(RowCells::Refs(&cell_refs)))?;
1033    }
1034    Ok(rows.len())
1035}
1036
1037/// One row's cells, in whichever shape the producer already holds them.
1038///
1039/// The channel used to be `&[&Value]` only, which cost a `Vec<&Value>`
1040/// per row at the two producers that build their cells into a
1041/// contiguous buffer: they had a `&[Value]` in hand and collected a
1042/// second vector of pointers into it purely to satisfy the type. That
1043/// is one heap allocation and one free per row — measured at 400k rows
1044/// (round 957) as **9 ns/row**, which on a narrow scan was 54-56% of
1045/// the whole walk and on a wide one 8-19%.
1046///
1047/// The reason it could not simply reuse one buffer is that the values
1048/// buffer is refilled each row, so any pointers into it die at the top
1049/// of the next iteration; only an owner of the storage (the
1050/// materialising path, whose rows outlive the loop) can hoist the
1051/// pointer vector out. Handing the contiguous slice over directly
1052/// removes the question instead of answering it.
1053///
1054/// `Refs` stays for producers whose cells really are scattered (a join
1055/// projecting out of several rows).
1056#[derive(Debug, Clone, Copy)]
1057pub enum RowCells<'a> {
1058    Refs(&'a [&'a Value<'static>]),
1059    Values(&'a [Value<'static>]),
1060}
1061
1062impl<'a> RowCells<'a> {
1063    pub fn len(&self) -> usize {
1064        match self {
1065            RowCells::Refs(v) => v.len(),
1066            RowCells::Values(v) => v.len(),
1067        }
1068    }
1069
1070    pub fn is_empty(&self) -> bool {
1071        self.len() == 0
1072    }
1073
1074    pub fn get(&self, i: usize) -> Option<&'a Value<'static>> {
1075        match self {
1076            RowCells::Refs(v) => v.get(i).copied(),
1077            RowCells::Values(v) => v.get(i),
1078        }
1079    }
1080}
1081
1082/// v7.37 — one item in the streaming SELECT emit channel. The
1083/// engine yields exactly one `Header` (before any row) then zero
1084/// or more `Row`s. Pgwire (or any other consumer) decides how to
1085/// turn those into wire bytes.
1086#[derive(Debug)]
1087pub enum StreamItem<'a> {
1088    Header(&'a [ColumnSchema]),
1089    Row(RowCells<'a>),
1090}
1091
1092impl Engine {
1093    /// v7.17.0 Phase 2.3 — prepared-statement entry that honors a
1094    /// caller-supplied `CancelToken`. Mirrors `execute_prepared`'s
1095    /// `current_tx` save/restore so the extended-query path stays
1096    /// transactionally consistent with the simple-query path.
1097    /// v7.39 (round 280) — `CREATE STATISTICS`.
1098    fn exec_create_statistics(
1099        &mut self,
1100        name: String,
1101        if_not_exists: bool,
1102        kinds: alloc::vec::Vec<String>,
1103        columns: alloc::vec::Vec<String>,
1104        table: String,
1105    ) -> Result<QueryResult, EngineError> {
1106        if columns.len() < 2 {
1107            return Err(EngineError::Unsupported(String::from(
1108                "extended statistics require at least 2 columns",
1109            )));
1110        }
1111        if self.active_catalog().get(&table).is_none() {
1112            return Err(EngineError::Unsupported(alloc::format!(
1113                "relation \"{table}\" does not exist"
1114            )));
1115        }
1116        // PG's default kind set is all three.
1117        let kinds = if kinds.is_empty() {
1118            alloc::vec![String::from("d"), String::from("f"), String::from("m")]
1119        } else {
1120            kinds
1121        };
1122        let def = spg_storage::StatisticsExtDef {
1123            name: name.clone(),
1124            table,
1125            kinds,
1126            columns,
1127        };
1128        let cat = self.active_catalog_mut();
1129        if let Err(taken) = cat.create_statistics_ext(def) {
1130            if if_not_exists {
1131                return Ok(QueryResult::CommandOk {
1132                    affected: 0,
1133                    modified_catalog: false,
1134                });
1135            }
1136            return Err(EngineError::Unsupported(alloc::format!(
1137                "statistics object \"{taken}\" already exists"
1138            )));
1139        }
1140        Ok(QueryResult::CommandOk {
1141            affected: 0,
1142            modified_catalog: true,
1143        })
1144    }
1145
1146    /// v7.39 (round 280) — `DROP STATISTICS`.
1147    fn exec_drop_statistics(
1148        &mut self,
1149        name: &str,
1150        if_exists: bool,
1151    ) -> Result<QueryResult, EngineError> {
1152        let dropped = self.active_catalog_mut().drop_statistics_ext(name);
1153        if !dropped && !if_exists {
1154            return Err(EngineError::Unsupported(alloc::format!(
1155                "statistics object \"{name}\" does not exist"
1156            )));
1157        }
1158        Ok(QueryResult::CommandOk {
1159            affected: 0,
1160            modified_catalog: dropped,
1161        })
1162    }
1163
1164    /// v7.39 (round 277) — `PREPARE`. Session-scoped, and a duplicate
1165    /// name is an error in PG rather than a silent replace.
1166    fn exec_prepare(
1167        &mut self,
1168        name: String,
1169        param_types: alloc::vec::Vec<String>,
1170        body: Statement,
1171        source: String,
1172    ) -> Result<QueryResult, EngineError> {
1173        if self.prepared_statements.contains_key(&name) {
1174            return Err(EngineError::Unsupported(alloc::format!(
1175                "prepared statement \"{name}\" already exists"
1176            )));
1177        }
1178        // v7.38.4 (sentori 6a, at their request) — PG refuses a PREPARE
1179        // whose parameter cannot be deduced consistently. Their
1180        // assert-stats upsert puts `$4` in a bigint column and again in
1181        // `CASE WHEN $4 > 0`, where the literal is integer: PG answers
1182        // "inconsistent types deduced for parameter $4". SPG let the
1183        // last context win silently.
1184        //
1185        // Only when the type was NOT declared. `PREPARE p (…, bigint, …)`
1186        // is accepted by PG and runs, and sqlx always declares — which is
1187        // why the statement works in their production and why refusing a
1188        // declared parameter would break every driver that does the
1189        // right thing.
1190        if let Some((n, first, second)) =
1191            crate::describe::conflicting_parameter_deductions(&body, self.active_catalog())
1192            && param_types.get((n as usize).saturating_sub(1)).is_none()
1193        {
1194            return Err(EngineError::Unsupported(alloc::format!(
1195                "inconsistent types deduced for parameter ${n} DETAIL: {first} versus {second}"
1196            )));
1197        }
1198        self.prepared_statements.insert(
1199            name,
1200            crate::PreparedSqlStatement {
1201                body,
1202                param_types,
1203                source,
1204            },
1205        );
1206        Ok(QueryResult::CommandOk {
1207            affected: 0,
1208            modified_catalog: false,
1209        })
1210    }
1211
1212    /// v7.39 (round 277) — `EXECUTE`. The arguments evaluate as
1213    /// constants and splice into the body's `$N` placeholders through
1214    /// the same `execute_prepared_with_cancel` the extended-query path
1215    /// uses, so a SQL EXECUTE and a wire Bind take the identical route.
1216    fn exec_execute(
1217        &mut self,
1218        name: &str,
1219        args: &[spg_sql::ast::Expr],
1220        cancel: CancelToken<'_>,
1221    ) -> Result<QueryResult, EngineError> {
1222        let Some(entry) = self.prepared_statements.get(name) else {
1223            return Err(EngineError::Unsupported(alloc::format!(
1224                "prepared statement \"{name}\" does not exist"
1225            )));
1226        };
1227        let body = entry.body.clone();
1228        let empty: alloc::vec::Vec<spg_storage::ColumnSchema> = alloc::vec::Vec::new();
1229        let ctx = self.ev_ctx(&empty, None);
1230        let blank = spg_storage::Row::new(alloc::vec::Vec::new());
1231        let mut params: alloc::vec::Vec<spg_storage::Value<'static>> =
1232            alloc::vec::Vec::with_capacity(args.len());
1233        for a in args {
1234            params.push(crate::eval::eval_expr(a, &blank, &ctx).map_err(EngineError::Eval)?);
1235        }
1236        self.execute_prepared_with_cancel(body, &params, cancel)
1237    }
1238
1239    /// v7.39 (round 277) — `DEALLOCATE <name>` / `DEALLOCATE ALL`.
1240    /// Dropping a name that does not exist is an error in PG; ALL is
1241    /// unconditional.
1242    fn exec_deallocate(&mut self, name: Option<&str>) -> Result<QueryResult, EngineError> {
1243        match name {
1244            None => {
1245                self.prepared_statements.clear();
1246                Ok(QueryResult::CommandOk {
1247                    affected: 0,
1248                    modified_catalog: false,
1249                })
1250            }
1251            Some(n) => {
1252                if self.prepared_statements.remove(n).is_none() {
1253                    return Err(EngineError::Unsupported(alloc::format!(
1254                        "prepared statement \"{n}\" does not exist"
1255                    )));
1256                }
1257                Ok(QueryResult::CommandOk {
1258                    affected: 0,
1259                    modified_catalog: false,
1260                })
1261            }
1262        }
1263    }
1264
1265    pub fn execute_prepared_with_cancel(
1266        &mut self,
1267        stmt: Statement,
1268        params: &[Value<'static>],
1269        cancel: CancelToken<'_>,
1270    ) -> Result<QueryResult, EngineError> {
1271        self.execute_prepared_in_with_cancel(stmt, params, IMPLICIT_TX, cancel)
1272    }
1273
1274    /// v7.39 (round 303, V22) — like [`Self::execute_prepared_with_cancel`]
1275    /// but binds the statement to an explicit transaction slot instead of
1276    /// the implicit one. The mysql-wire binary-protocol path uses this so a
1277    /// prepared INSERT/UPDATE lands in the connection's own `BEGIN`-opened
1278    /// transaction (and never collides with another connection on slot 0),
1279    /// mirroring what pgwire's `Bind`+`Execute` achieves by rendering
1280    /// bind-final SQL through [`Self::execute_in`].
1281    pub fn execute_prepared_in(
1282        &mut self,
1283        stmt: Statement,
1284        params: &[Value<'static>],
1285        tx_id: TxId,
1286    ) -> Result<QueryResult, EngineError> {
1287        self.execute_prepared_in_with_cancel(stmt, params, tx_id, CancelToken::none())
1288    }
1289
1290    pub fn execute_prepared_in_with_cancel(
1291        &mut self,
1292        mut stmt: Statement,
1293        params: &[Value<'static>],
1294        tx_id: TxId,
1295        cancel: CancelToken<'_>,
1296    ) -> Result<QueryResult, EngineError> {
1297        substitute_placeholders(&mut stmt, params)?;
1298        // v7.16.0 — set `current_tx` for the duration of the
1299        // dispatch so the `exec_*` helpers see the right TX
1300        // slot (matches what `execute_in_with_cancel` does for
1301        // simple-query). Pre-v7.16 the simple-query path
1302        // worked because every public entry point routed
1303        // through `execute_in_with_cancel`; the prepared path
1304        // skipped the wrap and so its INSERTs/UPDATEs landed
1305        // in the no-tx default slot, silently invisible to a
1306        // BEGIN/COMMIT-bracketed flow. Caught by spg-sqlx's
1307        // first transaction-visibility test.
1308        let saved = self.current_tx;
1309        self.current_tx = Some(tx_id);
1310        // v7.38 Epic P (panic isolation) — Slice 2: route the
1311        // prepared / extended-query path (the one sqlx / asyncpg / most
1312        // drivers actually use via pgwire `Bind`+`Execute`) through the
1313        // SAME `catch_unwind` firewall as the simple-query path (Slice 1,
1314        // `execute_inner_catching`). A panic in an extended-protocol
1315        // statement is caught inside the engine, the in-flight tx is
1316        // rolled back (shared `discard_tx_on_panic`), and the caller sees
1317        // an ordinary `EngineError::Internal` — never a poisoned write
1318        // guard or an aborted process. `current_tx` is `Some(IMPLICIT_TX)`
1319        // for the duration, so a caught panic rolls back the right tx; the
1320        // `saved` restore below still runs because the catch converts the
1321        // unwind into a normal `Result` return.
1322        let result = self.execute_stmt_catching(stmt, cancel);
1323        self.current_tx = saved;
1324        // r1059 — the r196 per-slot epoch witness, on THIS entry path
1325        // too. The bump lived only in `execute_in_with_cancel`, so an
1326        // autocommit write arriving over the extended protocol's
1327        // direct route moved the committed base with the epoch
1328        // unchanged; a concurrent RC transaction whose last rebase
1329        // matched the stale epoch then skipped its commit-time rebase
1330        // and installed its whole shadow — erasing the write. The
1331        // sqlx gate flaked ~1-in-6 on exactly this: DROP/CREATE
1332        // vanishing under a neighbouring transaction's COMMIT. Same
1333        // over-approximation as r196 (an extra rebase is only slower,
1334        // never wrong); large-object descriptors die at the same
1335        // boundary for the same per-slot reason (round 306).
1336        if !self.tx_catalogs.contains_key(&tx_id) {
1337            self.commit_epoch = self.commit_epoch.wrapping_add(1);
1338            self.lo_descriptors.clear();
1339            self.lo_next_fd = 0;
1340        }
1341        result
1342    }
1343
1344    /// v7.38 Epic P (panic isolation) — shared `catch_unwind` firewall
1345    /// (hosted `std` builds) used by every engine statement entry path: the
1346    /// simple-query ([`Self::execute_inner_catching`]), the prepared /
1347    /// extended-query ([`Self::execute_stmt_catching`]), and the read-only
1348    /// prepared-SELECT hot paths ([`Self::execute_prepared_select_no_params`]
1349    /// / [`Self::execute_prepared_select_streaming`]). Runs `run` under
1350    /// `catch_unwind`; a panic that unwinds out of statement execution is
1351    /// caught here and converted to [`EngineError::Internal`] after
1352    /// discarding the in-flight tx's shadow, so the caller sees a normal SQL
1353    /// error and the engine stays alive. This is the single place the
1354    /// rollback-on-panic policy lives — neither entry path reimplements it.
1355    ///
1356    /// **Why the post-catch engine state is consistent (COW shadow argument):**
1357    /// every uncommitted write of the panicked statement lives in
1358    /// `tx_catalogs[current_tx].catalog` — a per-tx *shadow* catalog that is
1359    /// only merged into the committed `self.catalog` at COMMIT (see
1360    /// `exec_commit`). The committed catalog is therefore never touched
1361    /// mid-statement, so dropping the shadow (mirroring `exec_rollback`)
1362    /// discards all half-applied work and leaves `self.catalog` exactly as it
1363    /// was before the statement. Redo-capture buffers live inside the
1364    /// shadow's tables and die with it, so no partial `RowChange` leaks into
1365    /// `last_redo` either (the caller publishes `last_redo` only on `Ok`).
1366    ///
1367    /// The `catch_unwind` closure holds `&mut self`; wrapping it in
1368    /// `AssertUnwindSafe` is sound precisely because of the above — the only
1369    /// caller-visible state a caught panic can leave behind is the discarded
1370    /// shadow, which is the correct rollback outcome, not a torn invariant.
1371    ///
1372    /// Generic over the closure's success type `T` so the read-only
1373    /// prepared-SELECT paths (which return a row count `usize`, not a
1374    /// `QueryResult`) reuse the *same* firewall — no second `catch_unwind`
1375    /// site. On those read-only paths `discard_tx_on_panic` is a no-op (a
1376    /// SELECT opens no shadow / writer version), which is the correct outcome:
1377    /// nothing to roll back, the point is purely to catch the unwind, return
1378    /// `Internal`, and leave the caller's write guard un-poisoned.
1379    #[cfg(feature = "std")]
1380    fn catch_stmt_panic<T>(
1381        &mut self,
1382        run: impl FnOnce(&mut Self) -> Result<T, EngineError>,
1383    ) -> Result<T, EngineError> {
1384        extern crate std;
1385        let caught = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| run(self)));
1386        match caught {
1387            Ok(result) => result,
1388            Err(payload) => {
1389                // The panic unwound past every `?`-return in the executor.
1390                // `current_tx` is Some here (set by the caller); roll that tx
1391                // back by discarding its shadow. A statement that panicked in
1392                // autocommit before any shadow was opened simply has nothing
1393                // to drop (`discard_tx_on_panic` is infallible).
1394                let tx_id = self.current_tx.unwrap_or(IMPLICIT_TX);
1395                self.discard_tx_on_panic(tx_id);
1396                Err(panic_payload_to_engine_error(payload.as_ref()))
1397            }
1398        }
1399    }
1400
1401    /// v7.38 Epic P (panic isolation) — simple-query path wrapper: run
1402    /// [`Self::execute_inner_with_cancel`] behind the shared
1403    /// [`Self::catch_stmt_panic`] firewall.
1404    #[cfg(feature = "std")]
1405    fn execute_inner_catching(
1406        &mut self,
1407        sql: &str,
1408        cancel: CancelToken<'_>,
1409    ) -> Result<QueryResult, EngineError> {
1410        self.catch_stmt_panic(|s| s.execute_inner_with_cancel(sql, cancel))
1411    }
1412
1413    /// `no_std` variant — there is no unwinding runtime, so statement
1414    /// execution runs directly with no catch.
1415    #[cfg(not(feature = "std"))]
1416    fn execute_inner_catching(
1417        &mut self,
1418        sql: &str,
1419        cancel: CancelToken<'_>,
1420    ) -> Result<QueryResult, EngineError> {
1421        self.execute_inner_with_cancel(sql, cancel)
1422    }
1423
1424    /// v7.38 Epic P (panic isolation) — Slice 2: prepared / extended-query
1425    /// path wrapper. The extended-protocol path already holds a resolved
1426    /// [`Statement`] (no re-parse), so it cannot reuse the `&str`-taking
1427    /// [`Self::execute_inner_catching`]; instead it runs
1428    /// [`Self::execute_stmt_with_cancel`] behind the SAME shared
1429    /// [`Self::catch_stmt_panic`] firewall — identical rollback + error
1430    /// semantics, zero duplicated policy.
1431    #[cfg(feature = "std")]
1432    fn execute_stmt_catching(
1433        &mut self,
1434        stmt: Statement,
1435        cancel: CancelToken<'_>,
1436    ) -> Result<QueryResult, EngineError> {
1437        self.catch_stmt_panic(|s| s.execute_stmt_with_cancel(stmt, cancel))
1438    }
1439
1440    /// `no_std` variant — there is no unwinding runtime, so statement
1441    /// execution runs directly with no catch.
1442    #[cfg(not(feature = "std"))]
1443    fn execute_stmt_catching(
1444        &mut self,
1445        stmt: Statement,
1446        cancel: CancelToken<'_>,
1447    ) -> Result<QueryResult, EngineError> {
1448        self.execute_stmt_with_cancel(stmt, cancel)
1449    }
1450
1451    /// v7.38 Epic P — discard an in-flight tx's shadow after a caught panic,
1452    /// mirroring the state cleanup of [`Engine::exec_rollback`] but
1453    /// infallibly. Drops the shadow catalog, marks the tx's writer version
1454    /// aborted, and releases its row locks. Leaves the committed
1455    /// `self.catalog` untouched (the COW model kept every uncommitted change
1456    /// inside the shadow), so this is a full rollback of the panicked
1457    /// statement's work.
1458    #[cfg(feature = "std")]
1459    fn discard_tx_on_panic(&mut self, tx_id: TxId) {
1460        self.tx_catalogs.remove(&tx_id);
1461        if let Some(v) = self.tx_writer_versions.remove(&tx_id) {
1462            self.abort_writer_version(v);
1463            self.release_tx_locks(v);
1464        }
1465        // Per-statement scratch: reset so no stale writer version leaks into
1466        // the next statement (the caller also restores the saved value).
1467        self.stmt_writer_version = None;
1468    }
1469
1470    fn execute_inner_with_cancel(
1471        &mut self,
1472        sql: &str,
1473        cancel: CancelToken<'_>,
1474    ) -> Result<QueryResult, EngineError> {
1475        cancel.check()?;
1476        let stmt = self.prepare(sql)?;
1477        // v6.5.1 — wrap the executor with a wall-clock window so we
1478        // can record into spg_stat_query. Skip when the engine has
1479        // no clock attached (no_std embedded callers).
1480        let start_us = self.clock.map(|f| f());
1481        let result = self.execute_stmt_with_cancel(stmt, cancel);
1482        if let (Some(t0), Ok(ok)) = (start_us, &result) {
1483            let now = self.clock.map_or(t0, |f| f());
1484            let elapsed = now.saturating_sub(t0).max(0) as u64;
1485            // v7.37.22 (22.9) — count rows produced (SELECT) or
1486            // affected (INSERT/UPDATE/DELETE) so pg_stat_statements'
1487            // `rows` column populates accurately.
1488            let row_count: u64 = match ok {
1489                QueryResult::Rows { rows, .. } => rows.len() as u64,
1490                QueryResult::CommandOk { affected, .. } => *affected as u64,
1491            };
1492            self.query_stats
1493                .record_with_rows(sql, elapsed, now as u64, row_count);
1494            // v6.5.6 — slow-query log: fire callback when elapsed
1495            // exceeds the configured floor.
1496            if let (Some(threshold), Some(logger)) =
1497                (self.slow_query_threshold_us, self.slow_query_logger)
1498                && elapsed >= threshold
1499            {
1500                logger(sql, elapsed);
1501            }
1502        }
1503        result
1504    }
1505
1506    /// v7.38 (read01 P3.26) — transaction-abort firewall around the raw
1507    /// statement dispatch. After a statement fails inside an explicit
1508    /// transaction PG aborts the whole block: every later statement except
1509    /// COMMIT / ROLLBACK / ROLLBACK TO SAVEPOINT is rejected, and a COMMIT
1510    /// is downgraded to a ROLLBACK so no partial work slips through. We
1511    /// mirror that here so both the embedded engine and the wire server
1512    /// enforce it uniformly.
1513    pub(crate) fn execute_stmt_with_cancel(
1514        &mut self,
1515        stmt: Statement,
1516        cancel: CancelToken<'_>,
1517    ) -> Result<QueryResult, EngineError> {
1518        // v7.39 (round 298) — ask THIS transaction, not "is any
1519        // transaction anywhere aborted".
1520        if self.current_tx_aborted() {
1521            match stmt {
1522                Statement::Rollback | Statement::RollbackToSavepoint(_) => {}
1523                // PG performs a ROLLBACK for a COMMIT in an aborted tx.
1524                Statement::Commit => {
1525                    let r = self.dispatch_stmt_inner(Statement::Rollback, cancel);
1526                    self.set_current_tx_aborted(false);
1527                    return r;
1528                }
1529                _ => return Err(EngineError::InFailedTransaction),
1530            }
1531        }
1532        let is_rollback_to_savepoint = matches!(stmt, Statement::RollbackToSavepoint(_));
1533        // v7.37.17 (Phase E2) — READ COMMITTED per-statement visibility:
1534        // classify (the statement moves into dispatch below), rebase the
1535        // open RC tx's shadow onto the latest committed catalog, then
1536        // record the statement's targets afterwards. Both calls are
1537        // no-ops outside an explicit transaction.
1538        let tx_class = crate::classify_stmt_for_tx(&stmt);
1539        if !matches!(tx_class, crate::TxStmtClass::TxControl) {
1540            // v7.37.17 (E4 r3) — a unique-key collision found while
1541            // rebasing fails THIS statement with 40001 (the tx aborts
1542            // via the standard failed-statement path below, like PG's
1543            // in-statement 23505 after the lock wait).
1544            self.maybe_rc_rebase()?;
1545        }
1546        // v7.39 (round 552) — what a SERIALIZABLE tx READ, taken before
1547        // the statement is consumed, recorded after it succeeds.
1548        let read_tables = crate::transaction::read_tables_of(&stmt);
1549        let result = self.dispatch_stmt_inner(stmt, cancel);
1550        if result.is_ok() {
1551            self.record_tx_stmt(&tx_class);
1552            self.record_tx_reads(read_tables);
1553        }
1554        // v7.39 (round 298) — the witness is THIS connection's slot.
1555        // `in_transaction()` is true whenever ANY connection holds a
1556        // transaction, so an autocommit failure used to abort a block
1557        // that belonged to somebody else.
1558        let mine_open = self.current_tx.is_some_and(|tx| self.is_tx_open(tx));
1559        if !mine_open {
1560            // The tx ended (COMMIT / ROLLBACK) or we were in autocommit;
1561            // either way there is no aborted block to remember.
1562            self.set_current_tx_aborted(false);
1563        } else if result.is_ok() && is_rollback_to_savepoint {
1564            // Rolling back to a savepoint recovers the transaction.
1565            self.set_current_tx_aborted(false);
1566        } else if matches!(result, Err(EngineError::LockWouldBlock)) {
1567            // v7.39 (round 300) — NOT a failure: the server drops the
1568            // engine lock and retries. Marking the block aborted here
1569            // made the FIRST block poison the transaction, so the
1570            // retry hit the abort firewall and the waiter lost a
1571            // deadlock it should have won.
1572        } else if result.is_err() {
1573            // A failure inside an open transaction aborts the whole block.
1574            self.set_current_tx_aborted(true);
1575        }
1576        result
1577    }
1578
1579    /// v7.38.18 (C12) — the one gate MySQL's diagnostics area passes
1580    /// through. Every statement runs inside this; the body below is the
1581    /// dispatch itself.
1582    pub(crate) fn dispatch_stmt_inner(
1583        &mut self,
1584        stmt: Statement,
1585        cancel: CancelToken<'_>,
1586    ) -> Result<QueryResult, EngineError> {
1587        // v7.38.18 (C12) — MySQL's diagnostics area belongs to ONE
1588        // statement, and a read returns the PREVIOUS statement's.
1589        // Measured on MySQL 9, after an INSERT that bends two values:
1590        //
1591        //   SELECT @@warning_count      -> 2   (the INSERT's)
1592        //   SELECT @@warning_count      -> 0   (the first SELECT's own)
1593        //   SHOW COUNT(*) WARNINGS      -> unchanged; reads do not publish
1594        //
1595        // So the visible set is replaced when a statement ENDS, not
1596        // when it starts — clearing on entry would make the first read
1597        // answer 0 and lose the warning entirely. Readers publish
1598        // nothing, which is why two reads in a row agree.
1599        //
1600        // Without any of this the warnings never expire, and a client
1601        // that checks after the wrong statement is told its data was
1602        // bent when it was not — worse than silence, because it is a
1603        // claim. I shipped exactly that a few hours ago; it took
1604        // writing `SHOW COUNT(*) WARNINGS` to notice.
1605        //
1606        // Same place as the NOTICE clear below, and for the same
1607        // reason: the one point the simple-query and prepared paths
1608        // both pass through.
1609        let publishes_warnings = !matches!(&stmt, Statement::ShowParameter(n)
1610            if n.eq_ignore_ascii_case("warnings")
1611                || n.eq_ignore_ascii_case("count(*) warnings"));
1612        if publishes_warnings {
1613            self.mysql_stmt_warnings.clear();
1614        }
1615        let result = self.dispatch_stmt_body(stmt, cancel);
1616        if publishes_warnings {
1617            self.mysql_warnings = core::mem::take(&mut self.mysql_stmt_warnings);
1618        }
1619        result
1620    }
1621
1622    fn dispatch_stmt_body(
1623        &mut self,
1624        stmt: Statement,
1625        cancel: CancelToken<'_>,
1626    ) -> Result<QueryResult, EngineError> {
1627        cancel.check()?;
1628        // v7.39 — a read-only transaction refuses writes. SPG enforced
1629        // nothing: `BEGIN READ ONLY; INSERT …` answered `INSERT 0 1` and
1630        // committed, and `default_transaction_read_only = on` changed
1631        // nothing either, though both GUCs were in the inventory and both
1632        // read back the value they were given. Applications open
1633        // read-only transactions as a SAFETY measure — a reporting
1634        // connection, a read-only leg in a pool, a "this path must not
1635        // write" discipline — so accepting the writes is the worst
1636        // available answer.
1637        //
1638        // Here because this is the one point the simple-query and the
1639        // prepared paths both pass through (see the note above on the
1640        // warning-area clear, which is here for the same reason).
1641        // `EXECUTE` and `DO` reach it again for their inner statement,
1642        // which is how PG gets `DO $$ … INSERT … $$` to fail with
1643        // `cannot execute INSERT` rather than something about DO.
1644        if self.current_tx_read_only
1645            && self
1646                .current_tx
1647                .is_some_and(|id| self.tx_catalogs.contains_key(&id))
1648            && let Some(tag) = stmt.read_only_violation_tag()
1649        {
1650            return Err(EngineError::Unsupported(alloc::format!(
1651                "cannot execute {tag} in a read-only transaction"
1652            )));
1653        }
1654        // v7.17.0 Phase 1.1 — pre-resolve nextval / currval /
1655        // setval calls in the statement tree. Walks SELECT
1656        // projection, INSERT VALUES, UPDATE SET, DELETE WHERE,
1657        // and DEFAULT exprs; replaces sequence FunctionCall
1658        // nodes with concrete Literal values minted against the
1659        // catalog. This is the only place that mutates sequence
1660        // state from a SELECT-shaped path (exec_select_cancel is
1661        // `&self` and can't reach the catalog mutably).
1662        //
1663        // Fast-path: when no sequences exist anywhere in the
1664        // catalog (the typical hot-path INSERT load), skip the
1665        // walker entirely. Single map-emptiness check on the
1666        // catalog beats walking every expression on every call.
1667        let mut stmt = stmt;
1668        // v7.17 dump-compat — the fast-path check
1669        // `sequences().is_empty()` skips pre-resolve when no
1670        // sequence exists in the *currently active* catalog
1671        // snapshot. The committed catalog or the implicit-TX
1672        // catalog may legitimately disagree on this between
1673        // CREATE SEQUENCE and a later setval(): always run the
1674        // resolver — the walk is O(expr-count) and dwarfed by
1675        // the parse cost we just paid.
1676        self.pre_resolve_sequence_calls_in_statement(&mut stmt)?;
1677        // v7.39 (round 305, V23) — evaluate any non-constant LIMIT /
1678        // OFFSET down to a literal row count. It belongs here, at the
1679        // one point both the simple-query and the prepared path pass
1680        // through, because every executor reads the row count as
1681        // `Option<u32>` and takes `None` for "no limit": an expression
1682        // that reached execution would silently widen the result to the
1683        // whole table rather than fail.
1684        self.resolve_limit_exprs_in_statement(&mut stmt, cancel)?;
1685        // v7.39 (read01 round 57) — the table-privilege gate. A superuser
1686        // session (the default login, or `SET ROLE admin`) skips it entirely,
1687        // so nothing changes for a customer who never assumes another role.
1688        self.acl_check_statement(&stmt)?;
1689        // v7.39 (round 435) — MySQL commits an open transaction BEFORE it
1690        // runs DDL (and before a nested START TRANSACTION), where PG keeps
1691        // the DDL inside the transaction. A MySQL client that writes rows,
1692        // runs DDL and then rolls back keeps those rows on MySQL and lost
1693        // them on SPG — silently, since nothing errors. This is the one
1694        // point every path (simple query, prepared, extended) passes
1695        // through, so the commit cannot be skipped by a spelling.
1696        //
1697        // v7.39 (round 444) — the witness is THIS connection's slot, not
1698        // `in_transaction()`. That predicate is true whenever ANY connection
1699        // holds a transaction, so a second client's `BEGIN` tried to commit a
1700        // slot of its own that held nothing and answered an error instead —
1701        // caught by `two_mysql_connections_can_each_hold_a_transaction`, which
1702        // had been failing since round 435 introduced this hook. Same
1703        // global-vs-slot confusion rounds 279 / 283 / 298 / 304 each fixed
1704        // elsewhere; `current_tx` is the connection's own slot here, set by
1705        // `execute_in_with_cancel` before dispatch.
1706        let in_own_tx = self.current_tx.is_some_and(|t| self.is_tx_open(t));
1707        if self.backslash_escapes && in_own_tx && stmt.mysql_implicit_commit() {
1708            self.exec_commit()?;
1709        }
1710        let result = match stmt {
1711            // v7.39 (round 547) — `ALTER ROLE … SET/RESET` and
1712            // `ALTER DATABASE … SET/RESET`. These reported success and
1713            // changed nothing: both fell into the parser's pg_dump
1714            // no-op tail, so a DBA setting a per-role default got no
1715            // effect and no error.
1716            Statement::SetDbRoleSetting(st) => {
1717                // PG refuses a scope that names something absent.
1718                // v7.39 (round 696) — one predicate. This wrote its own
1719                // (`users.any(…) || postgres`), `acl_check_role_exists`
1720                // wrote a third, and round 652 already recorded what
1721                // happens when a role predicate and the catalog it reflects
1722                // disagree. `role_exists` is the one that answers.
1723                if let Some(role) = &st.role
1724                    && !self.role_exists(role)
1725                {
1726                    return Err(EngineError::Unsupported(alloc::format!(
1727                        "role \"{role}\" does not exist"
1728                    )));
1729                }
1730                if let Some(db) = &st.database {
1731                    let current = self
1732                        .session_params
1733                        .get("spg.database")
1734                        .cloned()
1735                        .unwrap_or_else(|| alloc::string::String::from("spg"));
1736                    if !db.eq_ignore_ascii_case(&current) {
1737                        return Err(EngineError::Unsupported(alloc::format!(
1738                            "database \"{db}\" does not exist"
1739                        )));
1740                    }
1741                }
1742                let db = st.database.clone().unwrap_or_default();
1743                let role = st.role.clone().unwrap_or_default();
1744                let cat = self.active_catalog_mut();
1745                match (&st.param, &st.value) {
1746                    (None, _) => cat.reset_db_role_settings(&db, &role),
1747                    (Some(p), v) => cat.set_db_role_setting(&db, &role, p, v.as_deref()),
1748                }
1749                Ok(QueryResult::CommandOk {
1750                    affected: 0,
1751                    modified_catalog: true,
1752                })
1753            }
1754            // v7.39 (round 430) — MySQL USER variables. The value is an
1755            // arbitrary expression, evaluated against an empty row (a
1756            // user-variable assignment is a statement, not a per-row thing),
1757            // and stored in the session's own namespace.
1758            //
1759            // Every right-hand side sees the state as it was BEFORE the
1760            // statement — the assignments do NOT become visible to each
1761            // other. Measured on MariaDB 11: with both fresh,
1762            // `SET @p = 1, @q = @p + 1` leaves @q NULL; with @r already 100,
1763            // `SET @r = 1, @s = @r + 1` leaves @s at 101, i.e. @r's OLD
1764            // value. (Separate statements do chain, as you would expect.)
1765            // So: evaluate them all, THEN apply them all.
1766            Statement::SetUserVars(assigns, settings) => {
1767                let mut resolved: Vec<(String, spg_storage::Value<'static>)> =
1768                    Vec::with_capacity(assigns.len());
1769                for (name, mut expr) in assigns {
1770                    // `SET @total = (SELECT SUM(v) FROM t)` is ordinary MySQL,
1771                    // so the scalar subqueries have to be materialised the way
1772                    // every other statement's do — eval_expr itself refuses to
1773                    // meet one.
1774                    self.resolve_expr_subqueries(&mut expr, cancel)?;
1775                    let cols: Vec<ColumnSchema> = Vec::new();
1776                    let value = {
1777                        let ctx = self.ev_ctx(&cols, None);
1778                        let empty = spg_storage::Row::new(Vec::new());
1779                        crate::eval::eval_expr(&expr, &empty, &ctx).map_err(EngineError::Eval)?
1780                    };
1781                    resolved.push((name, value.into_owned()));
1782                }
1783                for (name, value) in resolved {
1784                    self.user_vars.insert(name, value);
1785                }
1786                // v7.39 (round 554) — the session settings written in
1787                // the same statement, applied after the saves. Routed
1788                // through the ordinary SET path so `SQL_MODE` still
1789                // flips strictness and the rest land where a plain
1790                // `SET x = y` puts them.
1791                for (name, value) in settings {
1792                    let rendered = match crate::conversions::literal_expr_to_value_in(
1793                        value.clone(),
1794                        Some(self.active_catalog()),
1795                    ) {
1796                        Ok(v) => crate::eval::value_to_text(&v),
1797                        Err(_) => alloc::format!("{value}"),
1798                    };
1799                    let _ = self.execute(&alloc::format!("SET {name} = '{rendered}'"));
1800                }
1801                Ok(QueryResult::CommandOk {
1802                    affected: 0,
1803                    modified_catalog: false,
1804                })
1805            }
1806            // v7.39 (round 277) — SQL-level prepared statements.
1807            Statement::Prepare {
1808                name,
1809                param_types,
1810                body,
1811                source,
1812            } => self.exec_prepare(name, param_types, *body, source),
1813            Statement::Execute { name, args } => self.exec_execute(&name, &args, cancel),
1814            Statement::Deallocate(name) => self.exec_deallocate(name.as_deref()),
1815            // v7.39 (round 278) — both were accepted and dropped. They
1816            // are reported as MISSING OBJECTS rather than as syntax
1817            // errors, because the SQL parses fine; what is absent is a
1818            // procedure catalog and a prepared-transaction registry.
1819            // v7.39 (round 280) — extended statistics as a real
1820            // catalog object. The planner does not consult them yet;
1821            // recording them is what makes a pg_dump restore and
1822            // reflection honest, instead of the statement vanishing.
1823            Statement::CreateStatistics {
1824                name,
1825                if_not_exists,
1826                kinds,
1827                columns,
1828                table,
1829            } => self.exec_create_statistics(name, if_not_exists, kinds, columns, table),
1830            Statement::DropStatistics { name, if_exists } => {
1831                self.exec_drop_statistics(&name, if_exists)
1832            }
1833            Statement::Call(name) => Err(EngineError::Unsupported(alloc::format!(
1834                "procedure {name}() does not exist HINT: No procedure matches the given name \
1835                 and argument types. You might need to add explicit type casts."
1836            ))),
1837            Statement::PrepareTransaction(_) => Err(EngineError::Unsupported(String::from(
1838                "prepared transactions are disabled HINT: Set \"max_prepared_transactions\" \
1839                 to a nonzero value.",
1840            ))),
1841            Statement::CreateTable(s) => self.exec_create_table(s),
1842            // v7.39 (round 218) — server-side cursors.
1843            Statement::DeclareCursor {
1844                name,
1845                scroll,
1846                hold,
1847                query,
1848            } => self.exec_declare_cursor(name, scroll, hold, *query),
1849            Statement::FetchCursor { name, direction } => self.exec_fetch_cursor(&name, direction),
1850            Statement::MoveCursor { name, direction } => self.exec_move_cursor(&name, direction),
1851            Statement::CloseCursor { name } => self.exec_close_cursor(name.as_deref()),
1852            // v7.39 (round 222) — LISTEN/NOTIFY with real delivery.
1853            Statement::Listen(ch) => self.exec_listen(ch),
1854            Statement::Notify { channel, payload } => self.exec_notify(channel, payload),
1855            Statement::Unlisten(ch) => self.exec_unlisten(ch),
1856            // v7.9.15 — CREATE EXTENSION is a no-op on SPG. Returns
1857            // CommandOk with affected=0; modified_catalog=false so
1858            // the WAL doesn't grow a useless entry. mailrs F3.
1859            Statement::CreateExtension(_) => Ok(QueryResult::CommandOk {
1860                affected: 0,
1861                modified_catalog: false,
1862            }),
1863            // v7.16.2 — DO $$ ... $$ block. mailrs round-10 A.2
1864            // — the pre-v7.9.27 no-op SILENTLY swallowed every
1865            // mailrs migrate-038/-040/-042 idempotent rename
1866            // (the IF EXISTS … THEN ALTER … END block never
1867            // ran). v7.16.2 dispatches to exec_do_block which
1868            // runs the PlPgSqlBlock at top level via the same
1869            // execute_stmts machinery the trigger executor
1870            // uses (NEW=None, OLD=None — DO blocks have no
1871            // row context).
1872            Statement::DoBlock(body) => self.exec_do_block(body),
1873            // v7.14.0 — empty-statement no-op for pg_dump /
1874            // mysqldump preamble lines that collapse to nothing
1875            // after comment-stripping.
1876            Statement::Empty => Ok(QueryResult::CommandOk {
1877                affected: 0,
1878                modified_catalog: false,
1879            }),
1880            // v7.39 (round 695) — `ALTER SYSTEM SET|RESET <name>`. SPG has
1881            // no postgresql.auto.conf to write, so nothing is APPLIED; what
1882            // changed is that a name PG18 does not know is now refused
1883            // instead of accepted. It reuses the session's own GUC check —
1884            // one place decides what a parameter name means, so `SET` and
1885            // `ALTER SYSTEM` cannot drift apart in what they accept.
1886            //
1887            // The F31 audit found this: the test was called
1888            // `alter_system_set_no_op` and set `work_mem`, a name that
1889            // exists, so it could never have caught a name that does not.
1890            // v7.39 (round 696) — the four statements the F31 sweep found
1891            // accepting a name that does not exist. SPG still performs
1892            // nothing for any of them; what changed is that it no longer
1893            // says "understood" about an object that is not there.
1894            // v7.39 (round 707) — see Statement::DropAggregate. Existence
1895            // first across the whole list (PG's order, measured), canonical
1896            // type names in the signature, and every SPG aggregate is a
1897            // built-in, so a name that exists is undroppable.
1898            Statement::DropAggregate { if_exists, items } => {
1899                let render = |name: &str, args: &Option<Vec<String>>| -> alloc::string::String {
1900                    match args {
1901                        None => alloc::format!("{name}(*)"),
1902                        Some(a) => {
1903                            let canon: Vec<alloc::string::String> = a
1904                                .iter()
1905                                .map(|t| {
1906                                    crate::conversions::type_name_to_data_type(t).map_or_else(
1907                                        || t.clone(),
1908                                        crate::conversions::pg_type_name_for_error,
1909                                    )
1910                                })
1911                                .collect();
1912                            alloc::format!("{name}({})", canon.join(", "))
1913                        }
1914                    }
1915                };
1916                for (name, args) in &items {
1917                    if !crate::aggregate::is_aggregate_name(name.as_str()) {
1918                        if if_exists {
1919                            continue;
1920                        }
1921                        return Err(EngineError::Unsupported(alloc::format!(
1922                            "aggregate {} does not exist",
1923                            render(name, args)
1924                        )));
1925                    }
1926                }
1927                if let Some((name, args)) = items
1928                    .iter()
1929                    .find(|(n, _)| crate::aggregate::is_aggregate_name(n.as_str()))
1930                {
1931                    return Err(EngineError::Unsupported(alloc::format!(
1932                        "cannot drop function {} because it is required by the database system",
1933                        render(name, args)
1934                    )));
1935                }
1936                Ok(QueryResult::CommandOk {
1937                    affected: 0,
1938                    modified_catalog: false,
1939                })
1940            }
1941            // v7.39 (round 750) — `ALTER ROLE … PASSWORD` really rotates
1942            // the credential now (it was a recorded no-op — ledgered as a
1943            // security defect in round 710: `ALTER USER x PASSWORD 'new'`
1944            // answered ALTER ROLE and the OLD password kept working).
1945            Statement::AlterRolePassword { name, password } => {
1946                if !self.role_exists(name.as_str()) {
1947                    return Err(EngineError::Unsupported(alloc::format!(
1948                        "role \"{name}\" does not exist"
1949                    )));
1950                }
1951                self.alter_user_password(&name, password.as_deref())
1952                    .map_err(|e| EngineError::Unsupported(alloc::format!("ALTER ROLE: {e}")))?;
1953                Ok(QueryResult::CommandOk {
1954                    affected: 0,
1955                    modified_catalog: self.catalog_change_is_committed(),
1956                })
1957            }
1958            Statement::ValidateOnly { kind, names } => {
1959                use spg_sql::ast::ValidateOnlyKind as K;
1960                match kind {
1961                    K::LockTable => {
1962                        for n in names {
1963                            if self.catalog.get(n.as_str()).is_none() {
1964                                return Err(EngineError::Storage(
1965                                    spg_storage::StorageError::TableNotFound { name: n.clone() },
1966                                ));
1967                            }
1968                        }
1969                    }
1970                    K::RoleName => {
1971                        for n in names {
1972                            if !self.role_exists(n.as_str()) {
1973                                return Err(EngineError::Unsupported(alloc::format!(
1974                                    "role \"{n}\" does not exist"
1975                                )));
1976                            }
1977                        }
1978                    }
1979                    // PG18 refuses this whatever it names, because no label
1980                    // provider is loaded — and SPG has none either, so the
1981                    // refusal is the honest answer rather than a stand-in.
1982                    // v7.39 (round 697) — one list answers both, which is
1983                    // why these and `pg_extension` cannot disagree.
1984                    //
1985                    // A WARNING, not an error, and that is a deliberate
1986                    // departure from PG. PG can error because an extension
1987                    // can be installed there; SPG cannot be installed into,
1988                    // so refusing would turn a customer dump that restores
1989                    // today into one that needs editing. Saying nothing was
1990                    // the actual defect: `CREATE EXTENSION hstore` reported
1991                    // success and nothing hstore-shaped worked afterwards.
1992                    K::ExtensionAvailable | K::ExtensionInstalled => {
1993                        for n in names {
1994                            if !crate::system_catalog::INSTALLED_EXTENSIONS
1995                                .iter()
1996                                .any(|(e, _)| e.eq_ignore_ascii_case(n.as_str()))
1997                            {
1998                                self.warning(alloc::format!(
1999                                    "extension \"{n}\" is not provided by this build; SPG \
2000                                     accepts the statement so a dump restores, but nothing \
2001                                     that extension supplies will be available"
2002                                ));
2003                            }
2004                        }
2005                    }
2006                    // v7.39 (round 708) — ALTER TYPE's no-op forms validate
2007                    // the name against the three user-type catalogs.
2008                    K::TypeName => {
2009                        for n in &names {
2010                            let cat = self.active_catalog();
2011                            if !cat.enum_types().contains_key(n)
2012                                && !cat.domain_types().contains_key(n)
2013                                && !cat.composite_types().contains_key(n)
2014                            {
2015                                return Err(EngineError::Unsupported(alloc::format!(
2016                                    "type \"{n}\" does not exist"
2017                                )));
2018                            }
2019                        }
2020                    }
2021                    // v7.39 (round 708) — names[0] = aggregate, rest = arg
2022                    // type names; existence by name (round 707's residual on
2023                    // overloads applies here too).
2024                    K::AggregateName => {
2025                        let Some(name) = names.first() else {
2026                            return Ok(QueryResult::CommandOk {
2027                                affected: 0,
2028                                modified_catalog: false,
2029                            });
2030                        };
2031                        if !crate::aggregate::is_aggregate_name(name.as_str()) {
2032                            let canon: Vec<alloc::string::String> = names[1..]
2033                                .iter()
2034                                .map(|t| {
2035                                    if t == "*" {
2036                                        alloc::string::String::from("*")
2037                                    } else {
2038                                        crate::conversions::type_name_to_data_type(t).map_or_else(
2039                                            || t.clone(),
2040                                            crate::conversions::pg_type_name_for_error,
2041                                        )
2042                                    }
2043                                })
2044                                .collect();
2045                            return Err(EngineError::Unsupported(alloc::format!(
2046                                "aggregate {name}({}) does not exist",
2047                                canon.join(", ")
2048                            )));
2049                        }
2050                    }
2051                    // v7.39 (round 708) — SPG ships no conversions at all,
2052                    // so PG's not-found answer is total here.
2053                    K::ConversionName => {
2054                        if let Some(n) = names.first() {
2055                            return Err(EngineError::Unsupported(alloc::format!(
2056                                "conversion \"{n}\" does not exist"
2057                            )));
2058                        }
2059                    }
2060                    // v7.39 (round 708) — the shipped languages are
2061                    // required; anything else does not exist. Both wordings
2062                    // are PG18 measurements.
2063                    K::LanguageName => {
2064                        // One name per statement; PG errors on the first
2065                        // either way, so `first` says what the loop only
2066                        // implied (clippy: never actually loops).
2067                        if let Some(n) = names.first() {
2068                            let lc = n.to_ascii_lowercase();
2069                            return Err(EngineError::Unsupported(match lc.as_str() {
2070                                "plpgsql" => alloc::format!(
2071                                    "cannot drop language {lc} because extension {lc} requires it"
2072                                ),
2073                                "sql" | "internal" | "c" => alloc::format!(
2074                                    "cannot drop language {lc} because it is required by the database system"
2075                                ),
2076                                _ => alloc::format!("language \"{n}\" does not exist"),
2077                            }));
2078                        }
2079                    }
2080                    // v7.39 (round 709) — batch-2 name checks, each wording
2081                    // a PG18 measurement.
2082                    K::CollationName => {
2083                        for n in &names {
2084                            if !crate::collate::is_supported(n) {
2085                                return Err(EngineError::Unsupported(alloc::format!(
2086                                    "collation \"{n}\" for encoding \"UTF8\" does not exist"
2087                                )));
2088                            }
2089                        }
2090                    }
2091                    K::TsConfigName => {
2092                        for n in &names {
2093                            // One list with the pg_ts_config synth: SPG
2094                            // ships `simple` and `english`.
2095                            if !n.eq_ignore_ascii_case("simple")
2096                                && !n.eq_ignore_ascii_case("english")
2097                            {
2098                                return Err(EngineError::Unsupported(alloc::format!(
2099                                    "text search configuration \"{n}\" does not exist"
2100                                )));
2101                            }
2102                        }
2103                    }
2104                    K::EventTriggerName => {
2105                        if let Some(n) = names.first() {
2106                            return Err(EngineError::Unsupported(alloc::format!(
2107                                "event trigger \"{n}\" does not exist"
2108                            )));
2109                        }
2110                    }
2111                    K::TablespaceName => {
2112                        if let Some(n) = names.first() {
2113                            return Err(EngineError::Unsupported(
2114                                if n.eq_ignore_ascii_case("pg_default")
2115                                    || n.eq_ignore_ascii_case("pg_global")
2116                                {
2117                                    alloc::format!("permission denied for tablespace {n}")
2118                                } else {
2119                                    alloc::format!("tablespace \"{n}\" does not exist")
2120                                },
2121                            ));
2122                        }
2123                    }
2124                    K::LargeObjectOid => {
2125                        if let Some(n) = names.first() {
2126                            let oid: u32 = n.parse().unwrap_or(0);
2127                            if !self.active_catalog().large_objects().contains_key(&oid) {
2128                                return Err(EngineError::Unsupported(alloc::format!(
2129                                    "large object {n} does not exist"
2130                                )));
2131                            }
2132                        }
2133                    }
2134                    // v7.39 (round 706) — see ValidateOnlyKind::ForeignInfra
2135                    // for why this warns instead of copying PG's refusal.
2136                    K::ForeignInfra => {
2137                        self.warning(alloc::string::String::from(
2138                            "foreign-data infrastructure is not provided by this build; \
2139                             SPG accepts the statement so a dump restores, but no foreign \
2140                             server, wrapper or table it defines will function",
2141                        ));
2142                    }
2143                    K::SecurityLabel => {
2144                        return Err(EngineError::Unsupported(alloc::string::String::from(
2145                            "no security label providers have been loaded",
2146                        )));
2147                    }
2148                }
2149                Ok(QueryResult::CommandOk {
2150                    affected: 0,
2151                    modified_catalog: false,
2152                })
2153            }
2154            Statement::DropDatabase { name, if_exists } => {
2155                // PG refuses this inside a transaction block; so does
2156                // CREATE DATABASE, and both go through the same guard.
2157                self.require_no_transaction_block("DROP DATABASE")?;
2158                // SPG serves one database, so the name is either the one
2159                // this session is connected to or a name that does not
2160                // exist here. PG has wording for both and never lets
2161                // either succeed, which is the whole behaviour.
2162                let is_current = self
2163                    .session_param("spg.database")
2164                    .unwrap_or("spg")
2165                    .eq_ignore_ascii_case(&name);
2166                if is_current {
2167                    return Err(EngineError::Unsupported(alloc::string::String::from(
2168                        "cannot drop the currently open database",
2169                    )));
2170                }
2171                if if_exists {
2172                    self.notice(alloc::format!(
2173                        "database \"{name}\" does not exist, skipping"
2174                    ));
2175                    return Ok(QueryResult::CommandOk {
2176                        affected: 0,
2177                        modified_catalog: false,
2178                    });
2179                }
2180                Err(EngineError::Unsupported(alloc::format!(
2181                    "database \"{name}\" does not exist"
2182                )))
2183            }
2184            Statement::NoOpPreventedInTransaction {
2185                what,
2186                collation,
2187                name,
2188            } => {
2189                self.require_no_transaction_block(&what)?;
2190                // v7.38.18 — the NAME is a no-op here; the collation is
2191                // not. A bootstrap script that says `LC_COLLATE
2192                // 'de_DE.utf8'` and gets the container's `LANG` instead
2193                // has a different answer to every ORDER BY it runs, and
2194                // nothing told it so.
2195                let mut modified_catalog = false;
2196                // v7.38.19 — record the name, so `pg_database` can list a
2197                // database that was just created and can be connected to.
2198                // sentori reported both halves of this against 7.38.18:
2199                // `dd` answered `current_database()` and was absent from
2200                // the catalogue, which is what `psql \l`, a migration
2201                // tool's "does this database exist", and a backup script
2202                // that enumerates all read.
2203                if let Some(n) = &name
2204                    && self.active_catalog_mut().record_created_database(n)
2205                {
2206                    modified_catalog = true;
2207                }
2208                if let Some(c) = collation {
2209                    if self.declare_database_collation(&c)? {
2210                        modified_catalog = true;
2211                        // v7.38.19 — and say so. SPG serves ONE database
2212                        // and answers to any name, so a collation asked
2213                        // for by any name is server-wide; under
2214                        // PostgreSQL's model nothing a CREATE DATABASE
2215                        // does can reach an existing database, and
2216                        // sentori watched a statement naming `dd` change
2217                        // how `d` compares text. The behaviour is what
2218                        // being single-database means and cannot be
2219                        // fixed without a second database; being silent
2220                        // about it can be.
2221                        self.warning(alloc::format!(
2222                            "SPG serves one database and answers to any name, so \
2223                             collation {c:?} now applies to this database too. \
2224                             PostgreSQL would have created a separate one; here \
2225                             the names are aliases onto the same storage"
2226                        ));
2227                    } else {
2228                        self.warning(alloc::format!(
2229                            "collation {c:?} was not applied: this database \
2230                             already has tables, and their index keys were \
2231                             built under {:?}",
2232                            self.catalog.db_collation()
2233                        ));
2234                    }
2235                }
2236                Ok(QueryResult::CommandOk {
2237                    affected: 0,
2238                    modified_catalog,
2239                })
2240            }
2241            Statement::AlterSystem { parameter } => {
2242                // PG refuses this inside a transaction block (25001): it
2243                // edits postgresql.auto.conf, which no rollback undoes.
2244                self.require_no_transaction_block("ALTER SYSTEM")?;
2245                if let Some(name) = parameter
2246                    && let Some(msg) = self.reject_unsettable_guc(name.as_str())
2247                {
2248                    return Err(EngineError::Unsupported(msg));
2249                }
2250                Ok(QueryResult::CommandOk {
2251                    affected: 0,
2252                    modified_catalog: false,
2253                })
2254            }
2255            Statement::DropTable { names, if_exists } => self.exec_drop_table(names, if_exists),
2256            Statement::DropIndex { name, if_exists } => self.exec_drop_index(name, if_exists),
2257            Statement::CreateIndex(s) => {
2258                // PG bars only the CONCURRENTLY form inside a transaction
2259                // block (25001); a plain CREATE INDEX there is fine.
2260                if s.concurrently {
2261                    self.require_no_transaction_block("CREATE INDEX CONCURRENTLY")?;
2262                }
2263                self.exec_create_index(s)
2264            }
2265            Statement::Insert(s) => {
2266                // v7.39 (pg_stat knife A) — per-table n_tup_ins. Charged
2267                // to the statement's target (a partition-routed insert
2268                // charges the parent; ON CONFLICT updates count here
2269                // too — split is a recorded residual).
2270                let stat_table = s.table.clone();
2271                let r = self.exec_insert(s)?;
2272                if let QueryResult::CommandOk { affected, .. } = &r {
2273                    self.stat_tup_inserted =
2274                        self.stat_tup_inserted.saturating_add(*affected as u64);
2275                    // r192 — engine-side, non-transactional (see
2276                    // table_write_stats): in-tx bumps used to land on
2277                    // the shadow table and vanish in the RC rebase.
2278                    self.note_table_write(&stat_table, *affected as u64, 0, 0);
2279                }
2280                Ok(r)
2281            }
2282            Statement::Update(mut s) => {
2283                // Materialise uncorrelated subqueries in SET / WHERE
2284                // before the row walk — the SELECT path has done this
2285                // since v4.10; UPDATE gained it for mailrs's
2286                // `UPDATE … WHERE id IN (SELECT … FOR UPDATE SKIP
2287                // LOCKED)` claim pattern (embed round-12).
2288                // v7.39 (round 157) — NOT with a WITH clause: the CTE
2289                // temps aren't installed yet here, so a subquery reading
2290                // a CTE either failed ("relation does not exist") or —
2291                // when a same-named real table existed — silently read
2292                // THAT. exec_update_with_ctes resolves after the temps
2293                // install instead.
2294                if s.ctes.is_empty() {
2295                    for (_, e) in &mut s.assignments {
2296                        self.resolve_expr_subqueries(e, cancel)?;
2297                    }
2298                    if let Some(w) = &mut s.where_ {
2299                        self.resolve_expr_subqueries(w, cancel)?;
2300                    }
2301                }
2302                let r = self.exec_update_cancel(&s, cancel)?;
2303                if let QueryResult::CommandOk { affected, .. } = &r {
2304                    self.stat_tup_updated = self.stat_tup_updated.saturating_add(*affected as u64);
2305                    self.note_table_write(&s.table, 0, *affected as u64, 0);
2306                }
2307                Ok(r)
2308            }
2309            Statement::Delete(mut s) => {
2310                // v7.39 (round 157) — see the Update arm: with a WITH
2311                // clause the resolve runs after the CTE temps install.
2312                if s.ctes.is_empty()
2313                    && let Some(w) = &mut s.where_
2314                {
2315                    self.resolve_expr_subqueries(w, cancel)?;
2316                }
2317                let r = self.exec_delete_cancel(&s, cancel)?;
2318                if let QueryResult::CommandOk { affected, .. } = &r {
2319                    self.stat_tup_deleted = self.stat_tup_deleted.saturating_add(*affected as u64);
2320                    self.note_table_write(&s.table, 0, 0, *affected as u64);
2321                }
2322                Ok(r)
2323            }
2324            Statement::Merge(s) => self.exec_merge_cancel(&s, cancel),
2325            // v7.39 (round 295, E3 Phase 1b) — a locking SELECT takes its
2326            // locks in a `&mut self` pre-pass that respects LIMIT, then
2327            // runs the ordinary read path with the rows another
2328            // transaction holds excluded.
2329            Statement::Select(ref sel) if sel.locking.is_some() => {
2330                let sel = sel.clone();
2331                self.lock_skip_rows = None;
2332                let pre = self.run_locking_prepass(&sel);
2333                if let Err(e) = pre {
2334                    self.lock_skip_rows = None;
2335                    return Err(e);
2336                }
2337                let out = self.exec_select_cancel(&sel, cancel);
2338                self.lock_skip_rows = None;
2339                out
2340            }
2341            Statement::Select(s) => {
2342                // v7.38 (read01 P3.20) — `SELECT set_config(name, value,
2343                // is_local)` is the writing sibling of SHOW / current_setting;
2344                // apply it to the session store (respecting is_local) so the
2345                // four GUC surfaces stay unified. pg_dump's
2346                // `SELECT set_config('search_path', '', false)` relies on this.
2347                if let Some(r) = self.try_exec_set_config(&s)? {
2348                    return Ok(r);
2349                }
2350                if s.ctes.iter().any(|c| c.body.is_modifying()) {
2351                    self.exec_select_with_modifying_ctes(s, cancel)
2352                } else {
2353                    self.exec_select_cancel(&s, cancel)
2354                }
2355            }
2356            // v7.39 (round 249) — the engine is no_std: the HOST reads the
2357            // file and calls `copy_from_buffer`. Reaching this arm means a
2358            // host that hasn't wired the file endpoint.
2359            Statement::CopyFromFile { path, .. } => Err(EngineError::Unsupported(alloc::format!(
2360                "COPY FROM file: the host must read {path:?} and call copy_from_buffer"
2361            ))),
2362            Statement::CopyTo {
2363                table,
2364                columns,
2365                query,
2366                options,
2367            } => self.exec_copy_to(
2368                &table,
2369                columns.as_deref(),
2370                query.as_deref(),
2371                &options,
2372                cancel,
2373            ),
2374            // v7.39 (round 252) — the engine is no_std: the HOST renders
2375            // via `copy_to_buffer` and writes the file itself.
2376            Statement::CopyToFile { path, .. } => Err(EngineError::Unsupported(alloc::format!(
2377                "COPY TO file: the host must render via copy_to_buffer and write {path:?}"
2378            ))),
2379            // v7.39 (round 475) — a redundant BEGIN inside a transaction.
2380            //
2381            // SPG raised "a transaction is already open" AND left the
2382            // transaction in the aborted state, so the next statement failed
2383            // with "current transaction is aborted" and the whole block was
2384            // lost. A connection pooler or a framework that wraps its own
2385            // BEGIN around one the caller already opened does this routinely.
2386            //
2387            // The two oracles genuinely differ, and both were measured:
2388            //   PG18       WARNING: there is already a transaction in
2389            //              progress — the BEGIN is a no-op and the existing
2390            //              transaction continues (a later ROLLBACK undoes
2391            //              everything, both rows in the probe).
2392            //   MariaDB 11 START TRANSACTION implicitly COMMITS the open one
2393            //              and begins a new one (the first row survives the
2394            //              rollback, the second does not).
2395            // The predicate is THIS connection's slot, not the engine-global
2396            // `in_transaction()`: the server shares one Engine, so the global
2397            // form makes connection B's BEGIN see connection A's transaction
2398            // (rounds 279 / 283 / 298 / 304 / 443 / 444 are the same trap).
2399            Statement::Begin(_)
2400                if self.current_tx.is_some_and(|t| self.is_tx_open(t))
2401                    && !self.backslash_escapes =>
2402            {
2403                self.warning(alloc::string::String::from(
2404                    "there is already a transaction in progress",
2405                ));
2406                Ok(QueryResult::CommandOk {
2407                    affected: 0,
2408                    modified_catalog: false,
2409                })
2410            }
2411            Statement::Begin(modes) if self.current_tx.is_some_and(|t| self.is_tx_open(t)) => {
2412                // MySQL dialect: commit what is open, then start fresh.
2413                self.exec_commit()?;
2414                self.exec_begin(modes)
2415            }
2416            Statement::Begin(modes) => self.exec_begin(modes),
2417            // v7.39 (round 435) — a bare COMMIT / ROLLBACK outside a
2418            // transaction is a no-op that SUCCEEDS. Measured on both
2419            // oracles: PG18 answers `WARNING: there is no transaction in
2420            // progress` and still reports COMMIT / ROLLBACK; MariaDB 11
2421            // succeeds silently. SPG answered "no active transaction" as an
2422            // ERROR to both dialects — a divergence from each of them.
2423            // It moved onto the hot path with the implicit-commit rule
2424            // above, which leaves a client's trailing ROLLBACK with nothing
2425            // to roll back.
2426            Statement::Commit | Statement::Rollback if !self.in_transaction() => {
2427                if !self.backslash_escapes {
2428                    self.warning(alloc::string::String::from(
2429                        "there is no transaction in progress",
2430                    ));
2431                }
2432                Ok(QueryResult::CommandOk {
2433                    affected: 0,
2434                    modified_catalog: false,
2435                })
2436            }
2437            Statement::Commit => self.exec_commit(),
2438            Statement::Rollback => self.exec_rollback(),
2439            Statement::Savepoint(name) => self.exec_savepoint(name),
2440            Statement::RollbackToSavepoint(name) => self.exec_rollback_to_savepoint(&name),
2441            Statement::ReleaseSavepoint(name) => self.exec_release_savepoint(&name),
2442            Statement::ShowTables => Ok(self.exec_show_tables()),
2443            Statement::ShowDatabases => Ok(self.exec_show_databases()),
2444            Statement::ShowCreateTable(name) => self.exec_show_create_table(&name),
2445            Statement::ShowIndexes(name) => self.exec_show_indexes(&name),
2446            Statement::ShowStatus => Ok(self.exec_show_status()),
2447            Statement::ShowVariables => Ok(self.exec_show_variables()),
2448            Statement::ShowVariablesLike(p) => Ok(self.exec_show_variables_like(&p)),
2449            Statement::ShowProcesslist => Ok(self.exec_show_processlist()),
2450            Statement::Kill { query_only, id } => self.exec_kill(query_only, &id),
2451            Statement::Discard(target) => self.exec_discard(target),
2452            Statement::ShowColumns(table) => self.exec_show_columns(&table),
2453            Statement::ShowUsers => Ok(self.exec_show_users()),
2454            Statement::ShowPublications => Ok(self.exec_show_publications()),
2455            Statement::ShowSubscriptions => Ok(self.exec_show_subscriptions()),
2456            Statement::CreateUser(s) => self.exec_create_user(&s),
2457            Statement::DropUser { name, if_exists } => self.exec_drop_user(&name, if_exists),
2458            Statement::SetRole(role) => {
2459                match role {
2460                    Some(name) => {
2461                        // v7.39 (read01 round 58) — PG rejects a SET ROLE to a
2462                        // role that does not exist. Before roles were real
2463                        // there was nothing to check against, so any name was
2464                        // accepted — and a typo silently put the session into
2465                        // a role that held nothing.
2466                        self.acl_check_role_exists(&name)?;
2467                        self.session_params.insert(
2468                            alloc::string::String::from(crate::session::CURRENT_ROLE_KEY),
2469                            name,
2470                        );
2471                    }
2472                    None => {
2473                        self.session_params.remove(crate::session::CURRENT_ROLE_KEY);
2474                    }
2475                }
2476                Ok(QueryResult::CommandOk {
2477                    affected: 0,
2478                    modified_catalog: false,
2479                })
2480            }
2481            Statement::Grant(g) => self.exec_grant(&g, true),
2482            Statement::Revoke(g) => self.exec_grant(&g, false),
2483            Statement::CreatePolicy(s) => self.exec_create_policy(s),
2484            Statement::AlterPolicy(s) => self.exec_alter_policy(s),
2485            Statement::DropPolicy(s) => self.exec_drop_policy(s),
2486            // v7.39 (round 286) — ANALYZE over DML really executes, so it
2487            // needs the `&mut self` sibling. Everything else (including
2488            // plain EXPLAIN of a write) stays on the read-only renderer.
2489            // v7.39 (round 288) — SET CONSTRAINTS sets the timing for the
2490            // rest of the transaction. IMMEDIATE also runs everything the
2491            // transaction has postponed, right here — PG raises the
2492            // violation at this statement, not at COMMIT.
2493            Statement::SetConstraints { names, deferred } => {
2494                self.exec_set_constraints(&names, deferred)
2495            }
2496            Statement::Explain(e)
2497                if e.analyze
2498                    && !e.suggest
2499                    && matches!(
2500                        &*e.inner,
2501                        Statement::Insert(_) | Statement::Update(_) | Statement::Delete(_)
2502                    ) =>
2503            {
2504                self.exec_explain_analyze_dml(&e, cancel)
2505            }
2506            Statement::Explain(e) => self.exec_explain(&e, cancel),
2507            Statement::AlterIndex(s) => self.exec_alter_index(s),
2508            Statement::AlterTable(s) => self.exec_alter_table(s),
2509            Statement::CreatePublication(s) => self.exec_create_publication(s),
2510            Statement::DropPublication { name, if_exists } => {
2511                self.exec_drop_publication(&name, if_exists)
2512            }
2513            Statement::CreateSubscription(s) => self.exec_create_subscription(s),
2514            Statement::DropSubscription { name, if_exists } => {
2515                self.exec_drop_subscription(&name, if_exists)
2516            }
2517            // v6.1.7 — WAIT FOR WAL POSITION needs `lag_state`,
2518            // which lives in spg-server's ServerState. The engine
2519            // surfaces a clear error; the server-layer dispatch
2520            // intercepts the SQL before it reaches the engine on
2521            // a server build, so this arm only fires for
2522            // engine-only callers (spg-embedded, lib tests).
2523            Statement::WaitForWalPosition { .. } => Err(EngineError::Unsupported(
2524                "WAIT FOR WAL POSITION must be handled by the server layer".into(),
2525            )),
2526            // v6.2.0 — ANALYZE recomputes per-column histograms.
2527            Statement::Analyze(target) => self.exec_analyze(target.as_deref()),
2528            // v7.39 (round 535) — REINDEX / CLUSTER. SPG has neither index
2529            // bloat to rebuild nor a clustering order to impose, so the
2530            // work is a no-op — but PG VALIDATES the target, and both
2531            // statements were swallowed at parse time AND intercepted at
2532            // the wire, so `REINDEX TABLE typo` answered `REINDEX`. A
2533            // maintenance script that misspells a table was told it
2534            // succeeded.
2535            Statement::Maintain {
2536                kind,
2537                concurrently,
2538                target,
2539            } => {
2540                use spg_sql::ast::MaintainKind;
2541                if concurrently {
2542                    self.require_no_transaction_block(match kind {
2543                        MaintainKind::ClusterRelation => "CLUSTER",
2544                        _ => "REINDEX CONCURRENTLY",
2545                    })?;
2546                }
2547                match (kind, target.as_deref()) {
2548                    (MaintainKind::ReindexRelation | MaintainKind::ClusterRelation, Some(t)) => {
2549                        // An INDEX is a relation too — `REINDEX INDEX ix`
2550                        // names one, and looking only at tables refused a
2551                        // name that is right there.
2552                        let is_index = self
2553                            .active_catalog()
2554                            .table_names()
2555                            .iter()
2556                            .filter_map(|n| self.active_catalog().get(n))
2557                            .any(|tbl| {
2558                                tbl.indices().iter().any(|i| i.name.eq_ignore_ascii_case(t))
2559                            });
2560                        if !is_index && self.active_catalog().get(t).is_none() {
2561                            return Err(EngineError::Storage(
2562                                spg_storage::StorageError::TableNotFound { name: t.into() },
2563                            ));
2564                        }
2565                    }
2566                    (MaintainKind::ReindexSchema, Some(t)) => {
2567                        if !spg_storage::is_builtin_schema(t)
2568                            && !self.active_catalog().schema_exists(t)
2569                        {
2570                            return Err(EngineError::Unsupported(alloc::format!(
2571                                "schema \"{t}\" does not exist"
2572                            )));
2573                        }
2574                    }
2575                    // `REINDEX SYSTEM` / `REINDEX DATABASE` / a bare
2576                    // `CLUSTER` name nothing to check.
2577                    _ => {}
2578                }
2579                Ok(QueryResult::CommandOk {
2580                    affected: 0,
2581                    modified_catalog: false,
2582                })
2583            }
2584            // v7.39 (round 169) — VACUUM does real work under the MVCC
2585            // gate (tombstoned versions are actual bloat); the pre-MVCC
2586            // parse-time no-op silently ignored a customer's manual
2587            // reclaim. Gate-off stays a provable no-op inside vacuum.
2588            Statement::Vacuum { table, analyze } => {
2589                // PG 18.4, measured: every VACUUM form — bare, with a
2590                // table, and VACUUM ANALYZE — is refused inside a
2591                // transaction block with 25001, while a plain ANALYZE is
2592                // allowed. Reclaiming storage cannot be rolled back, so
2593                // it must not be able to join a transaction that can.
2594                self.require_no_transaction_block("VACUUM")?;
2595                match &table {
2596                    Some(t) => {
2597                        // v7.39 (round 535) — PG refuses a VACUUM whose
2598                        // relation does not exist; `vacuum_one_table`
2599                        // simply found nothing to do and said nothing,
2600                        // so a typo'd table reported success.
2601                        if self.active_catalog().get(t).is_none() {
2602                            return Err(EngineError::Storage(
2603                                spg_storage::StorageError::TableNotFound { name: t.clone() },
2604                            ));
2605                        }
2606                        self.vacuum_one_table(t);
2607                    }
2608                    None => {
2609                        let _ = self.vacuum_pass(false);
2610                    }
2611                }
2612                if analyze {
2613                    self.exec_analyze(table.as_deref())?;
2614                }
2615                Ok(QueryResult::CommandOk {
2616                    affected: 0,
2617                    modified_catalog: false,
2618                })
2619            }
2620            // v7.37.17 (17.6 sibling) — TRUNCATE [TABLE] <t>[, ...]
2621            // [RESTART IDENTITY] [CASCADE]. Clears every row from
2622            // each named table. CASCADE currently accepts the syntax
2623            // + records the flag; the FK-referring cascade walk lands
2624            // when FK-cascade delete surface gets extended to
2625            // multi-relation batching (v7.38).
2626            Statement::Truncate {
2627                tables,
2628                restart_identity,
2629                cascade: _,
2630                only,
2631            } => {
2632                for t in &tables {
2633                    self.bump_table_change(t);
2634                }
2635                self.exec_truncate(tables.as_slice(), restart_identity, only)
2636            }
2637            // v6.7.3 — COMPACT COLD SEGMENTS.
2638            Statement::CompactColdSegments => self.exec_compact_cold_segments(),
2639            // v7.12.1 — SET / RESET session parameter. Engine
2640            // tracks the value in `session_params`; FTS dispatcher
2641            // reads `default_text_search_config`. Everything else
2642            // is a recorded no-op (PG dump compat).
2643            Statement::SetParameter { name, value, local } => {
2644                // v7.39 (round 501) — a name PG18 does not know, or one a
2645                // session cannot change, is an error there and was
2646                // silently accepted here (round 500).
2647                if let Some(msg) = self.reject_unsettable_guc(&name) {
2648                    return Err(EngineError::Unsupported(msg));
2649                }
2650                // v7.38 (read01) — SPG serves the wire as UTF8, so a
2651                // non-UTF8 client_encoding can't be honoured (the bytes
2652                // stay UTF8). Reject it rather than silently store a value
2653                // that would mislabel the stream; an unusable name is
2654                // rejected the way PG rejects an invalid one.
2655                if name.eq_ignore_ascii_case("client_encoding") {
2656                    let v: &str = match &value {
2657                        spg_sql::ast::SetValue::String(s)
2658                        | spg_sql::ast::SetValue::Ident(s)
2659                        | spg_sql::ast::SetValue::Number(s) => s.as_str(),
2660                        spg_sql::ast::SetValue::Default => "UTF8",
2661                    };
2662                    let norm: alloc::string::String = v
2663                        .trim()
2664                        .to_ascii_uppercase()
2665                        .chars()
2666                        .filter(|c| *c != '-' && *c != '_')
2667                        .collect();
2668                    if !matches!(norm.as_str(), "UTF8" | "UNICODE") {
2669                        return Err(EngineError::Unsupported(alloc::format!(
2670                            "invalid value for parameter \"client_encoding\": \"{v}\" \
2671                             (SPG serves UTF8 only)"
2672                        )));
2673                    }
2674                }
2675                // v7.38 (read01 P3.17) — reject a clearly-invalid value for
2676                // a handful of well-known typed GUCs (`SET work_mem =
2677                // 'bogus'` errors like PG). Unknown GUCs stay accept-and-
2678                // record for pg_dump compat.
2679                if let spg_sql::ast::SetValue::String(s)
2680                | spg_sql::ast::SetValue::Ident(s)
2681                | spg_sql::ast::SetValue::Number(s) = &value
2682                {
2683                    validate_known_guc(&name, s)?;
2684                    // v7.39 (tz epic) — timezone accepts UTC / fixed
2685                    // offsets / abbreviations (resolve_zone_offset) and
2686                    // IANA names (host tzdb); anything else is PG's
2687                    // invalid-parameter error. Named zones store their
2688                    // canonical spelling (SHOW returns 'Asia/Tokyo'
2689                    // after SET 'asia/tokyo').
2690                    if name.eq_ignore_ascii_case("timezone")
2691                        || name.eq_ignore_ascii_case("time zone")
2692                    {
2693                        let canon = self.canonicalize_timezone(s)?;
2694                        let local = local;
2695                        if local {
2696                            if self.in_transaction() {
2697                                let prior = self.session_param("timezone").map(String::from);
2698                                self.local_guc_saves.push(("timezone".into(), prior));
2699                                self.set_session_param(
2700                                    "timezone".into(),
2701                                    spg_sql::ast::SetValue::String(canon),
2702                                );
2703                            }
2704                        } else {
2705                            self.set_session_param(
2706                                "timezone".into(),
2707                                spg_sql::ast::SetValue::String(canon),
2708                            );
2709                        }
2710                        return Ok(QueryResult::CommandOk {
2711                            affected: 0,
2712                            modified_catalog: false,
2713                        });
2714                    }
2715                }
2716                // v7.38 (read01 P3.19) — `SET LOCAL` scopes the change to
2717                // the current transaction: record the prior value in the
2718                // undo log so COMMIT / ROLLBACK (and ROLLBACK TO) restore
2719                // it. Outside a transaction block it has no lasting effect
2720                // (PG scopes it to the implicit single-statement txn), so
2721                // it is dropped rather than persisted to the session.
2722                if local {
2723                    if self.in_transaction() {
2724                        let prior = self.session_param(&name).map(String::from);
2725                        self.local_guc_saves.push((name.clone(), prior));
2726                        self.set_session_param(name, value);
2727                    }
2728                } else {
2729                    self.set_session_param(name, value);
2730                }
2731                Ok(QueryResult::CommandOk {
2732                    affected: 0,
2733                    modified_catalog: false,
2734                })
2735            }
2736            // v7.38 轴 4 — `SET TRANSACTION ISOLATION LEVEL …`. The
2737            // surface is recorded on `Engine::current_isolation_level`
2738            // and visible via `SHOW transaction_isolation`. Behavioural
2739            // v7.39 — this comment used to end "today every level reads
2740            // as effective READ COMMITTED". That stopped being true in
2741            // v7.37.15, which caches the BEGIN snapshot for RR/SER;
2742            // measured against PG 18.6, an open REPEATABLE READ
2743            // transaction does not see a concurrent commit and a READ
2744            // COMMITTED one does. The comment outlived the code by
2745            // three versions.
2746            Statement::SetTransaction { modes } => {
2747                // v7.39 — outside a transaction block PG WARNS and does
2748                // nothing. Measured on PG 18.6:
2749                //
2750                //     SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;
2751                //     WARNING:  SET TRANSACTION can only be used in transaction blocks
2752                //     SHOW transaction_isolation;  ->  read committed
2753                //
2754                // SPG applied it to the session instead, so a bare
2755                // `SET TRANSACTION` silently changed every later
2756                // transaction — the opposite of PG, where it changes
2757                // nothing. `Session::warning`'s own doc comment names
2758                // `SET CONSTRAINTS` outside a transaction block as the
2759                // case it exists for; this is its sibling, and only one
2760                // of them had been wired.
2761                if !self
2762                    .current_tx
2763                    .is_some_and(|id| self.tx_catalogs.contains_key(&id))
2764                {
2765                    self.warning("SET TRANSACTION can only be used in transaction blocks".into());
2766                    return Ok(QueryResult::CommandOk {
2767                        affected: 0,
2768                        modified_catalog: false,
2769                    });
2770                }
2771                // v7.37.17 (Phase E3) — PG rejects an isolation switch
2772                // after the transaction's first query (SQLSTATE 25001);
2773                // silently applying it to the remaining statements would
2774                // give a tx that is half one level, half another.
2775                if let Some(tx_id) = self.current_tx
2776                    && self
2777                        .tx_catalogs
2778                        .get(&tx_id)
2779                        .is_some_and(|st| st.stmts_run > 0)
2780                {
2781                    return Err(EngineError::Unsupported(
2782                        "SET TRANSACTION ISOLATION LEVEL must be called before any query".into(),
2783                    ));
2784                }
2785                if let Some(isolation) = modes.isolation {
2786                    self.current_isolation_level = isolation;
2787                }
2788                // v7.39 — the read/write half of the same statement. It was
2789                // parsed and dropped with the rest of the clause.
2790                if let Some(ro) = modes.read_only {
2791                    self.current_tx_read_only = ro;
2792                }
2793                let isolation = self.current_isolation_level;
2794                // v7.37.17 (Phase E2) — inside an open tx, switching to
2795                // RR/SER BEFORE the first query freezes the tx's view by
2796                // caching a snapshot now (PG allows the switch until the
2797                // first query; the RC rebase keys off cached_snapshot).
2798                // Switching (back) to RC/RU clears it so the rebase
2799                // resumes.
2800                if let Some(tx_id) = self.current_tx
2801                    && self.tx_catalogs.contains_key(&tx_id)
2802                {
2803                    let cache = match isolation {
2804                        spg_sql::ast::IsolationLevel::RepeatableRead
2805                        | spg_sql::ast::IsolationLevel::Serializable => {
2806                            Some(self.current_snapshot())
2807                        }
2808                        spg_sql::ast::IsolationLevel::ReadUncommitted
2809                        | spg_sql::ast::IsolationLevel::ReadCommitted => None,
2810                    };
2811                    if let Some(st) = self.tx_catalogs.get_mut(&tx_id) {
2812                        st.cached_snapshot = cache;
2813                    }
2814                }
2815                Ok(QueryResult::CommandOk {
2816                    affected: 0,
2817                    modified_catalog: false,
2818                })
2819            }
2820            // v7.38 轴 4 surface expansion — `SHOW <parameter>`
2821            // returns a 1-row 1-column TEXT result (the PG psql
2822            // wire shape). The handler dispatches per-name:
2823            //
2824            // 1. transaction_isolation — direct read of
2825            //    current_isolation_level (the v7.38 axis-4 surface).
2826            // 2. PG preset / engine-tracked params — values mirror
2827            //    pg_catalog.pg_settings to keep ORM /
2828            //    driver-connect probes happy (sqlx asks
2829            //    server_version + standard_conforming_strings +
2830            //    client_encoding; npgsql asks application_name;
2831            //    asyncpg asks search_path). Any
2832            //    SET-tracked override on self.session_params wins.
2833            // 3. Anything else — error with a list-pointer to
2834            //    pg_settings (which lists every recognised name).
2835            Statement::ShowParameter(name) => self.exec_show_parameter(name),
2836            // v7.14.0 — MySQL multi-assignment SET. Each pair runs
2837            // through `set_session_param` so engine-known params
2838            // (FOREIGN_KEY_CHECKS, session_replication_role, …) take
2839            // effect; unknown pairs (including `@VAR` LHS from the
2840            // mysqldump preamble) are recorded then ignored.
2841            Statement::SetParameterList(pairs) => {
2842                // Same validation as the single form (round 501).
2843                for (name, _) in &pairs {
2844                    if let Some(msg) = self.reject_unsettable_guc(name) {
2845                        return Err(EngineError::Unsupported(msg));
2846                    }
2847                }
2848                for (name, value) in pairs {
2849                    self.set_session_param(name, value);
2850                }
2851                Ok(QueryResult::CommandOk {
2852                    affected: 0,
2853                    modified_catalog: false,
2854                })
2855            }
2856            // v7.12.4 — CREATE FUNCTION / CREATE TRIGGER / DROP …
2857            // for the PL/pgSQL trigger surface. exec_* methods are
2858            // defined alongside the existing CREATE handlers below.
2859            Statement::CreateFunction(s) => self.exec_create_function(s),
2860            Statement::CreateTrigger(s) => self.exec_create_trigger(s),
2861            Statement::DropTrigger {
2862                name,
2863                table,
2864                if_exists,
2865            } => self.exec_drop_trigger(&name, &table, if_exists),
2866            Statement::CreateRule(s) => self.exec_create_rule(s),
2867            Statement::DropRule {
2868                name,
2869                table,
2870                if_exists,
2871            } => self.exec_drop_rule(&name, &table, if_exists),
2872            Statement::DropFunction {
2873                name,
2874                args,
2875                if_exists,
2876            } => self.exec_drop_function(&name, args.as_deref(), if_exists),
2877            Statement::CreateSequence(s) => self.exec_create_sequence(s),
2878            Statement::AlterSequence(s) => self.exec_alter_sequence(s),
2879            Statement::DropSequence { names, if_exists } => {
2880                self.exec_drop_sequence(&names, if_exists)
2881            }
2882            Statement::CreateView(s) => self.exec_create_view(s),
2883            Statement::DropView { names, if_exists } => self.exec_drop_view(&names, if_exists),
2884            Statement::CreateMaterializedView(s) => self.exec_create_materialized_view(s),
2885            Statement::RefreshMaterializedView { name, with_data } => {
2886                self.exec_refresh_materialized_view(&name, with_data)
2887            }
2888            Statement::DropMaterializedView { names, if_exists } => {
2889                self.exec_drop_materialized_view(&names, if_exists)
2890            }
2891            Statement::CreateType(s) => self.exec_create_type(s),
2892            Statement::CommentOn {
2893                kind,
2894                name,
2895                comment,
2896            } => self.exec_comment_on(&kind, &name, comment.as_deref()),
2897            Statement::AlterTypeRenameValue {
2898                type_name,
2899                old,
2900                new,
2901            } => {
2902                self.active_catalog_mut()
2903                    .rename_enum_value(&type_name, &old, &new)
2904                    .map_err(EngineError::Storage)?;
2905                Ok(QueryResult::CommandOk {
2906                    affected: 0,
2907                    modified_catalog: self.catalog_change_is_committed(),
2908                })
2909            }
2910            Statement::AlterTypeAddValue {
2911                type_name,
2912                label,
2913                if_not_exists,
2914                position,
2915            } => {
2916                let added = self
2917                    .active_catalog_mut()
2918                    .add_enum_value(&type_name, &label, if_not_exists, position)
2919                    .map_err(EngineError::Storage)?;
2920                Ok(QueryResult::CommandOk {
2921                    affected: 0,
2922                    modified_catalog: added,
2923                })
2924            }
2925            Statement::DropType { names, if_exists } => self.exec_drop_type(&names, if_exists),
2926            Statement::CreateDomain(s) => self.exec_create_domain(s),
2927            Statement::AlterDomain { name, action } => self.exec_alter_domain(&name, action),
2928            Statement::DropDomain { names, if_exists } => self.exec_drop_domain(&names, if_exists),
2929            Statement::CreateSchema {
2930                name,
2931                if_not_exists,
2932            } => self.exec_create_schema(name, if_not_exists),
2933            Statement::DropSchema { names, if_exists } => self.exec_drop_schema(&names, if_exists),
2934            Statement::ResetParameter(target) => {
2935                match target {
2936                    // v7.39 (round 320, V53) — RESET ALL resets GUCs. It
2937                    // must NOT throw away the two internal keys the server
2938                    // parks in the same map: the connection's login
2939                    // identity and its database. PG has no way to reset
2940                    // those with RESET ALL (they are not GUCs), and
2941                    // clearing them here made `current_user` fall back to
2942                    // the admin default mid-session.
2943                    None => self.reset_all_gucs(),
2944                    Some(name) => {
2945                        self.session_params.remove(&name.to_ascii_lowercase());
2946                    }
2947                }
2948                self.refresh_render_style();
2949                Ok(QueryResult::CommandOk {
2950                    affected: 0,
2951                    modified_catalog: false,
2952                })
2953            }
2954        };
2955        self.enforce_row_limit(result)
2956    }
2957}
2958
2959impl Engine {
2960    /// v7.39 (round 247) — resolve the CSV-only extras. QUOTE / ESCAPE /
2961    /// FORCE_QUOTE outside CSV mode are PG's 0A000 refusals (SPG used to
2962    /// ignore a text-mode QUOTE silently); the returned mask marks the
2963    /// force-quoted columns of `column_names`.
2964    fn resolve_copy_csv_extras(
2965        options: &spg_sql::ast::CopyOptions,
2966        is_csv: bool,
2967        quote: char,
2968        column_names: &[alloc::string::String],
2969    ) -> Result<(char, Option<alloc::vec::Vec<bool>>), EngineError> {
2970        if !is_csv {
2971            if options.quote.is_some() {
2972                return Err(EngineError::Unsupported(
2973                    "COPY QUOTE requires CSV mode".into(),
2974                ));
2975            }
2976            if options.escape.is_some() {
2977                return Err(EngineError::Unsupported(
2978                    "COPY ESCAPE requires CSV mode".into(),
2979                ));
2980            }
2981        }
2982        // v7.39 (round 265) — the direction-dependent rules (FORCE_QUOTE is
2983        // TO-only, FORCE_NOT_NULL / FORCE_NULL are FROM-only), sharing one
2984        // validator with the FROM path.
2985        crate::copy::validate_copy_option_direction(options, true)?;
2986        let escape = options.escape.unwrap_or(quote);
2987        let force = match &options.force_quote {
2988            None => None,
2989            Some(cols) if cols.is_empty() => Some(alloc::vec![true; column_names.len()]),
2990            Some(cols) => {
2991                let mut mask = alloc::vec![false; column_names.len()];
2992                for c in cols {
2993                    let pos = column_names
2994                        .iter()
2995                        .position(|n| n.eq_ignore_ascii_case(c))
2996                        .ok_or_else(|| {
2997                            EngineError::Unsupported(alloc::format!(
2998                                "column \"{c}\" does not exist"
2999                            ))
3000                        })?;
3001                    mask[pos] = true;
3002                }
3003                Some(mask)
3004            }
3005        };
3006        Ok((escape, force))
3007    }
3008
3009    /// v7.39 (round 249) — resolve the effective COPY FROM target column
3010    /// list, running PG's pre-file checks in PG's order: the relation
3011    /// must exist, an explicit column must exist on it, and no column
3012    /// may appear twice — all before a single data row is looked at.
3013    ///
3014    /// # Errors
3015    /// `relation "t" does not exist`, `column "x" of relation "t" does
3016    /// not exist` (42703), `column "x" specified more than once` (42701).
3017    /// v7.39 (round 343, V40) — store a file the host just read as a
3018    /// large object. The host does the IO (the engine is `no_std`); the
3019    /// catalog side is the same `create_large_object` the rest of the
3020    /// lo_* family uses, so an imported object is indistinguishable from
3021    /// one built with `lo_from_bytea`.
3022    pub fn lo_import_bytes(
3023        &mut self,
3024        want_oid: u32,
3025        data: alloc::vec::Vec<u8>,
3026    ) -> Result<u32, EngineError> {
3027        self.active_catalog_mut()
3028            .create_large_object(want_oid, data)
3029            .map_err(EngineError::Unsupported)
3030    }
3031
3032    /// v7.39 (round 343, V40) — the bytes the host is about to write out.
3033    /// PG's message for a missing object, verbatim.
3034    pub fn lo_export_bytes(&self, oid: u32) -> Result<alloc::vec::Vec<u8>, EngineError> {
3035        self.active_catalog()
3036            .large_object(oid)
3037            .map(<[u8]>::to_vec)
3038            .ok_or_else(|| {
3039                EngineError::Unsupported(alloc::format!("large object {oid} does not exist"))
3040            })
3041    }
3042
3043    pub fn copy_target_columns(
3044        &self,
3045        table: &str,
3046        columns: Option<&[alloc::string::String]>,
3047    ) -> Result<alloc::vec::Vec<alloc::string::String>, EngineError> {
3048        let table_ref = self.active_catalog().get(table).ok_or_else(|| {
3049            EngineError::Storage(spg_storage::StorageError::TableNotFound {
3050                name: alloc::string::String::from(table),
3051            })
3052        })?;
3053        let schema_cols = &table_ref.schema().columns;
3054        match columns {
3055            None => Ok(schema_cols.iter().map(|c| c.name.clone()).collect()),
3056            Some(cols) => {
3057                for (i, name) in cols.iter().enumerate() {
3058                    if !schema_cols
3059                        .iter()
3060                        .any(|c| c.name.eq_ignore_ascii_case(name))
3061                    {
3062                        return Err(EngineError::Unsupported(alloc::format!(
3063                            "column \"{name}\" of relation \"{table}\" does not exist"
3064                        )));
3065                    }
3066                    if cols[..i].iter().any(|p| p.eq_ignore_ascii_case(name)) {
3067                        return Err(EngineError::Unsupported(alloc::format!(
3068                            "column \"{name}\" specified more than once"
3069                        )));
3070                    }
3071                }
3072                Ok(cols.to_vec())
3073            }
3074        }
3075    }
3076
3077    /// v7.39 (round 249) — execute a parsed `COPY … FROM '<file>'` whose
3078    /// file contents the HOST has already read (the engine is no_std and
3079    /// performs no I/O). Lowers to per-row INSERTs via
3080    /// [`crate::copy::copy_buffer_inserts`]; outside an explicit
3081    /// transaction the rows are wrapped in one, so a bad row aborts the
3082    /// whole COPY exactly as in PG.
3083    ///
3084    /// # Errors
3085    /// The failing row's INSERT error propagates (after rollback).
3086    pub fn copy_from_buffer(
3087        &mut self,
3088        table: &str,
3089        columns: Option<&[alloc::string::String]>,
3090        options: &spg_sql::ast::CopyOptions,
3091        data: &str,
3092    ) -> Result<QueryResult, EngineError> {
3093        let target = self.copy_target_columns(table, columns)?;
3094        let inserts = crate::copy::copy_buffer_inserts(table, columns, &target, options, data)?;
3095        let wrap = !self.in_transaction();
3096        if wrap {
3097            self.execute("BEGIN")?;
3098        }
3099        let mut affected: usize = 0;
3100        for insert in &inserts {
3101            match self.execute(insert) {
3102                Ok(QueryResult::CommandOk { affected: n, .. }) => affected += n,
3103                Ok(_) => affected += 1,
3104                Err(e) => {
3105                    if wrap {
3106                        let _ = self.execute("ROLLBACK");
3107                    }
3108                    return Err(e);
3109                }
3110            }
3111        }
3112        if wrap {
3113            self.execute("COMMIT")?;
3114        }
3115        Ok(QueryResult::CommandOk {
3116            affected,
3117            modified_catalog: false,
3118        })
3119    }
3120
3121    /// v7.39 (round 252) — render a `COPY … TO '<file>'` payload for the
3122    /// HOST to write (the engine is no_std and performs no I/O). Returns
3123    /// the encoded bytes (one line per record, trailing newline) and the
3124    /// DATA row count for the `COPY n` tag — the HEADER line, when
3125    /// present, is part of the payload but not of the count.
3126    ///
3127    /// # Errors
3128    /// Same surface as `COPY … TO STDOUT` (missing relation / column,
3129    /// CSV-mode option refusals).
3130    pub fn copy_to_buffer(
3131        &mut self,
3132        table: &str,
3133        columns: Option<&[alloc::string::String]>,
3134        query: Option<&Statement>,
3135        options: &spg_sql::ast::CopyOptions,
3136    ) -> Result<(alloc::string::String, usize), EngineError> {
3137        let result = self.exec_copy_to(table, columns, query, options, CancelToken::none())?;
3138        let QueryResult::Rows { rows, .. } = result else {
3139            return Err(EngineError::Unsupported(
3140                "COPY TO rendered a non-row result".into(),
3141            ));
3142        };
3143        let mut payload = alloc::string::String::new();
3144        for row in &rows {
3145            if let Some(Value::Text(line)) = row.values.first() {
3146                payload.push_str(line);
3147            }
3148            payload.push('\n');
3149        }
3150        let data_rows = rows.len().saturating_sub(usize::from(options.header));
3151        Ok((payload, data_rows))
3152    }
3153
3154    /// `COPY table [(cols)] TO STDOUT` — render the visible rows
3155    /// in COPY text format (tab-separated, `\N` nulls, backslash
3156    /// escapes) as a single-text-column result set. Embedded
3157    /// consumers read the lines directly; the wire layer streams
3158    /// CopyData frames from them.
3159    fn exec_copy_to(
3160        &mut self,
3161        table_name: &str,
3162        columns: Option<&[String]>,
3163        query: Option<&Statement>,
3164        options: &spg_sql::ast::CopyOptions,
3165        cancel: CancelToken<'_>,
3166    ) -> Result<QueryResult, EngineError> {
3167        use spg_sql::ast::CopyFormat;
3168        // v7.39 (read01 round 94) — `COPY (<query>) TO STDOUT`: run the inner
3169        // statement and render its result set with the same per-format cell
3170        // encoder the table form uses. Kept as an early branch so the
3171        // battle-tested table path below is untouched.
3172        if let Some(q) = query {
3173            return self.exec_copy_to_query(q, options, cancel);
3174        }
3175        let table = self.active_catalog().get(table_name).ok_or_else(|| {
3176            EngineError::Storage(spg_storage::StorageError::TableNotFound {
3177                name: alloc::string::String::from(table_name),
3178            })
3179        })?;
3180        let schema_cols = table.schema().columns.clone();
3181        let positions: alloc::vec::Vec<usize> = match columns {
3182            Some(cols) => cols
3183                .iter()
3184                .map(|c| {
3185                    schema_cols
3186                        .iter()
3187                        .position(|s| s.name.eq_ignore_ascii_case(c))
3188                        .ok_or_else(|| {
3189                            EngineError::Eval(crate::eval::EvalError::ColumnNotFound {
3190                                name: c.clone(),
3191                            })
3192                        })
3193                })
3194                .collect::<Result<_, _>>()?,
3195            None => (0..schema_cols.len()).collect(),
3196        };
3197        // Per-format defaults: text = tab / `\N`; csv = comma / `` / `"`.
3198        let is_csv = options.format == CopyFormat::Csv;
3199        let delimiter = options.delimiter.unwrap_or(if is_csv { ',' } else { '\t' });
3200        let quote = options.quote.unwrap_or('"');
3201        let null_str = options
3202            .null_str
3203            .clone()
3204            .unwrap_or_else(|| alloc::string::String::from(if is_csv { "" } else { "\\N" }));
3205        // v7.39 (round 247) — the FORCE_QUOTE mask follows the emitted
3206        // column order (the projection), not the table order.
3207        let out_names: alloc::vec::Vec<alloc::string::String> = positions
3208            .iter()
3209            .filter_map(|&p| schema_cols.get(p).map(|c| c.name.clone()))
3210            .collect();
3211        let (escape, force_mask) =
3212            Self::resolve_copy_csv_extras(options, is_csv, quote, &out_names)?;
3213        let encode_cells = |cells: &[Option<alloc::string::String>]| -> alloc::string::String {
3214            if is_csv {
3215                crate::copy::encode_copy_csv_cells_opts(
3216                    cells,
3217                    delimiter,
3218                    quote,
3219                    escape,
3220                    force_mask.as_deref(),
3221                    &null_str,
3222                )
3223            } else {
3224                crate::copy::encode_copy_text_cells_opts(cells, delimiter, &null_str)
3225            }
3226        };
3227        let snap = self.current_snapshot();
3228        let mut out_rows: alloc::vec::Vec<spg_storage::Row<'static>> = alloc::vec::Vec::new();
3229        // HEADER: the selected column names as the first line, encoded
3230        // per the same format rules (a name is never NULL).
3231        if options.header {
3232            let names: alloc::vec::Vec<Option<alloc::string::String>> = positions
3233                .iter()
3234                .map(|&p| Some(schema_cols[p].name.clone()))
3235                .collect();
3236            out_rows.push(spg_storage::Row::new(alloc::vec![Value::text(
3237                encode_cells(&names)
3238            )]));
3239        }
3240        // COPY renders each value with its type's output function, the
3241        // same as the wire — notably bool as `t` / `f`, not the engine's
3242        // debug-ish `true` / `false`.
3243        // v7.38 (T-tstz Phase 1) — `ty` is the column's declared type, needed
3244        // only to tell timestamptz from timestamp: PG's COPY renders the former
3245        // with its offset. Everything else renders identically either way.
3246        let cell_text = |v: &Value, ty: spg_storage::DataType| -> Option<alloc::string::String> {
3247            match v {
3248                Value::Null => None,
3249                Value::Bool(b) => Some(alloc::string::String::from(if *b { "t" } else { "f" })),
3250                Value::Timestamp(t) if matches!(ty, spg_storage::DataType::Timestamptz) => {
3251                    Some(crate::eval::format_timestamptz(*t))
3252                }
3253                other => Some(crate::eval::values::value_to_text(other)),
3254            }
3255        };
3256        let encode = |row: &spg_storage::Row<'static>| {
3257            let cells: alloc::vec::Vec<Option<alloc::string::String>> = positions
3258                .iter()
3259                .map(|&p| {
3260                    row.values
3261                        .get(p)
3262                        .and_then(|v| cell_text(v, schema_cols[p].ty))
3263                })
3264                .collect();
3265            encode_cells(&cells)
3266        };
3267        for (_, row) in table.scan_visible(&snap) {
3268            cancel.check()?;
3269            out_rows.push(spg_storage::Row::new(alloc::vec![Value::text(encode(row))]));
3270        }
3271        for row in self.iter_cold_rows_of_table(table) {
3272            cancel.check()?;
3273            out_rows.push(spg_storage::Row::new(alloc::vec![Value::text(encode(
3274                &row
3275            ))]));
3276        }
3277        Ok(QueryResult::Rows {
3278            columns: alloc::vec![spg_storage::ColumnSchema::new(
3279                alloc::string::String::from("copy"),
3280                spg_storage::DataType::Text,
3281                false,
3282            )],
3283            rows: out_rows,
3284        })
3285    }
3286
3287    /// v7.39 (read01 round 94) — the `COPY (<query>) TO STDOUT` renderer.
3288    /// Executes the inner statement and encodes its result set into a single
3289    /// `copy` text column (one row per COPY line, header first when asked),
3290    /// exactly like the table form's tail — the difference is only where the
3291    /// rows and their column types come from.
3292    fn exec_copy_to_query(
3293        &mut self,
3294        query: &Statement,
3295        options: &spg_sql::ast::CopyOptions,
3296        cancel: CancelToken<'_>,
3297    ) -> Result<QueryResult, EngineError> {
3298        use spg_sql::ast::CopyFormat;
3299        let (result_cols, result_rows) = match self.dispatch_stmt_inner(query.clone(), cancel)? {
3300            QueryResult::Rows { columns, rows } => (columns, rows),
3301            _ => {
3302                return Err(EngineError::Unsupported(
3303                    "COPY (query) source did not produce a result set".into(),
3304                ));
3305            }
3306        };
3307        let is_csv = options.format == CopyFormat::Csv;
3308        let delimiter = options.delimiter.unwrap_or(if is_csv { ',' } else { '\t' });
3309        let quote = options.quote.unwrap_or('"');
3310        let null_str = options
3311            .null_str
3312            .clone()
3313            .unwrap_or_else(|| alloc::string::String::from(if is_csv { "" } else { "\\N" }));
3314        let out_names: alloc::vec::Vec<alloc::string::String> =
3315            result_cols.iter().map(|c| c.name.clone()).collect();
3316        let (escape, force_mask) =
3317            Self::resolve_copy_csv_extras(options, is_csv, quote, &out_names)?;
3318        let encode_cells = |cells: &[Option<alloc::string::String>]| -> alloc::string::String {
3319            if is_csv {
3320                crate::copy::encode_copy_csv_cells_opts(
3321                    cells,
3322                    delimiter,
3323                    quote,
3324                    escape,
3325                    force_mask.as_deref(),
3326                    &null_str,
3327                )
3328            } else {
3329                crate::copy::encode_copy_text_cells_opts(cells, delimiter, &null_str)
3330            }
3331        };
3332        let cell_text = |v: &Value, ty: spg_storage::DataType| -> Option<alloc::string::String> {
3333            match v {
3334                Value::Null => None,
3335                Value::Bool(b) => Some(alloc::string::String::from(if *b { "t" } else { "f" })),
3336                Value::Timestamp(t) if matches!(ty, spg_storage::DataType::Timestamptz) => {
3337                    Some(crate::eval::format_timestamptz(*t))
3338                }
3339                other => Some(crate::eval::values::value_to_text(other)),
3340            }
3341        };
3342        let mut out_rows: alloc::vec::Vec<spg_storage::Row<'static>> = alloc::vec::Vec::new();
3343        if options.header {
3344            let names: alloc::vec::Vec<Option<alloc::string::String>> =
3345                result_cols.iter().map(|c| Some(c.name.clone())).collect();
3346            out_rows.push(spg_storage::Row::new(alloc::vec![Value::text(
3347                encode_cells(&names)
3348            )]));
3349        }
3350        for row in &result_rows {
3351            cancel.check()?;
3352            let cells: alloc::vec::Vec<Option<alloc::string::String>> = result_cols
3353                .iter()
3354                .enumerate()
3355                .map(|(p, c)| row.values.get(p).and_then(|v| cell_text(v, c.ty)))
3356                .collect();
3357            out_rows.push(spg_storage::Row::new(alloc::vec![Value::text(
3358                encode_cells(&cells)
3359            )]));
3360        }
3361        Ok(QueryResult::Rows {
3362            columns: alloc::vec![spg_storage::ColumnSchema::new(
3363                alloc::string::String::from("copy"),
3364                spg_storage::DataType::Text,
3365                false,
3366            )],
3367            rows: out_rows,
3368        })
3369    }
3370}
3371
3372impl Engine {
3373    /// PG's `PreventInTransactionBlock`: statements whose effect no
3374    /// rollback can undo are refused inside an explicit transaction with
3375    /// 25001, naming themselves in the message.
3376    ///
3377    /// The witness is THIS connection's slot, not the global
3378    /// `in_transaction()`: the engine is shared, so a global check would
3379    /// refuse an autocommit VACUUM merely because a different connection
3380    /// had a transaction open. Same predicate `DISCARD ALL` already uses.
3381    /// Whether a catalog change this statement made is already committed,
3382    /// i.e. THIS connection is not inside an explicit transaction block.
3383    ///
3384    /// It rides out on `QueryResult::modified_catalog`, and the server
3385    /// takes it as "persist and audit this now": in no-WAL mode it drives
3386    /// the snapshot write, and it gates the audit append in every mode.
3387    ///
3388    /// The witness has to be this connection's slot. Asking the
3389    /// engine-wide `in_transaction()` — true while ANY connection holds a
3390    /// transaction — reported an autocommit DDL as uncommitted, and both
3391    /// consequences were measured in round 795: the statement was missing
3392    /// from the audit log entirely, and after `kill -9` plus a restart the
3393    /// table it created was gone, having been acked to the client. A
3394    /// second connection idling inside a BEGIN was the whole cause.
3395    pub(crate) fn catalog_change_is_committed(&self) -> bool {
3396        !self.current_tx.is_some_and(|tx| self.is_tx_open(tx))
3397    }
3398
3399    pub(crate) fn require_no_transaction_block(&self, what: &str) -> Result<(), EngineError> {
3400        if self.current_tx.is_some_and(|tx| self.is_tx_open(tx)) {
3401            return Err(EngineError::Unsupported(alloc::format!(
3402                "{what} cannot run inside a transaction block"
3403            )));
3404        }
3405        Ok(())
3406    }
3407}