spg_engine/lib.rs
1//! SPG execution engine — v0.3 wires the SQL front-end to the in-memory
2//! storage layer. Implements `CREATE TABLE`, single-row `INSERT VALUES`, and
3//! `SELECT * FROM <table>` (no WHERE yet — that lands in v0.4 alongside
4//! expression evaluation against rows).
5#![no_std]
6
7extern crate alloc;
8
9// v7.37.9 T3 — `bump_counter!(C)` / `bump_counter!(C, N)` macros for the
10// Step VM + aggregate hot-path diagnostic counters. Gated on the
11// `perf-counters` feature so release builds pay zero cost; the
12// `xtests/dogfood_replay/spg-counter-dump` binary turns the feature on
13// to attribute Class A / B / C cascade cost.
14#[cfg(not(feature = "perf-counters"))]
15#[macro_export]
16macro_rules! bump_counter {
17 ($c:path) => {{
18 let _ = &$c;
19 }};
20 ($c:path, $n:expr) => {{
21 let _ = &$c;
22 let _ = &$n;
23 }};
24}
25
26#[cfg(feature = "perf-counters")]
27#[macro_export]
28macro_rules! bump_counter {
29 ($c:path) => {{
30 $c.fetch_add(1, core::sync::atomic::Ordering::Relaxed);
31 }};
32 ($c:path, $n:expr) => {{
33 $c.fetch_add($n, core::sync::atomic::Ordering::Relaxed);
34 }};
35}
36
37mod acl;
38pub mod aggregate;
39pub(crate) mod amcheck;
40mod bytebudget;
41mod cancel;
42mod clock;
43mod collate;
44mod collate_derive;
45mod constfold;
46mod constraints;
47mod conversions;
48pub mod copy;
49mod cursor;
50mod ddl;
51pub mod describe;
52mod distinct;
53mod dml;
54mod dump;
55mod envelope;
56pub mod eval;
57mod execute;
58mod explain;
59mod expr_analysis;
60pub(crate) mod extsort;
61pub mod fts;
62mod guc_catalog;
63mod immutable_fn;
64mod index_access;
65mod join;
66mod join_using;
67mod joinfold;
68pub mod json;
69pub mod largeobject;
70mod limit_expr;
71pub mod locks;
72mod maintenance;
73pub mod memoize;
74mod notify;
75mod numeric;
76mod opclass;
77mod orderby;
78mod partition;
79pub(crate) mod partition_walks;
80pub mod plan_cache;
81mod plpgsql;
82pub mod publications;
83mod qualorder;
84pub mod query_stats;
85mod readonly;
86pub mod reorder;
87mod rls;
88mod rules;
89pub mod scalarsq_streaming;
90mod select;
91pub mod selectivity;
92mod sequence;
93mod session;
94mod show;
95mod spg_admin;
96pub mod statistics;
97pub mod subquery;
98pub mod subscriptions;
99mod substitute;
100mod system_catalog;
101mod table_access;
102pub mod tempstore;
103pub mod testkit;
104mod transaction;
105pub(crate) use transaction::{TxStmtClass, classify_stmt_for_tx};
106pub mod triggers;
107pub mod users;
108mod window;
109
110pub use crate::users::{Role, ScramSecrets, UserError, UserStore};
111pub use cancel::{CancelToken, MonotonicNowFn};
112pub use execute::{RowCells, StreamItem};
113
114use bytebudget::*;
115pub(crate) use clock::{rewrite_clock_calls, value_to_literal};
116use constraints::*;
117pub use constraints::{UNIQ_FOLD_CHOSEN, UNIQ_PROBE_CALLS, UNIQ_PROBE_LOCATORS};
118use conversions::*;
119pub use conversions::{
120 format_bigint_2d_text_pub, format_bit_string, format_circle, format_hstore_text, format_inet,
121 format_int_2d_text_pub, format_line, format_lseg, format_macaddr, format_macaddr8,
122 format_multirange, format_path, format_pg_box, format_pg_lsn, format_point, format_polygon,
123 format_range_text, format_text_2d_text_pub,
124};
125pub(crate) use ddl::{
126 canonicalize_set_value, enforce_enum_label, eval_runtime_default_free,
127 resolve_column_default_free,
128};
129pub(crate) use envelope::{EnvelopeParse, build_envelope, split_envelope};
130use expr_analysis::*;
131use index_access::*;
132pub use join::{ANTI_JOIN_FAST_PATH_FIRED, ANTI_JOIN_FAST_PATH_TRIED};
133pub(crate) use orderby::{
134 OrderKey, apply_offset_and_limit, apply_offset_and_limit_tagged, build_order_keys,
135 canonical_value_repr, cmp_multi_key, expand_group_by_all, order_by_value_cmp,
136 order_by_value_cmp_in, render_histogram_bounds, resolve_order_by_position, sort_by_keys,
137 sort_values_for_histogram, topk_trim, value_cmp, value_to_f64,
138};
139pub use select::{DISTINCT_DUP_DROPPED, PROJ_DIRECT_FIRE, PROJ_ROW_BUILT, SCAN_PATH_ENTERED};
140pub(crate) use select::{build_projection, infer_column_types, value_to_order_key};
141pub use sequence::MUTATING_CALL_NEEDLES;
142pub(crate) use show::render_create_table;
143pub use subquery::{
144 BATCHED_SCALAR_FALL_THROUGH_COUNT, BATCHED_SCALAR_KEYED_FIRE_COUNT,
145 BATCHED_SCALAR_KEYED_PROBE_COUNT, EXISTS_BATCH_FALL_THROUGH_COUNT, EXISTS_BATCH_FIRE_COUNT,
146 EXISTS_PULLUP_BAIL_INNER_FROM, EXISTS_PULLUP_BAIL_INNER_SHAPE,
147 EXISTS_PULLUP_BAIL_MULTICOL_DISABLED, EXISTS_PULLUP_BAIL_NO_CORR, EXISTS_PULLUP_BAIL_NO_WHERE,
148 EXISTS_PULLUP_BAIL_RESIDUAL_NOT_INNER, EXISTS_PULLUP_BAIL_UNIQUE_KEY_MISSING,
149 EXISTS_PULLUP_CANDIDATE_COUNT, EXISTS_PULLUP_FIRE_COUNT, EXISTS_PULLUP_MULTICOL_DISABLE,
150 PULLUP_LIMIT1_FIRE_COUNT, SCALARSQ_PK_PROBE_FIRED, ScalarPkProbeFastPath,
151 expr_tree_has_subquery,
152};
153pub(crate) use subquery::{build_in_list_set, collect_scalar_subqueries, expr_has_subquery};
154pub use substitute::substitute_placeholders;
155use substitute::*;
156use system_catalog::*;
157use window::*;
158
159use alloc::collections::{BTreeMap, BTreeSet};
160use alloc::string::String;
161use alloc::vec::Vec;
162use core::fmt;
163
164// v7.16.0 — re-export the parsed-statement AST so downstream
165// crates (spg-embedded → spg-sqlx) don't need a direct dep on
166// spg-sql for the prepare/bind handle.
167pub use spg_sql::ast::{SelectStatement, Statement as ParsedStatement};
168// v7.37.15 Phase B — re-export the visibility primitives for engine
169// callers so the per-row MVCC types live behind one stable name
170// (`spg_engine::Snapshot` / `spg_engine::RowHeader`) instead of every
171// caller threading through `spg_storage::snapshot::*` directly.
172pub use spg_storage::RowChange;
173pub use spg_storage::row_header::{RowHeader, XMAX_ALIVE, XMIN_FROZEN};
174pub use spg_storage::snapshot::{
175 AllCommitted, InProgressSet, Snapshot, XactStatus, XactStatusOracle,
176};
177
178/// v7.37.15 (Phase C.2) — the engine is its own visibility oracle.
179/// Scans hold `&Engine` while reading, so a scan site can pass `self`
180/// as the [`XactStatusOracle`] alongside its [`Snapshot`] when the
181/// visibility gate migrates from `visible` to `visible_with_status`
182/// (next Phase C step). Delegates to [`Engine::xact_status`].
183impl XactStatusOracle for Engine {
184 fn status(&self, version: u64) -> XactStatus {
185 self.xact_status(version)
186 }
187}
188// v7.37.14 (A2.5-stub) — re-export the silent-FOR-UPDATE telemetry
189// helper through the engine surface so downstream wrappers
190// (spg-embedded / spg-embedded-tokio / spgctl) and their tests
191// don't need a direct `spg-sql` dep.
192use spg_sql::parser::ParseError;
193pub use spg_sql::silent_for_update_count;
194use spg_storage::{Catalog, ColumnSchema, Row, StorageError};
195
196use crate::eval::EvalError;
197
198/// Result of executing one statement.
199#[derive(Debug, Clone, PartialEq)]
200#[non_exhaustive]
201pub enum QueryResult {
202 /// DDL or DML succeeded.
203 ///
204 /// `affected` is the row count for `INSERT` and 0 elsewhere.
205 /// `modified_catalog` tells the server whether this statement
206 /// caused the *committed* catalog to change — it's the signal to
207 /// snapshot/audit. False for `BEGIN`/`ROLLBACK`, false for writeful
208 /// statements executed inside a transaction (those only touch the
209 /// shadow), and true for `COMMIT` and for writes outside a TX.
210 CommandOk {
211 affected: usize,
212 modified_catalog: bool,
213 },
214 /// `SELECT` returned a (possibly empty) row set.
215 Rows {
216 columns: Vec<ColumnSchema>,
217 rows: Vec<Row<'static>>,
218 },
219}
220
221/// All errors the engine can return.
222///
223/// Marked `#[non_exhaustive]` from v7.5.0 onward: external `match`
224/// must include a `_` arm so new variants in subsequent v7.x releases
225/// are not breaking changes.
226#[derive(Debug, Clone, PartialEq)]
227#[non_exhaustive]
228pub enum EngineError {
229 Parse(ParseError),
230 Storage(StorageError),
231 Eval(EvalError),
232 /// Front-end accepted a construct that the v0.x executor doesn't support.
233 Unsupported(String),
234 /// `BEGIN` while another transaction is already open.
235 TransactionAlreadyOpen,
236 /// `COMMIT` / `ROLLBACK` with no active transaction.
237 NoActiveTransaction,
238 /// v7.38 (read01 P3.26) — a statement other than COMMIT / ROLLBACK /
239 /// ROLLBACK TO SAVEPOINT was issued after an earlier statement in the
240 /// same transaction failed. PG aborts the whole transaction on the
241 /// first error and rejects everything until it is ended (SQLSTATE
242 /// 25P02); this mirrors that so partial work can't slip through.
243 InFailedTransaction,
244 /// v7.39 (round 299, E3 Phase 2) — a row lock is held by another
245 /// transaction and the policy is `Wait`.
246 ///
247 /// Its own variant, not an `Unsupported` string: the SERVER has to
248 /// recognise it to retry, and it cannot block inside the engine
249 /// write lock — doing so would stop the whole server, including the
250 /// transaction whose commit would release the lock.
251 LockWouldBlock,
252 /// v7.39 (round 299) — granting the wait would close a wait-for
253 /// cycle. PG's 40P01.
254 LockDeadlock,
255 /// v7.38 (read01 P4.02) — a scalar / row subquery used as an
256 /// expression returned more than one row. PG raises this as
257 /// SQLSTATE 21000 (CARDINALITY_VIOLATION) with a fixed message.
258 CardinalityViolation,
259 /// v7.37.17 (Phase E3) — a REPEATABLE READ / SERIALIZABLE commit
260 /// found a write-write conflict with a concurrently-committed
261 /// transaction (a row this tx wrote was deleted/updated by another
262 /// committed writer, or a unique key this tx inserted was taken).
263 /// PG raises SQLSTATE 40001; the client retries the transaction.
264 /// The failing COMMIT rolls the transaction back, like PG.
265 SerializationFailure(String),
266 /// v4.0 sentinel: `execute_readonly` got a statement that
267 /// mutates engine state (INSERT / CREATE / BEGIN / COMMIT / …).
268 /// The caller should retake the write lock and dispatch through
269 /// `execute(&mut self)` instead.
270 WriteRequired,
271 /// v4.2: a SELECT would have returned more rows than the
272 /// configured `max_query_rows` cap. Carries the cap.
273 RowLimitExceeded(usize),
274 /// v7.30.3 (mailrs round-26): a SELECT's join/filter
275 /// materialisation would have held more (approximate) heap
276 /// bytes than the configured `max_query_bytes` cap. The row
277 /// cap above counts rows; this counts bytes, because one row
278 /// can be a multi-MB mail body — 1000 fat rows pressure the
279 /// host long before any row ceiling trips. Carries the cap.
280 QueryBytesExceeded(usize),
281 /// v4.5: cooperative cancellation — the host (server's
282 /// per-query watchdog) set the cancel flag while a long-running
283 /// SELECT / UPDATE / DELETE was scanning rows. The partial work
284 /// is discarded; the caller should surface this as a timeout
285 /// to the client.
286 Cancelled,
287 /// v7.39 (round 318, V51) — MySQL `KILL <id>` naming an id no live
288 /// connection carries. MariaDB 11: `ERROR 1094 (HY000) Unknown thread
289 /// id: N`.
290 UnknownThreadId(u32),
291 /// v7.39 (round 318, V51) — MySQL `KILL <own id>`. The connection
292 /// really is killed; MariaDB reports it to the victim as
293 /// `ERROR 1927 (70100) Connection was killed` and closes.
294 ConnectionKilled,
295 /// v7.38 Epic P (panic isolation): a panic unwound out of
296 /// statement execution and was caught at the engine's
297 /// `execute_*` boundary (see `execute_in_with_cancel`). The
298 /// in-flight transaction's shadow was discarded (rollback) and
299 /// the engine left consistent; the caller sees this ordinary
300 /// error instead of a crashed process / poisoned lock. NOTE:
301 /// under the release `panic = "abort"` profile the process
302 /// aborts before any unwind, so this variant only ever surfaces
303 /// in dev/test (`panic = "unwind"`) — and in production once a
304 /// later slice flips the release profile to unwind.
305 Internal(String),
306}
307
308impl fmt::Display for EngineError {
309 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
310 match self {
311 Self::Parse(e) => write!(f, "parse: {e}"),
312 Self::Storage(e) => write!(f, "storage: {e}"),
313 Self::Eval(e) => write!(f, "eval: {e}"),
314 Self::Unsupported(s) => write!(f, "unsupported: {s}"),
315 Self::TransactionAlreadyOpen => f.write_str("a transaction is already open"),
316 Self::NoActiveTransaction => f.write_str("no active transaction"),
317 Self::LockWouldBlock => f.write_str("row is locked by another transaction"),
318 Self::LockDeadlock => f.write_str("deadlock detected"),
319 Self::InFailedTransaction => f.write_str(
320 "current transaction is aborted, commands ignored until end of transaction block",
321 ),
322 Self::CardinalityViolation => {
323 f.write_str("more than one row returned by a subquery used as an expression")
324 }
325 Self::SerializationFailure(detail) => {
326 // v7.39 (round 552) — PG has TWO wordings under 40001 and
327 // they mean different things: "concurrent update" for a
328 // write-write conflict, "read/write dependencies among
329 // transactions" for the antidependency a SERIALIZABLE
330 // transaction hits. A detail that already carries PG's
331 // own sentence is passed through rather than nested
332 // inside the other one.
333 if detail.starts_with("could not serialize access") {
334 f.write_str(detail)
335 } else {
336 write!(
337 f,
338 "could not serialize access due to concurrent update: {detail}"
339 )
340 }
341 }
342 Self::WriteRequired => {
343 f.write_str("statement requires a write lock (use execute, not execute_readonly)")
344 }
345 Self::RowLimitExceeded(n) => {
346 write!(f, "query exceeded max_query_rows={n}")
347 }
348 Self::QueryBytesExceeded(n) => {
349 write!(
350 f,
351 "query materialisation exceeded max_query_bytes={n} (set SPG_MAX_QUERY_BYTES to raise, 0 to disable)"
352 )
353 }
354 Self::Cancelled => f.write_str("query cancelled (timeout or client request)"),
355 Self::UnknownThreadId(id) => write!(f, "Unknown thread id: {id}"),
356 Self::ConnectionKilled => f.write_str("Connection was killed"),
357 Self::Internal(s) => write!(f, "internal error: {s}"),
358 }
359 }
360}
361
362impl From<ParseError> for EngineError {
363 fn from(e: ParseError) -> Self {
364 Self::Parse(e)
365 }
366}
367impl From<StorageError> for EngineError {
368 fn from(e: StorageError) -> Self {
369 Self::Storage(e)
370 }
371}
372impl From<EvalError> for EngineError {
373 fn from(e: EvalError) -> Self {
374 Self::Eval(e)
375 }
376}
377
378/// The execution engine. Holds the catalog and (later) other server-scope
379/// state. `Engine::new()` is intentionally cheap so callers can construct one
380/// per database, per test.
381/// Function pointer that returns "now" as microseconds since Unix
382/// epoch. The engine is `no_std`, so it can't reach for `std::time`
383/// itself — callers (`spg-server`, the sqllogictest runner) inject a
384/// concrete implementation. `None` means `NOW()` / `CURRENT_*` raise
385/// `Unsupported`.
386pub type ClockFn = fn() -> i64;
387
388/// Backing store for `SPG_TEST_FIXED_CLOCK_MICROS` (test-mode GUC).
389/// Only ever written when that GUC is set; production engines never
390/// touch it.
391static FIXED_CLOCK_MICROS: core::sync::atomic::AtomicI64 = core::sync::atomic::AtomicI64::new(0);
392
393fn fixed_clock_from_env() -> i64 {
394 FIXED_CLOCK_MICROS.load(core::sync::atomic::Ordering::Relaxed)
395}
396
397/// v7.39 (pg_stat knife A) — host-provided live connection count for
398/// `pg_stat_database.numbackends`.
399pub type BackendCountFn = fn() -> u32;
400
401/// v7.39 (read01 pgstatfuncs.c) — host-provided identity of the CALLING
402/// connection for `pg_backend_pid()` / the pg_stat_activity self-join.
403/// The host reads a connection-thread-local set at session start; the
404/// no_std engine just calls through. `None` (embedded) → pid 1.
405pub type BackendPidFn = fn() -> u32;
406
407/// v7.39 (round 476) — the WAL's current byte position, as a PG LSN.
408///
409/// `pg_current_wal_lsn()` answered the literal `0/0` forever, so every
410/// monitor watching WAL progress or replication lag saw an instance that
411/// had never written anything. SPG's WAL is a file and its length IS an
412/// LSN in every sense a monitor uses one: monotonic, byte-denominated, and
413/// comparable — `pg_wal_lsn_diff` over two samples gives real bytes.
414///
415/// `None` (embedded, or a server started without a WAL) keeps `0/0`, which
416/// is the honest answer there: nothing is being written.
417pub type WalLsnFn = fn() -> u64;
418
419/// v7.39 (round 318, V51) — host-provided connection control. `terminate`
420/// false = cancel the target's running statement (PG `pg_cancel_backend`,
421/// MySQL `KILL QUERY`); true = also close the connection (PG
422/// `pg_terminate_backend`, MySQL `KILL CONNECTION`). Returns whether a
423/// connection with that id exists — the engine has no registry of its own,
424/// so the answer has to come from the host that accepted the sockets.
425/// `None` (embedded, no connections) ⇒ nothing to signal.
426pub type BackendSignalFn = fn(pid: u32, terminate: bool) -> bool;
427
428pub use tempstore::{SpillStats, TempRun, TempRunFactory, TempStoreError};
429
430/// v7.39 (tz epic) — host-injected IANA timezone lookups (the no_std
431/// engine can't read the system zoneinfo directory; spg-tzif is the
432/// std-side implementation). All instants are MICROSECONDS.
433/// UTC offset (µs east) of a zone at a UTC instant; None = unknown zone.
434/// v7.39 (round 534) — the compiled-in default PG18 reports for a
435/// configuration parameter, for the wire's own SHOW shortcut.
436///
437/// The pgwire layer answers `SHOW <name>` from a small canned list
438/// before the statement ever reaches the engine, so it needs the same
439/// inventory the engine reads or the two disagree — which they did:
440/// `SHOW fsync` over the wire returned an empty row.
441#[must_use]
442pub fn pg_guc_boot_value(name: &str) -> Option<&'static str> {
443 crate::guc_catalog::guc_boot_value(name)
444}
445
446pub type TzOffsetFn = fn(&str, i64) -> Option<i64>;
447/// Local wall-clock µs -> UTC µs with PG's DST disambiguation.
448pub type TzLocalizeFn = fn(&str, i64) -> Option<i64>;
449/// Canonical zone spelling ("asia/tokyo" -> "Asia/Tokyo").
450pub type TzCanonFn = fn(&str) -> Option<alloc::string::String>;
451/// Zone designation ("JST", "EDT") at a UTC instant.
452pub type TzAbbrevFn = fn(&str, i64) -> Option<alloc::string::String>;
453/// v7.39 (round 502) — every zone the host knows at a UTC instant, as
454/// `(name, abbrev, utc_offset_secs, is_dst)`.
455///
456/// Backs `pg_timezone_names`. SPG resolved named zones correctly — round
457/// 502 measured DST boundaries byte-identical to PG18 — but could not
458/// LIST them, so a client populating a timezone picker got "relation
459/// pg_timezone_names does not exist". The data was there, only
460/// unlistable. No hook, or a host with no tzdata, yields an empty view
461/// rather than an error: that is what such a host honestly has.
462pub type TzAllFn =
463 fn(i64) -> alloc::vec::Vec<(alloc::string::String, alloc::string::String, i64, bool)>;
464
465/// v7.39 (tz epic) — per-statement snapshot of the session TimeZone,
466/// consumed per-VALUE by the timestamptz renderers (a DST zone's
467/// offset depends on the instant being rendered).
468#[derive(Debug, Clone)]
469pub enum SessionTz {
470 Utc,
471 /// Fixed offset, µs east.
472 Fixed(i64),
473 /// IANA zone + the host lookups.
474 Named(alloc::string::String, TzOffsetFn, TzAbbrevFn),
475}
476
477impl SessionTz {
478 #[must_use]
479 pub fn is_utc(&self) -> bool {
480 matches!(self, Self::Utc) || matches!(self, Self::Fixed(0))
481 }
482
483 /// Offset (µs east) at a UTC instant.
484 #[must_use]
485 pub fn offset_at(&self, utc_micros: i64) -> i64 {
486 match self {
487 Self::Utc => 0,
488 Self::Fixed(off) => *off,
489 Self::Named(zone, f, _) => f(zone, utc_micros).unwrap_or(0),
490 }
491 }
492
493 /// Designation for the non-ISO DateStyle suffix: a named zone's
494 /// abbreviation at the instant; None for UTC/fixed (callers spell
495 /// "UTC" / "+09" themselves).
496 #[must_use]
497 pub fn abbrev_at(&self, utc_micros: i64) -> Option<alloc::string::String> {
498 match self {
499 Self::Named(zone, _, f) => f(zone, utc_micros),
500 _ => None,
501 }
502 }
503}
504
505/// Function pointer that produces 16 cryptographically random bytes.
506/// Like `ClockFn`, the engine is `no_std` and can't reach for /dev/urandom
507/// itself — host (`spg-server`) injects an OS-backed source. `None`
508/// means SQL-driven `CREATE USER` falls back to a deterministic salt
509/// derived from the username (acceptable in tests; the server always
510/// installs a real RNG so production paths never see this).
511pub type SaltFn = fn() -> [u8; 16];
512
513/// v4.5 cooperative cancellation token. A long-running SELECT /
514/// UPDATE / DELETE checks `is_cancelled` at row-loop checkpoints
515/// and bails with `EngineError::Cancelled`. The host
516/// (`spg-server`) creates an `AtomicBool` per query, spawns a
517/// watchdog thread that sets it after `SPG_QUERY_TIMEOUT_MS`,
518/// and passes it via `execute_with_cancel` / `execute_readonly_with_cancel`.
519///
520/// `CancelToken::none()` is a no-op — used by the legacy `execute`
521/// and `execute_readonly` entry points so existing callers don't
522/// change.
523/// v4.41.1 opaque transaction handle. Returned by `Engine::alloc_tx_id`,
524/// threaded through `Engine::execute_in` so dispatch can identify which
525/// in-flight TX a statement belongs to. `IMPLICIT_TX` is the reserved
526/// slot every legacy caller — engine self-tests, spg-cli, spg-embedded,
527/// startup replay — implicitly uses through the unchanged
528/// `Engine::execute(sql)` API. v4.41.1 keeps at most one active slot at
529/// runtime (dispatch holds `engine.write()` across the wrap, same as
530/// v4.34); the map shape is here to let v4.42 turn on N in-flight
531/// implicit TXs without reshuffling the engine internals.
532#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
533pub struct TxId(pub u64);
534
535/// Reserved slot used by `Engine::execute(sql)` — the legacy single-
536/// global-shadow path. New `alloc_tx_id` handles start at 1.
537pub const IMPLICIT_TX: TxId = TxId(0);
538
539/// v6.7.3 — default segment-size threshold used by `COMPACT COLD
540/// SEGMENTS` when no explicit target is supplied. Segments whose
541/// `OwnedSegment::bytes().len()` is **strictly** less than this
542/// value are eligible to merge. spg-server reads
543/// `SPG_COMPACTION_TARGET_SEGMENT_BYTES` to override.
544pub const COMPACTION_TARGET_DEFAULT_BYTES: u64 = 4 * 1024 * 1024;
545
546/// Per-slot transaction state. Held inside `tx_catalogs[tx_id]` for the
547/// lifetime of a BEGIN..COMMIT (or BEGIN..ROLLBACK) window. Drops when
548/// the TX commits (its `catalog` is moved over `Engine.catalog`) or
549/// rolls back (slot removed, catalog discarded).
550#[derive(Debug, Default, Clone)]
551struct TxState {
552 /// The TX's shadow copy of the catalog. Started as a clone of
553 /// `Engine.catalog` at BEGIN time; writes flow into it; COMMIT
554 /// installs it over `Engine.catalog`. `Catalog::clone()` is O(1)
555 /// since v4.40 (`PersistentVec` rows + `PersistentBTreeMap` indices).
556 catalog: Catalog,
557 /// v7.37 (round 828) — the TX's shadow copy of the user store,
558 /// following exactly the catalog's model one field up: created
559 /// lazily by the first role DDL inside the TX (an ordinary TX
560 /// never pays the clone), written through for the rest of the TX,
561 /// installed over `Engine.users` at COMMIT, discarded on ROLLBACK.
562 /// PG treats roles as ordinary catalog rows — `BEGIN; CREATE ROLE
563 /// r; ROLLBACK` leaves no role — and SPG used to refuse the
564 /// statement instead, which no drop-in client expects.
565 ///
566 /// Other sessions and the auth path keep reading the committed
567 /// store, so an uncommitted role can neither log in nor be seen
568 /// elsewhere — the isolation PG gives via its catalog MVCC.
569 users: Option<crate::users::UserStore>,
570 /// Per-TX savepoint stack. Each entry pairs the savepoint name with
571 /// a clone of `catalog` (and of the role shadow, which subtransactions
572 /// roll back too) at the moment `SAVEPOINT <name>` fired.
573 /// `ROLLBACK TO <name>` restores from the entry and pops everything
574 /// after it; `RELEASE <name>` discards the entry and everything
575 /// after; COMMIT/ROLLBACK clears the whole stack.
576 savepoints: Vec<(String, Catalog, Option<crate::users::UserStore>)>,
577 /// v7.37.15 (Phase E) — cached MVCC snapshot for REPEATABLE
578 /// READ / SERIALIZABLE. Captured at `exec_begin` time when the
579 /// session's `current_isolation_level` is RR/SER; read paths
580 /// inside the TX use this snapshot rather than calling
581 /// `Engine::current_snapshot` per statement, so a row that
582 /// becomes visible mid-tx (because another writer committed)
583 /// is NOT exposed to this tx — preserving RR's invariant.
584 ///
585 /// `None` for READ COMMITTED (default): each statement gets a
586 /// fresh snapshot via `current_snapshot()`.
587 cached_snapshot: Option<spg_storage::snapshot::Snapshot>,
588 /// v7.37.17 (Phase E2 — RC rebase) — tables this tx has run DML
589 /// against. The per-statement rebase extracts/replays write-sets
590 /// only for these (see `maybe_rc_rebase`).
591 touched_tables: alloc::collections::BTreeSet<String>,
592 /// v7.39 (round 552) — tables this tx has READ. PG's SIREAD locks,
593 /// at table granularity: the coarse end of the same idea, and what
594 /// PG itself falls back to when its per-tuple lock memory runs out.
595 ///
596 /// A SERIALIZABLE tx aborts at COMMIT if any table it read was
597 /// written by a transaction that committed after its snapshot —
598 /// the read/write antidependency SI cannot see. Coarse granularity
599 /// means SPG aborts some transactions PG would let through; it
600 /// never lets through one PG would abort.
601 read_tables: alloc::collections::BTreeSet<String>,
602 /// v7.39 (round 552) — was THIS transaction opened SERIALIZABLE?
603 ///
604 /// `Engine::current_isolation_level` is one field for the whole
605 /// engine, not part of the per-session bag, so with two connections
606 /// open one transaction's COMMIT resets it under the other's feet —
607 /// the shared-engine leak rounds 279 and 283 chased through session
608 /// state and advisory locks. The level a transaction runs at has to
609 /// live on the transaction.
610 serializable: bool,
611 /// The engine's commit sequence when this tx began.
612 begin_commit_seq: u64,
613 /// v7.39 (round 494) — has anything asked for this shadow catalog
614 /// MUTABLY since BEGIN?
615 ///
616 /// COMMIT installs the shadow over the committed catalog, so a
617 /// transaction that changed nothing must install nothing — otherwise
618 /// it reverts whatever other sessions committed while it was open.
619 /// `touched_tables` cannot answer this: it records DML targets for the
620 /// rebase, and a `SELECT lo_write(…)` classifies read-only while
621 /// mutating (the large-object pins caught exactly that).
622 ///
623 /// Set in `active_catalog_mut`, the single place a `&mut Catalog` is
624 /// handed out. A caller that takes the mutable handle without writing
625 /// merely keeps the old install behaviour, so the flag errs toward
626 /// installing.
627 shadow_dirty: bool,
628 /// v7.39 (round 298) — this transaction is in the aborted state.
629 ///
630 /// Per SLOT. It used to be one flag on the shared `Engine`, guarded
631 /// by `in_transaction()` — the GLOBAL "is any transaction open"
632 /// test. So an autocommit statement that failed while a DIFFERENT
633 /// connection happened to hold a transaction set the flag, and
634 /// every other connection was then refused with 25P02. Round 283
635 /// fixed seven sites of this exact shape in the server; this one is
636 /// in the engine and was missed.
637 aborted: bool,
638 /// v7.39 (round 288) — `SET CONSTRAINTS … {DEFERRED|IMMEDIATE}`
639 /// override for this transaction. `None` = each constraint uses
640 /// its own declared timing; `Some(true)` = every DEFERRABLE one is
641 /// deferred; `Some(false)` = every one is immediate.
642 constraints_deferred: Option<bool>,
643 /// v7.39 (round 308) — per-constraint overrides from the NAMED form
644 /// of `SET CONSTRAINTS`. Consulted before `constraints_deferred`, so
645 /// `ALL DEFERRED` followed by `fk_a IMMEDIATE` leaves fk_a immediate
646 /// and everything else deferred. An `ALL` form clears this map,
647 /// which is what makes a later blanket setting win — PG resets the
648 /// whole set the same way.
649 constraints_deferred_by_name: BTreeMap<String, bool>,
650 /// v7.37.17 — the tx executed a statement whose effect on the
651 /// shadow catalog can't be expressed as a versioned row write-set
652 /// (DDL, COPY, anything unclassified). The rebase would lose it,
653 /// so the tx degrades to its frozen BEGIN-time view (SI) for the
654 /// rest of its life — the pre-E2 behaviour, honestly kept.
655 rebase_poisoned: bool,
656 /// v7.37.17 — statements successfully run inside this tx. The
657 /// first statement sees the BEGIN-time clone unchanged (it IS the
658 /// latest base at that point); rebasing starts from the second.
659 stmts_run: u32,
660 /// v7.39 (round 196) — the engine `commit_epoch` this tx last
661 /// rebased against (BEGIN seeds it). When the epoch hasn't moved,
662 /// no other path committed to the base catalog, so the
663 /// per-statement RC rebase — whose write-set extraction is a full
664 /// scan of every touched table — is skipped entirely. The r196
665 /// wire panel traced tx_batch's 2.8× LOSS to exactly that scan
666 /// running before EVERY in-tx statement (~200 µs/stmt on a
667 /// 20k-row table, 58× the statement itself). Over-incrementing
668 /// the epoch is safe (an extra rebase is only slower, never
669 /// wrong); missing an increment would be a correctness bug, so
670 /// the epoch bumps on every completed non-tx statement.
671 rebased_at_epoch: u64,
672 /// v7.37.17 (Phase E4 fix) — (old RowId → new RowId) pairs recorded
673 /// by every in-place UPDATE this tx ran, keyed by table (RowIds are
674 /// per-relation). An UPDATE's write-set is tombstone(old) +
675 /// insert(new); when a rebase skips a CONFLICTING tombstone (the
676 /// row was updated/deleted by a concurrently-committed tx), the
677 /// paired insert must be dropped too — otherwise the row
678 /// DUPLICATES (caught by the E4 isolation matrix).
679 update_pairs: alloc::collections::BTreeMap<
680 String,
681 Vec<(
682 spg_storage::row_header::RowId,
683 spg_storage::row_header::RowId,
684 )>,
685 >,
686}
687
688/// v7.11.0 — frozen read-only view of the engine's committed state.
689/// Constructed via [`Engine::clone_snapshot`]. Holds clones of the
690/// catalog, statistics, clock function, and row-cap config — the
691/// four fields the `execute_readonly` path actually reads. Cheap to
692/// `Clone` (each clone shares the underlying `PersistentVec` row
693/// storage; only the trie root pointers copy). Send + Sync so a
694/// snapshot can be moved across `tokio::task::spawn_blocking`
695/// boundaries without coordination.
696///
697/// The contract: a snapshot reflects the engine's state at the
698/// moment `clone_snapshot()` returned. Subsequent writes to the
699/// engine are NOT visible. Callers who need fresher data take a
700/// new snapshot.
701#[derive(Debug, Clone)]
702pub struct CatalogSnapshot {
703 catalog: Catalog,
704 statistics: statistics::Statistics,
705 clock: Option<ClockFn>,
706 max_query_rows: Option<usize>,
707}
708
709/// CoW-1 (v7.34) — frozen view of the *persisted* committed engine
710/// state. Carries every field the `snapshot()` envelope serializes;
711/// v7.39 (round 279) — the per-CONNECTION state, parked while another
712/// connection holds the engine.
713///
714/// The server runs ONE shared `Engine` behind a `RwLock`
715/// (`ServerState.engine`, built once at startup), so everything the
716/// engine called "session state" was in fact process-wide and leaked
717/// between clients: two connections saw each other's prepared
718/// statements, and one client's `SET sql_mode` re-dialected another's
719/// string literals. PG scopes all of this per session.
720///
721/// Rather than thread a session handle through every call site, the
722/// engine keeps the ACTIVE session's state in its own fields — so the
723/// ~40 existing `self.session_params` / `self.backslash_escapes` uses
724/// are untouched — and swaps the whole bag when the caller announces a
725/// different session. Embedded hosts never announce one and stay on
726/// session 0 forever, exactly as before.
727#[derive(Debug, Default)]
728pub(crate) struct SessionBag {
729 pub(crate) session_params: BTreeMap<String, String>,
730 pub(crate) backslash_escapes: bool,
731 /// v7.39 (round 470) — is the MySQL session in a strict `sql_mode`?
732 ///
733 /// MariaDB's default includes `STRICT_TRANS_TABLES`, so this starts
734 /// true; `SET sql_mode=''` (or any list without a STRICT_ flag) turns
735 /// it off and a value that would otherwise raise is bent to fit
736 /// instead — the same conversion `INSERT IGNORE` uses.
737 pub(crate) mysql_strict: bool,
738 pub(crate) prepared_statements: BTreeMap<String, PreparedSqlStatement>,
739 /// v7.39 (round 499) — the value `nextval` last returned IN THIS
740 /// SESSION, per sequence, and which sequence that was.
741 ///
742 /// PG defines `currval` and `lastval` as session-local: they answer
743 /// the number THIS session was given, and error with 55000 ("not yet
744 /// defined in this session") when it has not called `nextval`. They
745 /// are deliberately not the sequence's current value — another
746 /// session may have advanced it since, and reading that would hand
747 /// back a number this session never owned, which is what a caller
748 /// then uses as a foreign key.
749 ///
750 /// Measured before this (`iso_session` T1/T2): `currval` answered in
751 /// a connection that had never called `nextval`, and `lastval`
752 /// answered across connections, because the tracking lived on the
753 /// shared engine rather than in the bag.
754 pub(crate) seq_currvals: BTreeMap<String, i64>,
755 pub(crate) last_sequence_used: Option<String>,
756 /// v7.39 (round 553) — the isolation level THIS connection is
757 /// running at.
758 ///
759 /// It lived on the shared engine, so it leaked both ways between
760 /// connections. Measured over pgwire against PG18: connection B
761 /// opened a plain BEGIN and `SHOW transaction_isolation` answered
762 /// `serializable` — A's level; and A, still inside its SERIALIZABLE
763 /// block, then read `read committed`, because B's COMMIT reset the
764 /// field under it. PG answers `read committed` and `serializable`
765 /// throughout. So a transaction that asked for SERIALIZABLE ran at
766 /// READ COMMITTED and one that asked for nothing ran at
767 /// SERIALIZABLE, purely because another connection was busy.
768 ///
769 /// Round 552 saw the same field give way and worked around it by
770 /// putting the level on the TRANSACTION; this puts the session's
771 /// own copy where the rest of its state already lives — the place
772 /// r306's comment says every piece of per-connection state belongs
773 /// so it never gets a process-wide version to regress from.
774 pub(crate) isolation_level: spg_sql::ast::IsolationLevel,
775 /// v7.39 (round 306) — open large-object descriptors. Per session
776 /// from the start, deliberately: r277/r279/r283 each landed a piece
777 /// of per-connection state on the process-wide engine first and had
778 /// to be unpicked afterwards, so this one never gets a process-wide
779 /// version to regress from. PG additionally scopes descriptors to
780 /// the transaction, so the table is emptied at COMMIT / ROLLBACK.
781 pub(crate) lo_descriptors: BTreeMap<i32, LargeObjectDescriptor>,
782 /// Next descriptor number to hand out. PG starts at 0 and counts up
783 /// within a transaction, restarting once the transaction ends.
784 pub(crate) lo_next_fd: i32,
785 /// v7.39 (round 321, V54) — open server-side cursors. They lived on
786 /// the shared engine until now, i.e. in ONE namespace for every
787 /// connection: two clients could not both `DECLARE c`, a `FETCH`
788 /// could read another client's rows, and `CLOSE ALL` closed
789 /// everybody's.
790 pub(crate) cursors: BTreeMap<String, cursor::OpenCursor>,
791 /// v7.39 (round 347, M2) — MySQL's `LAST_INSERT_ID()`. Per SESSION
792 /// from the start (r277/r279/r283 each paid for landing per-connection
793 /// state on the shared engine first): one connection's insert must not
794 /// be readable as another's. MariaDB, measured: a fresh session reads
795 /// 0; an insert that generates an AUTO_INCREMENT value sets it to the
796 /// FIRST one generated; a statement that generates none — an explicit
797 /// id, an UPDATE, a DELETE, a plain table — leaves it alone.
798 pub(crate) last_insert_id: i64,
799 /// v7.39 (round 426) — MySQL's `ROW_COUNT()`. Per SESSION like
800 /// `last_insert_id`. MariaDB, measured: a DML statement leaves the
801 /// number of rows it CHANGED (an UPDATE that matched but changed
802 /// nothing leaves 0); a SELECT leaves -1; DDL leaves 0. A FRESH
803 /// session reads 0 (measured), not -1.
804 pub(crate) row_count: i64,
805 /// v7.39 (round 430) — MySQL USER variables (`SET @x = 5`). Per
806 /// SESSION like `last_insert_id` / `row_count`; its own namespace,
807 /// separate from the `@@` session parameters. Reading an unset one
808 /// answers NULL, as MariaDB does.
809 pub(crate) user_vars: BTreeMap<String, spg_storage::Value<'static>>,
810 /// v7.39 (round 436) — the logical names of this session's TEMPORARY
811 /// tables. Each is stored in the catalog under a per-session prefix; this
812 /// set is what says "resolve `t` to my temp one" and what `end_session`
813 /// walks to drop them.
814 pub(crate) temp_tables: alloc::collections::BTreeSet<String>,
815 /// v7.39 (round 469) — the session's TEMPORARY sequences and views, by
816 /// logical name. Separate sets because dropping one at session end has
817 /// to name the catalog map it lives in.
818 pub(crate) temp_sequences: alloc::collections::BTreeSet<String>,
819 pub(crate) temp_views: alloc::collections::BTreeSet<String>,
820}
821
822/// v7.39 (round 306) — one open large-object descriptor.
823#[derive(Debug, Clone, Copy)]
824pub(crate) struct LargeObjectDescriptor {
825 pub(crate) oid: u32,
826 /// Byte offset the next read / write starts at.
827 pub(crate) pos: u64,
828 /// Whether the descriptor was opened with `INV_WRITE`. Reads need no
829 /// permission at all in PG — a write-only descriptor reads fine —
830 /// so only this half is worth remembering.
831 pub(crate) writable: bool,
832}
833
834/// v7.39 (round 277) — one SQL-level prepared statement.
835#[derive(Debug, Clone)]
836pub(crate) struct PreparedSqlStatement {
837 /// The body with its `$N` placeholders still in place.
838 pub(crate) body: spg_sql::ast::Statement,
839 /// Declared parameter type names, in order; empty when PG would
840 /// have inferred them.
841 pub(crate) param_types: alloc::vec::Vec<String>,
842 /// The whole `PREPARE …` text, which `pg_prepared_statements`
843 /// reports verbatim.
844 pub(crate) source: String,
845}
846
847/// `Clone` is O(1) on the catalog (Arc bump) and cheap typed-clones
848/// on the trailers. Decouples "capture state" from "serialize bytes"
849/// so the background-checkpoint worker can hold the snapshot and
850/// produce bytes off the engine write lock.
851#[derive(Debug, Clone)]
852pub struct EngineSnapshot {
853 catalog: Catalog,
854 users: UserStore,
855 publications: publications::Publications,
856 subscriptions: subscriptions::Subscriptions,
857 statistics: statistics::Statistics,
858}
859
860impl EngineSnapshot {
861 /// Same envelope rules as `Engine::snapshot()`: bare catalog when
862 /// every trailer is empty, full envelope otherwise.
863 pub fn serialize(&self) -> Vec<u8> {
864 if self.users.is_empty()
865 && self.publications.is_empty()
866 && self.subscriptions.is_empty()
867 && self.statistics.is_empty()
868 {
869 self.catalog.serialize()
870 } else {
871 build_envelope(
872 &self.catalog.serialize(),
873 &users::serialize_users(&self.users),
874 &self.publications.serialize(),
875 &self.subscriptions.serialize(),
876 &self.statistics.serialize(),
877 )
878 }
879 }
880}
881
882/// v7.39 (parallel-agg P0) — host-injected parallel executor. The
883/// engine is `no_std` and cannot spawn threads; like `ClockFn` /
884/// `RandomFn`, the std-side host (spg-server / embedded-tokio)
885/// injects an implementation at startup. `None` (the default, and
886/// the only option in pure-`no_std` embeddings) keeps every code
887/// path single-threaded and byte-identical to pre-P0 behaviour.
888///
889/// The callback returns `Box<dyn Any + Send>` so one trait serves
890/// any shard-result type; call sites downcast what they produced.
891pub trait ParallelRunner: Send + Sync {
892 /// Run `f(0) .. f(n-1)`, possibly concurrently; return the
893 /// results in shard order. Every call completes before return.
894 fn run_shards(
895 &self,
896 n: usize,
897 f: &(dyn Fn(usize) -> alloc::boxed::Box<dyn core::any::Any + Send> + Sync),
898 ) -> alloc::vec::Vec<alloc::boxed::Box<dyn core::any::Any + Send>>;
899}
900
901/// Engine slot for the injected runner — a newtype so the `Engine`
902/// derive(Debug) keeps working over the non-Debug trait object.
903#[derive(Clone, Default)]
904pub struct ParallelRunnerSlot(pub(crate) Option<alloc::sync::Arc<dyn ParallelRunner>>);
905
906impl core::fmt::Debug for ParallelRunnerSlot {
907 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
908 f.write_str(if self.0.is_some() {
909 "ParallelRunner(<injected>)"
910 } else {
911 "ParallelRunner(none)"
912 })
913 }
914}
915
916/// v7.39 (parallel-agg P0) — below this many input rows a query
917/// never parallelises: thread spin-up beats the win on small scans.
918pub(crate) const PARALLEL_MIN_ROWS: usize = 100_000;
919
920/// v7.39 — diagnostic counter: how many aggregate scans took the
921/// sharded path (read by benches to ground-truth activation).
922/// v7.39 (round 740) — matview delta ground-truth counters (the r735
923/// lesson: a green content pin cannot distinguish "delta applied" from
924/// "silently fell back to full"; these can).
925pub static MATVIEW_FANOUT_BUFFERED: core::sync::atomic::AtomicU64 =
926 core::sync::atomic::AtomicU64::new(0);
927pub static MATVIEW_DELTA_APPLIED: core::sync::atomic::AtomicU64 =
928 core::sync::atomic::AtomicU64::new(0);
929pub static MATVIEW_DELTA_BAILED: core::sync::atomic::AtomicU64 =
930 core::sync::atomic::AtomicU64::new(0);
931pub static PARALLEL_AGG_FIRED: core::sync::atomic::AtomicU64 =
932 core::sync::atomic::AtomicU64::new(0);
933
934// The engine carries several independent session/capture flags (dialect,
935// FK-checks, meta-view materialisation, redo capture); they're orthogonal
936// switches, not a state enum begging to be modelled.
937#[allow(clippy::struct_excessive_bools)]
938#[derive(Debug, Default)]
939pub struct Engine {
940 /// v7.39 (parallel-agg P0) — see [`ParallelRunner`].
941 pub(crate) parallel_runner: ParallelRunnerSlot,
942 /// Committed catalog — what survives `Engine::snapshot()` and what
943 /// outside-TX `SELECT`s read.
944 catalog: Catalog,
945 /// Active TX slots, keyed by `TxId`. Empty when no TX is in flight.
946 /// v4.41.1 runtime invariant: at most one entry (single-writer
947 /// model unchanged). v4.42 will let dispatch hold multiple entries
948 /// concurrently for group commit + engine MVCC.
949 tx_catalogs: BTreeMap<TxId, TxState>,
950 /// v7.39 (round 552) — the COMMIT SEQUENCE at which each table was
951 /// last written. Commit order, not begin order: a transaction that
952 /// began first can commit last, so the writer version allocated at
953 /// BEGIN cannot answer "did this change after I read it".
954 table_last_commit: BTreeMap<String, u64>,
955 /// Monotonic, bumped once per successful COMMIT.
956 commit_seq: u64,
957 /// Which slot the next exec_* call should mutate. Set by
958 /// `execute_in(sql, tx_id)` at the entry point; legacy `execute(sql)`
959 /// sets it to `IMPLICIT_TX`. None when no TX is in flight (read /
960 /// write goes straight against `catalog`).
961 current_tx: Option<TxId>,
962 /// Monotonic counter for `alloc_tx_id`. Starts at 1 — slot 0 is
963 /// reserved for `IMPLICIT_TX`.
964 next_tx_id: u64,
965 /// v7.37.15 (Phase C) — versions allocated by in-flight
966 /// writers. Snapshot construction folds this into the
967 /// `Snapshot.in_progress` set so concurrent readers (or readers
968 /// inside an older snapshot's REPEATABLE READ) don't see
969 /// uncommitted writes.
970 ///
971 /// SPG's single-writer invariant means at most one writer
972 /// version sits here at any moment (the one currently
973 /// executing inside the engine write lock). The set survives
974 /// engine clones because tx-commit removes versions before the
975 /// `Engine::snapshot_data` returns, so a snapshot taken after
976 /// commit observes an empty set.
977 ///
978 /// `BTreeSet` (not Vec) so iteration is sorted — Snapshot
979 /// constructor expects the input sorted for binary-search
980 /// `contains` correctness.
981 active_writer_versions: BTreeSet<u64>,
982 /// v7.37.15 (Phase C.2) — writer versions that ABORTED (rolled
983 /// back). The engine-side visibility oracle ([`Self::xact_status`])
984 /// consults this to report `Aborted` for a version that left the
985 /// in-flight set via rollback rather than commit — the third state
986 /// the abort-aware [`spg_storage::snapshot::Snapshot::visible_with_status`]
987 /// needs once Phase C.3's in-place writes leave aborted stamps in
988 /// place. Pruned below `oldest_active` by vacuum (Phase D); until
989 /// then it grows only with rolled-back transactions (a never-die
990 /// follow-up, not a commit-path leak).
991 aborted_versions: BTreeSet<u64>,
992 /// v7.37.15 (Phase C.4) — row-level lock table keyed on stable
993 /// `(RelId, RowId)`. The in-place write path (C.3) acquires a
994 /// tuple lock before stamping xmax; `exec_commit` / `exec_rollback`
995 /// release the whole transaction's locks at end. No writer acquires
996 /// yet at this commit — the field + delegating methods are the
997 /// plumbing the write path consumes next. Rides on `Engine` like
998 /// `active_writer_versions`; the sharded lock-free manager is C.5.
999 locks: crate::locks::LockTable,
1000 /// v7.37.15 (Phase C.3) — kill switch for the in-place MVCC write
1001 /// path. `false` (default) = legacy physical semantics (DELETE
1002 /// physically removes the row, UPDATE replaces in place). `true` =
1003 /// the C.3 write path (DELETE tombstones via `mark_row_deleted`,
1004 /// UPDATE tombstones the old version + appends the new one, both
1005 /// keeping dead versions physically present for the now-uniformly-
1006 /// gated readers until vacuum reclaims them). `no_std` engine can't
1007 /// read env; the host (spg-server / spg-embedded) reads
1008 /// `SPG_MVCC_INPLACE` and calls [`Self::set_mvcc_inplace`]. Off
1009 /// until the write path + PG18 differential tests are proven.
1010 mvcc_inplace: bool,
1011 /// v7.37.16 — threshold-triggered synchronous vacuum at DML statement
1012 /// exit (autovacuum-lite; see .claude/state/autovacuum-design.md).
1013 /// Default ON; hosts may disable via `SPG_AUTOVACUUM=0`.
1014 autovacuum: bool,
1015 /// v7.39 (round 173) — whether the statement-exit trigger runs the
1016 /// vacuum **inline**. Default ON (embedded: single-threaded host,
1017 /// the statement path is the only place work can happen). A host
1018 /// with a background autovacuum worker (spg-server) flips this off
1019 /// and drives [`Self::autovacuum_tick`] from its own thread instead
1020 /// — PG's shape, where autovacuum never runs inside a client
1021 /// statement. Only meaningful while `autovacuum` itself is on.
1022 autovacuum_inline: bool,
1023 /// v7.37.15 (Phase C) — TxId → writer version registry. When
1024 /// `exec_begin` opens an explicit transaction it allocates a
1025 /// fresh writer version (via [`Self::begin_writer_version`])
1026 /// and stashes the mapping here so the matching `exec_commit`
1027 /// / `exec_rollback` can call
1028 /// [`Self::commit_writer_version`] on the right entry. Empty
1029 /// when no explicit transactions are open.
1030 /// v7.39 (round 295, E3 Phase 1b) — rows a `SKIP LOCKED` pass found
1031 /// held by another transaction. Set by the locking pre-pass and
1032 /// consulted by the base scan, which is READ-only here: the locks
1033 /// themselves were taken under `&mut self` in the pre-pass, so the
1034 /// `&self` scan never mutates the lock table. (A `RefCell` there
1035 /// would cost `Engine: Sync`, which the server's `RwLock<Engine>`
1036 /// needs — see the RFC's §5.6.)
1037 pub(crate) lock_skip_rows: Option<(String, alloc::collections::BTreeSet<usize>)>,
1038 tx_writer_versions: BTreeMap<TxId, u64>,
1039 /// v7.37.15 (Epic W slice 2) — the current statement's autocommit
1040 /// writer version, memoized. In autocommit
1041 /// [`Self::writer_version_for_current_stmt`] mints a fresh version
1042 /// via `next_version()` (a `fetch_add`), so calling it a second
1043 /// time — e.g. when the redo drain post-stamps `RowChange`s —
1044 /// would allocate a *different* number than the writes actually
1045 /// used. Memoizing the first allocation for the duration of one
1046 /// statement makes the drain stamp read back the exact version the
1047 /// rows were written with, without advancing the counter twice.
1048 /// `None` outside a statement / before the first fetch; saved and
1049 /// reset per `execute_in_with_cancel` so it never leaks across
1050 /// statements. Explicit transactions bypass this (their version is
1051 /// the deterministic `tx_writer_versions` entry).
1052 stmt_writer_version: Option<u64>,
1053 /// v7.22 (round-13 T3) — session string-literal dialect. `false`
1054 /// (default) = PG semantics (backslash literal, `''` escape);
1055 /// `true` = MySQL semantics (`\'` etc.). Flipped by the
1056 /// deterministic session signals each dump emits: `SET sql_mode`
1057 /// (only MySQL clients/dumps send it) turns it on,
1058 /// `SET standard_conforming_strings = on` (every pg_dump
1059 /// preamble) turns it off. The plan cache is cleared on every
1060 /// flip — the same SQL text lexes differently per dialect.
1061 backslash_escapes: bool,
1062 /// v7.39 (round 470) — see [`SessionBag::mysql_strict`].
1063 mysql_strict: bool,
1064 /// v7.39 (round 306) — the live session's open large-object
1065 /// descriptors, swapped in and out with the rest of its bag.
1066 pub(crate) lo_descriptors: BTreeMap<i32, LargeObjectDescriptor>,
1067 pub(crate) lo_next_fd: i32,
1068 /// v7.37.17 — name of the sequence most recently advanced by
1069 /// nextval() in this Engine (session). Backs PG's lastval().
1070 /// None until the first nextval; PG errors in that state.
1071 last_sequence_used: Option<String>,
1072 /// v7.39 (round 499) — per-session `currval` values; see
1073 /// [`SessionBag::seq_currvals`].
1074 seq_currvals: alloc::collections::BTreeMap<String, i64>,
1075 /// v7.39 (round 277) — SQL-level prepared statements, session
1076 /// scoped exactly as in PG. Keyed by name; each entry keeps the
1077 /// parsed body (placeholders intact), the declared parameter type
1078 /// names and the statement text `pg_prepared_statements` reports.
1079 prepared_statements: alloc::collections::BTreeMap<String, PreparedSqlStatement>,
1080 /// v7.39 (round 279) — which connection's state is currently
1081 /// installed in the fields above. 0 is the embedded / default
1082 /// session.
1083 current_session: u32,
1084 /// Parked state for every OTHER connection.
1085 sessions: BTreeMap<u32, SessionBag>,
1086 /// v7.39 (round 279) — advisory locks, held ACROSS sessions and so
1087 /// deliberately NOT part of the swapped bag: the whole purpose of
1088 /// an advisory lock is to be visible to the other connection.
1089 /// key → (owning session, re-entrant depth). PG allows the same
1090 /// session to take a lock it already holds.
1091 advisory_locks: BTreeMap<i64, (u32, u32)>,
1092 /// Optional wall clock used to satisfy `NOW()` / `CURRENT_TIMESTAMP`
1093 /// / `CURRENT_DATE`. Set by the host environment.
1094 clock: Option<ClockFn>,
1095 /// v4.1 cryptographic RNG for per-user password salt. Set by the
1096 /// host. `None` means SQL-driven `CREATE USER` uses a
1097 /// deterministic fallback — see `SaltFn`.
1098 salt_fn: Option<SaltFn>,
1099 /// v4.2 per-query row cap. `None` = unlimited. When set, a
1100 /// SELECT that materialises more than `n` rows returns
1101 /// `EngineError::RowLimitExceeded`. Enforced before the result
1102 /// is shaped into wire frames so a runaway scan can't blow the
1103 /// server's heap.
1104 max_query_rows: Option<usize>,
1105 /// v7.30.3 (mailrs round-26) per-query byte cap on join/filter
1106 /// materialisation. `None` = unlimited. Approximate net
1107 /// accounting (Value heap payloads + per-cell enum overhead)
1108 /// charged at every point the join pipeline clones rows;
1109 /// crossing the cap raises `EngineError::QueryBytesExceeded`
1110 /// instead of pressuring the host into reclaim livelock. The
1111 /// host wires this to `SPG_MAX_QUERY_BYTES` (embed defaults it
1112 /// ON; the server keeps its allocator-precise budget as the
1113 /// outer layer).
1114 pub(crate) max_query_bytes: Option<usize>,
1115 /// v7.39 (round 786, T35 Phase A) — host factory for spill runs.
1116 /// `None` (the default, and every embedded caller that has not opted
1117 /// in) keeps today's behaviour exactly: a sort that outgrows
1118 /// `max_query_bytes` still refuses rather than spilling.
1119 pub(crate) temp_run_factory: Option<crate::TempRunFactory>,
1120 /// v4.1 RBAC user table. Empty means "no RBAC configured yet" —
1121 /// the server decides what that means at the auth boundary
1122 /// (open mode vs legacy single-password mode). User CRUD goes
1123 /// through `create_user`/`drop_user`/`verify_user`; persistence
1124 /// rides the snapshot envelope alongside the catalog.
1125 pub(crate) users: UserStore,
1126 /// v6.1.2 logical-replication publication catalog. Empty until
1127 /// `CREATE PUBLICATION` runs. Persistence rides the v3 envelope
1128 /// trailer (see `build_envelope`).
1129 publications: publications::Publications,
1130 /// v6.1.4 logical-replication subscription catalog. Empty until
1131 /// `CREATE SUBSCRIPTION` runs. Persistence rides the v4 envelope
1132 /// trailer.
1133 subscriptions: subscriptions::Subscriptions,
1134 /// v6.2.0 — per-column statistics for the cost-based optimizer.
1135 /// Populated by `ANALYZE`; queried via `spg_statistic` virtual
1136 /// table. Persistence rides the v5 envelope trailer.
1137 statistics: statistics::Statistics,
1138 /// v6.3.0 — engine-level plan cache. Caches the post-`prepare()`
1139 /// `Statement` keyed on SQL text. In-memory only — does NOT ride
1140 /// the snapshot envelope (rebuilt on demand after restart).
1141 plan_cache: plan_cache::PlanCache,
1142 /// v6.5.1 — per-distinct-SQL execution stats. In-memory only,
1143 /// surfaced via `spg_stat_query` virtual table. Updated by the
1144 /// `execute_*` paths after a successful execute.
1145 query_stats: query_stats::QueryStats,
1146 /// v6.5.2 — connection-state provider callback. spg-server
1147 /// registers a function at startup that snapshots its
1148 /// per-pgwire-connection registry into `ActivityRow`s; engine
1149 /// reads through it on every `SELECT * FROM spg_stat_activity`.
1150 /// `None` ⇒ no-data (returns empty rows; matches the no_std
1151 /// embedded callers that don't run pgwire).
1152 activity_provider: Option<ActivityProvider>,
1153 /// v6.5.3 — audit-chain provider + verifier. Same pattern as
1154 /// activity_provider: spg-server registers both at startup;
1155 /// engine reads through on `SELECT * FROM spg_audit_chain` and
1156 /// `SELECT * FROM spg_audit_verify`. `None` ⇒ no-data.
1157 audit_chain_provider: Option<AuditChainProvider>,
1158 audit_verifier: Option<AuditVerifier>,
1159 /// v6.5.6 — slow-query log threshold in microseconds. When set,
1160 /// every successful execute whose elapsed exceeds the threshold
1161 /// gets fed to the registered slow-query log callback (so
1162 /// spg-server can emit a structured log line). Default `None`
1163 /// = no slow-query logging.
1164 slow_query_threshold_us: Option<u64>,
1165 slow_query_logger: Option<SlowQueryLogger>,
1166 /// v7.12.1 — session parameters set via `SET <name> = <value>`.
1167 /// Only `default_text_search_config` is consumed by the engine
1168 /// today (the FTS function dispatcher reads it when
1169 /// `to_tsvector(text)` is called without an explicit config).
1170 /// All other names are accepted + recorded so PG-dump output
1171 /// loads, but have no behavioural effect.
1172 pub(crate) session_params: BTreeMap<String, String>,
1173 /// v7.39 (round 218) — open server-side cursors (DECLARE … CURSOR),
1174 /// keyed by name. Materialized at DECLARE (INSENSITIVE semantics —
1175 /// PG's only actual behaviour too); FETCH / MOVE walk the stored rows.
1176 /// Lifecycle: created only inside a transaction; COMMIT closes
1177 /// non-HOLD cursors and marks WITH HOLD ones held; ROLLBACK closes
1178 /// everything not already held by an earlier commit. Never serialized.
1179 /// Session-scoped in PG; SPG stores them engine-wide (the same
1180 /// process-level session-state architecture wall as `session_params`).
1181 pub(crate) cursors: BTreeMap<String, cursor::OpenCursor>,
1182 /// v7.39 (round 347, M2) — the current session's LAST_INSERT_ID().
1183 /// Swapped with [`SessionBag`] like every other per-connection slot.
1184 /// An atomic because `LAST_INSERT_ID(expr)` SETS it while evaluation
1185 /// holds only `&Engine` — and `Engine` must stay `Sync`, which a
1186 /// `Cell` would have taken away (spg-embedded-tokio shares one across
1187 /// tasks; clippy caught it there before the tests did).
1188 pub(crate) last_insert_id: core::sync::atomic::AtomicI64,
1189 /// v7.39 (round 426) — the current session's ROW_COUNT(). Swapped
1190 /// with [`SessionBag`] like every other per-connection slot. A plain
1191 /// i64: unlike LAST_INSERT_ID it is only ever WRITTEN from the
1192 /// statement driver, which holds `&mut Engine`.
1193 pub(crate) row_count: i64,
1194 /// v7.39 (round 430) — this session's MySQL USER variables.
1195 /// Swapped with [`SessionBag`] like every other per-connection slot.
1196 pub(crate) user_vars: BTreeMap<String, spg_storage::Value<'static>>,
1197 /// v7.39 (round 436) — the logical names of this session's TEMPORARY
1198 /// tables. Swapped with [`SessionBag`]; see `session_temp_name`.
1199 pub(crate) temp_tables: BTreeSet<String>,
1200 pub(crate) temp_sequences: BTreeSet<String>,
1201 pub(crate) temp_views: BTreeSet<String>,
1202 /// v7.39 (round 222) — channels this session LISTENs on. Engine-wide
1203 /// (the same process-level session-state architecture wall as
1204 /// `session_params`). Never serialized.
1205 pub(crate) listen_channels: BTreeSet<String>,
1206 /// v7.39 (round 222) — NOTIFYs raised inside the current transaction,
1207 /// held until COMMIT (PG: transactional delivery, deduplicated within
1208 /// the tx); dropped at ROLLBACK.
1209 pub(crate) tx_pending_notifies: Vec<(String, String)>,
1210 /// v7.39 (round 222) — committed notifications on LISTENed channels,
1211 /// awaiting a drain by the wire layer ('A' NotificationResponse) or an
1212 /// embedded caller ([`Engine::take_notifications`]).
1213 pub(crate) delivered_notifies: Vec<(String, String)>,
1214 /// v7.39 (read01 round 46) — NOTICEs raised by the statement now
1215 /// executing. PG emits a NoticeResponse whenever an `IF EXISTS` /
1216 /// `IF NOT EXISTS` clause makes it skip work ("table \"t\" does not
1217 /// exist, skipping"). The engine appends the PG-worded text here;
1218 /// the caller drains it with [`Engine::take_notices`] after each
1219 /// statement (pgwire turns each into an 'N' message, embedded
1220 /// callers can ignore or surface them). Cleared at the start of
1221 /// every statement so a notice never leaks into the next one.
1222 pending_notices: Vec<Notice>,
1223 /// v7.38 (read01 P3.12) — cumulative row-write counters feeding
1224 /// `pg_stat_database` (database-wide `tup_inserted` / `tup_updated` /
1225 /// `tup_deleted`). Bumped by the affected-row count of each successful
1226 /// INSERT / UPDATE / DELETE statement. Per-Engine (so tests stay
1227 /// isolated); on the server's shared engine they read as the
1228 /// since-start database totals PG reports.
1229 /// v7.39 (pg_stat knife A) — committed / rolled-back transaction
1230 /// counters for pg_stat_database. Atomics so the read-only
1231 /// autocommit path (&self) can count its implicit commit, matching
1232 /// PG (every successful statement outside a tx block is one
1233 /// xact_commit — SELECTs included).
1234 /// v7.37 (round 884) — what sorts have spilled in this process, for
1235 /// `pg_stat_database` and for EXPLAIN ANALYZE's `Sort Method`.
1236 pub(crate) spill_stats: crate::tempstore::SpillStats,
1237 pub(crate) xact_commit: core::sync::atomic::AtomicU64,
1238 pub(crate) xact_rollback: core::sync::atomic::AtomicU64,
1239 /// v7.39 (pg_stat knife A) — host-injected live backend count for
1240 /// pg_stat_database.numbackends (ClockFn-style fn slot; the server
1241 /// wires its connection registry, embedded stays None -> 1).
1242 pub(crate) backend_count_fn: Option<BackendCountFn>,
1243 pub(crate) backend_pid_fn: Option<BackendPidFn>,
1244 /// v7.39 (round 476) — see [`WalLsnFn`].
1245 pub(crate) wal_lsn_fn: Option<WalLsnFn>,
1246 /// v7.39 (round 318, V51) — host connection-control hook. See
1247 /// [`BackendSignalFn`].
1248 pub(crate) backend_signal_fn: Option<BackendSignalFn>,
1249 /// v7.39 (tz epic) — injected IANA timezone lookups; None on a
1250 /// host without zoneinfo (named zones then fail to SET, honestly).
1251 pub(crate) tz_offset_fn: Option<TzOffsetFn>,
1252 pub(crate) tz_localize_fn: Option<TzLocalizeFn>,
1253 pub(crate) tz_canon_fn: Option<TzCanonFn>,
1254 pub(crate) tz_abbrev_fn: Option<TzAbbrevFn>,
1255 /// v7.39 (round 502) — see [`TzAllFn`].
1256 pub(crate) tz_all_fn: Option<TzAllFn>,
1257 pub(crate) stat_tup_inserted: u64,
1258 pub(crate) stat_tup_updated: u64,
1259 pub(crate) stat_tup_deleted: u64,
1260 /// v7.39 (round 192) — per-table DML counters for
1261 /// pg_stat_user_tables (n_tup_ins / n_tup_upd / n_tup_del).
1262 /// Engine-side and NON-transactional, like PG's stats collector:
1263 /// a rolled-back INSERT still counts, and a tx's counts don't
1264 /// ride the shadow catalog (the RC rebase rebuilt shadow tables
1265 /// from the committed base, silently dropping any counter bumped
1266 /// on the shadow — the r192 probe's tx-wrapped inserts read 0).
1267 /// Keyed by table name; DROP TABLE clears, RENAME re-keys.
1268 pub(crate) table_write_stats: alloc::collections::BTreeMap<String, (u64, u64, u64)>,
1269 /// v7.39 (round 196) — bumped after every completed statement that
1270 /// ran OUTSIDE a transaction block (any autocommit statement, plus
1271 /// COMMIT itself via the post-statement check). An open tx whose
1272 /// `rebased_at_epoch` equals this value knows the committed base
1273 /// hasn't moved and skips the per-statement RC rebase (whose
1274 /// write-set extraction full-scans every touched table).
1275 /// Over-approximation is deliberate: read-only statements bump it
1276 /// too, which only costs an extra (correct) rebase.
1277 pub(crate) commit_epoch: u64,
1278 /// v7.38 (read01 P3.19) — `SET LOCAL` undo log for the current
1279 /// transaction. Each entry is `(param_name, prior_value)` captured
1280 /// just before a `SET LOCAL` overwrote it (`None` = the param had no
1281 /// session value, so restoring means removing it). Replayed in
1282 /// reverse at COMMIT / ROLLBACK to revert transaction-local settings;
1283 /// `savepoint_guc_marks` records the stack depth at each open
1284 /// savepoint so `ROLLBACK TO` can unwind just the later ones.
1285 pub(crate) local_guc_saves: Vec<(String, Option<String>)>,
1286 /// v7.39 (GUC knife 3) — parsed DateStyle / IntervalStyle /
1287 /// extra_float_digits, kept in lockstep with `session_params` so
1288 /// renderers don't re-parse GUC text per cell.
1289 pub(crate) render_style: crate::eval::RenderStyle,
1290 pub(crate) savepoint_guc_marks: Vec<(String, usize)>,
1291 /// v7.12.7 — depth counter for trigger-emitted embedded SQL.
1292 /// Each time the engine executes a `DeferredEmbeddedStmt` it
1293 /// increments this; the recursive `execute_stmt_with_cancel`
1294 /// inside that path checks against [`MAX_TRIGGER_RECURSION`]
1295 /// to bound runaway cascades (trigger A's UPDATE on table B
1296 /// fires trigger B which UPDATEs table A which fires trigger
1297 /// A again…). Reset to 0 once the original DML returns.
1298 trigger_recursion_depth: u32,
1299 /// v7.39 (round 140) — set while a DELETE / UPDATE is being re-run by the
1300 /// DO ALSO rule wrapper so the wrapper's inner call does not re-enter the
1301 /// rule-rewrite path (which would recurse forever). INSERT captures its
1302 /// post-image rows directly and needs no such guard.
1303 rule_rewrite_active: bool,
1304 /// v7.14.0 — when `SET FOREIGN_KEY_CHECKS=0` is in effect
1305 /// (mysqldump preamble), the FK existence + arity check at
1306 /// CREATE TABLE time is deferred. FKs referencing a
1307 /// not-yet-existing parent land in `pending_foreign_keys`
1308 /// keyed by child table; `SET FOREIGN_KEY_CHECKS=1` drains
1309 /// the queue and resolves each FK against the now-complete
1310 /// catalog. Empty by default; the queue is drained on every
1311 /// `RESET ALL` too.
1312 foreign_key_checks: bool,
1313 /// v7.16.2 — true on the temp Engine an outer
1314 /// `exec_select_with_meta_views` builds, telling that
1315 /// temp engine "stop short-circuiting into the meta-view
1316 /// path — your catalog already has the materialised
1317 /// tables; just run the regular SELECT." Without this we'd
1318 /// infinite-loop since the meta-view name (e.g.
1319 /// `__spg_info_columns`) still triggers
1320 /// `select_references_meta_view`.
1321 meta_views_materialised: bool,
1322 pending_foreign_keys: Vec<(alloc::string::String, spg_sql::ast::ForeignKeyConstraint)>,
1323 /// v7.38 元机制 D — frozen snapshot of `SPG_TEST_*` env vars. Read
1324 /// once at construction (`with_env_cfg`) and queried on hot paths
1325 /// via `engine.env_cfg().<field>`. Production builds keep this at
1326 /// `EnvConfig::default()`, so the optimiser can const-fold every
1327 /// `if env_cfg.<field>` gate. See `testkit::env_config` + the
1328 /// `xtests/sigil/test-mode-gucs.md` index.
1329 env_cfg: testkit::EnvConfig,
1330 /// v7.38 P0 元机制 A — per-engine `injection_points` attach
1331 /// table. Only exists when the crate is built with the
1332 /// `injection-points` feature; release builds carry no field.
1333 /// Pushed onto the thread-local stack by
1334 /// `enter_injection_scope()` so the `injection_point!()` macro
1335 /// can find it from anywhere in the executor without rewiring
1336 /// every signature. See
1337 /// `crates/spg-engine/src/testkit/injection.rs`.
1338 #[cfg(feature = "injection-points")]
1339 injection_store: alloc::sync::Arc<crate::testkit::injection::InjectionStore>,
1340 /// v7.34 (crash-recovery P0 #2) — row-level redo capture. When the
1341 /// embedding layer turns this on (persistence enabled), each mutating
1342 /// `execute` records the physical [`RowChange`]s it applied; the
1343 /// engine drains them into `last_redo` on success, and the embedded
1344 /// layer reads them via [`Engine::take_redo`] to write the WAL in
1345 /// place of the SQL text. Off (default) = zero capture overhead.
1346 redo_capture: bool,
1347 /// Redo captured by the most recent successful mutating `execute`,
1348 /// awaiting drain by the embedding layer. Cleared on each capture.
1349 last_redo: Vec<RowChange>,
1350 /// v7.39 (round 735, S14/B3) — per-table change sequence, bumped on
1351 /// every write entry (INSERT / UPDATE / DELETE / TRUNCATE / COPY /
1352 /// table-shape DDL). In-memory only: after a restart the map is
1353 /// empty, every watermark comparison misses, and the next REFRESH
1354 /// is a full one — stale-view-safe by construction. A rolled-back
1355 /// transaction's bump stays too, which can only cause an EXTRA full
1356 /// refresh, never a wrong no-op.
1357 table_change_seq: alloc::collections::BTreeMap<String, u64>,
1358 /// v7.39 (round 735, S14/B3) — per-materialized-view refresh
1359 /// watermark: the (table, change-seq) pairs its last full refresh
1360 /// saw. When every dependency's seq is unchanged, REFRESH is an
1361 /// O(1) no-op — an incremental-maintenance first step PG does not
1362 /// have (its REFRESH always recomputes).
1363 matview_refresh_watermark: alloc::collections::BTreeMap<String, Vec<(String, u64)>>,
1364 /// v7.39 (round 736, S14/B3 knife 2) — delta-maintainable
1365 /// materialized views: mv name -> its single base table. Registered
1366 /// at CREATE MATERIALIZED VIEW / full REFRESH when the body is a
1367 /// single-stored-table pure projection (no aggregates / joins /
1368 /// CTEs / subqueries / DISTINCT / ORDER / LIMIT / windows / SRFs).
1369 matview_maintainable: alloc::collections::BTreeMap<String, String>,
1370 /// Buffered base-table row changes per maintainable view, fanned
1371 /// out from the statement redo drain. Capped (see
1372 /// `MATVIEW_DELTA_CEILING`); an overflowed view falls back to a
1373 /// full refresh — never-die, never-stale.
1374 matview_delta_buf: alloc::collections::BTreeMap<String, Vec<RowChange>>,
1375 matview_delta_overflow: alloc::collections::BTreeSet<String>,
1376 /// v7.39 (round 738, S14/B3 knife 3) — per-view row map: expected
1377 /// PHYSICAL length of the view's backing table, plus base-row
1378 /// RowId -> view row position. Built only by the maintainable full
1379 /// refresh's internal scan (the SQL path cannot see rowids), and
1380 /// consulted by the delete/tombstone delta arms. In-memory: restart
1381 /// or any length mismatch (a vacuum moved rows) -> full refresh.
1382 matview_row_map:
1383 alloc::collections::BTreeMap<String, (usize, alloc::collections::BTreeMap<u64, usize>)>,
1384 /// v7.38 轴 4 — currently-selected SQL isolation level. Set by
1385 /// `SET TRANSACTION ISOLATION LEVEL …`; read by
1386 /// `SHOW transaction_isolation`. v7.37.8 implements the
1387 /// SQL surface; actual semantic differentiation (REPEATABLE READ
1388 /// snapshot / SERIALIZABLE SSI) lands in a separate train.
1389 pub(crate) current_isolation_level: spg_sql::ast::IsolationLevel,
1390}
1391
1392/// v7.12.7 — hard cap on nested trigger-emitted embedded SQL
1393/// fires. 16 deep is well past anything a normal trigger graph
1394/// uses while still preventing infinite-loop wedging.
1395const MAX_TRIGGER_RECURSION: u32 = 16;
1396
1397/// v6.5.6 — callback signature for slow-query log emission. Called
1398/// with `(sql, elapsed_us)` once per successful execute that crosses
1399/// the threshold.
1400pub type SlowQueryLogger = fn(&str, u64);
1401
1402/// v6.5.2 — one row of `spg_stat_activity`. Engine-public so
1403/// spg-server can construct rows without re-exporting internal
1404/// dispatch types.
1405#[derive(Debug, Clone)]
1406pub struct ActivityRow {
1407 pub pid: u32,
1408 pub user: String,
1409 /// v7.39 (round 319, V52) — the peer's IP, empty when the connection
1410 /// has no TCP peer (PG reports NULL there).
1411 pub client_addr: String,
1412 /// v7.39 (round 319, V52) — the peer's port. PG reports **-1**, not
1413 /// NULL, for a connection with no TCP port; measured on PG 18.4.
1414 pub client_port: i32,
1415 /// v7.39 (round 319, V52) — the database this connection named. Empty
1416 /// when it named none; both `pg_stat_activity.datname` and
1417 /// `SHOW PROCESSLIST.db` report that as NULL.
1418 pub database: String,
1419 pub started_at_us: i64,
1420 pub current_sql: String,
1421 /// v7.37.14 (B6.3) — PG-style wait-event categorisation
1422 /// ("Lock", "LWLock", "IPC", "IO", "Timeout", "Client",
1423 /// "BufferPin", "Extension", ""). Empty string means idle.
1424 /// Pair with `wait_event` to identify "what specifically is
1425 /// the backend waiting on" the same way PG does.
1426 pub wait_event_type: String,
1427 pub wait_event: String,
1428 pub elapsed_us: i64,
1429 pub in_transaction: bool,
1430 /// v7.17 Phase 2.4 — startup-param `application_name` (or the
1431 /// last value the client sent via `SET application_name = '...'`).
1432 /// Empty when the client never declared one.
1433 pub application_name: String,
1434 /// v7.39 (round 474) — PG's `backend_type`: `client backend` for a
1435 /// connection, or the worker's own name for a background process.
1436 ///
1437 /// pg_stat_activity used to hardcode `client backend`, so SPG's own
1438 /// background workers — the ones that hold the engine write lock and
1439 /// are exactly what an operator is looking for when a statement
1440 /// stalls — did not appear at all. PG18 lists eight of them beside
1441 /// the single client backend on an idle server.
1442 pub backend_type: String,
1443}
1444
1445impl ActivityRow {
1446 /// The `backend_type` PG gives a background process: no database, no
1447 /// user, no query, and a state PG reports as NULL.
1448 #[must_use]
1449 pub fn background(pid: u32, backend_type: &str) -> Self {
1450 Self {
1451 pid,
1452 user: String::new(),
1453 client_addr: String::new(),
1454 client_port: -1,
1455 database: String::new(),
1456 started_at_us: 0,
1457 current_sql: String::new(),
1458 wait_event_type: String::new(),
1459 wait_event: String::new(),
1460 elapsed_us: 0,
1461 in_transaction: false,
1462 application_name: String::new(),
1463 backend_type: backend_type.into(),
1464 }
1465 }
1466}
1467
1468/// v6.5.2 — provider callback type. Fresh snapshot returned each
1469/// call; engine doesn't cache the slice.
1470pub type ActivityProvider = fn() -> Vec<ActivityRow>;
1471
1472/// v7.39 (round 318, V41) — how loud a diagnostic the statement raised is.
1473/// PG distinguishes them on the wire (`S`/`V` fields of NoticeResponse) and
1474/// clients act on it: psql prints `WARNING:` in a different colour, and
1475/// several drivers surface warnings to the application while dropping
1476/// notices. Emitting everything as NOTICE loses that.
1477#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1478pub enum NoticeSeverity {
1479 Notice,
1480 Warning,
1481 /// v7.39 (round 757, F31-B3) — `RAISE INFO`. PG sends INFO to the
1482 /// client ALWAYS, regardless of `client_min_messages`.
1483 Info,
1484}
1485
1486impl NoticeSeverity {
1487 /// The non-localized severity string PG puts in the `V` field.
1488 #[must_use]
1489 pub const fn as_pg_str(self) -> &'static str {
1490 match self {
1491 Self::Notice => "NOTICE",
1492 Self::Warning => "WARNING",
1493 Self::Info => "INFO",
1494 }
1495 }
1496}
1497
1498/// v7.39 (round 318, V41) — one diagnostic the statement raised, in PG's
1499/// exact wording minus the severity banner (the wire layer adds that).
1500#[derive(Debug, Clone)]
1501pub struct Notice {
1502 pub severity: NoticeSeverity,
1503 pub message: String,
1504}
1505
1506/// v6.5.3 — one row of `spg_audit_chain`. Engine-public so
1507/// spg-server can construct rows directly from `AuditEntry`.
1508#[derive(Debug, Clone)]
1509pub struct AuditRow {
1510 pub seq: i64,
1511 pub ts_ms: i64,
1512 pub prev_hash_hex: String,
1513 pub entry_hash_hex: String,
1514 pub sql: String,
1515}
1516
1517/// v6.5.3 — chain-table provider + verifier. spg-server registers
1518/// fn pointers that snapshot / verify the audit log. `verify`
1519/// returns `(verified_count, broken_at_seq)` — `broken_at_seq` is
1520/// `-1` on a clean chain.
1521pub type AuditChainProvider = fn() -> Vec<AuditRow>;
1522pub type AuditVerifier = fn() -> (i64, i64);
1523
1524impl Engine {
1525 pub fn new() -> Self {
1526 Self {
1527 catalog: Catalog::new(),
1528 parallel_runner: ParallelRunnerSlot::default(),
1529 tx_catalogs: BTreeMap::new(),
1530 table_last_commit: BTreeMap::new(),
1531 commit_seq: 0,
1532 current_tx: None,
1533 backslash_escapes: false,
1534 mysql_strict: true,
1535 lo_descriptors: BTreeMap::new(),
1536 lo_next_fd: 0,
1537 prepared_statements: alloc::collections::BTreeMap::new(),
1538 current_session: 0,
1539 sessions: BTreeMap::new(),
1540 advisory_locks: BTreeMap::new(),
1541 last_sequence_used: None,
1542 seq_currvals: alloc::collections::BTreeMap::new(),
1543 next_tx_id: 1,
1544 active_writer_versions: BTreeSet::new(),
1545 aborted_versions: BTreeSet::new(),
1546 locks: crate::locks::LockTable::new(),
1547 mvcc_inplace: !cfg!(feature = "mvcc-inplace-off"),
1548 autovacuum: true,
1549 autovacuum_inline: true,
1550 lock_skip_rows: None,
1551 tx_writer_versions: BTreeMap::new(),
1552 stmt_writer_version: None,
1553 clock: None,
1554 salt_fn: None,
1555 max_query_rows: None,
1556 max_query_bytes: None,
1557 temp_run_factory: None,
1558 users: UserStore::new(),
1559 publications: publications::Publications::new(),
1560 subscriptions: subscriptions::Subscriptions::new(),
1561 statistics: statistics::Statistics::new(),
1562 plan_cache: plan_cache::PlanCache::new(),
1563 query_stats: query_stats::QueryStats::new(),
1564 activity_provider: None,
1565 audit_chain_provider: None,
1566 audit_verifier: None,
1567 slow_query_threshold_us: None,
1568 slow_query_logger: None,
1569 session_params: BTreeMap::new(),
1570 cursors: BTreeMap::new(),
1571 last_insert_id: core::sync::atomic::AtomicI64::new(0),
1572 row_count: 0,
1573 user_vars: BTreeMap::new(),
1574 temp_tables: BTreeSet::new(),
1575 temp_sequences: BTreeSet::new(),
1576 temp_views: BTreeSet::new(),
1577 listen_channels: BTreeSet::new(),
1578 tx_pending_notifies: Vec::new(),
1579 delivered_notifies: Vec::new(),
1580 pending_notices: Vec::new(),
1581 spill_stats: crate::tempstore::SpillStats::default(),
1582 xact_commit: core::sync::atomic::AtomicU64::new(0),
1583 xact_rollback: core::sync::atomic::AtomicU64::new(0),
1584 backend_count_fn: None,
1585 backend_pid_fn: None,
1586 wal_lsn_fn: None,
1587 backend_signal_fn: None,
1588 tz_offset_fn: None,
1589 tz_localize_fn: None,
1590 tz_canon_fn: None,
1591 tz_abbrev_fn: None,
1592 tz_all_fn: None,
1593 stat_tup_inserted: 0,
1594 table_write_stats: alloc::collections::BTreeMap::new(),
1595 commit_epoch: 0,
1596 stat_tup_updated: 0,
1597 stat_tup_deleted: 0,
1598 local_guc_saves: Vec::new(),
1599 render_style: crate::eval::RenderStyle::default(),
1600 savepoint_guc_marks: Vec::new(),
1601 trigger_recursion_depth: 0,
1602 rule_rewrite_active: false,
1603 foreign_key_checks: true,
1604 meta_views_materialised: false,
1605 pending_foreign_keys: Vec::new(),
1606 env_cfg: testkit::EnvConfig::default(),
1607 #[cfg(feature = "injection-points")]
1608 injection_store: alloc::sync::Arc::new(
1609 crate::testkit::injection::InjectionStore::default(),
1610 ),
1611 redo_capture: false,
1612 current_isolation_level: spg_sql::ast::IsolationLevel::ReadCommitted,
1613 last_redo: Vec::new(),
1614 table_change_seq: alloc::collections::BTreeMap::new(),
1615 matview_refresh_watermark: alloc::collections::BTreeMap::new(),
1616 matview_maintainable: alloc::collections::BTreeMap::new(),
1617 matview_delta_buf: alloc::collections::BTreeMap::new(),
1618 matview_delta_overflow: alloc::collections::BTreeSet::new(),
1619 matview_row_map: alloc::collections::BTreeMap::new(),
1620 }
1621 }
1622
1623 /// v7.11.0 — clone the engine's committed catalog + read-time
1624 /// state into a frozen `CatalogSnapshot`. Cheap (`Catalog` is
1625 /// backed by `PersistentVec`; cloning is O(log n) per table).
1626 /// Subsequent writes to this engine are invisible to the
1627 /// snapshot; the snapshot is self-contained and can be moved
1628 /// to another thread for concurrent `execute_readonly_on_snapshot`
1629 /// calls. The basis for [`AsyncReadHandle`] in spg-embedded-tokio
1630 /// and any other read-fanout pattern.
1631 #[must_use]
1632 pub fn clone_snapshot(&self) -> CatalogSnapshot {
1633 CatalogSnapshot {
1634 catalog: self.active_catalog().clone(),
1635 statistics: self.statistics.clone(),
1636 clock: self.clock,
1637 max_query_rows: self.max_query_rows,
1638 }
1639 }
1640
1641 /// v7.39 (round 513) — does this role exist? `'x'::regrole` needs it,
1642 /// and roles live on the engine rather than the catalog.
1643 #[must_use]
1644 pub fn role_exists(&self, name: &str) -> bool {
1645 // v7.39 (round 696) — the SESSION's own identity, same class as the
1646 // `postgres` case below and missed by it. `current_user` reported
1647 // the connected name while this predicate denied it, so `SET ROLE
1648 // <me>` refused the role the session was already running as.
1649 if name == self.session_user() {
1650 return true;
1651 }
1652 // The engine's default identity exists even before any CREATE USER.
1653 //
1654 // v7.39 (round 652) — and so does `postgres`. `synth_pg_roles`
1655 // has always inserted it as the bootstrap superuser when no user
1656 // by that name was created, so this predicate and the catalogue
1657 // it is supposed to reflect disagreed: `pg_roles` listed
1658 // `postgres` while `'postgres'::regrole` said it did not exist.
1659 // Every pg_dump names it (`OWNER TO postgres`), so the ALTER
1660 // TABLE OWNER check added this round would have refused the one
1661 // role that appears in essentially every dump.
1662 self.effective_users().contains(name)
1663 || name.eq_ignore_ascii_case("admin")
1664 || name.eq_ignore_ascii_case("postgres")
1665 // 7.38.1 S5.2 — PG's predefined pg_* roles exist without
1666 // anyone creating them, and pg_dump's ACL section GRANTs
1667 // to `pg_database_owner` on every dump of `public`.
1668 || matches!(
1669 name.to_ascii_lowercase().as_str(),
1670 "pg_database_owner"
1671 | "pg_read_all_data"
1672 | "pg_write_all_data"
1673 | "pg_monitor"
1674 | "pg_read_all_settings"
1675 | "pg_read_all_stats"
1676 | "pg_stat_scan_tables"
1677 | "pg_signal_backend"
1678 | "pg_checkpoint"
1679 | "pg_maintain"
1680 | "pg_use_reserved_connections"
1681 | "pg_create_subscription"
1682 )
1683 }
1684
1685 /// v7.39 (round 520) — the role an oid names, as `pg_get_userbyid`
1686 /// reports it. The numbering is `synth_pg_roles`': base 10, one per
1687 /// user in catalog order.
1688 #[must_use]
1689 pub fn role_name_for_oid(&self, oid: i64) -> Option<String> {
1690 // Oid 10 is the bootstrap superuser, which `synth_pg_roles` always
1691 // publishes as `postgres`. Following the catalogue rather than the
1692 // session is the point: a join on `relowner = pg_roles.oid` and
1693 // `pg_get_userbyid(relowner)` have to name the same role.
1694 if oid == 10 {
1695 return Some(alloc::string::String::from("postgres"));
1696 }
1697 let idx = usize::try_from(oid - 11).ok()?;
1698 self.users
1699 .iter()
1700 .nth(idx)
1701 .map(|(n, _)| alloc::string::String::from(n))
1702 }
1703
1704 /// v7.37.15 (Phase B / C / E) — current per-row visibility
1705 /// snapshot for in-engine scans. Captures the live writer-
1706 /// version cursor + active-writer set; readers built from this
1707 /// Snapshot see committed state through the moment of capture
1708 /// and DO NOT observe uncommitted writes still inside
1709 /// `active_writer_versions`.
1710 ///
1711 /// Phase E: if there's an explicit transaction in flight under
1712 /// REPEATABLE READ or SERIALIZABLE isolation, returns the
1713 /// snapshot the tx cached at BEGIN time — every statement in
1714 /// the tx sees the same coherent prior-committed view. READ
1715 /// COMMITTED (the default) returns a fresh snapshot per call,
1716 /// matching PG's per-statement visibility semantics.
1717 ///
1718 /// `oldest_active = version` when no writer is in flight (== no
1719 /// dead row could still be observed); else == min of active
1720 /// versions (vacuum-floor).
1721 #[must_use]
1722 pub fn current_snapshot(&self) -> spg_storage::snapshot::Snapshot {
1723 // v7.39 (round 297, E3 Phase 1b) — carry the SKIP LOCKED
1724 // exclusions on the snapshot. Every row source threads a
1725 // snapshot through `is_row_visible`, so this is the one place
1726 // that cannot be routed around; adding the filter per scan site
1727 // missed the live path three times.
1728 let locked_out = self.lock_skip_rows.as_ref().and_then(|(t, set)| {
1729 self.active_catalog()
1730 .get(t)
1731 .map(|tbl| (tbl.rel_id(), set.clone()))
1732 });
1733 let mut snap = self.current_snapshot_inner();
1734 snap.locked_out = locked_out;
1735 snap
1736 }
1737
1738 fn current_snapshot_inner(&self) -> spg_storage::snapshot::Snapshot {
1739 // Phase E — if we're inside a RR/SER tx, return its
1740 // cached snapshot so the whole tx sees one frozen view.
1741 if let Some(tx_id) = self.current_tx
1742 && let Some(state) = self.tx_catalogs.get(&tx_id)
1743 && let Some(s) = state.cached_snapshot.as_ref()
1744 {
1745 return s.clone();
1746 }
1747 // v7.37.15 (Phase C.3, step 1) — carry the current tx's writer
1748 // version as the snapshot's `tx_id` so the visibility gate's
1749 // self-write branch (`visible` step 1) recognises rows this
1750 // transaction stamped (`xmin == v`, with `v` in
1751 // `active_writer_versions`). Without this the tx's own
1752 // uncommitted rows fall to the in-progress step and become
1753 // invisible to itself on the gated read paths. Autocommit reads
1754 // (no `tx_writer_versions` entry) keep `tx_id = 0`.
1755 let reader_tx_id = self
1756 .current_tx
1757 .and_then(|t| self.tx_writer_versions.get(&t).copied())
1758 .unwrap_or(0);
1759 let version = spg_storage::row_header::current_version();
1760 if self.active_writer_versions.is_empty() {
1761 // Hot path: no writer in flight. Snapshot::unbounded()
1762 // would also work, but pinning to the live cursor
1763 // means the snapshot's oldest_active is accurate
1764 // (= version) so subsequent vacuum can advance.
1765 return spg_storage::snapshot::Snapshot::new(
1766 version,
1767 spg_storage::snapshot::InProgressSet::empty(),
1768 version,
1769 reader_tx_id,
1770 );
1771 }
1772 let sorted: alloc::vec::Vec<u64> = self.active_writer_versions.iter().copied().collect();
1773 let oldest = *sorted.first().unwrap_or(&version);
1774 spg_storage::snapshot::Snapshot::new(
1775 version,
1776 spg_storage::snapshot::InProgressSet::from_sorted(sorted),
1777 oldest,
1778 reader_tx_id,
1779 )
1780 }
1781
1782 /// v7.37.15 (Phase C) — allocate the next writer version AND
1783 /// add it to the in-flight set so concurrent snapshots hide
1784 /// the resulting writes until [`Self::commit_writer_version`]
1785 /// removes the entry. Returns the allocated version so the
1786 /// writer can stamp it on `xmin` / `xmax`.
1787 pub fn begin_writer_version(&mut self) -> u64 {
1788 let v = spg_storage::row_header::next_version();
1789 self.active_writer_versions.insert(v);
1790 v
1791 }
1792
1793 /// v7.37.15 (Phase C) — mark a previously-allocated writer
1794 /// version as committed. Subsequent snapshots stop including
1795 /// it in `in_progress`, so the writes the version stamped
1796 /// become visible to new readers.
1797 ///
1798 /// No-op if the version was never allocated; matches PG's
1799 /// idempotent `TransactionIdCommitTree` semantics.
1800 pub fn commit_writer_version(&mut self, v: u64) {
1801 self.active_writer_versions.remove(&v);
1802 }
1803
1804 /// v7.37.15 (Phase C.2) — mark a previously-allocated writer
1805 /// version as ABORTED (rolled back). Removes it from the in-flight
1806 /// set and records it in `aborted_versions` so the visibility
1807 /// oracle ([`Self::xact_status`]) reports `Aborted` rather than
1808 /// silently treating it as committed once it leaves the in-flight
1809 /// set. Phase C.3's in-place write path relies on this: a
1810 /// rolled-back version's xmin/xmax stamps stay physically present
1811 /// until vacuum reclaims them, and readers must NOT see them.
1812 ///
1813 /// Idempotent; a no-op if the version was never allocated.
1814 pub fn abort_writer_version(&mut self, v: u64) {
1815 self.active_writer_versions.remove(&v);
1816 self.aborted_versions.insert(v);
1817 }
1818
1819 /// v7.37.15 (Phase C.2) — the visibility oracle's terminal-status
1820 /// lookup for one version. In-flight if still allocated, Aborted
1821 /// if it rolled back, otherwise Committed (the default for a
1822 /// version that left the in-flight set the normal way, and for
1823 /// every frozen / pruned old version the engine no longer tracks).
1824 ///
1825 /// `aborted_versions` is bounded by pruning below `oldest_active`
1826 /// during vacuum (Phase D): once no live snapshot can still see an
1827 /// aborted version's stamps, its entry is dropped. Until Phase D
1828 /// lands the set only grows with rolled-back transactions — noted
1829 /// as a never-die follow-up, not a steady-state leak on the
1830 /// commit path.
1831 #[must_use]
1832 pub fn xact_status(&self, v: u64) -> spg_storage::snapshot::XactStatus {
1833 use spg_storage::snapshot::XactStatus;
1834 if self.active_writer_versions.contains(&v) {
1835 XactStatus::InProgress
1836 } else if self.aborted_versions.contains(&v) {
1837 XactStatus::Aborted
1838 } else {
1839 XactStatus::Committed
1840 }
1841 }
1842
1843 /// v7.37.15 (Phase C.4) — acquire a tuple lock on a stable
1844 /// `(RelId, RowId)` for writer `version`. The in-place write path
1845 /// (C.3) calls this before stamping xmax; `SELECT ... FOR UPDATE`
1846 /// wires here via the parser's lock-strength clause (C.4). Returns
1847 /// the [`LockOutcome`](crate::locks::LockOutcome) the caller acts on
1848 /// (grant / park / skip / fail / deadlock-abort).
1849 pub fn acquire_row_lock(
1850 &mut self,
1851 rel: spg_storage::row_header::RelId,
1852 row: spg_storage::row_header::RowId,
1853 mode: crate::locks::LockMode,
1854 version: u64,
1855 policy: crate::locks::WaitPolicy,
1856 ) -> crate::locks::LockOutcome {
1857 self.locks.acquire(rel, row, mode, version, policy)
1858 }
1859
1860 /// v7.37.15 (Phase C.4) — release every lock + wait held by
1861 /// `version` at transaction end. Called from `exec_commit` /
1862 /// `exec_rollback` alongside the writer-version bookkeeping.
1863 pub fn release_tx_locks(&mut self, version: u64) {
1864 self.locks.release_all(version);
1865 }
1866
1867 /// 7.38.1 S2.1 — drop the tuple locks an AUTOCOMMIT statement took
1868 /// (its implicit transaction ends with it). A no-op inside an open
1869 /// transaction (those release at COMMIT/ROLLBACK) and when the
1870 /// statement allocated no writer version.
1871 pub(crate) fn release_autocommit_stmt_locks(&mut self) {
1872 let in_tx = self
1873 .current_tx
1874 .is_some_and(|tx| self.tx_writer_versions.contains_key(&tx));
1875 if in_tx {
1876 return;
1877 }
1878 if let Some(v) = self.stmt_writer_version {
1879 self.locks.release_all(v);
1880 }
1881 }
1882
1883 /// v7.37.15 (Phase C.4) — number of rows currently locked, for the
1884 /// `pg_locks` enumeration and tests.
1885 #[must_use]
1886 pub fn locked_row_count(&self) -> usize {
1887 self.locks.locked_row_count()
1888 }
1889
1890 /// v7.37.15 (Phase C.3) — is the in-place MVCC write path enabled?
1891 /// `false` (default) keeps legacy physical DELETE/UPDATE. The C.3
1892 /// writers consult this to choose tombstone-vs-physical.
1893 #[must_use]
1894 pub fn mvcc_inplace(&self) -> bool {
1895 self.mvcc_inplace
1896 }
1897
1898 /// v7.37.15 (Phase C.3) — enable/disable the in-place MVCC write
1899 /// path. Called by the host after reading `SPG_MVCC_INPLACE` (the
1900 /// `no_std` engine can't read the environment itself). Off until
1901 /// the write path is proven against PG18 differential tests.
1902 pub fn set_mvcc_inplace(&mut self, on: bool) {
1903 self.mvcc_inplace = on;
1904 }
1905
1906 /// v7.39 (parallel-agg P0) — inject the host's parallel executor
1907 /// (see [`ParallelRunner`]). Called once at host startup; the
1908 /// engine stays single-threaded without it.
1909 /// v7.39 (pg_stat knife A) — inject the host's live backend count.
1910 pub fn set_backend_count_fn(&mut self, f: BackendCountFn) {
1911 self.backend_count_fn = Some(f);
1912 }
1913
1914 /// v7.39 (read01 pgstatfuncs.c) — inject the host's calling-connection
1915 /// identity for pg_backend_pid().
1916 /// v7.39 (round 476) — register the WAL byte-position provider.
1917 pub fn set_wal_lsn_fn(&mut self, f: WalLsnFn) {
1918 self.wal_lsn_fn = Some(f);
1919 }
1920
1921 pub fn set_backend_pid_fn(&mut self, f: BackendPidFn) {
1922 self.backend_pid_fn = Some(f);
1923 }
1924
1925 /// v7.39 (round 318, V51) — inject the host's connection-control hook,
1926 /// so `pg_cancel_backend` / `pg_terminate_backend` / `KILL` act instead
1927 /// of answering a constant.
1928 pub fn set_backend_signal_fn(&mut self, f: BackendSignalFn) {
1929 self.backend_signal_fn = Some(f);
1930 }
1931
1932 /// v7.39 (round 786, T35 Phase A) — install the host's spill-run
1933 /// factory. Without one the engine cannot spill and a sort that
1934 /// outgrows `max_query_bytes` keeps refusing, which is exactly the
1935 /// behaviour every caller has today.
1936 pub fn set_temp_run_factory(&mut self, f: crate::TempRunFactory) {
1937 self.temp_run_factory = Some(f);
1938 }
1939
1940 /// Whether spilling is available in this process.
1941 #[must_use]
1942 pub fn can_spill(&self) -> bool {
1943 self.temp_run_factory.is_some()
1944 }
1945
1946 /// v7.39 (round 786) — open a fresh spill run, or `None` when no
1947 /// host factory is installed. Phase B's run generation calls this;
1948 /// it lives here so the `None` path stays a single decision point.
1949 pub(crate) fn open_temp_run(
1950 &self,
1951 ) -> Option<Result<alloc::boxed::Box<dyn crate::TempRun>, crate::TempStoreError>> {
1952 self.temp_run_factory.map(|f| f())
1953 }
1954
1955 /// v7.39 (tz epic) — inject the host's IANA timezone lookups
1956 /// (spg-tzif's fn family on std hosts).
1957 pub fn set_tz_fns(
1958 &mut self,
1959 offset: TzOffsetFn,
1960 localize: TzLocalizeFn,
1961 canon: TzCanonFn,
1962 abbrev: TzAbbrevFn,
1963 ) {
1964 self.tz_offset_fn = Some(offset);
1965 self.tz_localize_fn = Some(localize);
1966 self.tz_canon_fn = Some(canon);
1967 self.tz_abbrev_fn = Some(abbrev);
1968 }
1969
1970 /// v7.39 (round 502) — the zone enumerator behind `pg_timezone_names`.
1971 /// Separate from `set_tz_fns` so an embedder that already calls that
1972 /// one keeps compiling.
1973 pub fn set_tz_all_fn(&mut self, all: TzAllFn) {
1974 self.tz_all_fn = Some(all);
1975 }
1976
1977 /// Every zone the host knows at `utc_micros`; empty without a hook.
1978 pub(crate) fn tz_all_at(
1979 &self,
1980 utc_micros: i64,
1981 ) -> alloc::vec::Vec<(alloc::string::String, alloc::string::String, i64, bool)> {
1982 self.tz_all_fn
1983 .map_or_else(alloc::vec::Vec::new, |f| f(utc_micros))
1984 }
1985
1986 pub fn set_parallel_runner(&mut self, runner: alloc::sync::Arc<dyn ParallelRunner>) {
1987 self.parallel_runner = ParallelRunnerSlot(Some(runner));
1988 }
1989
1990 /// v7.37.15 (Phase C) — allocate a fresh version number for
1991 /// the next write. Always strictly monotonic + process-wide
1992 /// shared so concurrent engines on the same process agree on
1993 /// "tx 17 commits before tx 18". Phase C writer paths call
1994 /// this once per INSERT / UPDATE / DELETE statement to obtain
1995 /// the version they'll stamp on the new row's `xmin` (or the
1996 /// existing row's `xmax`).
1997 ///
1998 /// Returns [`XMIN_FROZEN`] when MVCC stamping is intentionally
1999 /// off (legacy `in_memory` flow / WAL replay): the writer
2000 /// then takes the legacy frozen-insert short-circuit path
2001 /// inside `Table::insert_with_xmin`.
2002 #[must_use]
2003 pub fn next_writer_version(&self) -> u64 {
2004 spg_storage::row_header::next_version()
2005 }
2006
2007 /// v7.37.15 (Phase C) — version a writer should stamp on
2008 /// rows produced by the current statement. Inside an explicit
2009 /// transaction the version is the tx's pre-allocated one (so
2010 /// every statement in the tx commits atomically at COMMIT);
2011 /// in autocommit it allocates a fresh version per statement.
2012 ///
2013 /// This is the canonical helper engine writers should call
2014 /// — using it instead of `next_writer_version` ensures
2015 /// explicit-tx semantics where every row produced by the tx
2016 /// shares one xmin and concurrent readers don't see partial
2017 /// state until COMMIT.
2018 ///
2019 /// v7.37.15 (Epic W slice 2) — takes `&mut self` so the autocommit
2020 /// branch can **memoize** its freshly-minted version in
2021 /// `stmt_writer_version`. `next_writer_version()` is a `fetch_add`,
2022 /// so without memoization a second call within one statement (the
2023 /// redo drain post-stamps the captured `RowChange`s) would allocate
2024 /// a *different* version than the writes used. Memoizing makes the
2025 /// value stable for the statement's lifetime; it is reset per
2026 /// `execute_in_with_cancel`, so the counter still advances exactly
2027 /// once per autocommit statement — identical to before.
2028 pub fn writer_version_for_current_stmt(&mut self) -> u64 {
2029 if let Some(tx_id) = self.current_tx
2030 && let Some(&v) = self.tx_writer_versions.get(&tx_id)
2031 {
2032 return v;
2033 }
2034 // Autocommit shape: fresh version, immediately "committed"
2035 // (no entry in active_writer_versions, so subsequent
2036 // readers see the row). Memoized for the statement so the
2037 // redo drain reads back the same version the writes used.
2038 if let Some(v) = self.stmt_writer_version {
2039 return v;
2040 }
2041 let v = self.next_writer_version();
2042 self.stmt_writer_version = Some(v);
2043 v
2044 }
2045
2046 /// Construct an engine restored from a previously-snapshotted catalog
2047 /// (see `snapshot()`).
2048 pub fn restore(catalog: Catalog) -> Self {
2049 Self {
2050 lock_skip_rows: None,
2051 catalog,
2052 parallel_runner: ParallelRunnerSlot::default(),
2053 tx_catalogs: BTreeMap::new(),
2054 table_last_commit: BTreeMap::new(),
2055 commit_seq: 0,
2056 current_tx: None,
2057 backslash_escapes: false,
2058 mysql_strict: true,
2059 lo_descriptors: BTreeMap::new(),
2060 lo_next_fd: 0,
2061 prepared_statements: alloc::collections::BTreeMap::new(),
2062 current_session: 0,
2063 sessions: BTreeMap::new(),
2064 advisory_locks: BTreeMap::new(),
2065 last_sequence_used: None,
2066 seq_currvals: alloc::collections::BTreeMap::new(),
2067 next_tx_id: 1,
2068 active_writer_versions: BTreeSet::new(),
2069 aborted_versions: BTreeSet::new(),
2070 locks: crate::locks::LockTable::new(),
2071 mvcc_inplace: !cfg!(feature = "mvcc-inplace-off"),
2072 autovacuum: true,
2073 autovacuum_inline: true,
2074 tx_writer_versions: BTreeMap::new(),
2075 stmt_writer_version: None,
2076 clock: None,
2077 salt_fn: None,
2078 max_query_rows: None,
2079 max_query_bytes: None,
2080 temp_run_factory: None,
2081 users: UserStore::new(),
2082 publications: publications::Publications::new(),
2083 subscriptions: subscriptions::Subscriptions::new(),
2084 statistics: statistics::Statistics::new(),
2085 plan_cache: plan_cache::PlanCache::new(),
2086 query_stats: query_stats::QueryStats::new(),
2087 activity_provider: None,
2088 audit_chain_provider: None,
2089 audit_verifier: None,
2090 slow_query_threshold_us: None,
2091 slow_query_logger: None,
2092 session_params: BTreeMap::new(),
2093 cursors: BTreeMap::new(),
2094 last_insert_id: core::sync::atomic::AtomicI64::new(0),
2095 row_count: 0,
2096 user_vars: BTreeMap::new(),
2097 temp_tables: BTreeSet::new(),
2098 temp_sequences: BTreeSet::new(),
2099 temp_views: BTreeSet::new(),
2100 listen_channels: BTreeSet::new(),
2101 tx_pending_notifies: Vec::new(),
2102 delivered_notifies: Vec::new(),
2103 pending_notices: Vec::new(),
2104 spill_stats: crate::tempstore::SpillStats::default(),
2105 xact_commit: core::sync::atomic::AtomicU64::new(0),
2106 xact_rollback: core::sync::atomic::AtomicU64::new(0),
2107 backend_count_fn: None,
2108 backend_pid_fn: None,
2109 wal_lsn_fn: None,
2110 backend_signal_fn: None,
2111 tz_offset_fn: None,
2112 tz_localize_fn: None,
2113 tz_canon_fn: None,
2114 tz_abbrev_fn: None,
2115 tz_all_fn: None,
2116 stat_tup_inserted: 0,
2117 table_write_stats: alloc::collections::BTreeMap::new(),
2118 commit_epoch: 0,
2119 stat_tup_updated: 0,
2120 stat_tup_deleted: 0,
2121 local_guc_saves: Vec::new(),
2122 render_style: crate::eval::RenderStyle::default(),
2123 savepoint_guc_marks: Vec::new(),
2124 trigger_recursion_depth: 0,
2125 rule_rewrite_active: false,
2126 foreign_key_checks: true,
2127 meta_views_materialised: false,
2128 pending_foreign_keys: Vec::new(),
2129 env_cfg: testkit::EnvConfig::default(),
2130 #[cfg(feature = "injection-points")]
2131 injection_store: alloc::sync::Arc::new(
2132 crate::testkit::injection::InjectionStore::default(),
2133 ),
2134 redo_capture: false,
2135 current_isolation_level: spg_sql::ast::IsolationLevel::ReadCommitted,
2136 last_redo: Vec::new(),
2137 table_change_seq: alloc::collections::BTreeMap::new(),
2138 matview_refresh_watermark: alloc::collections::BTreeMap::new(),
2139 matview_maintainable: alloc::collections::BTreeMap::new(),
2140 matview_delta_buf: alloc::collections::BTreeMap::new(),
2141 matview_delta_overflow: alloc::collections::BTreeSet::new(),
2142 matview_row_map: alloc::collections::BTreeMap::new(),
2143 }
2144 }
2145
2146 /// Restore an engine + user table from a v4.1 envelope produced
2147 /// by `snapshot_with_users()`. Falls back to plain catalog-only
2148 /// restore if the envelope magic isn't present (so v3.x snapshot
2149 /// files still load). v6.1.2 adds the optional publications
2150 /// trailer (envelope v3); a v1/v2 envelope deserialises to an
2151 /// empty publication table.
2152 pub fn restore_envelope(buf: &[u8]) -> Result<Self, EngineError> {
2153 match split_envelope(buf) {
2154 EnvelopeParse::Pair {
2155 catalog: catalog_bytes,
2156 users: user_bytes,
2157 publications: pub_bytes,
2158 subscriptions: sub_bytes,
2159 statistics: stats_bytes,
2160 } => {
2161 let mut catalog =
2162 Catalog::deserialize(catalog_bytes).map_err(EngineError::Storage)?;
2163 crate::ddl::rebuild_all_excl_indexes(&mut catalog);
2164 let users = users::deserialize_users(user_bytes)
2165 .map_err(|e| EngineError::Unsupported(alloc::format!("users restore: {e}")))?;
2166 let publications = match pub_bytes {
2167 Some(b) => publications::Publications::deserialize(b).map_err(|e| {
2168 EngineError::Unsupported(alloc::format!("publications restore: {e:?}"))
2169 })?,
2170 None => publications::Publications::new(),
2171 };
2172 let subscriptions = match sub_bytes {
2173 Some(b) => subscriptions::Subscriptions::deserialize(b).map_err(|e| {
2174 EngineError::Unsupported(alloc::format!("subscriptions restore: {e:?}"))
2175 })?,
2176 None => subscriptions::Subscriptions::new(),
2177 };
2178 let statistics = match stats_bytes {
2179 Some(b) => statistics::Statistics::deserialize(b).map_err(|e| {
2180 EngineError::Unsupported(alloc::format!("statistics restore: {e:?}"))
2181 })?,
2182 None => statistics::Statistics::new(),
2183 };
2184 Ok(Self {
2185 lock_skip_rows: None,
2186 catalog,
2187 parallel_runner: ParallelRunnerSlot::default(),
2188 tx_catalogs: BTreeMap::new(),
2189 table_last_commit: BTreeMap::new(),
2190 commit_seq: 0,
2191 current_tx: None,
2192 backslash_escapes: false,
2193 mysql_strict: true,
2194 lo_descriptors: BTreeMap::new(),
2195 lo_next_fd: 0,
2196 prepared_statements: alloc::collections::BTreeMap::new(),
2197 current_session: 0,
2198 sessions: BTreeMap::new(),
2199 advisory_locks: BTreeMap::new(),
2200 last_sequence_used: None,
2201 seq_currvals: alloc::collections::BTreeMap::new(),
2202 next_tx_id: 1,
2203 active_writer_versions: BTreeSet::new(),
2204 aborted_versions: BTreeSet::new(),
2205 locks: crate::locks::LockTable::new(),
2206 mvcc_inplace: !cfg!(feature = "mvcc-inplace-off"),
2207 autovacuum: true,
2208 autovacuum_inline: true,
2209 tx_writer_versions: BTreeMap::new(),
2210 stmt_writer_version: None,
2211 clock: None,
2212 salt_fn: None,
2213 max_query_rows: None,
2214 max_query_bytes: None,
2215 temp_run_factory: None,
2216 users,
2217 publications,
2218 subscriptions,
2219 statistics,
2220 plan_cache: plan_cache::PlanCache::new(),
2221 query_stats: query_stats::QueryStats::new(),
2222 activity_provider: None,
2223 audit_chain_provider: None,
2224 audit_verifier: None,
2225 slow_query_threshold_us: None,
2226 slow_query_logger: None,
2227 session_params: BTreeMap::new(),
2228 cursors: BTreeMap::new(),
2229 last_insert_id: core::sync::atomic::AtomicI64::new(0),
2230 row_count: 0,
2231 user_vars: BTreeMap::new(),
2232 temp_tables: BTreeSet::new(),
2233 temp_sequences: BTreeSet::new(),
2234 temp_views: BTreeSet::new(),
2235 listen_channels: BTreeSet::new(),
2236 tx_pending_notifies: Vec::new(),
2237 delivered_notifies: Vec::new(),
2238 pending_notices: Vec::new(),
2239 spill_stats: crate::tempstore::SpillStats::default(),
2240 xact_commit: core::sync::atomic::AtomicU64::new(0),
2241 xact_rollback: core::sync::atomic::AtomicU64::new(0),
2242 backend_count_fn: None,
2243 backend_pid_fn: None,
2244 wal_lsn_fn: None,
2245 backend_signal_fn: None,
2246 tz_offset_fn: None,
2247 tz_localize_fn: None,
2248 tz_canon_fn: None,
2249 tz_abbrev_fn: None,
2250 tz_all_fn: None,
2251 stat_tup_inserted: 0,
2252 table_write_stats: alloc::collections::BTreeMap::new(),
2253 commit_epoch: 0,
2254 stat_tup_updated: 0,
2255 stat_tup_deleted: 0,
2256 local_guc_saves: Vec::new(),
2257 render_style: crate::eval::RenderStyle::default(),
2258 savepoint_guc_marks: Vec::new(),
2259 trigger_recursion_depth: 0,
2260 rule_rewrite_active: false,
2261 foreign_key_checks: true,
2262 meta_views_materialised: false,
2263 pending_foreign_keys: Vec::new(),
2264 env_cfg: testkit::EnvConfig::default(),
2265 #[cfg(feature = "injection-points")]
2266 injection_store: alloc::sync::Arc::new(
2267 crate::testkit::injection::InjectionStore::default(),
2268 ),
2269 redo_capture: false,
2270 current_isolation_level: spg_sql::ast::IsolationLevel::ReadCommitted,
2271 last_redo: Vec::new(),
2272 table_change_seq: alloc::collections::BTreeMap::new(),
2273 matview_refresh_watermark: alloc::collections::BTreeMap::new(),
2274 matview_maintainable: alloc::collections::BTreeMap::new(),
2275 matview_delta_buf: alloc::collections::BTreeMap::new(),
2276 matview_delta_overflow: alloc::collections::BTreeSet::new(),
2277 matview_row_map: alloc::collections::BTreeMap::new(),
2278 })
2279 }
2280 EnvelopeParse::CrcMismatch { expected, computed } => {
2281 Err(EngineError::Storage(StorageError::Corrupt(alloc::format!(
2282 "snapshot envelope CRC32 mismatch (expected={expected:#010x}, computed={computed:#010x})"
2283 ))))
2284 }
2285 EnvelopeParse::Bare => {
2286 let mut catalog = Catalog::deserialize(buf).map_err(EngineError::Storage)?;
2287 crate::ddl::rebuild_all_excl_indexes(&mut catalog);
2288 Ok(Self::restore(catalog))
2289 }
2290 }
2291 }
2292
2293 pub const fn users(&self) -> &UserStore {
2294 &self.users
2295 }
2296
2297 /// Builder: attach a wall clock so `NOW()` / `CURRENT_TIMESTAMP` /
2298 /// `CURRENT_DATE` evaluate to a real value instead of erroring out.
2299 /// v7.39 (round 279) — announce which connection is about to run.
2300 /// The server calls this before every statement; embedded hosts
2301 /// never do and stay on session 0.
2302 ///
2303 /// Swapping parks the outgoing connection's state and installs the
2304 /// incoming one's, creating it on first sight. The plan cache is
2305 /// cleared because the string-literal dialect is part of what
2306 /// swaps and the same SQL text lexes differently under it.
2307 pub fn set_current_session(&mut self, id: u32) {
2308 if id == self.current_session {
2309 return;
2310 }
2311 let outgoing = SessionBag {
2312 session_params: core::mem::take(&mut self.session_params),
2313 backslash_escapes: self.backslash_escapes,
2314 mysql_strict: self.mysql_strict,
2315 prepared_statements: core::mem::take(&mut self.prepared_statements),
2316 lo_descriptors: core::mem::take(&mut self.lo_descriptors),
2317 lo_next_fd: self.lo_next_fd,
2318 cursors: core::mem::take(&mut self.cursors),
2319 last_insert_id: self
2320 .last_insert_id
2321 .load(core::sync::atomic::Ordering::Relaxed),
2322 row_count: self.row_count,
2323 user_vars: core::mem::take(&mut self.user_vars),
2324 temp_tables: core::mem::take(&mut self.temp_tables),
2325 temp_sequences: core::mem::take(&mut self.temp_sequences),
2326 temp_views: core::mem::take(&mut self.temp_views),
2327 seq_currvals: core::mem::take(&mut self.seq_currvals),
2328 last_sequence_used: self.last_sequence_used.take(),
2329 isolation_level: self.current_isolation_level,
2330 };
2331 self.sessions.insert(self.current_session, outgoing);
2332 let incoming = self.sessions.remove(&id).unwrap_or_default();
2333 self.session_params = incoming.session_params;
2334 self.backslash_escapes = incoming.backslash_escapes;
2335 self.mysql_strict = incoming.mysql_strict;
2336 self.prepared_statements = incoming.prepared_statements;
2337 self.lo_descriptors = incoming.lo_descriptors;
2338 self.lo_next_fd = incoming.lo_next_fd;
2339 self.cursors = incoming.cursors;
2340 self.last_insert_id.store(
2341 incoming.last_insert_id,
2342 core::sync::atomic::Ordering::Relaxed,
2343 );
2344 self.row_count = incoming.row_count;
2345 self.user_vars = incoming.user_vars;
2346 self.temp_tables = incoming.temp_tables;
2347 self.temp_sequences = incoming.temp_sequences;
2348 self.temp_views = incoming.temp_views;
2349 self.seq_currvals = incoming.seq_currvals;
2350 self.last_sequence_used = incoming.last_sequence_used;
2351 self.current_isolation_level = incoming.isolation_level;
2352 self.current_session = id;
2353 // The incoming session's temp namespace must be live before its very
2354 // first statement resolves a name.
2355 self.refresh_temp_prefix();
2356 self.plan_cache.clear();
2357 }
2358
2359 /// v7.39 (round 436) — the catalog-name prefix session `id` stores its
2360 /// TEMPORARY tables under. Mirrors PG's per-session `pg_temp_N` schema;
2361 /// the leading underscores keep it out of any name a client can write.
2362 fn temp_prefix_for(id: u32) -> String {
2363 alloc::format!("__spg_temp_{id}__")
2364 }
2365
2366 /// The catalog name this session's TEMPORARY table `logical` takes.
2367 pub(crate) fn session_temp_name(&self, logical: &str) -> String {
2368 alloc::format!("{}{logical}", Self::temp_prefix_for(self.current_session))
2369 }
2370
2371 /// v7.39 (round 436) — point every catalog this session can reach at its
2372 /// temp namespace, or at none when it owns no temporary tables (so a
2373 /// session that never made one pays a single `Option` check per lookup).
2374 /// Both the committed catalog and any open transaction's shadow are set:
2375 /// a temp table created inside a transaction must resolve there too.
2376 pub(crate) fn refresh_temp_prefix(&mut self) {
2377 let prefix = if self.temp_tables.is_empty()
2378 && self.temp_sequences.is_empty()
2379 && self.temp_views.is_empty()
2380 {
2381 None
2382 } else {
2383 Some(Self::temp_prefix_for(self.current_session))
2384 };
2385 self.catalog.set_temp_prefix(prefix.clone());
2386 for shadow in self.tx_catalogs.values_mut() {
2387 shadow.catalog.set_temp_prefix(prefix.clone());
2388 }
2389 }
2390
2391 /// v7.39 (round 279) — a connection has gone away: drop its parked
2392 /// state and release every advisory lock it still held, which is
2393 /// what PG does at backend exit.
2394 pub fn end_session(&mut self, id: u32) {
2395 // v7.39 (round 436) — a TEMPORARY table dies with its session, in
2396 // both PG and MySQL. Done before the bag is dropped, since the bag
2397 // is what knows which tables the session owns.
2398 let owned: Vec<String> = if id == self.current_session {
2399 self.temp_tables.iter().cloned().collect()
2400 } else {
2401 self.sessions
2402 .get(&id)
2403 .map(|b| b.temp_tables.iter().cloned().collect())
2404 .unwrap_or_default()
2405 };
2406 // v7.39 (round 469) — the same for TEMPORARY sequences and views,
2407 // which PG also drops at backend exit.
2408 let owned_seqs: Vec<String> = if id == self.current_session {
2409 self.temp_sequences.iter().cloned().collect()
2410 } else {
2411 self.sessions
2412 .get(&id)
2413 .map(|b| b.temp_sequences.iter().cloned().collect())
2414 .unwrap_or_default()
2415 };
2416 let owned_views: Vec<String> = if id == self.current_session {
2417 self.temp_views.iter().cloned().collect()
2418 } else {
2419 self.sessions
2420 .get(&id)
2421 .map(|b| b.temp_views.iter().cloned().collect())
2422 .unwrap_or_default()
2423 };
2424 if !owned.is_empty() || !owned_seqs.is_empty() || !owned_views.is_empty() {
2425 let prefix = Self::temp_prefix_for(id);
2426 for logical in owned {
2427 let mangled = alloc::format!("{prefix}{logical}");
2428 self.catalog.drop_table(&mangled);
2429 }
2430 for logical in owned_seqs {
2431 let mangled = alloc::format!("{prefix}{logical}");
2432 self.catalog.drop_sequence(&mangled);
2433 }
2434 for logical in owned_views {
2435 let mangled = alloc::format!("{prefix}{logical}");
2436 self.catalog.drop_view(&mangled);
2437 }
2438 if id == self.current_session {
2439 self.temp_tables.clear();
2440 self.temp_sequences.clear();
2441 self.temp_views.clear();
2442 self.refresh_temp_prefix();
2443 }
2444 }
2445 self.sessions.remove(&id);
2446 self.advisory_locks.retain(|_, (owner, _)| *owner != id);
2447 if id == self.current_session {
2448 self.session_params.clear();
2449 self.prepared_statements.clear();
2450 self.backslash_escapes = false;
2451 self.mysql_strict = true;
2452 self.lo_descriptors.clear();
2453 self.lo_next_fd = 0;
2454 self.cursors.clear();
2455 self.current_session = 0;
2456 }
2457 }
2458
2459 /// v7.39 (round 302, V15) — force the current session's string-literal
2460 /// dialect. A MySQL-protocol connection defaults to MySQL semantics
2461 /// (backslash is an escape: `'\n'` is a newline), which PG's own
2462 /// default (`standard_conforming_strings = on`) does not do. The
2463 /// mysql-wire shim calls this once, right after installing its
2464 /// session, so a client that never sends `SET sql_mode` still gets
2465 /// MySQL string handling; a later `SET sql_mode='NO_BACKSLASH_ESCAPES'`
2466 /// flips it back through the normal SET path. Clearing the plan cache
2467 /// mirrors [`set_current_session`] — the same SQL text lexes
2468 /// differently once the flag moves.
2469 pub fn set_backslash_escapes(&mut self, flag: bool) {
2470 if flag != self.backslash_escapes {
2471 self.backslash_escapes = flag;
2472 self.plan_cache.clear();
2473 }
2474 }
2475
2476 /// v7.39 (round 279) — take an advisory lock. Returns false only
2477 /// when ANOTHER session holds it; re-taking one this session
2478 /// already holds bumps a depth counter, as in PG.
2479 pub(crate) fn advisory_try_lock(&mut self, key: i64) -> bool {
2480 let me = self.current_session;
2481 match self.advisory_locks.get_mut(&key) {
2482 Some((owner, depth)) if *owner == me => {
2483 *depth += 1;
2484 true
2485 }
2486 Some(_) => false,
2487 None => {
2488 self.advisory_locks.insert(key, (me, 1));
2489 true
2490 }
2491 }
2492 }
2493
2494 /// Release one level. False when this session does not hold it —
2495 /// PG answers false and emits a warning; SPG answers false.
2496 pub(crate) fn advisory_unlock(&mut self, key: i64) -> bool {
2497 let me = self.current_session;
2498 match self.advisory_locks.get_mut(&key) {
2499 Some((owner, depth)) if *owner == me => {
2500 *depth -= 1;
2501 if *depth == 0 {
2502 self.advisory_locks.remove(&key);
2503 }
2504 true
2505 }
2506 _ => false,
2507 }
2508 }
2509
2510 /// Release every advisory lock this session holds.
2511 pub(crate) fn advisory_unlock_all(&mut self) {
2512 let me = self.current_session;
2513 self.advisory_locks.retain(|_, (owner, _)| *owner != me);
2514 }
2515
2516 /// v7.39 (round 417) — the current session's id (for MySQL
2517 /// `IS_USED_LOCK`, which reports the connection that holds a lock).
2518 /// v7.39 (round 430) — read one of this session's MySQL USER
2519 /// variables. `None` when it was never set, which the caller turns
2520 /// into NULL (MariaDB reads an unset user variable as NULL).
2521 pub(crate) fn user_var(&self, name: &str) -> Option<&spg_storage::Value<'static>> {
2522 self.user_vars.get(name)
2523 }
2524
2525 pub(crate) const fn current_session_id(&self) -> u32 {
2526 self.current_session
2527 }
2528
2529 /// v7.39 (round 417) — who holds an advisory-lock key (any session id),
2530 /// or `None` when nobody holds it. Used by MySQL `IS_USED_LOCK` and to
2531 /// separate `RELEASE_LOCK`'s "not held by anyone" (returns NULL) from
2532 /// "held by someone else" (returns 0).
2533 pub(crate) fn advisory_holder(&self, key: i64) -> Option<u32> {
2534 self.advisory_locks.get(&key).map(|(owner, _)| *owner)
2535 }
2536
2537 /// v7.39 (round 417) — MySQL `RELEASE_ALL_LOCKS()` returns the number of
2538 /// locks it released; PG's `pg_advisory_unlock_all()` returns void.
2539 pub(crate) fn advisory_unlock_all_count(&mut self) -> i32 {
2540 let me = self.current_session;
2541 // Total depth held by this session, so re-locked keys count as many.
2542 let mut n: i32 = 0;
2543 for (_, (owner, depth)) in &self.advisory_locks {
2544 if *owner == me {
2545 n = n.saturating_add(*depth as i32);
2546 }
2547 }
2548 self.advisory_locks.retain(|_, (owner, _)| *owner != me);
2549 n
2550 }
2551
2552 #[must_use]
2553 pub const fn with_clock(mut self, clock: ClockFn) -> Self {
2554 self.clock = Some(clock);
2555 self
2556 }
2557
2558 /// Builder: attach an OS-backed RNG for per-user password salts.
2559 /// The host (`spg-server`) typically wires this to `/dev/urandom`.
2560 #[must_use]
2561 pub const fn with_salt_fn(mut self, f: SaltFn) -> Self {
2562 self.salt_fn = Some(f);
2563 self
2564 }
2565
2566 /// v7.38 元机制 D — install a frozen [`testkit::EnvConfig`] snapshot.
2567 ///
2568 /// Hosts (spg-server, spg-embedded, tests) call this once at engine
2569 /// init with either `EnvConfig::from_env()` (production-with-test-vars)
2570 /// or `EnvConfig::builder()....build()` (programmatic). After
2571 /// construction the engine never reads env vars; all test-mode
2572 /// behaviour flows through `self.env_cfg()`.
2573 #[must_use]
2574 pub fn with_env_cfg(mut self, env_cfg: testkit::EnvConfig) -> Self {
2575 // r1051 — a configured seed reaches `random()` too, not only
2576 // the `rng_seed()` accessor: the D-mechanism's "single seed
2577 // source" claim, made true at the SQL level (first pin_v738_
2578 // catch). Production engines carry no seed and never touch
2579 // the PRNG state here.
2580 if let Some(seed) = env_cfg.random_seed {
2581 crate::eval::math::prng_install_seed(seed);
2582 }
2583 // r1058 — `SPG_TEST_FIXED_CLOCK_MICROS` pins the clock for
2584 // hosts that read GUCs from env instead of calling
2585 // `with_clock` (the server). Process-global by necessity: a
2586 // `ClockFn` is a plain fn pointer and cannot capture.
2587 if let Some(micros) = env_cfg.fixed_clock_micros {
2588 FIXED_CLOCK_MICROS.store(micros, core::sync::atomic::Ordering::Relaxed);
2589 self = self.with_clock(fixed_clock_from_env);
2590 }
2591 self.env_cfg = env_cfg;
2592 self
2593 }
2594
2595 /// v7.38 元机制 D — frozen test-mode GUC snapshot. Hot paths gate
2596 /// nondeterministic surfaces on fields of this struct; production
2597 /// default keeps every field at `false / None / Auto` so the
2598 /// optimiser can const-fold the gate.
2599 pub fn env_cfg(&self) -> &testkit::EnvConfig {
2600 &self.env_cfg
2601 }
2602
2603 /// v7.38 元机制 D acceptor — single seed source for every
2604 /// nondeterministic engine subsystem (hash builders, randomised
2605 /// tie-breakers, …). Honour `SPG_TEST_RANDOM_SEED=N` when set;
2606 /// otherwise derive from the engine's wall clock (production) or
2607 /// fall back to a fixed sentinel when the host hasn't installed
2608 /// a clock. Two engines built with the same builder seed return
2609 /// byte-equal output for the same query.
2610 /// See `xtests/sigil/test-mode-gucs.md`.
2611 pub fn rng_seed(&self) -> u64 {
2612 if let Some(seed) = self.env_cfg.random_seed {
2613 return seed;
2614 }
2615 match self.clock {
2616 Some(f) => f() as u64,
2617 // Production engines without a clock installed get a fixed
2618 // non-zero sentinel; same shape as PG's `random()` start
2619 // state under a `setseed(0)`.
2620 None => 0xBAD_5EED_DEAD_BEEF,
2621 }
2622 }
2623
2624 /// v7.38 P0 元机制 A — push this engine's `InjectionStore` onto
2625 /// the thread-local stack so any `injection_point!()` reached
2626 /// during the returned guard's lifetime resolves against this
2627 /// engine. Mirrors PG's per-backend injection table.
2628 ///
2629 /// Returns a no-op guard when the `injection-points` feature is
2630 /// off so call sites don't need `#[cfg]`.
2631 pub fn enter_injection_scope(&self) -> crate::testkit::injection::InjectionGuard {
2632 #[cfg(feature = "injection-points")]
2633 {
2634 crate::testkit::injection::enter_scope(&self.injection_store)
2635 }
2636 #[cfg(not(feature = "injection-points"))]
2637 {
2638 crate::testkit::injection::new_guard()
2639 }
2640 }
2641
2642 /// v7.38 P0 元机制 A — expose the per-engine store so tests can
2643 /// query notice counts / detach actions without parsing SQL
2644 /// output. Only present when the feature is on.
2645 #[cfg(feature = "injection-points")]
2646 pub fn injection_store(&self) -> alloc::sync::Arc<crate::testkit::injection::InjectionStore> {
2647 self.injection_store.clone()
2648 }
2649
2650 /// Builder: cap the number of rows a single SELECT may return.
2651 /// Exceeding the cap raises `EngineError::RowLimitExceeded` —
2652 /// the bound is checked inside the executor so a runaway
2653 /// catalog scan can't allocate millions of rows before the
2654 /// server gets a chance to reject the result.
2655 #[must_use]
2656 pub const fn with_max_query_rows(mut self, n: usize) -> Self {
2657 self.max_query_rows = Some(n);
2658 self
2659 }
2660
2661 /// Builder: cap the approximate heap bytes a single SELECT's
2662 /// join/filter materialisation may hold. Exceeding the cap
2663 /// raises `EngineError::QueryBytesExceeded`. Rows are the wrong
2664 /// unit when one row carries a multi-MB body (mailrs round-26:
2665 /// 1000-row batches of full mail text walked a 15 GiB host into
2666 /// reclaim livelock without ever tripping a row ceiling).
2667 #[must_use]
2668 pub const fn with_max_query_bytes(mut self, n: usize) -> Self {
2669 self.max_query_bytes = Some(n);
2670 self
2671 }
2672
2673 /// The *committed* catalog. Note: during a transaction this returns the
2674 /// pre-TX state — `SELECT` inside a TX goes through `execute()` and reads
2675 /// the shadow. Tests that inspect outside-TX state should use this.
2676 pub const fn catalog(&self) -> &Catalog {
2677 &self.catalog
2678 }
2679
2680 /// Capture a frozen view of the committed engine state. Catalog
2681 /// is O(1) Arc bump; trailers are cheap clones. Decouples "capture"
2682 /// (needs &Engine) from "serialize" (CPU, no engine access) — the
2683 /// seam the background-checkpoint worker rides in CoW-2.
2684 pub fn snapshot_data(&self) -> EngineSnapshot {
2685 EngineSnapshot {
2686 catalog: self.catalog.clone(),
2687 users: self.users.clone(),
2688 publications: self.publications.clone(),
2689 subscriptions: self.subscriptions.clone(),
2690 statistics: self.statistics.clone(),
2691 }
2692 }
2693
2694 /// Serialize the *committed* catalog to bytes. v0.6 was full-snapshot; v0.9
2695 /// adds the rule that an open TX's shadow is never snapshotted — only the
2696 /// post-COMMIT state is persisted. v4.1 wraps the catalog in an envelope
2697 /// when there are users to persist; an empty user table snapshots as the
2698 /// bare catalog format (backwards-compat with v3.x readers). v6.1.2
2699 /// adds publications to the envelope condition: either non-empty
2700 /// users OR non-empty publications now triggers the envelope path.
2701 pub fn snapshot(&self) -> Vec<u8> {
2702 self.snapshot_data().serialize()
2703 }
2704
2705 /// True when at least one TX slot is in flight. v4.41.1 runtime
2706 /// invariant: at most one slot active at a time (dispatch holds
2707 /// `engine.write()` across the entire wrap). v4.42 will let this
2708 /// return true with multiple slots concurrently.
2709 pub fn in_transaction(&self) -> bool {
2710 !self.tx_catalogs.is_empty()
2711 }
2712
2713 /// v7.37 C.5 (A.2) — per-connection in-transaction test. A given
2714 /// connection is "in a transaction" iff its own `tx_id` has an open
2715 /// shadow slot. Unlike [`in_transaction`] (which is true if *any* tx is
2716 /// open), this lets concurrent connections each carry their own explicit
2717 /// transaction without colliding on the global slot. `IMPLICIT_TX` never
2718 /// has a persistent slot (autocommit reads/writes the main catalog), so
2719 /// this is false for the autocommit id.
2720 pub fn is_tx_open(&self, tx_id: TxId) -> bool {
2721 self.tx_catalogs.contains_key(&tx_id)
2722 }
2723
2724 /// v7.37 (round 828) — the user store THIS session should read:
2725 /// its transaction's role shadow when one exists, the committed
2726 /// store otherwise. The auth path and other sessions read
2727 /// `self.users` directly on purpose — an uncommitted role must not
2728 /// be visible to them, let alone able to log in.
2729 pub(crate) fn effective_users(&self) -> &crate::users::UserStore {
2730 if let Some(tx) = self.current_tx
2731 && let Some(state) = self.tx_catalogs.get(&tx)
2732 && let Some(shadow) = &state.users
2733 {
2734 return shadow;
2735 }
2736 &self.users
2737 }
2738
2739 /// v7.37 (round 828) — the store role DDL writes to: the TX's role
2740 /// shadow (created from the committed store on first use) inside a
2741 /// transaction, the committed store in autocommit. Every mutation
2742 /// of roles or memberships goes through here, so `BEGIN; CREATE
2743 /// ROLE r; ROLLBACK` leaves nothing behind — the shadow drops with
2744 /// the TxState — and COMMIT installs the shadow wholesale.
2745 pub(crate) fn role_ddl_users_mut(&mut self) -> &mut crate::users::UserStore {
2746 let tx_slot = self
2747 .current_tx
2748 .filter(|tx| self.tx_catalogs.contains_key(tx));
2749 match tx_slot {
2750 Some(tx) => {
2751 if self
2752 .tx_catalogs
2753 .get(&tx)
2754 .is_some_and(|state| state.users.is_none())
2755 {
2756 let committed = self.users.clone();
2757 if let Some(state) = self.tx_catalogs.get_mut(&tx) {
2758 state.users = Some(committed);
2759 }
2760 }
2761 self.tx_catalogs
2762 .get_mut(&tx)
2763 .and_then(|state| state.users.as_mut())
2764 .expect("role shadow ensured just above for an open tx slot")
2765 }
2766 None => &mut self.users,
2767 }
2768 }
2769
2770 /// v4.41.1 allocate a fresh TX handle. Used by spg-server dispatch
2771 /// to scope each implicit-wrap BEGIN..stmt..COMMIT to its own slot
2772 /// in `tx_catalogs`. v4.42 — the commit-barrier leader allocates
2773 /// one of these per task in its group, runs `BEGIN`+sql+`COMMIT`
2774 /// sequentially under a single `engine.write()` so each task's
2775 /// mutations accumulate into shared state, then either keeps the
2776 /// accumulated state (fsync OK) or restores the pre-image via
2777 /// `replace_catalog` (fsync err).
2778 pub fn alloc_tx_id(&mut self) -> TxId {
2779 let id = TxId(self.next_tx_id);
2780 self.next_tx_id = self.next_tx_id.saturating_add(1);
2781 id
2782 }
2783
2784 /// v4.42 — atomically replace the live catalog. Used by the
2785 /// commit-barrier leader to roll back a group whose batched
2786 /// fsync failed: the leader snapshots `engine.catalog().clone()`
2787 /// (O(1) Arc bump after the v4.39/v4.40 persistent migration)
2788 /// at group start, sequentially applies each task's BEGIN+sql+
2789 /// COMMIT under the same write lock to accumulate mutations
2790 /// into shared state, batches the WAL bytes, fsyncs once, and
2791 /// on failure calls this with the pre-image to undo every
2792 /// task in the group at once.
2793 ///
2794 /// **Does NOT touch `tx_catalogs` / `current_tx`.** Any
2795 /// explicit-TX slot from a concurrent client (created via the
2796 /// legacy `IMPLICIT_TX`-less dispatch path or via the future
2797 /// MVCC-readers v5+ work) has its own snapshot baked into the
2798 /// slot — restoring `self.catalog` to the pre-image leaves
2799 /// those slots untouched, exactly as they were when the leader
2800 /// took the lock. The leader's own implicit-TX slots are all
2801 /// already discarded (`exec_commit` removed them as each
2802 /// task's COMMIT ran) by the time this is reached.
2803 pub fn replace_catalog(&mut self, catalog: Catalog) {
2804 self.catalog = catalog;
2805 }
2806
2807 /// v6.7.0 — public shim around `Catalog::freeze_oldest_to_cold`
2808 /// so tests + the spg-server freezer can drive a freeze without
2809 /// reaching into the private `active_catalog_mut`. v6.7.4
2810 /// parallel freezer will build on this surface.
2811 ///
2812 /// Marks the table's cached `cold_row_count` stale because the
2813 /// freeze added cold locators that ANALYZE hasn't yet refreshed.
2814 pub fn freeze_oldest_to_cold(
2815 &mut self,
2816 table_name: &str,
2817 index_name: &str,
2818 max_rows: usize,
2819 ) -> Result<spg_storage::FreezeReport, EngineError> {
2820 let report = self
2821 .active_catalog_mut()
2822 .freeze_oldest_to_cold(table_name, index_name, max_rows)
2823 .map_err(EngineError::Storage)?;
2824 if let Some(t) = self.active_catalog_mut().get_mut(table_name) {
2825 t.mark_cold_row_count_stale();
2826 }
2827 Ok(report)
2828 }
2829
2830 /// v6.7.5 — public shim used by the spg-server follower's
2831 /// segment-forwarding receiver. Registers a cold-tier segment
2832 /// at a specific id (the master's id, as transmitted on the
2833 /// wire) so the follower's BTree-Cold locators stay byte-
2834 /// identical with the master's. Wraps
2835 /// `Catalog::load_segment_bytes_at` under the standard
2836 /// clone-mutate-replace pattern.
2837 ///
2838 /// Returns `Ok(())` on success **and** on the "slot already
2839 /// occupied" case — a follower mid-reconnect may receive a
2840 /// segment chunk for a segment_id it already has on disk
2841 /// (forwarded last session); the caller should treat that
2842 /// path as a no-op rather than a fatal error.
2843 pub fn receive_cold_segment(
2844 &mut self,
2845 segment_id: u32,
2846 bytes: Vec<u8>,
2847 ) -> Result<(), EngineError> {
2848 let mut new_cat = self.catalog.clone();
2849 match new_cat.load_segment_bytes_at(segment_id, bytes) {
2850 Ok(()) => {
2851 self.replace_catalog(new_cat);
2852 Ok(())
2853 }
2854 Err(StorageError::Corrupt(msg)) if msg.contains("already occupied") => Ok(()),
2855 Err(e) => Err(EngineError::Storage(e)),
2856 }
2857 }
2858
2859 /// v7.39 (round 598) — mutable access to the base catalog, for the
2860 /// recursive-CTE loop.
2861 ///
2862 /// It built a whole `Engine` per iteration to hold the working set:
2863 /// `Engine::restore` initialises 82 fields, and a counting allocator put
2864 /// the loop at 63 allocations and 104 kB PER ITERATION — 1 GB for a
2865 /// 10,000-row recursive CTE, none of it dependent on how much else was
2866 /// in the catalog. One engine, whose CTE table is refilled each round,
2867 /// needs this.
2868 pub(crate) fn base_catalog_mut(&mut self) -> &mut Catalog {
2869 &mut self.catalog
2870 }
2871
2872 pub(crate) fn active_catalog(&self) -> &Catalog {
2873 match self.current_tx {
2874 Some(t) => self
2875 .tx_catalogs
2876 .get(&t)
2877 .map_or(&self.catalog, |s| &s.catalog),
2878 None => &self.catalog,
2879 }
2880 }
2881
2882 fn active_catalog_mut(&mut self) -> &mut Catalog {
2883 let tx = self.current_tx;
2884 match tx {
2885 Some(t) => match self.tx_catalogs.get_mut(&t) {
2886 Some(s) => {
2887 // v7.39 (round 494) — see `TxState::shadow_dirty`.
2888 s.shadow_dirty = true;
2889 &mut s.catalog
2890 }
2891 None => &mut self.catalog,
2892 },
2893 None => &mut self.catalog,
2894 }
2895 }
2896
2897 /// v7.34 (crash-recovery P0 #2) — turn row-level redo capture on/off.
2898 /// The embedding layer enables it when persistence is on so each
2899 /// mutating `execute` records the physical [`RowChange`]s it applied
2900 /// (drained via [`Engine::take_redo`]). Off = zero capture overhead.
2901 pub fn set_redo_capture(&mut self, on: bool) {
2902 self.redo_capture = on;
2903 }
2904
2905 /// v7.39 (round 735, S14/B3) — record that `table`'s rows (or shape)
2906 /// changed. Cheap (one BTreeMap bump), called from every write entry;
2907 /// the materialized-view refresh watermark reads it.
2908 /// v7.39 (round 736) — per-view buffered-delta ceiling. Past this,
2909 /// the view's next REFRESH is a full one (the buffer is the
2910 /// optimisation, not the truth).
2911 pub(crate) const MATVIEW_DELTA_CEILING: usize = 65_536;
2912
2913 /// v7.39 (round 736) — fan the drained redo out to every
2914 /// maintainable view whose base table it touches.
2915 pub(crate) fn fan_out_matview_deltas(&mut self, drained: &[RowChange]) {
2916 if self.matview_maintainable.is_empty() {
2917 return;
2918 }
2919 for ch in drained {
2920 let t = ch.table_name().to_ascii_lowercase();
2921 let hit: Vec<String> = self
2922 .matview_maintainable
2923 .iter()
2924 .filter(|(_, base)| **base == t)
2925 .map(|(mv, _)| mv.clone())
2926 .collect();
2927 for mv in hit {
2928 if self.matview_delta_overflow.contains(&mv) {
2929 continue;
2930 }
2931 let buf = self.matview_delta_buf.entry(mv.clone()).or_default();
2932 if buf.len() >= Self::MATVIEW_DELTA_CEILING {
2933 self.matview_delta_overflow.insert(mv.clone());
2934 self.matview_delta_buf.remove(&mv);
2935 } else {
2936 buf.push(ch.clone());
2937 MATVIEW_FANOUT_BUFFERED.fetch_add(1, core::sync::atomic::Ordering::Relaxed);
2938 }
2939 }
2940 }
2941 }
2942
2943 pub(crate) fn bump_table_change(&mut self, table: &str) {
2944 let k = table.to_ascii_lowercase();
2945 *self.table_change_seq.entry(k).or_insert(0) += 1;
2946 }
2947
2948 /// v7.37.8 — read accessor for tests / observability. The
2949 /// embedding layer flips this on once per `open_path` (after
2950 /// replay completes) when `SPG_WAL_ROW_REDO` is enabled (now
2951 /// default in v7.37.8). A consumer that wants to verify the
2952 /// post-upgrade contract ("writes go to V5 ROW_REDO by default")
2953 /// reads this through `Database::engine_redo_capture()` instead
2954 /// of inspecting WAL bytes (which the auto-checkpoint truncates
2955 /// on `Drop`).
2956 pub fn redo_capture_enabled(&self) -> bool {
2957 self.redo_capture
2958 }
2959
2960 /// v7.38 轴 4 — currently-selected SQL isolation level. Default
2961 /// `ReadCommitted` after construction; updated by
2962 /// `SET TRANSACTION ISOLATION LEVEL …`. Read by
2963 /// `SHOW transaction_isolation` and any future MVCC/SSI gate.
2964 pub fn current_isolation_level(&self) -> spg_sql::ast::IsolationLevel {
2965 self.current_isolation_level
2966 }
2967
2968 /// v7.34 — take the redo captured by the most recent successful
2969 /// mutating `execute` (empty when capture is off, the statement was a
2970 /// read, or it changed nothing). The embedding layer writes these to
2971 /// the WAL in place of the SQL text.
2972 pub fn take_redo(&mut self) -> Vec<RowChange> {
2973 core::mem::take(&mut self.last_redo)
2974 }
2975
2976 /// v7.34 (crash-recovery P0 #2) — replay a row-level redo log onto the
2977 /// committed catalog (the row-level WAL recovery primitive: apply the
2978 /// captured physical changes from a checkpoint baseline, in place of
2979 /// re-executing the SQL). Trusts the log — no uniqueness/FK/parse.
2980 pub fn apply_redo(&mut self, changes: &[RowChange]) -> Result<(), EngineError> {
2981 self.catalog
2982 .apply_redo(changes)
2983 .map_err(EngineError::Storage)
2984 }
2985
2986 /// Read-only execute path. Succeeds for `SELECT` / `SHOW TABLES`
2987 /// / `SHOW COLUMNS`; returns `EngineError::WriteRequired` for
2988 /// every other statement, so the caller can fall through to the
2989 /// `&mut self` `execute` path under a write lock. Engine state is
2990 /// not mutated even on the success path (`rewrite_clock_calls`
2991 /// and `resolve_order_by_position` both mutate the locally-owned
2992 /// AST, not `self`).
2993 ///
2994 /// v4.2: cap result-set size. Applied after the executor
2995 /// materialises rows but before they leave the engine — wrapping
2996 /// every Rows-returning exec_* function would scatter the check.
2997 ///
2998 /// v7.31 (memory campaign, bucket A) — the same choke point now
2999 /// also enforces the BYTE budget on the final result set, so
3000 /// single-table and aggregate paths (which don't route through
3001 /// the join materialiser's incremental accounting) still cannot
3002 /// hand the host an unbounded result. Intermediate single-table
3003 /// clones are the 7.31.x follow-up (design doc, bucket A).
3004 fn enforce_row_limit(
3005 &self,
3006 result: Result<QueryResult, EngineError>,
3007 ) -> Result<QueryResult, EngineError> {
3008 if let Ok(QueryResult::Rows { rows, .. }) = &result {
3009 if let Some(cap) = self.max_query_rows
3010 && rows.len() > cap
3011 {
3012 return Err(EngineError::RowLimitExceeded(cap));
3013 }
3014 if let Some(byte_cap) = self.max_query_bytes
3015 && approx_rows_bytes(rows) > byte_cap
3016 {
3017 return Err(EngineError::QueryBytesExceeded(byte_cap));
3018 }
3019 }
3020 result
3021 }
3022}
3023
3024/// v7.31 (memory campaign — ceiling-first / never-die, design v1) —
3025/// per-table slice of the engine's resident-memory accounting.
3026/// `hot_encoded_bytes` is the storage layer's maintained meter (what
3027/// the rows encode to); `approx_resident_bytes` is what they COST in
3028/// RAM (per-cell enum slots + heap payloads via `approx_row_bytes`)
3029/// — the gap between the two is the representation multiplier the
3030/// round-26 report measured at ~11× end-to-end.
3031#[derive(Debug, Clone)]
3032pub struct TableMemoryStats {
3033 pub name: String,
3034 pub hot_rows: u64,
3035 /// Cached cold-row count (refreshed by ANALYZE — see
3036 /// `Table::cold_row_count`'s staleness contract).
3037 pub cold_rows: u64,
3038 pub hot_encoded_bytes: u64,
3039 pub approx_resident_bytes: u64,
3040 pub index_count: u64,
3041 /// v7.31 C2 — sum of `IndexKind::approx_resident_bytes()` over the
3042 /// table's indices: every variant (BTree / NSW / BRIN / GIN family)
3043 /// walks its own structure, so the GIN posting lists and NSW layer
3044 /// adjacency that dominate text/vector tables are counted honestly
3045 /// instead of the old flat-token estimate.
3046 pub approx_index_bytes: u64,
3047}
3048
3049/// v7.31 — whole-engine memory snapshot: the polling form of the
3050/// round-26 ask-4 watermark signal. Hosts compare
3051/// `total_approx_resident_bytes` (+ their own WAL/file accounting)
3052/// against their deployment ceiling and shed/shrink before the
3053/// kernel does it for them.
3054#[derive(Debug, Clone)]
3055pub struct MemoryStats {
3056 pub tables: Vec<TableMemoryStats>,
3057 pub total_hot_encoded_bytes: u64,
3058 pub total_approx_resident_bytes: u64,
3059 pub total_approx_index_bytes: u64,
3060 /// The active per-query materialisation budget (bucket A), so a
3061 /// monitoring host sees ceiling and usage through one call.
3062 pub max_query_bytes: Option<usize>,
3063 /// v7.31 C2 — bucket D: live WAL bytes (active chunk + buffered,
3064 /// uncheckpointed). `None` from the engine itself — it has no WAL;
3065 /// the durable hosts (embed `Database`, server) fill it in from
3066 /// their own WAL accounting. `Some(0)` means "host has a WAL and
3067 /// it is empty"; `None` means "no WAL on this path" (in-memory).
3068 pub wal_bytes: Option<u64>,
3069}
3070
3071/// v6.2.0 — true for engine-managed catalog tables that the bare
3072/// `ANALYZE` (no target) should skip. v6.2.0 has no internal
3073/// tables yet (publications / subscriptions / users / statistics
3074/// all live as engine fields, not catalog tables), so this is a
3075/// reserved future-proofing hook — every existing user table is
3076/// analysed.
3077const fn is_internal_table_name(_name: &str) -> bool {
3078 false
3079}
3080
3081#[cfg(test)]
3082mod tests;