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