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