Skip to main content

spg_storage/
lib.rs

1//! In-memory storage primitives.
2//!
3//! v0.3 is intentionally simple: a flat catalog of tables, each holding rows
4//! as `Vec<Value>` (positional, matching the table's `TableSchema`). No MVCC,
5//! no on-disk format — those land in later milestones.
6#![no_std]
7// v3.3.2 NEON path for l2_distance_sq (aarch64 only). Scoped allow:
8// `unsafe_code = "deny"` at workspace level stays in force for every
9// other crate.
10#![cfg_attr(target_arch = "aarch64", allow(unsafe_code))]
11
12extern crate alloc;
13
14pub mod bignum;
15pub mod bloom;
16mod codec;
17pub mod fts_simple;
18pub mod halfvec;
19pub mod jsonb_gin;
20mod nsw;
21pub mod persistent;
22pub mod persistent_btree;
23pub mod posting;
24pub mod quantize;
25pub mod row_header;
26pub mod row_locator;
27pub mod segment;
28pub mod snapshot;
29mod table;
30pub mod trgm;
31pub mod vacuum;
32
33pub use self::bloom::{BloomError, BloomFilter};
34// v7.31 monster tier-3 cut 3 — on-disk codec moved to `codec`; the
35// public dense-row surface keeps its `spg_storage::*` paths, and the
36// low-level write/read primitives stay crate-visible for the
37// `Catalog::serialize`/`deserialize` methods that remain in this file.
38pub(crate) use self::codec::*;
39pub use self::codec::{
40    decode_row_body_dense, decode_row_body_dense_pruned, encode_row_body_dense,
41    encode_row_body_dense_into, encode_row_body_dense_masked_into, row_body_encoded_len,
42};
43// v7.31 monster tier-3 cut 2 — HNSW algorithms moved to `nsw`; the
44// public vector-search surface keeps its `spg_storage::*` paths via
45// these re-exports, and `nsw_insert_at` stays crate-visible for the
46// `Table` insert paths in the `table` module.
47pub(crate) use self::nsw::nsw_insert_at;
48pub use self::nsw::{NswMetric, cosine_dot_norms_f32, inner_product_f32, nsw_index_on, nsw_query};
49pub use self::posting::PostingList;
50
51/// The list handed back for an absent key, so callers cannot tell an
52/// absent key from an empty posting list — the property the old
53/// `&[][..]` return had, kept.
54static EMPTY_POSTINGS: crate::posting::PostingList = crate::posting::PostingList::new();
55pub use self::row_locator::{RowLocator, RowLocatorError};
56pub use self::segment::{
57    BRIN_SIDECAR_MAGIC, BrinSummary, OwnedSegment, SEGMENT_COMPRESS_ALGO_LZSS,
58    SEGMENT_COMPRESS_ALGO_NONE, SEGMENT_MAGIC, SEGMENT_MAGIC_V2, SEGMENT_PAGE_BYTES, SegmentError,
59    SegmentMeta, SegmentReader, derive_brin_summaries, encode_segment, wrap_v2_envelope,
60    wrap_v2_envelope_with_brin,
61};
62
63use alloc::borrow::Cow;
64use alloc::boxed::Box;
65use alloc::collections::{BTreeMap, BTreeSet};
66use alloc::format;
67use alloc::string::{String, ToString};
68use alloc::sync::Arc;
69use alloc::vec::Vec;
70use core::fmt;
71
72use self::persistent::PersistentVec;
73use self::persistent_btree::PersistentBTreeMap;
74
75/// In-cell encoding for `DataType::Vector`. Mirrors
76/// `spg_sql::ast::VecEncoding` — kept here so storage stays
77/// dep-free of `spg-sql`. The engine bridges between the two
78/// at DDL-execution time.
79///
80/// `F32` is the pre-v6 default: each cell holds a raw `Vec<f32>`.
81/// `Sq8` (v6.0.1) stores `Sq8Vector { min, max, bytes: Vec<u8> }`
82/// per cell; 4× compression vs `F32` with recall@10 ≥ 0.95 on
83/// natural embeddings (Gaussian / unit-sphere corpora).
84/// `F16` (v6.0.3, DDL keyword `HALF`) stores each element as
85/// IEEE-754 binary16; 2× compression and bit-exact dequantise.
86#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
87pub enum VecEncoding {
88    #[default]
89    F32,
90    Sq8,
91    F16,
92}
93
94impl fmt::Display for VecEncoding {
95    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
96        match self {
97            Self::F32 => f.write_str("F32"),
98            Self::Sq8 => f.write_str("SQ8"),
99            Self::F16 => f.write_str("HALF"),
100        }
101    }
102}
103
104/// Runtime type tags. `Vector { dim, encoding }` / `Varchar(max)` /
105/// `Char(size)` are parameterised; the parameter travels with both
106/// the column schema and the on-wire serialised representation.
107#[derive(Debug, Clone, Copy, PartialEq, Eq)]
108pub enum DataType {
109    /// 16-bit signed. Backed by `Value::SmallInt(i16)`; arithmetic that
110    /// would overflow surfaces as a type error at INSERT time.
111    SmallInt,
112    Int,    // 32-bit signed
113    BigInt, // 64-bit signed
114    Float,  // f64 (PG double precision)
115    /// v7.38 (read01, T-float4) — `real` / `float4`: 32-bit IEEE float (PG
116    /// `real`). Backed by `Value::Real(f32)`; behaves like `Float` for most
117    /// dispatch but renders / stores at f32 precision.
118    Real,
119    Text,
120    /// `VARCHAR(n)` — same byte representation as `Text`, but INSERT
121    /// rejects values longer than `n` Unicode characters.
122    Varchar(u32),
123    /// `CHAR(n)` — same representation as `Text`, but INSERT right-pads
124    /// with U+0020 to exactly `n` Unicode characters (or rejects when
125    /// the input is already longer).
126    Char(u32),
127    Bool,
128    /// pgvector-style fixed-dimension vector. `encoding` selects
129    /// the in-cell representation (`F32` = pre-v6 raw f32 buffer;
130    /// `Sq8` = v6.0.1 8-bit scalar-quantised). The DDL grammar
131    /// surfaces encoding via the optional `USING <encoding>`
132    /// clause: `VECTOR(128) USING SQ8`.
133    Vector {
134        dim: u32,
135        encoding: VecEncoding,
136    },
137    /// `NUMERIC(precision, scale)` — exact fixed-point decimal stored as
138    /// a scaled `i128`. `precision` caps total decimal digits, `scale`
139    /// fixes digits after the decimal point. v1.12 supports up to
140    /// precision 38 (the i128-safe ceiling). `NUMERIC` and `NUMERIC(p)`
141    /// surface as `Numeric { precision: p, scale: 0 }`.
142    Numeric {
143        /// v7.39 (round 272) — widened from u8. PG's declared precision
144        /// runs to 1000; at u8 it could not even be spelled, and the
145        /// parser rejected anything past 38 (i128's width) outright.
146        precision: u16,
147        /// v7.39 (round 271) — widened alongside the value's scale.
148        /// v7.39 (round 273) — and signed: PG's DECLARED scale runs
149        /// -1000..=1000, where a negative one rounds to tens / hundreds.
150        /// A VALUE's display scale is always non-negative.
151        scale: i16,
152    },
153    /// `DATE` — calendar date with day precision, stored as `i32` days
154    /// since the Unix epoch (1970-01-01).
155    Date,
156    /// `TIMESTAMP` (a.k.a. `MySQL` `DATETIME`) — instant with microsecond
157    /// precision, stored as `i64` microseconds since the Unix epoch.
158    Timestamp,
159    /// v7.9.2 `TIMESTAMPTZ` — bit-identical to `Timestamp` on disk
160    /// (i64 microseconds, UTC by convention). Carried as a distinct
161    /// type tag so the PG-wire layer can advertise OID 1184 (PG's
162    /// `timestamp with time zone`) and `sqlx`/`pgx`/JDBC clients
163    /// decode into their TZ-aware datetime types. The internal
164    /// semantics are unchanged: SPG never stored per-row offsets,
165    /// and neither did PG — `TIMESTAMPTZ` in PG is also UTC i64.
166    Timestamptz,
167    /// v7.39 (round 291) — PG's `name`: the type its catalogs use for
168    /// identifiers. Text truncated to NAMEDATALEN-1 (63) bytes, with
169    /// its own type identity — `pg_typeof('abc'::name)` is `name`, and
170    /// `CREATE TABLE t (a name)` is legal SQL that SPG rejected.
171    Name,
172    /// v7.39 (round 640) — PG's `xid`: a transaction id. [`Value::Xid`]
173    /// has existed since round 512, so a `'5'::xid` literal already knew
174    /// what it was; this is the DECLARED half, which nothing had. Without
175    /// it `pg_typeof(NULL::xid)` answered `bigint`, `pg_type` could not
176    /// list oid 28 — leaving the 48 `pg_attribute` rows that describe
177    /// `xmin` / `xmax` pointing at a type no catalog carried — and
178    /// `CREATE TABLE t (a xid)` was refused as an unknown type.
179    ///
180    /// On disk it is the 8-byte body its BIGINT sibling writes, and it
181    /// reads back as a `Value::Xid`, so a stored column and a literal are
182    /// the same thing to everything downstream.
183    ///
184    /// What is NOT yet true of the identity: PG gives `xid` equality and
185    /// hashing and no ordering operator at all, so `min` / `max` /
186    /// `count(DISTINCT …)` / `<=` all error there and all answer here.
187    /// Measured, not assumed — and left for the operator surface rather
188    /// than claimed by this comment.
189    Xid,
190    /// v7.39 (round 640) — PG's `xid8`: the same transaction id, 64 bits
191    /// wide and monotonic. Unlike [`DataType::Xid`] it has no value of
192    /// its own; a cell is a `Value::BigInt` and only the declared type
193    /// witnesses it. That is enough for `pg_typeof`, the catalogs and
194    /// the wire OID, and not enough to refuse a bigint where PG refuses
195    /// one. `pg_current_xact_id()` returns this type on PG.
196    Xid8,
197    /// v7.39 (round 667) — PG's `oid`: an unsigned 32-bit object
198    /// identifier. Modelled exactly like [`DataType::Xid8`] above: it has
199    /// no value of its own, a cell is a `Value::BigInt`, and only the
200    /// declared type witnesses it.
201    ///
202    /// That deliberately buys less than a full value type. What it buys:
203    /// `CREATE TABLE t(o OID)` is accepted (it was rejected outright with
204    /// `type "oid" does not exist`, while the neighbouring `XID` worked),
205    /// `pg_typeof` answers `oid` rather than `bigint`, and the catalogs
206    /// report their own key columns honestly. What it does NOT buy is
207    /// refusing a bigint where PG refuses an oid — `sum(oid)` and
208    /// `avg(oid)` still answer here and error on PG, because at runtime
209    /// the cell is indistinguishable from a bigint. Round 664 tried to
210    /// close those two by name and withdrew: a guard keyed on the name
211    /// would have caught `sum(bigint)` with it.
212    ///
213    /// The cast itself was already right before this — `4294967296::oid`
214    /// and `'abc'::oid` produce PG's errors word for word, and `(-1)::oid`
215    /// wraps to 4294967295 as PG does. Only the resulting type was lost,
216    /// because `conversions.rs` mapped the target to `BigInt`.
217    Oid,
218    /// `INTERVAL` — calendar-aware span (months + microseconds). v2.11
219    /// supports INTERVAL only as a runtime intermediate (literals,
220    /// arithmetic results); on-disk encoding is rejected so this branch
221    /// can't appear in a `ColumnSchema`.
222    Interval,
223    /// v4.9: `JSON` — text-backed JSON document. We don't parse
224    /// the content (no path operators or jsonb functions yet) —
225    /// the column accepts any TEXT-compatible value and round-trips
226    /// it verbatim. PG OID 114 on the wire.
227    Json,
228    /// v7.9.0: `JSONB` — semantically identical to `Json` on
229    /// the storage side (same `Value::Json` cells, same
230    /// row codec), but advertised as PG OID 3802 on the wire
231    /// so `sqlx`-style clients that bind `jsonb` columns
232    /// decode correctly. mailrs migration blocker #3.
233    Jsonb,
234    /// v7.10.4: `BYTES` / `BYTEA` — variable-length raw binary.
235    /// Backed by `Value::Bytes(Vec<u8>)`. PG wire OID 17. Literal
236    /// forms accepted by parser/engine: PG hex form `'\xDEADBEEF'`
237    /// (case-insensitive hex pairs) and escape form
238    /// `'foo\\000bar'` (the latter decoded at coercion time when
239    /// the target column is BYTEA — TEXT columns leave the
240    /// backslash sequence verbatim).
241    Bytes,
242    /// v7.10.9: `TEXT[]` — single-dimension TEXT array. Elements
243    /// may be NULL (PG semantics). PG wire OID 1009. Literal
244    /// forms: `ARRAY['a', 'b', NULL]` and the PG external form
245    /// `'{a,b,NULL}'::TEXT[]`. Engine implements `= ANY(arr)`,
246    /// `<> ALL(arr)`, and 1-based indexing `arr[i]`. Catalog
247    /// FILE_VERSION 18+; older snapshots reject this DataType
248    /// (forward-only by design — TEXT[] columns aren't readable
249    /// on a pre-v7.10 binary).
250    TextArray,
251    /// v7.11.12: `INT[]` — single-dimension i32 array. PG wire
252    /// OID 1007 (_int4). Same `ARRAY[...]` / `'{1,2,3}'::INT[]`
253    /// literal surface as TEXT[]. Catalog FILE_VERSION 19+.
254    IntArray,
255    /// v7.11.12: `BIGINT[]` — single-dimension i64 array. PG
256    /// wire OID 1016 (_int8). Catalog FILE_VERSION 19+.
257    BigIntArray,
258    /// v7.39 (round 694) — `oid[]`. It exists for the reason
259    /// [`DataType::Oid`] does: mapping it onto `BigIntArray` answers
260    /// `pg_typeof('{1,2}'::oid[])` with `bigint[]`, which is the defect
261    /// round 667 closed for the scalar.
262    OidArray,
263    /// v7.37.5 β-P4 — `INTERVAL[]` — single-dimension array of
264    /// `IntervalSpan { months, days, micros }`. PG wire OID 1187
265    /// (`_interval`). Catalog tag 35 + per-cell body
266    /// `[u16 count][per elem: u8 null + (if non-null) 16-byte
267    /// interval body in LE PG-byte-equal field order]`.
268    /// FILE_VERSION 48+.
269    IntervalArray,
270    /// v7.37.5 γ — full PG array-of-scalar family. Catalog tags
271    /// 36..48; wire OIDs from PG `pg_type.dat`. Per-element body
272    /// uses the scalar's existing `write_value_body` shape.
273    /// FILE_VERSION 48+ (same window as β; no separate bump).
274    BoolArray, // PG `_bool`        OID 1000, tag 36
275    SmallIntArray,    // PG `_int2`        OID 1005, tag 37
276    FloatArray,       // PG `_float8`      OID 1022, tag 38
277    NumericArray,     // PG `_numeric`     OID 1231, tag 39
278    DateArray,        // PG `_date`        OID 1182, tag 40
279    TimestampArray,   // PG `_timestamp`   OID 1115, tag 41
280    TimestamptzArray, // PG `_timestamptz` OID 1185, tag 42
281    UuidArray,        // PG `_uuid`        OID 2951, tag 43
282    JsonArray,        // PG `_json`        OID 199,  tag 44
283    JsonbArray,       // PG `_jsonb`       OID 3807, tag 45
284    BytesArray,       // PG `_bytea`       OID 1001, tag 46
285    VarcharArray,     // PG `_varchar`     OID 1015, tag 47
286    CharArray,        // PG `_bpchar`      OID 1014, tag 48
287    /// v7.37.5 δ — PG 14+ multirange types. A multirange is an
288    /// ordered collection of non-overlapping ranges of the same
289    /// element kind (e.g. `int4multirange(int4range(1,5),
290    /// int4range(10,15))` → `{[1,5),[10,15)}`). The same DataType
291    /// variant covers all six builtin multiranges; `RangeKind`
292    /// pins the element type so encode/decode/display can route
293    /// off one switch (parallel to `Range(RangeKind)`).
294    /// Wire OIDs: int4multirange=4451, int8multirange=4537,
295    /// nummultirange=4536, tsmultirange=4533, tstzmultirange=4534,
296    /// datemultirange=4535. Catalog tag 49 + 1-byte RangeKind on
297    /// the dense type-tag side. FILE_VERSION 48+ (same window as
298    /// β/γ, no separate bump).
299    Multirange(RangeKind),
300    /// v7.37.5 ε — PG geometry scalar family. Mirrors PG's seven
301    /// builtin geometric types one-for-one. Body shapes (LE):
302    ///   Point   = 16 B fixed (f64 x + f64 y)            OID 600
303    ///   Lseg    = 32 B fixed (Point p1 + Point p2)      OID 601
304    ///   Path    = varlena ([u8 closed][u32 n][Point*n]) OID 602
305    ///   Box     = 32 B fixed (Point ur + Point ll)      OID 603
306    ///   Polygon = varlena ([u32 n][Point*n])            OID 604
307    ///   Line    = 24 B fixed (f64 a + f64 b + f64 c)    OID 628
308    ///   Circle  = 24 B fixed (Point center + f64 r)     OID 718
309    /// Catalog tags 50..56. FILE_VERSION 48+ (same window as β/γ/δ;
310    /// no separate bump). Geometric operators (`<->` / `@>` / `&&`
311    /// / `<<` / `>>` / `~=`) are a planner-integration follow-up,
312    /// parallel to the Range operator defer in e2e_pg_range.rs.
313    Point,
314    Lseg,
315    Path,
316    PgBox,
317    Polygon,
318    Line,
319    Circle,
320    /// v7.37.5 ζ-A — PG network address family. Body shapes (LE):
321    ///   Inet     = 18 B fixed (u8 family + u8 bits + 16 B addr)  OID 869
322    ///   Cidr     = 18 B fixed (same shape as Inet; CIDR rejects
323    ///                          host bits at parse / coerce)       OID 650
324    ///   Macaddr  = 6 B fixed                                      OID 829
325    ///   Macaddr8 = 8 B fixed (EUI-64)                             OID 774
326    /// Catalog tags 57-60. FILE_VERSION 48+. `family = 4` is IPv4
327    /// (uses the first 4 bytes of the 16-B addr slot, rest 0);
328    /// `family = 6` is IPv6 (full 16 B).
329    Inet,
330    Cidr,
331    Macaddr,
332    Macaddr8,
333    /// v7.39 (read01 pg_lsn.c) — PG `pg_lsn` (WAL location). 8 bytes,
334    /// rendered `%X/%X`. Catalog tag 66. OID 3220.
335    PgLsn,
336    /// v7.37.5 ζ-A — PG bit string. Body = `[u32 nbits][ceil(nbits/8) bytes]`,
337    /// big-endian within each byte (matches PG binary).
338    ///   Bit         OID 1560 (fixed-length, but SPG carries the
339    ///                         length per cell — column declaration
340    ///                         `BIT(n)` constrains at coerce time)
341    ///   BitVarying  OID 1562 (variable-length, declared as `VARBIT`)
342    /// Catalog tags 61-62.
343    /// v7.39 (round 281) — `BIT(n)`: a FIXED-length bit string. `0`
344    /// means the type was written without a typmod, which PG treats as
345    /// `bit(1)`. Column assignment requires the length to match
346    /// exactly; an explicit cast pads or truncates instead.
347    Bit(u32),
348    /// v7.39 (round 281) — `BIT VARYING(n)`: `n` is a MAXIMUM, and `0`
349    /// means unbounded (`varbit` with no typmod).
350    BitVarying(u32),
351    /// v7.37.5 ζ-A — PG `xml`. Body identical to TEXT (storage is
352    /// the verbatim XML string; no parse-time validation). Only
353    /// the wire OID (142) differs. Catalog tag 63.
354    Xml,
355    /// v7.37.5 ζ-A — PG `"char"` (the internal single-byte type,
356    /// distinct from `CHAR(n)` / `BPCHAR`). Body = 1 byte raw.
357    /// OID 18. Catalog tag 64.
358    Char1,
359    /// v7.37.5 ζ-A — `MONEY[]`. Body = `[u16 count][per elem: u8 null
360    /// + (non-null) i64 LE cents]`. OID 791. Catalog tag 65.
361    MoneyArray,
362    /// v7.12.0: PG `tsvector` — ordered, deduplicated set of
363    /// `(lexeme, positions, weight)` tuples. PG wire OID 3614.
364    /// Catalog FILE_VERSION 20+. Storage shape is row-codec
365    /// tag 22; the schema-agnostic `write_value` path emits tag
366    /// 18. Literal: `'foo:1 bar:2,3'::tsvector` (PG external
367    /// form). G-CRIT-3 entry — v7.12.0 only ships the type +
368    /// codec; matching `@@` lands in v7.12.2.
369    TsVector,
370    /// v7.12.0: PG `tsquery` — parse tree of lexemes joined by
371    /// `&` `|` `!` and phrase operators. PG wire OID 3615.
372    /// Catalog FILE_VERSION 20+.
373    TsQuery,
374    /// v7.17.0: PG `uuid` — 128-bit identifier stored as
375    /// `Value::Uuid([u8; 16])`. PG wire OID 2950. Canonical
376    /// text form is lowercase 8-4-4-4-12 hyphenated; input
377    /// also accepts uppercase, unhyphenated, and brace-wrapped
378    /// forms (`{xxxx…}`). Catalog FILE_VERSION 36+; tag 24 on
379    /// the dense type-tag side, tag 20 on the schema-agnostic
380    /// value side. The drop-in PG/MySQL surface for Django /
381    /// Rails / Hibernate "id UUID PRIMARY KEY DEFAULT
382    /// gen_random_uuid()" default-PK pattern.
383    Uuid,
384    /// v7.17.0 Phase 3.P0-32: PG `time` (without time zone) — i64
385    /// microseconds since 00:00:00. PG wire OID 1083. Display:
386    /// canonical zero-padded `HH:MM:SS` when fractional is zero,
387    /// `HH:MM:SS.ffffff` otherwise. Catalog FILE_VERSION 37+;
388    /// tag 25 on the dense type-tag side, tag 21 on the schema-
389    /// agnostic value side. The wall-clock-of-day half of PG's
390    /// date/time triplet (date / time / timestamp).
391    Time,
392    /// v7.17.0 Phase 3.P0-33: MySQL `YEAR` — u16 in range
393    /// 1901..=2155 plus the special zero-year sentinel 0. No
394    /// dedicated PG OID (advertised as INT4 / OID 23 on the wire
395    /// — psql renders integers, MySQL CLI renders 4-digit
396    /// zero-padded text). Display always 4 digits: `0000` for the
397    /// zero-year, `1985` / `2007` / etc otherwise. Catalog
398    /// FILE_VERSION 38+; tag 26 on the dense type-tag side, tag
399    /// 22 on the schema-agnostic value side.
400    Year,
401    /// v7.17.0 Phase 3.P0-34: PG `time with time zone` (TIMETZ) —
402    /// i64 microseconds since 00:00:00 in the local wall clock
403    /// PLUS i32 offset-from-UTC in seconds. PG wire OID 1266.
404    /// Display: `HH:MM:SS[.ffffff]±HH[:MM]` (PG `timetz_out`).
405    /// Range: offset in ±50400 seconds (±14 hours). Catalog
406    /// FILE_VERSION 39+; tag 27 on the dense type-tag side, tag
407    /// 23 on the schema-agnostic value side.
408    TimeTz,
409    /// v7.17.0 Phase 3.P0-35: PG `money` — i64 cents (locale-
410    /// independent storage). PG wire OID 790. Display: en_US
411    /// locale (`$N,NNN.CC`, negative → `-$1.23`). Input accepts
412    /// `$N.NN`, `$N,NNN.NN`, bare integer (treated as major
413    /// units), optional leading `-`. Range: full i64. Catalog
414    /// FILE_VERSION 40+; tag 28 on the dense type-tag side, tag
415    /// 24 on the schema-agnostic value side.
416    Money,
417    /// v7.17.0 Phase 3.P0-38: PG range type. The same DataType
418    /// variant covers all six builtin ranges (int4range,
419    /// int8range, numrange, tsrange, tstzrange, daterange) —
420    /// `RangeKind` pins the element type so encode / decode /
421    /// display can route off one switch. Catalog FILE_VERSION
422    /// 43+; tag 29 + a 1-byte RangeKind on the dense type-tag
423    /// side, tag 25 on the schema-agnostic value side.
424    Range(RangeKind),
425    /// v7.17.0 Phase 3.P0-39: PG `hstore` extension type — flat
426    /// `text => text` map with NULL value support. Catalog
427    /// FILE_VERSION 44+; tag 30 on the dense type-tag side, tag
428    /// 26 on the schema-agnostic value side. The contrib OID is
429    /// installation-dependent in real PG; SPG advertises it via
430    /// dynamic lookup, falling back to TEXT (OID 25) on the wire
431    /// when the installed `hstore` extension hasn't claimed an
432    /// OID yet.
433    Hstore,
434    /// v7.17.0 Phase 3.P0-40: PG `int[][]` — 2-dimensional INT
435    /// matrix. Storage: row-major Vec<Vec<Option<i32>>>. All
436    /// rows must share the same column count. Wire OID 1007
437    /// (same as INT[]; the dimension count travels in the data
438    /// header, not the OID). Catalog FILE_VERSION 45+; tag 31
439    /// on the dense type-tag side, tag 27 on the schema-agnostic
440    /// value side.
441    IntArray2D,
442    /// v7.17.0 Phase 3.P0-40: PG `bigint[][]` — 2-dimensional
443    /// BIGINT matrix. Storage / OID / tags mirror IntArray2D.
444    /// Tag 32 dense, tag 28 schema-agnostic.
445    BigIntArray2D,
446    /// v7.17.0 Phase 3.P0-40: PG `text[][]` — 2-dimensional TEXT
447    /// matrix. Storage: row-major Vec<Vec<Option<String>>>.
448    /// Tag 33 dense, tag 29 schema-agnostic.
449    TextArray2D,
450    /// v7.39 (read01 round 75) — `bool[][]`. BOOL is the ONE element type whose
451    /// ARRAY rendering differs from its scalar one (`t` vs `true`), so a
452    /// text-backed 2-D cannot be PG-faithful for it: rendering the whole array
453    /// wants `t`, and subscripting a cell to text wants `false`. Every other
454    /// element type renders the same either way, which is why this is the only
455    /// typed 2-D variant SPG needs.
456    BoolArray2D,
457}
458
459/// v7.17.0 Phase 3.P0-38 — pins the element type of a range value
460/// or column. Wire OIDs: Int4=3904, Int8=3926, Num=3906,
461/// Ts=3908, TsTz=3910, Date=3912.
462#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
463pub enum RangeKind {
464    Int4,
465    Int8,
466    Num,
467    Ts,
468    TsTz,
469    Date,
470}
471
472impl RangeKind {
473    pub const fn tag(self) -> u8 {
474        match self {
475            Self::Int4 => 0,
476            Self::Int8 => 1,
477            Self::Num => 2,
478            Self::Ts => 3,
479            Self::TsTz => 4,
480            Self::Date => 5,
481        }
482    }
483    pub const fn from_tag(t: u8) -> Option<Self> {
484        Some(match t {
485            0 => Self::Int4,
486            1 => Self::Int8,
487            2 => Self::Num,
488            3 => Self::Ts,
489            4 => Self::TsTz,
490            5 => Self::Date,
491            _ => return None,
492        })
493    }
494    pub const fn keyword(self) -> &'static str {
495        match self {
496            Self::Int4 => "INT4RANGE",
497            Self::Int8 => "INT8RANGE",
498            Self::Num => "NUMRANGE",
499            Self::Ts => "TSRANGE",
500            Self::TsTz => "TSTZRANGE",
501            Self::Date => "DATERANGE",
502        }
503    }
504}
505
506impl fmt::Display for DataType {
507    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
508        match self {
509            Self::SmallInt => f.write_str("SMALLINT"),
510            Self::Int => f.write_str("INT"),
511            Self::BigInt => f.write_str("BIGINT"),
512            Self::Xid => f.write_str("XID"),
513            Self::Xid8 => f.write_str("XID8"),
514            Self::Oid => f.write_str("OID"),
515            Self::OidArray => f.write_str("OID[]"),
516            Self::Float => f.write_str("FLOAT"),
517            Self::Real => f.write_str("REAL"),
518            Self::Text => f.write_str("TEXT"),
519            Self::Varchar(n) => write!(f, "VARCHAR({n})"),
520            Self::Char(n) => write!(f, "CHAR({n})"),
521            Self::Bool => f.write_str("BOOL"),
522            Self::Vector { dim, encoding } => match encoding {
523                VecEncoding::F32 => write!(f, "VECTOR({dim})"),
524                VecEncoding::Sq8 => write!(f, "VECTOR({dim}) USING SQ8"),
525                VecEncoding::F16 => write!(f, "VECTOR({dim}) USING HALF"),
526            },
527            Self::Numeric { precision, scale } => {
528                if *scale == 0 {
529                    write!(f, "NUMERIC({precision})")
530                } else {
531                    write!(f, "NUMERIC({precision}, {scale})")
532                }
533            }
534            Self::Date => f.write_str("DATE"),
535            Self::Timestamp => f.write_str("TIMESTAMP"),
536            Self::Timestamptz => f.write_str("TIMESTAMPTZ"),
537            Self::Name => f.write_str("NAME"),
538            Self::Interval => f.write_str("INTERVAL"),
539            Self::Json => f.write_str("JSON"),
540            Self::Jsonb => f.write_str("JSONB"),
541            Self::Bytes => f.write_str("BYTEA"),
542            Self::TextArray => f.write_str("TEXT[]"),
543            Self::IntArray => f.write_str("INT[]"),
544            Self::BigIntArray => f.write_str("BIGINT[]"),
545            Self::IntervalArray => f.write_str("INTERVAL[]"),
546            Self::BoolArray => f.write_str("BOOL[]"),
547            Self::SmallIntArray => f.write_str("SMALLINT[]"),
548            Self::FloatArray => f.write_str("FLOAT[]"),
549            Self::NumericArray => f.write_str("NUMERIC[]"),
550            Self::DateArray => f.write_str("DATE[]"),
551            Self::TimestampArray => f.write_str("TIMESTAMP[]"),
552            Self::TimestamptzArray => f.write_str("TIMESTAMPTZ[]"),
553            Self::UuidArray => f.write_str("UUID[]"),
554            Self::JsonArray => f.write_str("JSON[]"),
555            Self::JsonbArray => f.write_str("JSONB[]"),
556            Self::BytesArray => f.write_str("BYTEA[]"),
557            Self::VarcharArray => f.write_str("VARCHAR[]"),
558            Self::CharArray => f.write_str("CHAR[]"),
559            Self::Multirange(k) => f.write_str(match k {
560                RangeKind::Int4 => "INT4MULTIRANGE",
561                RangeKind::Int8 => "INT8MULTIRANGE",
562                RangeKind::Num => "NUMMULTIRANGE",
563                RangeKind::Ts => "TSMULTIRANGE",
564                RangeKind::TsTz => "TSTZMULTIRANGE",
565                RangeKind::Date => "DATEMULTIRANGE",
566            }),
567            Self::Point => f.write_str("POINT"),
568            Self::Lseg => f.write_str("LSEG"),
569            Self::Path => f.write_str("PATH"),
570            Self::PgBox => f.write_str("BOX"),
571            Self::Polygon => f.write_str("POLYGON"),
572            Self::Line => f.write_str("LINE"),
573            Self::Circle => f.write_str("CIRCLE"),
574            Self::Inet => f.write_str("INET"),
575            Self::Cidr => f.write_str("CIDR"),
576            Self::Macaddr => f.write_str("MACADDR"),
577            Self::Macaddr8 => f.write_str("MACADDR8"),
578            Self::PgLsn => f.write_str("PG_LSN"),
579            Self::Bit(0) => f.write_str("BIT"),
580            Self::Bit(n) => write!(f, "BIT({n})"),
581            Self::BitVarying(0) => f.write_str("VARBIT"),
582            Self::BitVarying(n) => write!(f, "VARBIT({n})"),
583            Self::Xml => f.write_str("XML"),
584            Self::Char1 => f.write_str("\"char\""),
585            Self::MoneyArray => f.write_str("MONEY[]"),
586            Self::TsVector => f.write_str("TSVECTOR"),
587            Self::TsQuery => f.write_str("TSQUERY"),
588            Self::Uuid => f.write_str("UUID"),
589            Self::Time => f.write_str("TIME"),
590            Self::Year => f.write_str("YEAR"),
591            Self::TimeTz => f.write_str("TIMETZ"),
592            Self::Money => f.write_str("MONEY"),
593            Self::Range(k) => f.write_str(k.keyword()),
594            Self::Hstore => f.write_str("HSTORE"),
595            Self::IntArray2D => f.write_str("INT[][]"),
596            Self::BigIntArray2D => f.write_str("BIGINT[][]"),
597            Self::TextArray2D => f.write_str("TEXT[][]"),
598            Self::BoolArray2D => f.write_str("BOOL[][]"),
599        }
600    }
601}
602
603/// v7.12.0 — one entry in a `Value::TsVector`. The lexeme is the
604/// (already-tokenised + stemmed in v7.12.1+) word; `positions` is
605/// a strictly-ascending list of 1-based positions; `weight` is the
606/// PG weight letter (A=3, B=2, C=1, D=0) — v7.12.0 defaults every
607/// lexeme to D, the v7.12.2 ranking path consumes the weight.
608#[derive(Debug, Clone, PartialEq, Eq)]
609pub struct TsLexeme {
610    pub word: String,
611    pub positions: Vec<u16>,
612    pub weight: u8,
613}
614
615/// v7.12.0 — parse tree for a PG `tsquery`. v7.12.0 ships the
616/// type + codec only; the `to_tsquery` / `plainto_tsquery` lexer
617/// lands in v7.12.1 and the `@@` evaluator in v7.12.2.
618#[derive(Debug, Clone, PartialEq, Eq)]
619pub enum TsQueryAst {
620    /// Single lexeme term. The `weight_mask` is the PG-style
621    /// bitmask of accepted weights (`A=1<<3`, `B=1<<2`, `C=1<<1`,
622    /// `D=1<<0`); `0` = any weight. v7.12.0 always sets it to 0.
623    Term {
624        word: String,
625        weight_mask: u8,
626    },
627    And(Box<TsQueryAst>, Box<TsQueryAst>),
628    Or(Box<TsQueryAst>, Box<TsQueryAst>),
629    Not(Box<TsQueryAst>),
630    /// `phrase <distance> phrase`. v7.12.0 only persists this; the
631    /// match semantics arrive in v7.12.2 alongside `@@`.
632    Phrase {
633        left: Box<TsQueryAst>,
634        right: Box<TsQueryAst>,
635        distance: u16,
636    },
637}
638
639/// v7.38.19 — whether an `interval` is finite, and if not, which way.
640///
641/// PostgreSQL has no NaN interval — measured, not assumed: `'nan'::interval`
642/// is a syntax error on 18.4 while `'infinity'` and `'-infinity'` parse —
643/// so this carries three states where `NumericKind` carries four.
644#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Default)]
645pub enum IntervalKind {
646    #[default]
647    Finite,
648    NegInf,
649    PosInf,
650}
651
652impl IntervalKind {
653    /// PostgreSQL's own representation of the two infinities, measured
654    /// off the wire rather than read out of its source.
655    ///
656    /// ```text
657    /// COPY (SELECT 'infinity'::interval)  TO STDOUT (FORMAT binary)
658    ///   … 7fffffffffffffff 7fffffff 7fffffff
659    /// COPY (SELECT '-infinity'::interval) TO STDOUT (FORMAT binary)
660    ///   … 8000000000000000 80000000 80000000
661    /// COPY (SELECT '1 day'::interval)     TO STDOUT (FORMAT binary)
662    ///   … 0000000000000000 00000001 00000000
663    /// ```
664    ///
665    /// All three fields at their extreme, which is why SPG can carry an
666    /// explicit `kind` in memory -- so the compiler names every site
667    /// that has to decide what infinity means there -- and still write
668    /// sixteen bytes on disk and on the wire. No finite interval reaches
669    /// the triple: PostgreSQL reserves it, so no value PostgreSQL ever
670    /// produced holds it either, and a file written before this version
671    /// cannot contain one.
672    #[must_use]
673    pub const fn from_fields(months: i32, days: i32, micros: i64) -> Self {
674        if micros == i64::MAX && days == i32::MAX && months == i32::MAX {
675            Self::PosInf
676        } else if micros == i64::MIN && days == i32::MIN && months == i32::MIN {
677            Self::NegInf
678        } else {
679            Self::Finite
680        }
681    }
682
683    /// The three fields this kind is written as. `Finite` hands back
684    /// what it was given.
685    #[must_use]
686    pub const fn to_fields(self, months: i32, days: i32, micros: i64) -> (i32, i32, i64) {
687        match self {
688            Self::Finite => (months, days, micros),
689            Self::PosInf => (i32::MAX, i32::MAX, i64::MAX),
690            Self::NegInf => (i32::MIN, i32::MIN, i64::MIN),
691        }
692    }
693
694    #[must_use]
695    pub const fn is_finite(self) -> bool {
696        matches!(self, Self::Finite)
697    }
698
699    /// Where this kind sits in the total order.
700    ///
701    /// v7.38.19 — PostgreSQL 18.4, measured: `'-infinity' < '-100 years'`
702    /// and `'infinity' > '100 years'` are both true, and `'infinity' =
703    /// 'infinity'` is true. So the rank decides first and the numbers
704    /// only speak between two finite values.
705    ///
706    /// Every comparison of two intervals asks THIS -- the ordering
707    /// comparator, the value comparator and the binary operators each
708    /// had their own copy of the span arithmetic, and three copies of a
709    /// question is how they come to disagree.
710    #[must_use]
711    pub const fn rank(self) -> i8 {
712        match self {
713            Self::NegInf => -1,
714            Self::Finite => 0,
715            Self::PosInf => 1,
716        }
717    }
718}
719
720/// A row-cell value, including SQL `NULL`. `Float` uses `f64`; NaN compares
721/// non-equal to itself (PG behaviour) — `PartialEq` is derived so callers
722/// must opt into NaN-aware comparison if they need stronger guarantees.
723///
724/// v7.37.42-arena Phase 1: parameterised on `'arena` so heap-bearing
725/// variants (Text/Json/Xml/Bytes/Vector/BitString.bytes) can borrow from
726/// a per-query bump arena (`Cow::Borrowed(&'arena ...)`). Persistent /
727/// catalog Values use `Value<'static>` (alias `ValueOwned`) with
728/// `Cow::Owned(...)`. Phase 1 keeps Range/Multirange recursive `Box<Value>`
729/// at `'static` (owned) — arena migration deferred to a later phase.
730/// Array-of-Option<String> variants (TextArray etc.) also stay owned in
731/// Phase 1; their nested shape is awkward for the simple Cow lift and the
732/// SCALARSQ hot path doesn't touch them.
733/// v7.38 (read01, T6) — the IEEE-style class of a NUMERIC value. `Finite` is the
734/// ordinary fixed-point case; the specials mirror PG's `'NaN'` / `'Infinity'` /
735/// `'-Infinity'`. Derived `PartialEq` gives `NaN == NaN` — correct for NUMERIC
736/// (unlike float's NaN ≠ NaN); the total order (`-Inf < finite < +Inf < NaN`)
737/// lives in the comparison paths, not in `Ord`.
738#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Hash)]
739pub enum NumericKind {
740    #[default]
741    Finite,
742    NaN,
743    PosInf,
744    NegInf,
745}
746
747#[derive(Debug, Clone, PartialEq)]
748#[non_exhaustive]
749pub enum Value<'arena> {
750    SmallInt(i16),
751    Int(i32),
752    BigInt(i64),
753    Float(f64),
754    /// v7.38 (read01, T-float4) — PG `real` (32-bit IEEE float).
755    Real(f32),
756    Text(Cow<'arena, str>),
757    Bool(bool),
758    Vector(Cow<'arena, [f32]>),
759    /// v6.0.1: 8-bit scalar-quantised vector cell. Lives in
760    /// columns declared `VECTOR(N) USING SQ8`. Layout per cell:
761    /// `Sq8Vector { min: f32, max: f32, bytes: Vec<u8> }` —
762    /// 4× compression vs `Vector(Vec<f32>)`. The wire layer
763    /// dequantises to `f32` on SELECT; INSERT path quantises
764    /// incoming `Vector(Vec<f32>)` cells into this variant.
765    Sq8Vector(crate::quantize::Sq8Vector),
766    /// v6.0.3: IEEE-754 binary16 vector cell. Lives in columns
767    /// declared `VECTOR(N) USING HALF`. Stores raw u16 LE bits
768    /// (2× compression vs `Vector(Vec<f32>)`). Wire / display
769    /// paths dequantise to f32 bit-exactly; INSERT path converts
770    /// incoming f32 vectors at the engine boundary.
771    HalfVector(crate::halfvec::HalfVector),
772    /// Exact fixed-point decimal. `scaled` holds the value as
773    /// `actual * 10^scale` so the storage type is always integral —
774    /// arithmetic never falls back to floating-point. v7.38 (read01, T6) —
775    /// `kind` classifies the value as finite (the common case, using
776    /// `scaled`/`scale`) or one of PG's NUMERIC specials (NaN / ±Infinity),
777    /// which ignore `scaled`/`scale` (canonicalized to 0).
778    Numeric {
779        scaled: i128,
780        /// v7.39 (round 271) — widened from u8. PG's numeric carries a
781        /// display scale up to 16383; at u8 a literal with 256 decimal
782        /// places could not be represented at all, and the conversion
783        /// aborted the query with an internal error.
784        scale: u16,
785        kind: NumericKind,
786    },
787    /// v7.38 (read01, T3) — an exact NUMERIC whose mantissa overflows `i128`
788    /// (PG's NUMERIC is unbounded). Boxed so the common finite case keeps its
789    /// small footprint; specials never take this form (they stay `Numeric`).
790    NumericBig(alloc::boxed::Box<crate::bignum::BigNumeric>),
791    /// Days since the Unix epoch (1970-01-01). Negative for earlier dates.
792    Date(i32),
793    /// Microseconds since the Unix epoch (1970-01-01T00:00:00Z).
794    Timestamp(i64),
795    /// Calendar span: `months` + `days` + `micros`. Three fields are
796    /// required for PG byte-equal: `'1 day'` ≠ `'24 hours'` (DST,
797    /// month-boundary, and the on-wire `pg_type` `interval` are all
798    /// `i64 micros + i32 days + i32 months`). v7.37.5 β widened from
799    /// `{months, micros}`; column storage lands in the same window.
800    Interval {
801        months: i32,
802        days: i32,
803        micros: i64,
804        /// v7.38.19 — finite, or one of the two infinities.
805        ///
806        /// PostgreSQL 17 gave `interval` an infinite value and SPG had
807        /// none, so `'infinity'::interval` was refused outright and the
808        /// subtraction error the ledger described was one symptom of
809        /// that, not the defect.
810        ///
811        /// A field beside the numbers rather than a sentinel inside
812        /// them, which is the shape `Value::Numeric` already uses for
813        /// exactly this question — and a field on THIS variant rather
814        /// than a new one, so the compiler names every site that has to
815        /// decide what infinity means there. A new variant would have
816        /// compiled everywhere on the first try and let a `_` arm
817        /// answer for it at one of a hundred and five of them.
818        kind: IntervalKind,
819    },
820    /// v4.9 `JSON` — raw JSON text. No structural validation
821    /// happens at the storage layer; whatever the parser hands us
822    /// round-trips verbatim. Equality is byte-wise.
823    Json(Cow<'arena, str>),
824    /// v7.10.4 `BYTEA` — raw binary blob. Equality is byte-wise.
825    /// Layout matches `Text`'s length-prefixed shape (`[u32 LE
826    /// len][bytes]`) under tag 18; the engine accepts PG hex
827    /// literals (`'\xDEADBEEF'`) and escape literals at the
828    /// coercion boundary.
829    Bytes(Cow<'arena, [u8]>),
830    /// v7.10.9 `TEXT[]` — single-dimension TEXT array with
831    /// optional NULL elements. Equality is element-wise. PG's
832    /// NULL-element comparison semantics: NULL ≠ NULL inside
833    /// arrays under `=`, so `[NULL] != [NULL]` (the engine
834    /// honours this).
835    TextArray(Vec<Option<String>>),
836    /// v7.11.12 `INT[]` — single-dimension i32 array with optional
837    /// NULL elements. Codec mirrors TextArray with i32 LE per
838    /// element instead of length-prefixed UTF-8.
839    IntArray(Vec<Option<i32>>),
840    /// v7.11.12 `BIGINT[]` — single-dimension i64 array with optional
841    /// NULL elements.
842    BigIntArray(Vec<Option<i64>>),
843    /// v7.37.5 β-P4 `INTERVAL[]` — single-dimension array of
844    /// `IntervalSpan { months, days, micros }` with optional NULL
845    /// elements. PG external form quotes each non-NULL element
846    /// (`{"1 day","24:00:00",NULL}`) because interval text contains
847    /// spaces and colons. Storage codec follows the BigIntArray
848    /// shape with a 16-byte per-element body.
849    IntervalArray(Vec<Option<IntervalSpan>>),
850    /// v7.37.5 γ — single-dimension arrays of the remaining PG
851    /// scalar types. Each carries `Vec<Option<T>>` with the
852    /// scalar's natural Rust shape; element NULLs are first-class
853    /// (per PG: `{1,NULL,3}` is a 3-element array, not a 2-element
854    /// one). Codec follows the IntervalArray shape — `[u16 count]
855    /// [per elem: u8 null + (non-null) scalar body]`.
856    BoolArray(Vec<Option<bool>>),
857    SmallIntArray(Vec<Option<i16>>),
858    FloatArray(Vec<Option<f64>>),
859    /// PG `NUMERIC[]` — `(scaled: i128, scale: u16)` per element.
860    NumericArray(Vec<Option<(i128, u16)>>),
861    DateArray(Vec<Option<i32>>),
862    TimestampArray(Vec<Option<i64>>),
863    TimestamptzArray(Vec<Option<i64>>),
864    UuidArray(Vec<Option<[u8; 16]>>),
865    JsonArray(Vec<Option<String>>),
866    JsonbArray(Vec<Option<String>>),
867    BytesArray(Vec<Option<Vec<u8>>>),
868    VarcharArray(Vec<Option<String>>),
869    CharArray(Vec<Option<String>>),
870    /// v7.37.5 δ — PG 14+ multirange. `ranges` is a Vec of
871    /// non-overlapping bounds spans of the shared `kind`. PG's
872    /// canonical text form is `{[a,b),[c,d),...}` (comma-separated
873    /// ranges in braces; `{}` for the empty multirange). SPG's
874    /// constructor enforces no overlap/coalescing — for now the
875    /// engine trusts the caller (mirrors PG's `_construct_array`
876    /// pattern). Catalog tag 49 + 1-byte RangeKind on the dense
877    /// type-tag side; schema-less path is unreachable (multirange
878    /// is column-typed only).
879    Multirange {
880        kind: RangeKind,
881        ranges: Vec<RangeSpan>,
882    },
883    /// v7.37.5 ε — PG geometry scalars. Per-type Vec/struct shape;
884    /// codec body shape is described on the matching DataType
885    /// variant. PG canonical text forms:
886    ///   Point   `(x,y)`
887    ///   Lseg    `[(x1,y1),(x2,y2)]`
888    ///   Path    open `[(x,y),(x,y),...]` / closed `((x,y),(x,y),...)`
889    ///   Box     `(ux,uy),(lx,ly)` (PG normalises to upper-right + lower-left)
890    ///   Polygon `((x,y),(x,y),...)` (implicit closed)
891    ///   Line    `{a,b,c}` (Ax + By + C = 0)
892    ///   Circle  `<(x,y),r>`
893    Point(Point2D),
894    Lseg(Point2D, Point2D),
895    /// `closed = true` is `((p,p,...))`; `false` is `[(p,p,...)]`.
896    Path {
897        points: Vec<Point2D>,
898        closed: bool,
899    },
900    /// PG `box` — stored as `(upper_right, lower_left)` (PG's
901    /// normalised order). The engine accepts both endpoint
902    /// orderings at parse time and normalises here.
903    PgBox(Point2D, Point2D),
904    Polygon(Vec<Point2D>),
905    Line {
906        a: f64,
907        b: f64,
908        c: f64,
909    },
910    Circle {
911        center: Point2D,
912        radius: f64,
913    },
914    /// v7.37.5 ζ-A — PG `inet`. `family = 4` (IPv4) or `6` (IPv6).
915    /// `bits` is the netmask bit count (0..=32 for IPv4, 0..=128
916    /// for IPv6). `addr` is right-padded with zeros when family=4
917    /// (first 4 bytes are the address).
918    Inet {
919        family: u8,
920        bits: u8,
921        addr: [u8; 16],
922    },
923    /// v7.37.5 ζ-A — PG `cidr`. Same shape as Inet; CIDR's
924    /// invariant (host bits zero) is enforced at parse / coerce.
925    Cidr {
926        family: u8,
927        bits: u8,
928        addr: [u8; 16],
929    },
930    /// v7.37.5 ζ-A — PG `macaddr`. 6 bytes (XX:XX:XX:XX:XX:XX).
931    Macaddr([u8; 6]),
932    /// v7.37.5 ζ-A — PG `macaddr8`. 8 bytes (EUI-64).
933    Macaddr8([u8; 8]),
934    /// v7.39 (read01 pg_lsn.c) — PG `pg_lsn`, a 64-bit WAL location.
935    PgLsn(u64),
936    /// v7.39 (read01 ruleutils.c) — PG `regclass`: an OID-typed relation
937    /// reference that renders as the relation name. SPG carries BOTH
938    /// (the synthetic oid for catalog joins, the name for display) so
939    /// `conrelid = 't'::regclass` and `'t'::regclass::text` agree.
940    /// Eval-only (no column storage).
941    RegClass(i64, alloc::boxed::Box<str>),
942    /// v7.39 (round 342, V65) — PG `regproc`: an OID-typed FUNCTION
943    /// reference that renders as the function name. Same dual shape
944    /// [`Value::RegClass`] carries, and for the same reason: without the
945    /// oid half, `pg_proc.oid = 'f'::regproc` cannot join, and a callee
946    /// cannot tell `pg_get_functiondef('f'::regproc)` — which PG answers
947    /// — from `pg_get_functiondef('f')` — which PG rejects.
948    /// Eval-only (no column storage).
949    RegProc(i64, alloc::boxed::Box<str>),
950    /// v7.39 (round 648) — PG `regtype`: an OID-typed TYPE reference
951    /// that renders as the type name. The third of the shape
952    /// [`Value::RegClass`] and [`Value::RegProc`] carry, and the one
953    /// that was missing it: `::regtype` produced a plain `Value::Text`
954    /// holding the canonical name, so `'text'::regtype::oid` tried to
955    /// parse the NAME as a number and answered `invalid input syntax
956    /// for type oid: "text"` where PG answers 25. `pg_typeof` on one
957    /// said `text` rather than `regtype` for the same reason.
958    ///
959    /// Eval-only (no column storage).
960    RegType(i64, alloc::boxed::Box<str>),
961    /// v7.39 (round 512) — PG `xid` and `cid`, the transaction and command
962    /// ids the `xmin` / `xmax` / `cmin` / `cmax` system columns carry.
963    ///
964    /// Their own types rather than integers, because PG deliberately gives
965    /// them almost no operators: measured on PG18, `xmin + 1` is "operator
966    /// does not exist: xid + integer", `xmin > 0` likewise, `xmin::bigint`
967    /// is "cannot cast type xid to bigint", and there is no `max(xid)`.
968    /// Carrying them as BigInt would quietly allow all four.
969    ///
970    /// Eval-only (no column storage).
971    Xid(u32),
972    Cid(u32),
973    /// v7.39 (round 511) — PG `tid`, the physical row identity `ctid`
974    /// carries: a block number and a one-based offset inside it, rendered
975    /// `(block,offset)`.
976    ///
977    /// It is a real type rather than a two-field record because the idiom
978    /// that makes `ctid` worth having — `DELETE … WHERE ctid NOT IN (SELECT
979    /// min(ctid) … GROUP BY key)` — needs `min()` over it, and PG has no
980    /// `min(record)`. Ordering is by block then offset, so `(0,2) < (0,9) <
981    /// (0,10)`; a text form would order those `(0,10) < (0,2) < (0,9)` and
982    /// the dedup would keep the wrong row.
983    ///
984    /// Eval-only (no column storage).
985    Tid(u32, u32),
986    /// v7.37.5 ζ-A — PG `bit` / `bit varying`. `nbits` is the
987    /// actual bit count; `bytes` is the packed representation
988    /// (big-endian within each byte; final byte right-padded
989    /// with 0s if `nbits % 8 != 0`).
990    BitString {
991        nbits: u32,
992        bytes: Cow<'arena, [u8]>,
993    },
994    /// v7.37.5 ζ-A — PG `xml`. Stored verbatim as a string; no
995    /// parse-time validation (matches the SPG JSON convention).
996    Xml(Cow<'arena, str>),
997    /// v7.37.5 ζ-A — PG `"char"` (internal single-byte type,
998    /// distinct from CHAR(n)).
999    Char1(u8),
1000    /// v7.38 (read01, T11) — PG `bpchar` / CHAR(n): blank-padded fixed-length
1001    /// string. Stored space-padded to the declared width (as PG does + for wire
1002    /// display); length / comparison / ::text / concat all ignore the trailing
1003    /// blanks (handled at those sites).
1004    BpChar(Cow<'arena, str>),
1005    /// v7.37.5 ζ-A — PG `money[]`.
1006    MoneyArray(Vec<Option<i64>>),
1007    /// v7.12.0 `tsvector` — sorted-by-word, deduped lexeme set with
1008    /// positions + weights. The engine enforces sort/dedup on
1009    /// construction; consumers can rely on `lexemes.windows(2)`
1010    /// being strictly ascending by `word`.
1011    TsVector(Vec<TsLexeme>),
1012    /// v7.12.0 `tsquery` — boolean / phrase parse tree over
1013    /// lexemes. Engine builds via `to_tsquery` family.
1014    TsQuery(TsQueryAst),
1015    /// v7.17.0 `uuid` — 128-bit identifier. Stored as 16 bytes
1016    /// (big-endian / network-byte order, same as RFC 4122).
1017    /// Display normalises to canonical lowercase 8-4-4-4-12
1018    /// hyphenated form. Equality is byte-wise.
1019    Uuid([u8; 16]),
1020    /// v7.17.0 Phase 3.P0-32 — PG `time` (without time zone) —
1021    /// i64 microseconds since 00:00:00. Range 0..86_400_000_000.
1022    /// Display: `HH:MM:SS` zero-padded, with optional `.ffffff`
1023    /// suffix when fractional is non-zero.
1024    Time(i64),
1025    /// v7.17.0 Phase 3.P0-33 — MySQL `YEAR` — u16 in range
1026    /// 1901..=2155 plus the special zero-year sentinel 0.
1027    /// Display always 4 digits zero-padded (`0000` for the
1028    /// sentinel; `1985`/`2007` otherwise).
1029    Year(u16),
1030    /// v7.17.0 Phase 3.P0-34 — PG `time with time zone` — i64
1031    /// microseconds since 00:00:00 in the LOCAL wall clock PLUS
1032    /// an i32 offset-from-UTC in seconds. PG preserves the
1033    /// offset on output, so the wall-clock value is NOT shifted
1034    /// to UTC at storage time. Offset range: ±50400 seconds
1035    /// (±14 hours).
1036    TimeTz {
1037        us: i64,
1038        offset_secs: i32,
1039    },
1040    /// v7.17.0 Phase 3.P0-35 — PG `money` — i64 cents
1041    /// (locale-independent storage; the en_US locale renders on
1042    /// display via `$N,NNN.CC`).
1043    Money(i64),
1044    /// v7.17.0 Phase 3.P0-39 — PG `hstore` value: flat
1045    /// `text => text` map with NULL value support. Insertion
1046    /// order preserved on input; duplicate keys take last-write-
1047    /// wins at parse time.
1048    Hstore(Vec<(String, Option<String>)>),
1049    /// v7.17.0 Phase 3.P0-40 — 2D INT matrix (row-major).
1050    IntArray2D(Vec<Vec<Option<i32>>>),
1051    /// v7.17.0 Phase 3.P0-40 — 2D BIGINT matrix (row-major).
1052    BigIntArray2D(Vec<Vec<Option<i64>>>),
1053    /// v7.17.0 Phase 3.P0-40 — 2D TEXT matrix (row-major).
1054    TextArray2D(Vec<Vec<Option<String>>>),
1055    /// v7.39 (read01 round 75) — see `DataType::BoolArray2D`.
1056    BoolArray2D(Vec<Vec<Option<bool>>>),
1057    /// v7.17.0 Phase 3.P0-38 — PG range value. One shape covers
1058    /// all six builtin range types; `kind` pins the element type
1059    /// (must match the column's `DataType::Range(kind)`).
1060    /// `lower` / `upper` are `None` for the unbounded sides;
1061    /// `lower_inc` / `upper_inc` mirror the canonical PG
1062    /// `[` / `(` / `]` / `)` bracket inclusivity. `empty=true`
1063    /// supersedes all other fields (the empty range has no
1064    /// bounds).
1065    Range {
1066        kind: RangeKind,
1067        // v7.37.42-arena Phase 1: Range bounds stay owned ('static).
1068        // Recursive arena lifetimes are awkward to migrate at this
1069        // phase and the SCALARSQ hot path doesn't construct ranges.
1070        lower: Option<alloc::boxed::Box<Value<'static>>>,
1071        upper: Option<alloc::boxed::Box<Value<'static>>>,
1072        lower_inc: bool,
1073        upper_inc: bool,
1074        empty: bool,
1075    },
1076    /// v7.38 (read01, T9) — a composite / record value (a `row(...)`
1077    /// constructor or a whole-row reference). Fields are `(name, value)`; the
1078    /// names are `f1..fN` for an anonymous `row(...)` or the source column
1079    /// names for a table row. Transient — flows through row_to_json / to_json
1080    /// and the composite text form `(a,b)`; not a storable column type here.
1081    Composite(alloc::vec::Vec<(alloc::string::String, Value<'static>)>),
1082    Null,
1083}
1084
1085/// Owned `Value` — heap-bearing variants are `Cow::Owned`. Used everywhere
1086/// a Value must outlive a query-scoped arena (catalog defaults, persistent
1087/// storage, public APIs).
1088pub type ValueOwned = Value<'static>;
1089
1090/// v7.37.5 ε — PG `point` building block. Shared by every other
1091/// geometric type (lseg / path / box / polygon / circle all
1092/// reduce to compositions of `Point2D`). Packed `{x: f64, y: f64}`,
1093/// 16 B, on-disk LE field order matches the PG binary point
1094/// format byte-for-byte (so a future binary BIND path lands
1095/// without rearrangement).
1096#[derive(Debug, Clone, Copy, PartialEq)]
1097pub struct Point2D {
1098    pub x: f64,
1099    pub y: f64,
1100}
1101
1102/// v7.37.5 δ — single-range bounds without the kind tag. Used as
1103/// the element type of `Value::Multirange { kind, ranges }` so a
1104/// multirange carries one shared `RangeKind` plus N bounds-only
1105/// spans (saves 1 byte/elem vs duplicating the kind). The five
1106/// other fields mirror `Value::Range` exactly.
1107#[derive(Debug, Clone, PartialEq)]
1108pub struct RangeSpan {
1109    // v7.37.42-arena Phase 1: stays owned ('static) — same rationale as
1110    // Range bounds above.
1111    pub lower: Option<alloc::boxed::Box<Value<'static>>>,
1112    pub upper: Option<alloc::boxed::Box<Value<'static>>>,
1113    pub lower_inc: bool,
1114    pub upper_inc: bool,
1115    pub empty: bool,
1116}
1117
1118/// v7.37.5 β-P4 — element type for `Value::IntervalArray`. Mirrors
1119/// the `{months, days, micros}` shape of scalar `Value::Interval`,
1120/// broken out as a named struct so `IntervalArray`'s element type
1121/// is concrete (24 bytes, packed) instead of an enum-boxed Value.
1122/// All three dimensions are independent — `IntervalSpan { days: 1,
1123/// .. }` is distinct from `IntervalSpan { micros: 86_400_000_000,
1124/// .. }` per PG byte-equal.
1125#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1126pub struct IntervalSpan {
1127    pub months: i32,
1128    pub days: i32,
1129    pub micros: i64,
1130    /// v7.38.19 — see [`IntervalKind`].
1131    pub kind: IntervalKind,
1132}
1133
1134impl<'arena> Value<'arena> {
1135    /// Type tag, or `None` for `NULL` (unknown at value level).
1136    pub fn data_type(&self) -> Option<DataType> {
1137        match self {
1138            Self::SmallInt(_) => Some(DataType::SmallInt),
1139            Self::Int(_) => Some(DataType::Int),
1140            Self::BigInt(_) => Some(DataType::BigInt),
1141            Self::Float(_) => Some(DataType::Float),
1142            Self::Real(_) => Some(DataType::Real),
1143            // `Text` covers both unbounded TEXT and bounded VARCHAR/CHAR
1144            // — the constraint lives on the column schema, not the value.
1145            Self::Text(_) => Some(DataType::Text),
1146            Self::Bool(_) => Some(DataType::Bool),
1147            Self::Vector(v) => Some(DataType::Vector {
1148                dim: u32::try_from(v.len()).expect("vector dim ≤ u32"),
1149                encoding: VecEncoding::F32,
1150            }),
1151            Self::Sq8Vector(q) => Some(DataType::Vector {
1152                dim: u32::try_from(q.bytes.len()).expect("vector dim ≤ u32"),
1153                encoding: VecEncoding::Sq8,
1154            }),
1155            Self::HalfVector(h) => Some(DataType::Vector {
1156                dim: u32::try_from(h.dim()).expect("vector dim ≤ u32"),
1157                encoding: VecEncoding::F16,
1158            }),
1159            // `Value::Numeric` doesn't carry its precision (the column
1160            // schema does); we surface precision=0 as "unknown" and let
1161            // the engine reconcile against the column type at coercion
1162            // time.
1163            // v7.39 (round 273) — a VALUE's display scale is unsigned and
1164            // never exceeds PG's 16383 ceiling, so it always fits the
1165            // signed declared-scale field this describes itself with.
1166            Self::Numeric { scale, .. } => Some(DataType::Numeric {
1167                precision: 0,
1168                scale: i16::try_from(*scale).unwrap_or(i16::MAX),
1169            }),
1170            Self::NumericBig(b) => Some(DataType::Numeric {
1171                precision: 0,
1172                scale: i16::try_from(b.scale()).unwrap_or(i16::MAX),
1173            }),
1174            Self::Date(_) => Some(DataType::Date),
1175            Self::Timestamp(_) => Some(DataType::Timestamp),
1176            Self::Interval { .. } => Some(DataType::Interval),
1177            Self::Json(_) => Some(DataType::Json),
1178            Self::Bytes(_) => Some(DataType::Bytes),
1179            Self::TextArray(_) => Some(DataType::TextArray),
1180            Self::IntArray(_) => Some(DataType::IntArray),
1181            Self::BigIntArray(_) => Some(DataType::BigIntArray),
1182            Self::IntervalArray(_) => Some(DataType::IntervalArray),
1183            Self::BoolArray(_) => Some(DataType::BoolArray),
1184            Self::SmallIntArray(_) => Some(DataType::SmallIntArray),
1185            Self::FloatArray(_) => Some(DataType::FloatArray),
1186            Self::NumericArray(_) => Some(DataType::NumericArray),
1187            Self::DateArray(_) => Some(DataType::DateArray),
1188            Self::TimestampArray(_) => Some(DataType::TimestampArray),
1189            Self::TimestamptzArray(_) => Some(DataType::TimestamptzArray),
1190            Self::UuidArray(_) => Some(DataType::UuidArray),
1191            Self::JsonArray(_) => Some(DataType::JsonArray),
1192            Self::JsonbArray(_) => Some(DataType::JsonbArray),
1193            Self::BytesArray(_) => Some(DataType::BytesArray),
1194            Self::VarcharArray(_) => Some(DataType::VarcharArray),
1195            Self::CharArray(_) => Some(DataType::CharArray),
1196            Self::Multirange { kind, .. } => Some(DataType::Multirange(*kind)),
1197            Self::Point(_) => Some(DataType::Point),
1198            Self::Lseg(_, _) => Some(DataType::Lseg),
1199            Self::Path { .. } => Some(DataType::Path),
1200            Self::PgBox(_, _) => Some(DataType::PgBox),
1201            Self::Polygon(_) => Some(DataType::Polygon),
1202            Self::Line { .. } => Some(DataType::Line),
1203            Self::Circle { .. } => Some(DataType::Circle),
1204            Self::Inet { .. } => Some(DataType::Inet),
1205            Self::Cidr { .. } => Some(DataType::Cidr),
1206            Self::Macaddr(_) => Some(DataType::Macaddr),
1207            Self::Macaddr8(_) => Some(DataType::Macaddr8),
1208            Self::PgLsn(_) => Some(DataType::PgLsn),
1209            // BitString could be either Bit or BitVarying; column
1210            // schema decides. Default to BitVarying when called
1211            // schema-less (rare; storage path is always
1212            // schema-aware so this only matters for diagnostics).
1213            Self::BitString { .. } => Some(DataType::BitVarying(0)),
1214            Self::Xml(_) => Some(DataType::Xml),
1215            Self::Char1(_) => Some(DataType::Char1),
1216            // BpChar reports its declared width from the padded length.
1217            Self::BpChar(s) => Some(DataType::Char(
1218                u32::try_from(s.chars().count()).unwrap_or(0),
1219            )),
1220            Self::MoneyArray(_) => Some(DataType::MoneyArray),
1221            Self::TsVector(_) => Some(DataType::TsVector),
1222            Self::TsQuery(_) => Some(DataType::TsQuery),
1223            Self::Uuid(_) => Some(DataType::Uuid),
1224            Self::Time(_) => Some(DataType::Time),
1225            Self::Year(_) => Some(DataType::Year),
1226            Self::TimeTz { .. } => Some(DataType::TimeTz),
1227            Self::Money(_) => Some(DataType::Money),
1228            Self::Range { kind, .. } => Some(DataType::Range(*kind)),
1229            Self::Hstore(_) => Some(DataType::Hstore),
1230            Self::IntArray2D(_) => Some(DataType::IntArray2D),
1231            Self::BigIntArray2D(_) => Some(DataType::BigIntArray2D),
1232            Self::TextArray2D(_) => Some(DataType::TextArray2D),
1233            Self::BoolArray2D(_) => Some(DataType::BoolArray2D),
1234            // v7.38 (read01, T9) — a transient composite/record has no storable
1235            // column DataType (it flows through row_to_json / to_json).
1236            Self::Composite(_) => None,
1237            // v7.39 (read01 ruleutils.c) — regclass is eval-only (dual
1238            // oid+name shape); no column storage type.
1239            // v7.39 (round 640) — `xid` became a column type, so its value
1240            // has a DataType to answer with. `cid` and `tid` are equally
1241            // legal column types on PG (measured: `CREATE TABLE t (a cid,
1242            // b tid)` is accepted), but SPG's grammar has no keyword for
1243            // them yet; they stay eval-only rather than half-declared.
1244            Self::Xid(_) => Some(DataType::Xid),
1245            Self::RegClass(..)
1246            | Self::RegProc(..)
1247            | Self::RegType(..)
1248            | Self::Tid(..)
1249            | Self::Cid(_) => None,
1250            Self::Null => None,
1251        }
1252    }
1253
1254    pub const fn is_null(&self) -> bool {
1255        matches!(self, Self::Null)
1256    }
1257
1258    /// v7.37.42-arena Phase 1: lift any `Value<'arena>` (possibly
1259    /// borrowing from a bump arena) into a fully-owned `Value<'static>`.
1260    /// Used at boundaries that must outlive the per-query arena
1261    /// (catalog write, public QueryResult emit, sqlx materialise).
1262    ///
1263    /// For the recursive Range/Multirange variants — bounds are already
1264    /// `Box<Value<'static>>` per Phase 1 design, so we just rebuild the
1265    /// outer enum at `'static`.
1266    pub fn into_owned(self) -> Value<'static> {
1267        match self {
1268            Value::SmallInt(n) => Value::SmallInt(n),
1269            Value::Int(n) => Value::Int(n),
1270            Value::BigInt(n) => Value::BigInt(n),
1271            Value::Float(f) => Value::Float(f),
1272            Value::Real(f) => Value::Real(f),
1273            Value::Text(s) => Value::Text(Cow::Owned(s.into_owned())),
1274            Value::Bool(b) => Value::Bool(b),
1275            Value::Vector(v) => Value::Vector(Cow::Owned(v.into_owned())),
1276            Value::Sq8Vector(q) => Value::Sq8Vector(q),
1277            Value::HalfVector(h) => Value::HalfVector(h),
1278            Value::Numeric {
1279                scaled,
1280                scale,
1281                kind,
1282            } => Value::Numeric {
1283                scaled,
1284                scale,
1285                kind,
1286            },
1287            Value::NumericBig(b) => Value::NumericBig(b),
1288            Value::Date(d) => Value::Date(d),
1289            Value::Timestamp(t) => Value::Timestamp(t),
1290            Value::Interval {
1291                months,
1292                days,
1293                micros,
1294                kind,
1295            } => Value::Interval {
1296                months,
1297                days,
1298                micros,
1299                kind,
1300            },
1301            Value::Json(s) => Value::Json(Cow::Owned(s.into_owned())),
1302            Value::Bytes(b) => Value::Bytes(Cow::Owned(b.into_owned())),
1303            Value::TextArray(v) => Value::TextArray(v),
1304            Value::IntArray(v) => Value::IntArray(v),
1305            Value::BigIntArray(v) => Value::BigIntArray(v),
1306            Value::IntervalArray(v) => Value::IntervalArray(v),
1307            Value::BoolArray(v) => Value::BoolArray(v),
1308            Value::SmallIntArray(v) => Value::SmallIntArray(v),
1309            Value::FloatArray(v) => Value::FloatArray(v),
1310            Value::NumericArray(v) => Value::NumericArray(v),
1311            Value::DateArray(v) => Value::DateArray(v),
1312            Value::TimestampArray(v) => Value::TimestampArray(v),
1313            Value::TimestamptzArray(v) => Value::TimestamptzArray(v),
1314            Value::UuidArray(v) => Value::UuidArray(v),
1315            Value::JsonArray(v) => Value::JsonArray(v),
1316            Value::JsonbArray(v) => Value::JsonbArray(v),
1317            Value::BytesArray(v) => Value::BytesArray(v),
1318            Value::VarcharArray(v) => Value::VarcharArray(v),
1319            Value::CharArray(v) => Value::CharArray(v),
1320            Value::Multirange { kind, ranges } => Value::Multirange { kind, ranges },
1321            // v7.38 (read01, T9) — Composite fields are already `Value<'static>`.
1322            Value::Composite(fields) => Value::Composite(fields),
1323            Value::RegClass(oid, name) => Value::RegClass(oid, name),
1324            Value::Tid(b, o) => Value::Tid(b, o),
1325            Value::Xid(x) => Value::Xid(x),
1326            Value::Cid(c) => Value::Cid(c),
1327            Value::RegProc(oid, name) => Value::RegProc(oid, name),
1328            Value::RegType(oid, name) => Value::RegType(oid, name),
1329            Value::Point(p) => Value::Point(p),
1330            Value::Lseg(a, b) => Value::Lseg(a, b),
1331            Value::Path { points, closed } => Value::Path { points, closed },
1332            Value::PgBox(a, b) => Value::PgBox(a, b),
1333            Value::Polygon(p) => Value::Polygon(p),
1334            Value::Line { a, b, c } => Value::Line { a, b, c },
1335            Value::Circle { center, radius } => Value::Circle { center, radius },
1336            Value::Inet { family, bits, addr } => Value::Inet { family, bits, addr },
1337            Value::Cidr { family, bits, addr } => Value::Cidr { family, bits, addr },
1338            Value::Macaddr(m) => Value::Macaddr(m),
1339            Value::Macaddr8(m) => Value::Macaddr8(m),
1340            Value::PgLsn(l) => Value::PgLsn(l),
1341            Value::BitString { nbits, bytes } => Value::BitString {
1342                nbits,
1343                bytes: Cow::Owned(bytes.into_owned()),
1344            },
1345            Value::Xml(s) => Value::Xml(Cow::Owned(s.into_owned())),
1346            Value::Char1(c) => Value::Char1(c),
1347            Value::BpChar(s) => Value::BpChar(Cow::Owned(s.into_owned())),
1348            Value::MoneyArray(v) => Value::MoneyArray(v),
1349            Value::TsVector(v) => Value::TsVector(v),
1350            Value::TsQuery(q) => Value::TsQuery(q),
1351            Value::Uuid(u) => Value::Uuid(u),
1352            Value::Time(t) => Value::Time(t),
1353            Value::Year(y) => Value::Year(y),
1354            Value::TimeTz { us, offset_secs } => Value::TimeTz { us, offset_secs },
1355            Value::Money(m) => Value::Money(m),
1356            Value::Range {
1357                kind,
1358                lower,
1359                upper,
1360                lower_inc,
1361                upper_inc,
1362                empty,
1363            } => Value::Range {
1364                kind,
1365                lower,
1366                upper,
1367                lower_inc,
1368                upper_inc,
1369                empty,
1370            },
1371            Value::Hstore(h) => Value::Hstore(h),
1372            Value::IntArray2D(a) => Value::IntArray2D(a),
1373            Value::BigIntArray2D(a) => Value::BigIntArray2D(a),
1374            Value::TextArray2D(a) => Value::TextArray2D(a),
1375            Value::BoolArray2D(a) => Value::BoolArray2D(a),
1376            Value::Null => Value::Null,
1377        }
1378    }
1379
1380    /// v7.37.42-arena Phase 4 — copy heap payloads into the supplied
1381    /// bump arena, yielding a `Value<'a>` whose Cow-variant payloads
1382    /// are arena-borrowed (or stay as small owned scalars for the
1383    /// `Copy`-able variants).
1384    ///
1385    /// Used at the catalog ↔ ephemeral boundary: a `ColumnSchema.default`
1386    /// is `Value<'static>` but INSERT-time eval may want it stamped into
1387    /// the per-statement arena alongside other arena-built scalars.
1388    ///
1389    /// Allocates only into the supplied arena; the input `&self` keeps
1390    /// its own storage. For `Copy`-able / nested-owned variants the
1391    /// implementation falls back to `clone()` (the nested heap blocks
1392    /// stay on the global allocator, which is fine — the boundary
1393    /// requirement is just "no aliasing of caller-owned strings").
1394    pub fn clone_into<'a>(&self, arena: &'a bumpalo::Bump) -> Value<'a> {
1395        match self {
1396            Value::Text(s) => Value::Text(Cow::Borrowed(arena.alloc_str(s))),
1397            Value::Json(s) => Value::Json(Cow::Borrowed(arena.alloc_str(s))),
1398            Value::Xml(s) => Value::Xml(Cow::Borrowed(arena.alloc_str(s))),
1399            Value::BpChar(s) => Value::BpChar(Cow::Borrowed(arena.alloc_str(s))),
1400            Value::Bytes(b) => {
1401                let slot = arena.alloc_slice_copy::<u8>(b);
1402                Value::Bytes(Cow::Borrowed(slot))
1403            }
1404            Value::Vector(v) => {
1405                let slot = arena.alloc_slice_copy::<f32>(v);
1406                Value::Vector(Cow::Borrowed(slot))
1407            }
1408            Value::BitString { nbits, bytes } => {
1409                let slot = arena.alloc_slice_copy::<u8>(bytes);
1410                Value::BitString {
1411                    nbits: *nbits,
1412                    bytes: Cow::Borrowed(slot),
1413                }
1414            }
1415            // Copy-able scalars + variants whose nested heap blocks are
1416            // `'static` regardless of `'arena` (TextArray, JsonArray,
1417            // Hstore, TsVector, Range bounds, …). Clone the heap block
1418            // via the standard `into_owned()` path then lift the
1419            // resulting `Value<'static>` to `Value<'a>` via the Cow
1420            // variance — `'static` covers any lifetime.
1421            other => other.clone().into_owned(),
1422        }
1423    }
1424}
1425
1426impl Value<'static> {
1427    /// v7.37.42-arena Phase 1 — owned-Text constructor. The variant now
1428    /// holds `Cow<'arena, str>`, so the previous `Value::Text(String)`
1429    /// shape no longer compiles directly. This helper preserves the
1430    /// historical ergonomics: `Value::text("foo")` or
1431    /// `Value::text(String::from("foo"))`.
1432    pub fn text<S: Into<String>>(s: S) -> Self {
1433        Value::Text(Cow::Owned(s.into()))
1434    }
1435
1436    /// v7.38 (read01, T6) — a finite NUMERIC from its fixed-point parts.
1437    pub const fn numeric(scaled: i128, scale: u16) -> Self {
1438        Value::Numeric {
1439            scaled,
1440            scale,
1441            kind: NumericKind::Finite,
1442        }
1443    }
1444
1445    /// v7.38 (read01, T6) — a special NUMERIC (NaN / ±Infinity). The fixed-point
1446    /// fields are canonicalized to 0 so equal specials compare byte-identical.
1447    pub const fn numeric_special(kind: NumericKind) -> Self {
1448        Value::Numeric {
1449            scaled: 0,
1450            scale: 0,
1451            kind,
1452        }
1453    }
1454
1455    /// v7.37.42-arena Phase 1 — owned-Json constructor (mirrors `text`).
1456    pub fn json<S: Into<String>>(s: S) -> Self {
1457        Value::Json(Cow::Owned(s.into()))
1458    }
1459
1460    /// v7.37.42-arena Phase 1 — owned-Xml constructor.
1461    pub fn xml<S: Into<String>>(s: S) -> Self {
1462        Value::Xml(Cow::Owned(s.into()))
1463    }
1464
1465    /// v7.37.42-arena Phase 1 — owned-Bytes constructor.
1466    pub fn bytes<B: Into<Vec<u8>>>(b: B) -> Self {
1467        Value::Bytes(Cow::Owned(b.into()))
1468    }
1469
1470    /// v7.37.42-arena Phase 1 — owned-Vector constructor.
1471    pub fn vector<V: Into<Vec<f32>>>(v: V) -> Self {
1472        Value::Vector(Cow::Owned(v.into()))
1473    }
1474
1475    /// v7.37.42-arena Phase 1 — owned-BitString constructor.
1476    pub fn bit_string<B: Into<Vec<u8>>>(nbits: u32, bytes: B) -> Self {
1477        Value::BitString {
1478            nbits,
1479            bytes: Cow::Owned(bytes.into()),
1480        }
1481    }
1482}
1483
1484/// One table row — values are positional and must match
1485/// `TableSchema.columns` in length and (modulo NULL) in `DataType`.
1486///
1487/// v7.37.42-arena Phase 1: parameterised on `'arena` so per-query rows
1488/// can borrow from a bump arena. The owned shape (`Row<'static>`, alias
1489/// `RowOwned`) is what catalog storage, public APIs, and tests use.
1490#[derive(Debug, Clone, PartialEq)]
1491pub struct Row<'arena> {
1492    pub values: Vec<Value<'arena>>,
1493}
1494
1495/// Owned `Row` — values are `Value<'static>`. Used everywhere a row must
1496/// outlive a query-scoped arena.
1497pub type RowOwned = Row<'static>;
1498
1499impl<'arena> Row<'arena> {
1500    pub const fn new(values: Vec<Value<'arena>>) -> Self {
1501        Self { values }
1502    }
1503
1504    pub fn len(&self) -> usize {
1505        self.values.len()
1506    }
1507
1508    pub fn is_empty(&self) -> bool {
1509        self.values.is_empty()
1510    }
1511}
1512
1513impl<'arena> Row<'arena> {
1514    /// v7.37.42-arena Phase 4 — copy every cell into the supplied bump
1515    /// arena, yielding a `Row<'a>` whose Cow-payloads are arena-borrowed.
1516    /// Boundary helper for catalog defaults → DML eval handoff and
1517    /// arena-local row scratch.
1518    pub fn clone_into<'a>(&self, arena: &'a bumpalo::Bump) -> Row<'a> {
1519        Row {
1520            values: self.values.iter().map(|v| v.clone_into(arena)).collect(),
1521        }
1522    }
1523
1524    /// v7.37.42-arena Phase 4 — lift this `Row<'arena>` to a fully-owned
1525    /// `Row<'static>` for catalog write / WAL serialisation. Equivalent
1526    /// to `Row::from_arena(self)` but consumes by value at any lifetime
1527    /// (callers can write `row.into_owned()` mirroring `Value::into_owned`).
1528    pub fn into_owned(self) -> Row<'static> {
1529        Row {
1530            values: self.values.into_iter().map(Value::into_owned).collect(),
1531        }
1532    }
1533}
1534
1535impl Row<'static> {
1536    /// v7.37.42-arena Phase 1 — lift any `Row<'arena>` (possibly arena-
1537    /// borrowed) into a fully-owned `Row<'static>`. Mirrors
1538    /// `Value::into_owned`.
1539    pub fn from_arena(row: Row<'_>) -> Self {
1540        Self {
1541            values: row.values.into_iter().map(Value::into_owned).collect(),
1542        }
1543    }
1544}
1545
1546/// Each bool is an independent, separately-persisted column attribute
1547/// (`nullable`, `auto_increment`, `is_unsigned`, `identity_always`) that the
1548/// catalog appendix reads and writes by name. Packing them into a bitflags
1549/// word would buy nothing and would put a decoding step between the on-disk
1550/// format and every reader of the schema.
1551#[allow(clippy::struct_excessive_bools)]
1552#[derive(Debug, Clone, PartialEq)]
1553pub struct ColumnSchema {
1554    pub name: String,
1555    pub ty: DataType,
1556    pub nullable: bool,
1557    /// Optional `DEFAULT` value, frozen at CREATE TABLE time. `None`
1558    /// means "no default" (so omitted columns become NULL, or error
1559    /// out when the column is NOT NULL). Literal defaults take this
1560    /// path.
1561    ///
1562    /// v7.37.42-arena Phase 1: explicitly `Value<'static>` — catalog
1563    /// defaults must outlive any per-query arena.
1564    pub default: Option<Value<'static>>,
1565    /// v7.9.21 — for DEFAULT expressions that need INSERT-time
1566    /// evaluation (e.g. `DEFAULT now()`, `DEFAULT CURRENT_TIMESTAMP`),
1567    /// the Display form of the expression. The engine re-parses
1568    /// it on each INSERT default-fill, evaluates against an empty
1569    /// row context, and coerces to the column type. mailrs G4.
1570    /// Persisted in catalog FILE_VERSION 15+; older catalogs
1571    /// deserialise with None.
1572    pub runtime_default: Option<String>,
1573    /// MySQL-style `AUTO_INCREMENT`. When set, an INSERT that leaves
1574    /// this column unbound (or sets it to NULL) gets the next integer
1575    /// computed from the column's current max + 1.
1576    /// v7.39 (round 676) — the collation NAME as written, when the column
1577    /// carried an explicit `COLLATE`.
1578    ///
1579    /// `spg_sql::Collation` cannot carry it: it is a two-variant MySQL enum
1580    /// and `from_collation_name` folds `C`, `POSIX`, `en_US` and `default`
1581    /// all into `Binary`. Without the name `pg_attribute.attcollation` can
1582    /// only ever report the type's default, which is what F36 records as
1583    /// "the declaration is taken and ignored".
1584    ///
1585    /// None means the column was written without a `COLLATE` clause and
1586    /// takes its type's collation. Persisted through the v88 appendix,
1587    /// which costs two bytes for a table that declares none.
1588    pub collation_name: Option<String>,
1589    pub auto_increment: bool,
1590    /// v7.17.0 Phase 1.4 — when the column is bound to a user-
1591    /// defined ENUM type (the parser saw an unknown type ident
1592    /// and the engine resolved it against `catalog.enum_types`),
1593    /// this carries the enum name so INSERT/UPDATE can validate
1594    /// the cell value against the enum's labels. `ty` is
1595    /// `DataType::Text` in that case. Persisted in catalog
1596    /// FILE_VERSION 29+; older catalogs deserialise with None.
1597    pub user_enum_type: Option<String>,
1598    /// v7.17.0 Phase 1.5 — when the column is bound to a user-
1599    /// defined DOMAIN (the parser saw an unknown type ident and
1600    /// the engine resolved it against `catalog.domain_types`),
1601    /// this carries the domain name. `ty` is the domain's base
1602    /// type; INSERT/UPDATE re-evaluates the domain's CHECK list
1603    /// + NOT NULL against the cell value. Persisted in catalog
1604    /// FILE_VERSION 30+; older catalogs deserialise with None.
1605    pub user_domain_type: Option<String>,
1606    /// v7.39 (read01 round 56) — when the column is bound to a user-defined
1607    /// COMPOSITE type. `ty` stays `DataType::Jsonb` (the on-disk form), but the
1608    /// engine REHYDRATES the stored JSON into a `Value::Composite` on read, so
1609    /// field access `(p).x`, `= ROW(…)`, ordering and the canonical `(2,b)`
1610    /// text form all work — they were already implemented on Value::Composite;
1611    /// what was missing was that the column never recorded WHICH composite type
1612    /// it holds (this field's doc comment existed for two releases, the field
1613    /// itself did not). Persisted in the composite-column appendix
1614    /// (FILE_VERSION 63+); older catalogs deserialise with None.
1615    pub user_composite_type: Option<String>,
1616    /// v7.39 (read01 round 59) — column-level privileges (PG
1617    /// `pg_attribute.attacl`). `GRANT SELECT (pub) ON t TO dan` lands here and
1618    /// does NOT touch the table's `relacl`. Empty = no column grant, which is
1619    /// every column until one is made.
1620    pub acl: Vec<AclItem>,
1621    /// v7.17.0 Phase 2.1 — MySQL `ON UPDATE CURRENT_TIMESTAMP`
1622    /// column attribute. When `Some(expr_src)`, an UPDATE that
1623    /// does NOT bind this column overrides the new value with
1624    /// the engine-evaluated expression (always `now()` in
1625    /// v7.17.0). Stored as Display-form source so storage
1626    /// stays free of spg-sql; the engine re-parses at UPDATE
1627    /// time. Persisted in catalog FILE_VERSION 32+; older
1628    /// catalogs deserialise with None — preserves the existing
1629    /// "silent ignore" behaviour for snapshots written before
1630    /// the upgrade.
1631    pub on_update_runtime: Option<String>,
1632    /// v7.17.0 Phase 2.5 — text collation. Pre-2.5 SPG accepted
1633    /// `COLLATE <name>` clauses but discarded the name, so a
1634    /// column declared `COLLATE "case_insensitive"` (or any
1635    /// MySQL `_ci` collation) still compared byte-wise — a
1636    /// Tier-S silent failure where `WHERE name = 'foo'` never
1637    /// matched stored `'Foo'`. This carries the parser-derived
1638    /// classification so the engine's WHERE evaluator can route
1639    /// text equality through a case-aware compare. `Binary` (the
1640    /// default) preserves the prior byte-wise behaviour. Only
1641    /// CaseInsensitive lands in the catalog appendix — Binary
1642    /// columns stay implicit, keeping snapshots compact.
1643    /// Persisted in catalog FILE_VERSION 34+; older catalogs
1644    /// deserialise every column as `Binary`.
1645    pub collation: Collation,
1646    /// v7.17.0 Phase 4.4 — MySQL `UNSIGNED` modifier flag. Drives
1647    /// engine-side INSERT / UPDATE range enforcement (rejects
1648    /// negative values on UNSIGNED int columns). Pre-4.4 the
1649    /// parser consumed and discarded the keyword silently, so
1650    /// every UNSIGNED column quietly accepted negatives — a
1651    /// Tier-A correctness drift. Sparse: only UNSIGNED columns
1652    /// land in the catalog appendix; the default `false` keeps
1653    /// snapshots compact for the common signed-int path.
1654    /// Persisted in catalog FILE_VERSION 35+; older catalogs
1655    /// deserialise every column as `is_unsigned = false`.
1656    pub is_unsigned: bool,
1657    /// v7.17.0 Phase 3.P0-36 — MySQL inline `ENUM('a','b','c')`
1658    /// value list. Distinct from `user_enum_type` (which points
1659    /// to a separately CREATE TYPE'd PG enum); this carries the
1660    /// column-local list MySQL DDL declares inline. When `Some`,
1661    /// `ty` is `DataType::Text` and INSERT/UPDATE validates the
1662    /// cell value against this list. Variant ORDER is preserved
1663    /// (MySQL uses it for `ORDER BY col`). Sparse: only ENUM
1664    /// columns land in the catalog appendix.
1665    /// Persisted in catalog FILE_VERSION 41+; older catalogs
1666    /// deserialise with None — preserves silent-drop behaviour
1667    /// for snapshots written before P0-36.
1668    pub inline_enum_variants: Option<Vec<String>>,
1669    /// v7.17.0 Phase 3.P0-37 — MySQL inline `SET('a','b','c')`
1670    /// variant list. Storage is TEXT (canonical comma-joined in
1671    /// definition order, de-duplicated). INSERT/UPDATE validates
1672    /// every comma-separated token against this list. Sparse:
1673    /// only SET columns land in the catalog appendix.
1674    /// Persisted in catalog FILE_VERSION 42+; older catalogs
1675    /// deserialise with None.
1676    pub inline_set_variants: Option<Vec<String>>,
1677    /// v7.37.7(sentori Epic 3 P1)— `GENERATED ALWAYS AS (<expr>)
1678    /// STORED` computed-column source. When `Some`, INSERT / UPDATE
1679    /// recompute the cell against the candidate row(re-parse the
1680    /// stored Display form and evaluate)and overwrite any
1681    /// user-supplied value, matching PG's stored-generated-column
1682    /// semantics. `None` (the default) preserves the regular
1683    /// "column value is whatever the caller passed" path.
1684    /// Persisted in catalog FILE_VERSION 50+; older catalogs
1685    /// deserialise with None.
1686    pub generated_stored_expr: Option<String>,
1687    /// v7.38 (read01) — `GENERATED ALWAYS AS IDENTITY`. Both identity
1688    /// flavours set `auto_increment`; this additionally marks the ALWAYS
1689    /// flavour, whose explicit INSERT value PG rejects ("cannot insert a
1690    /// non-DEFAULT value into column …") unless `OVERRIDING SYSTEM VALUE`.
1691    /// `false` (serial / `BY DEFAULT`) keeps the permissive path. In-memory
1692    /// only for now — not yet in the catalog appendix, so a reloaded table
1693    /// deserialises as `false` (the pre-existing permissive behaviour).
1694    pub identity_always: bool,
1695    /// v7.38 (read01) — the DEFAULT expression's source text, deparsed to
1696    /// PG-compatible form at CREATE TABLE time (e.g. `0`, `(3 + 4)`,
1697    /// `'hi'::text`, `now()`, `CURRENT_DATE`). Distinct from `default`
1698    /// (the coerced value the INSERT path fills) and `runtime_default`
1699    /// (the recompute-per-row Display form): those lose the source
1700    /// spelling, so `information_schema.columns.column_default` /
1701    /// `pg_attrdef` / `pg_get_expr` reported the coerced render
1702    /// (`0.00` for `numeric(10,2) DEFAULT 0`) instead of PG's `0`.
1703    /// `None` for a column with no explicit default. Persisted in catalog
1704    /// FILE_VERSION 58+; older catalogs deserialise with None.
1705    pub default_text: Option<String>,
1706    /// v7.39 (round 220) — `ALTER TABLE … ALTER COLUMN … RESTART [WITH n]`
1707    /// on an identity column. SPG's identity allocation is a max+1 scan;
1708    /// this floor lifts the next allocated value to at least `n`
1709    /// (`max(max+1, n)`) — exactly what a dump-restore RESTART needs, and
1710    /// safer than PG for a backward RESTART (no duplicate-key landmine).
1711    /// Persisted in the FILE_VERSION 73+ sparse appendix; older catalogs
1712    /// deserialise with None.
1713    pub auto_restart: Option<i64>,
1714    /// v7.39 (read01 round 78) — this column is the ONLY column of a FROM item
1715    /// that calls a function returning a BASE type, so the item's row type IS
1716    /// this column: a whole-row reference collapses to the value
1717    /// (`SELECT j FROM jsonb_array_elements('[1]') AS j` → `1`, PG). Runtime
1718    /// only — a catalogued table column is never one, and it is not persisted.
1719    pub scalar_row_source: bool,
1720    /// v7.39 (round 386, type-fidelity epic P1) — the declared MySQL narrow
1721    /// integer width (TINYINT / MEDIUMINT) whose range the storage `ty`
1722    /// (SmallInt / Int) is too wide to enforce. `None` for every other
1723    /// column. Drives the epic-P2 write-path range check. Persisted in the
1724    /// FILE_VERSION 81+ sparse appendix; older catalogs deserialise as None.
1725    pub mysql_int_width: Option<MysqlIntWidth>,
1726    /// v7.39 (round 424, type-fidelity epic) — the declared MySQL
1727    /// fractional-seconds precision of a temporal column: `DATETIME(3)` is
1728    /// `Some(3)`, a BARE `DATETIME` / `TIME` / `TIMESTAMP` is `Some(0)`
1729    /// (MySQL's default is zero — the fraction is dropped on write), and
1730    /// `None` means "not a MySQL-declared temporal column", which is every
1731    /// PG column and leaves microsecond behaviour untouched.
1732    ///
1733    /// Drives write-path truncation (toward zero) and render padding
1734    /// (exactly this many digits, `.000` when the fraction is zero).
1735    /// Persisted in the FILE_VERSION 82+ sparse appendix; older catalogs
1736    /// deserialise as None.
1737    pub mysql_fsp: Option<u8>,
1738    /// v7.39.2 — this column was DECLARED `TIMESTAMP` in a MySQL
1739    /// session.
1740    ///
1741    /// MySQL and MariaDB both keep `timestamp` and `datetime` apart in
1742    /// `SHOW CREATE TABLE`, `SHOW COLUMNS` and `information_schema`
1743    /// (measured on 9.7.2 and 12.3.3); SPG stores both as
1744    /// `DataType::Timestamp` and so reported `datetime` for both. A
1745    /// client dumping and reloading had the column's declared type
1746    /// SILENTLY CHANGED — and MySQL's TIMESTAMP is not DATETIME: it has
1747    /// a different range and converts to and from UTC.
1748    ///
1749    /// What this records is the SPELLING, which is the half a dump
1750    /// round-trips. The storage and the semantics are unchanged, and
1751    /// that gap is written down rather than papered over.
1752    ///
1753    /// Persisted in the FILE_VERSION 93+ sparse appendix; older
1754    /// catalogs deserialise as `false`.
1755    pub mysql_declared_timestamp: bool,
1756    /// v7.39.3 — a MySQL `FLOAT(m,d)` / `DOUBLE(m,d)`'s declared pair.
1757    ///
1758    /// The digits are NOT a display hint, which is what SPG's comment
1759    /// claimed and 7.39.2 recorded as a residual: MySQL 9.7.2 ROUNDS on
1760    /// write (3.14159265358979 into either stores 3.14) and refuses a
1761    /// value wider than `m` with errno 1264. SPG accepted the syntax and
1762    /// kept the full double, so a column declared for money held more
1763    /// precision than the schema said and every reader saw a different
1764    /// number from MySQL's.
1765    ///
1766    /// Persisted in the FILE_VERSION 94+ sparse appendix; older catalogs
1767    /// deserialise as None, which is "no declared pair".
1768    pub mysql_float_md: Option<(u8, u8)>,
1769}
1770
1771/// v7.17.0 Phase 2.5 — column-level text collation. Drives the
1772/// engine's WHERE / GROUP BY equality routing for `Value::Text`.
1773/// Only two variants are modelled in v7.17:
1774///   * `Binary`  — byte-wise comparison (the SPG default;
1775///                 matches PG `COLLATE "C"` / `pg_catalog.default`
1776///                 and MySQL `*_bin`).
1777///   * `CaseInsensitive` — ASCII case-folded comparison (like
1778///                 MySQL `*_ci` collations; PG has NO built-in
1779///                 collation of this name — round-761 audit: a
1780///                 nondeterministic ICU collation must be CREATEd
1781///                 there first). Non-ASCII bytes
1782///                 still compare byte-wise; full ICU folding is
1783///                 out of v7.17 scope.
1784/// New variants append at the end — older catalogs read missing
1785/// columns as `Binary`.
1786#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1787pub enum Collation {
1788    Binary,
1789    CaseInsensitive,
1790}
1791
1792/// v7.39 (round 386, type-fidelity epic P1) — the declared MySQL narrow
1793/// integer type for a column whose storage `DataType` cannot express it.
1794/// MySQL `TINYINT` (i8, -128..127) collapses to `DataType::SmallInt` (i16)
1795/// and `MEDIUMINT` (24-bit) to `DataType::Int` (i32) — both wider than the
1796/// declared type, so a range check against `ty` alone accepts out-of-range
1797/// values (`INSERT 128 INTO TINYINT` is stored silently where MariaDB
1798/// strict raises ERROR 1264). This annotation records the lost width so the
1799/// write path (epic P2) can enforce the real bounds. `SMALLINT` / `INT` /
1800/// `BIGINT` need no marker — their storage `DataType` is already faithful.
1801/// Sparse: only TINYINT / MEDIUMINT columns carry it; persisted in the
1802/// FILE_VERSION 81+ appendix, older catalogs deserialise as None.
1803#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1804pub enum MysqlIntWidth {
1805    /// MySQL `TINYINT` — signed -128..127, unsigned 0..255. Storage i16.
1806    Tiny,
1807    /// MySQL `SMALLINT UNSIGNED` — 0..65535. Storage widened to i32 (a
1808    /// signed SMALLINT keeps `DataType::SmallInt` and carries no marker).
1809    Small,
1810    /// MySQL `MEDIUMINT` — signed -8388608..8388607, unsigned 0..16777215.
1811    /// Storage i32.
1812    Medium,
1813    /// MySQL `INT UNSIGNED` — 0..4294967295. Storage widened to i64 (a
1814    /// signed INT keeps `DataType::Int` and carries no marker).
1815    Int,
1816    /// v7.39 (round 471, epic P4b) — MySQL `BIGINT UNSIGNED` —
1817    /// 0..18446744073709551615. i64 stops at 2^63-1, so the storage tag is
1818    /// widened to `Numeric` (i128-backed, scale 0), which already compares,
1819    /// orders, indexes and renders as an exact integer. A signed BIGINT
1820    /// keeps `DataType::BigInt` and carries no marker.
1821    Big,
1822}
1823
1824/// v7.39 (round 363, M4 P1) — MySQL's default accent- and
1825/// case-insensitive fold (`utf8mb4_uca1400_ai_ci`).
1826///
1827/// This is the primitive M4 rests on: a session on the MySQL dialect
1828/// compares, groups, sorts and de-duplicates text by its FOLDED form, so
1829/// `Foo` = `foo` = `FOO` and, because the default collation is accent-
1830/// insensitive too, `Bär` = `bar`. The later stages (read path, then the
1831/// UNIQUE / index write path) all route through here so they cannot fold
1832/// differently from one another.
1833///
1834/// The fold is more than case + strip-combining: MariaDB EXPANDS some
1835/// letters — `ß` → `ss`, `æ` → `ae`, `œ` → `oe` — which is why the result
1836/// is built as a `String` rather than mapped char-for-char. Every mapping
1837/// below was measured on MariaDB 11 (`'Bär'='bar'` is 1, `'straße'=
1838/// 'strasse'` is 1, `'a'='æ'` is 0, `'s'='ß'` is 0). Characters with no
1839/// entry keep their lower-cased self, so ASCII and unknown scripts pass
1840/// through unchanged.
1841#[must_use]
1842pub fn mysql_ci_fold(s: &str) -> String {
1843    let mut out = String::with_capacity(s.len());
1844    for ch in s.chars() {
1845        // Lower-case first (`À` → `à`, `Æ` → `æ`), then fold the base.
1846        for lc in ch.to_lowercase() {
1847            match fold_latin_base(lc) {
1848                Some(base) => out.push_str(base),
1849                None => out.push(lc),
1850            }
1851        }
1852    }
1853    out
1854}
1855
1856/// The fold used to COMPARE / GROUP / de-dup text on the MySQL dialect:
1857/// case- and accent-insensitive, and **trailing spaces significant**.
1858///
1859/// v7.38.17 — this used to strip trailing spaces first, and its comment
1860/// said why: "measured on MariaDB 11". MariaDB's default collation is
1861/// PAD SPACE, so that measurement was right about MariaDB. SPG
1862/// advertises `8.0.0-spg-v…` on the MySQL wire, and MySQL 8.0's default
1863/// `utf8mb4_0900_ai_ci` is **NO PAD**. The rule had been calibrated
1864/// against the engine we do not claim to be.
1865///
1866/// Measured today, MySQL 9.7.2 against MariaDB 12.3.2, each in its own
1867/// default collation, over rows `'alpha'` and `'alpha  '`:
1868///
1869/// | | MySQL | MariaDB |
1870/// |---|---|---|
1871/// | `WHERE s = 'alpha'` | 1 | 1,2 |
1872/// | `s IN ('alpha','beta')` | 1,3,4 | 1,2,3,4 |
1873/// | `COUNT(DISTINCT s)` | 3 | 2 |
1874/// | `GROUP BY s` groups | 3 | 2 |
1875/// | `JOIN ON v.s = r.s` | 1/10, 2/20 | all four pairs |
1876///
1877/// SPG answered MariaDB's four and MySQL's join — the same question
1878/// decided differently by two paths, which is the shape v7.38.13,
1879/// v7.38.14 and v7.38.16 were each spent on.
1880///
1881/// `CHAR(n)` is a separate question and keeps its old answer: BOTH
1882/// engines ignore a CHAR's trailing spaces, because that is a property
1883/// of the TYPE rather than of the collation. Use
1884/// [`mysql_compare_fold_char`] for a `BpChar` cell.
1885///
1886/// Only literal spaces ever padded — a tab is significant either way —
1887/// and neither function is used by `LIKE`, whose pattern treats a
1888/// trailing space literally.
1889/// Whether a collation of this NAME orders by bytes.
1890///
1891/// v7.38.18 (S0) — pure string classification, and it lives here because
1892/// storage has to ask it: an index whose column collates by a locale
1893/// cannot key on the raw text, and the write path is here. The engine's
1894/// `collate::is_byte_wise` delegates to this one, for the reason the SQL
1895/// type spellings have one owner.
1896///
1897/// `C`, `POSIX`, MySQL's `binary` and every `_bin` family member. The
1898/// encoding suffix rides along: PG publishes `C.utf8` beside `C`.
1899pub fn collation_is_byte_wise(collation: &str) -> bool {
1900    let name = collation.trim();
1901    let base = name.split(['.', '@']).next().unwrap_or(name);
1902    base.eq_ignore_ascii_case("C")
1903        || base.eq_ignore_ascii_case("POSIX")
1904        || base.eq_ignore_ascii_case("binary")
1905        || base
1906            .rsplit_once('_')
1907            .is_some_and(|(_, tail)| tail.eq_ignore_ascii_case("bin"))
1908}
1909
1910/// v7.38.18 (S0/S2) — does an index on a column of this collation key
1911/// by an ICU SORT KEY rather than by the raw text?
1912///
1913/// True for a locale collation (`en_US.utf8`, `de_DE`), which orders by
1914/// rules a byte comparison cannot express.
1915///
1916/// False for byte-wise names, and false for MySQL's folding collations
1917/// (`utf8mb4_0900_ai_ci` and family). Those fold rather than collate,
1918/// and the engine has folded them since v7.37 — routing them here made
1919/// an indexed `s = 'ALPHA'` over the MySQL wire answer nothing where
1920/// MySQL 9.7.1 answers one row, because ICU at PG's strength does not
1921/// call `ALPHA` and `alpha` equal.
1922///
1923/// One owner for the same reason the byte-wise question has one: the
1924/// engine builds the PROBE and this crate builds the ENTRIES, and a
1925/// probe built in another space finds nothing — which reads exactly
1926/// like "no matching rows".
1927pub fn collation_uses_sort_key(collation: &str) -> bool {
1928    if collation_is_byte_wise(collation) {
1929        return false;
1930    }
1931    let name = collation.trim();
1932    let base = name.split(['.', '@']).next().unwrap_or(name);
1933    let lower = base.to_ascii_lowercase();
1934    !(lower.ends_with("_ci") || lower.ends_with("_cs"))
1935}
1936
1937pub fn mysql_compare_fold(s: &str) -> String {
1938    mysql_ci_fold(s)
1939}
1940
1941/// The comparison form of one text value under the MySQL default
1942/// collation, or `None` for a value that is not text.
1943///
1944/// v7.38.18 — one function, applied to each side SEPARATELY, because
1945/// the pair is not the unit. Several sites matched
1946/// `(Text, Text) | (BpChar, BpChar)` and folded a pair; a CHAR compared
1947/// against a VARCHAR or against a literal is neither shape, so it fell
1948/// through and was compared by bytes — with the CHAR still carrying its
1949/// padding. `CASE c WHEN 'ALPHA'` on a `CHAR(8)` holding `'alpha'`
1950/// answered ELSE where MySQL 9.7.2 answers the branch.
1951///
1952/// Folding per value also states the rule correctly: whether trailing
1953/// spaces count is a property of EACH side's own type, so a pair whose
1954/// sides differ has two answers rather than one.
1955pub fn mysql_fold_value(v: &Value<'_>) -> Option<String> {
1956    match v {
1957        Value::BpChar(s) => Some(mysql_compare_fold_char(s)),
1958        Value::Text(s) => Some(mysql_compare_fold(s)),
1959        _ => None,
1960    }
1961}
1962
1963/// [`mysql_compare_fold`] for a `CHAR(n)` cell, whose trailing spaces
1964/// are padding rather than data.
1965///
1966/// Measured on both engines: over `'alpha'` and `'alpha  '` in a
1967/// `CHAR(8)`, `WHERE s = 'alpha'` returns both rows and
1968/// `COUNT(DISTINCT s)` is 2 (four rows folding to two values) — MySQL
1969/// 9.7.2 and MariaDB 12.3.2 agree, unlike the VARCHAR case above.
1970pub fn mysql_compare_fold_char(s: &str) -> String {
1971    mysql_ci_fold(s.trim_end_matches(' '))
1972}
1973
1974/// The base letter(s) a lower-cased Latin character folds to, or `None`
1975/// when it is already a base / has no fold. Expansions (`ß` → `ss`) are
1976/// why this returns a string.
1977fn fold_latin_base(c: char) -> Option<&'static str> {
1978    Some(match c {
1979        'à' | 'á' | 'â' | 'ã' | 'ä' | 'å' | 'ā' | 'ă' | 'ą' => "a",
1980        'æ' => "ae",
1981        'ç' | 'ć' | 'č' | 'ĉ' | 'ċ' => "c",
1982        'ð' | 'ď' | 'đ' => "d",
1983        'è' | 'é' | 'ê' | 'ë' | 'ē' | 'ĕ' | 'ė' | 'ę' | 'ě' => "e",
1984        'ĝ' | 'ğ' | 'ġ' | 'ģ' => "g",
1985        'ì' | 'í' | 'î' | 'ï' | 'ĩ' | 'ī' | 'ĭ' | 'į' => "i",
1986        'ĵ' => "j",
1987        'ķ' => "k",
1988        'ł' | 'ĺ' | 'ļ' | 'ľ' => "l",
1989        'ñ' | 'ń' | 'ņ' | 'ň' => "n",
1990        'ò' | 'ó' | 'ô' | 'õ' | 'ö' | 'ø' | 'ō' | 'ŏ' | 'ő' => "o",
1991        'œ' => "oe",
1992        'ŕ' | 'ŗ' | 'ř' => "r",
1993        'ś' | 'š' | 'ŝ' | 'ş' => "s",
1994        'ß' => "ss",
1995        'ţ' | 'ť' | 'ŧ' => "t",
1996        'ù' | 'ú' | 'û' | 'ü' | 'ũ' | 'ū' | 'ŭ' | 'ů' | 'ű' | 'ų' => "u",
1997        'ý' | 'ÿ' => "y",
1998        'ź' | 'ž' | 'ż' => "z",
1999        _ => return None,
2000    })
2001}
2002
2003#[allow(clippy::derivable_impls)]
2004impl Default for Collation {
2005    fn default() -> Self {
2006        Self::Binary
2007    }
2008}
2009
2010impl Collation {
2011    /// Wire tag persisted in the FILE_VERSION 34+ catalog appendix.
2012    /// Stable: future variants append above the recognised range
2013    /// and unknown tags read back as `Binary` for forward-compat
2014    /// on rollback.
2015    pub const TAG_BINARY: u8 = 0;
2016    pub const TAG_CASE_INSENSITIVE: u8 = 1;
2017}
2018
2019/// v7.39 (RLS) — the command a policy applies to. `ALL` is the default and
2020/// covers every command; the others scope the policy to one statement kind.
2021/// Persisted as a single byte in the policy appendix (FILE_VERSION 59+).
2022#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2023pub enum PolicyCmd {
2024    All,
2025    Select,
2026    Insert,
2027    Update,
2028    Delete,
2029}
2030
2031impl PolicyCmd {
2032    /// PG `pg_policy.polcmd` single-char encoding.
2033    #[must_use]
2034    pub const fn as_pg_char(self) -> char {
2035        match self {
2036            Self::All => '*',
2037            Self::Select => 'r',
2038            Self::Insert => 'a',
2039            Self::Update => 'w',
2040            Self::Delete => 'd',
2041        }
2042    }
2043
2044    /// PG `pg_policies.cmd` word form.
2045    #[must_use]
2046    pub const fn as_pg_word(self) -> &'static str {
2047        match self {
2048            Self::All => "ALL",
2049            Self::Select => "SELECT",
2050            Self::Insert => "INSERT",
2051            Self::Update => "UPDATE",
2052            Self::Delete => "DELETE",
2053        }
2054    }
2055
2056    #[must_use]
2057    pub const fn to_wire_byte(self) -> u8 {
2058        match self {
2059            Self::All => 0,
2060            Self::Select => 1,
2061            Self::Insert => 2,
2062            Self::Update => 3,
2063            Self::Delete => 4,
2064        }
2065    }
2066
2067    #[must_use]
2068    pub const fn from_wire_byte(b: u8) -> Option<Self> {
2069        match b {
2070            0 => Some(Self::All),
2071            1 => Some(Self::Select),
2072            2 => Some(Self::Insert),
2073            3 => Some(Self::Update),
2074            4 => Some(Self::Delete),
2075            _ => None,
2076        }
2077    }
2078}
2079
2080/// v7.39 (RLS) — one `CREATE POLICY` object, stored per table. The `using_expr`
2081/// / `with_check_expr` hold the qualifying expression's `Display` form
2082/// (re-parsed and evaluated per row at enforcement time, exactly like
2083/// `TableSchema.checks`); `None` means the clause was absent. `roles` empty =
2084/// PUBLIC. Persisted in the policy appendix (FILE_VERSION 59+).
2085#[derive(Debug, Clone, PartialEq)]
2086pub struct PolicyDef {
2087    pub name: String,
2088    pub cmd: PolicyCmd,
2089    /// `true` = PERMISSIVE (default, OR-combined), `false` = RESTRICTIVE
2090    /// (AND-combined).
2091    pub permissive: bool,
2092    pub roles: Vec<String>,
2093    pub using_expr: Option<String>,
2094    pub with_check_expr: Option<String>,
2095}
2096
2097#[derive(Debug, Clone, PartialEq)]
2098pub struct TableSchema {
2099    pub name: String,
2100    pub columns: Vec<ColumnSchema>,
2101    /// v6.7.2 — per-table hot-tier byte budget override. `None`
2102    /// falls through to the global `SPG_HOT_TIER_BYTES` setting;
2103    /// `Some(n)` overrides it for this specific table. Set via
2104    /// `ALTER TABLE t SET hot_tier_bytes = X`. Persisted in
2105    /// catalog FILE_VERSION 11+.
2106    pub hot_tier_bytes: Option<u64>,
2107    /// v7.6.1 — FOREIGN KEY constraints declared on this table.
2108    /// Engine maintains this in lock-step with `spg-sql`'s parser
2109    /// AST; the storage layer carries the on-disk shape so a
2110    /// catalog snapshot round-trips without external mapping.
2111    /// Persisted in catalog FILE_VERSION 13+. Older catalogs
2112    /// deserialise with an empty vec.
2113    pub foreign_keys: Vec<ForeignKeyConstraint>,
2114    /// v7.9.19 — composite UNIQUE / PRIMARY KEY constraints
2115    /// declared at the table level. Each entry's leading column
2116    /// has a BTree index (created via the constraint), and INSERT
2117    /// path enforces the full-tuple uniqueness via a scan keyed
2118    /// by the leading column. Persisted in catalog FILE_VERSION
2119    /// 15+. Older catalogs (≤ 14) deserialise with an empty vec.
2120    pub uniqueness_constraints: Vec<UniquenessConstraint>,
2121    /// v7.39 (round 210) — `EXCLUDE` constraints declared at the table level.
2122    /// Enforced on INSERT/UPDATE by a full live-row scan re-checking each
2123    /// element's operator (no equality index can answer overlap). Persisted
2124    /// in catalog FILE_VERSION 72+; older catalogs deserialise with an empty
2125    /// vec.
2126    pub exclusion_constraints: Vec<ExclusionConstraint>,
2127    /// v7.13.0 — `CHECK (<expr>)` predicates declared on this
2128    /// table. Both column-level inline `CHECK (…)` and
2129    /// table-level `CHECK (…)` fold into this list. Each entry
2130    /// is the AST Expr's `Display` form, re-parsed on every
2131    /// INSERT/UPDATE and evaluated against the candidate row.
2132    /// A false / NULL result rejects the mutation (PG semantics).
2133    /// Persisted in catalog FILE_VERSION 23+. Older catalogs
2134    /// deserialise with an empty vec. v7.39 (read01 round 48) — each entry
2135    /// now carries the user's constraint name too (FILE_VERSION 60+).
2136    pub checks: Vec<CheckConstraint>,
2137    /// v7.37.6-B — declarative partition role(sentori Epic 2 P0).
2138    /// `None` = 普通表(后向兼容,< v49 catalog 默认 None)。
2139    /// `Some(Parent { … })` = `CREATE TABLE p (...) PARTITION BY RANGE (key_col)` 父表 —
2140    /// 父表自己 `rows` 永远空,INSERT 在引擎层路由到命中的 child。
2141    /// `Some(Range { … })` = `CREATE TABLE c PARTITION OF p FOR VALUES FROM (a) TO (b)` 范围子表。
2142    /// `Some(Default { … })` = `CREATE TABLE c PARTITION OF p DEFAULT` 兜底子表。
2143    /// 持久化于 FILE_VERSION 49+。
2144    pub partition_role: Option<PartitionRole>,
2145    /// v7.39 (RLS) — `CREATE POLICY` objects on this table, independent of the
2146    /// `row_security` flag (PG stores policies even on non-RLS tables; they
2147    /// only take effect once RLS is enabled). Persisted in the policy appendix
2148    /// (FILE_VERSION 59+). Older catalogs deserialise with an empty vec.
2149    pub policies: Vec<PolicyDef>,
2150    /// v7.39 (RLS) — `ALTER TABLE … ENABLE ROW LEVEL SECURITY`
2151    /// (PG `pg_class.relrowsecurity`). Fresh table = `false`.
2152    pub row_security: bool,
2153    /// v7.39 (RLS) — `ALTER TABLE … FORCE ROW LEVEL SECURITY`
2154    /// (PG `pg_class.relforcerowsecurity`); subjects the table owner to RLS
2155    /// too. Fresh table = `false`.
2156    pub force_row_security: bool,
2157    /// v7.39 (read01 round 57, ACL) — the role that owns this table: whoever
2158    /// ran CREATE TABLE (PG `pg_class.relowner`). The owner holds every
2159    /// privilege implicitly and is the only role that may ALTER / DROP it.
2160    /// `None` = an image written before FILE_VERSION 64, which predates roles
2161    /// entirely; those tables read back as owned by the login role.
2162    pub owner: Option<String>,
2163    /// v7.39 (read01 round 57, ACL) — explicit GRANTs on this table
2164    /// (PG `pg_class.relacl`). EMPTY means "never granted": PG leaves relacl
2165    /// NULL while only the owner's implicit privileges apply, and materialises
2166    /// the whole list — owner's default entry included — on the first GRANT.
2167    /// Once materialised it stays, even after every grant is revoked.
2168    pub acl: Vec<AclItem>,
2169}
2170
2171/// v7.39 (read01 round 57) — one PG `aclitem`: what `grantee` may do to a
2172/// table, and who granted it. Renders as `grantee=privs/grantor`, with an
2173/// EMPTY grantee meaning PUBLIC (`=r/owner`).
2174#[derive(Debug, Clone, PartialEq, Eq)]
2175pub struct AclItem {
2176    /// The role the privileges are held by. Empty string = PUBLIC.
2177    pub grantee: String,
2178    /// Bitmask over `priv_bits`: which privileges are held.
2179    pub privs: u16,
2180    /// Bitmask over `priv_bits`: which of them carry WITH GRANT OPTION
2181    /// (PG renders those with a trailing `*` — `r*`).
2182    pub grantable: u16,
2183    /// The role that ran the GRANT.
2184    pub grantor: String,
2185}
2186
2187/// v7.39 (read01 round 57) — the table-privilege bits, in PG's `aclitem`
2188/// rendering order (`arwdDxtm`). The order matters: `relacl` output is
2189/// byte-compared against PG.
2190pub mod priv_bits {
2191    pub const INSERT: u16 = 1 << 0; // a
2192    pub const SELECT: u16 = 1 << 1; // r
2193    pub const UPDATE: u16 = 1 << 2; // w
2194    pub const DELETE: u16 = 1 << 3; // d
2195    pub const TRUNCATE: u16 = 1 << 4; // D
2196    pub const REFERENCES: u16 = 1 << 5; // x
2197    pub const TRIGGER: u16 = 1 << 6; // t
2198    pub const MAINTAIN: u16 = 1 << 7; // m
2199    /// v7.39 (read01 round 60) — the non-table privileges. They share the
2200    /// bitmask because an aclitem is an aclitem whatever it hangs off; which
2201    /// bits are MEANINGFUL depends on the object (a sequence has r / w / U, a
2202    /// schema has U / C, a database has C / c / T).
2203    pub const USAGE: u16 = 1 << 8; // U
2204    pub const CREATE: u16 = 1 << 9; // C
2205    pub const CONNECT: u16 = 1 << 10; // c
2206    pub const TEMPORARY: u16 = 1 << 11; // T
2207    pub const EXECUTE: u16 = 1 << 12; // X
2208    /// Every TABLE privilege — what `GRANT ALL ON <table>` grants and what a
2209    /// table's owner holds.
2210    pub const ALL: u16 =
2211        INSERT | SELECT | UPDATE | DELETE | TRUNCATE | REFERENCES | TRIGGER | MAINTAIN;
2212    /// `GRANT ALL ON SEQUENCE` — PG renders a sequence owner's default as `rwU`.
2213    pub const ALL_SEQUENCE: u16 = SELECT | UPDATE | USAGE;
2214    /// `GRANT ALL ON SCHEMA` — `UC`.
2215    pub const ALL_SCHEMA: u16 = USAGE | CREATE;
2216    /// `GRANT ALL ON DATABASE` — `CTc`.
2217    pub const ALL_DATABASE: u16 = CREATE | CONNECT | TEMPORARY;
2218    /// `GRANT ALL ON FUNCTION` — just `X`.
2219    pub const ALL_FUNCTION: u16 = EXECUTE;
2220}
2221
2222/// v7.37.6-B — partition 三态(parent / range child / default child)。
2223#[derive(Debug, Clone, PartialEq, Eq)]
2224pub enum PartitionRole {
2225    Parent {
2226        kind: PartitionKind,
2227        /// 父表 columns 中 key 列的下标(单列 v7.37.6-B,
2228        /// `Vec` 为将来扩多列预留)。
2229        key_column_positions: Vec<usize>,
2230        /// `CREATE INDEX ON parent (…)` 的 Display-form 源串。
2231        /// child 创建时再 parse + 在 child 上 execute,这样 future
2232        /// child 也自动继承父表索引。fan-out 实施在引擎层。
2233        index_template_sources: Vec<String>,
2234    },
2235    Range {
2236        parent_name: String,
2237        /// 半开区间下界(`>=`,SQL `FROM (lower)`).
2238        lower: PartitionBound,
2239        /// 半开区间上界(`<`,SQL `TO (upper)`).
2240        upper: PartitionBound,
2241    },
2242    /// v7.37.16 (16.1) — LIST child:行属于本 child iff key ∈ values。
2243    /// `values` 在 child 创建时从 SQL `FOR VALUES IN (lit, …)` 求值;
2244    /// 跟 PG 一样,显式 NULL ∈ values 由 caller 单独处理(不在
2245    /// PartitionBound 内表达 NULL)。
2246    List {
2247        parent_name: String,
2248        values: Vec<PartitionBound>,
2249    },
2250    /// v7.39 (round 645) — PG 表继承的 CHILD:`CREATE TABLE c (…)
2251    /// INHERITS (p1, p2)`。跟分区 child 的三个本质区别(实测 PG18):
2252    ///   * 父表**自己有行**(分区父表永远空),所以父表的联合体要含自身;
2253    ///   * `INSERT INTO 父表` **不路由**到 child(分区会路由);
2254    ///   * `DROP TABLE 父表` 不带 CASCADE **报错**(分区父表连子表一起删)。
2255    /// 多父继承合法,故 `parent_names` 是 Vec;`pg_inherits.inhseqno`
2256    /// 正是父表在这个列表里的位置(1-based)。
2257    Inherits {
2258        parent_names: Vec<String>,
2259    },
2260    /// v7.37.16 (16.2) — HASH child:行属于本 child iff
2261    /// `pg_compatible_hash(key) mod modulus == remainder`。
2262    /// PG 强制 `0 ≤ remainder < modulus`;parser/DDL 层先 gate。
2263    Hash {
2264        parent_name: String,
2265        modulus: u32,
2266        remainder: u32,
2267    },
2268    Default {
2269        parent_name: String,
2270    },
2271}
2272
2273/// v7.37.6-B — 分区策略。
2274///
2275/// - `Range`:半开区间 `[lower, upper)`(v7.37.6-B 初始)
2276/// - `List` (v7.37.16):枚举集合 — 行属于 partition iff key ∈ children list
2277/// - `Hash` (v7.37.16):`hash(key) mod modulus == remainder`
2278#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2279pub enum PartitionKind {
2280    Range,
2281    List,
2282    Hash,
2283}
2284
2285/// v7.37.6-B — partition 边界 literal。
2286///
2287/// v7.37.6-B 仅 `TimestampTz`(i64 microseconds since epoch);
2288/// v7.37.16 (16.6) 加全 PG 内建可比类型,匹配 `Value` 的对应 variant
2289/// 以避免 LIST membership 比较时的类型转换。
2290///
2291/// `MinValue` / `MaxValue` 对应 SQL `MINVALUE` / `MAXVALUE`,仅
2292/// Range 策略有意义(LIST 无 minvalue/maxvalue 概念,HASH 不
2293/// 使用 PartitionBound)。
2294#[derive(Debug, Clone, PartialEq, Eq)]
2295pub enum PartitionBound {
2296    MinValue,
2297    MaxValue,
2298    TimestampTz(i64),
2299    /// v7.37.16 (16.6) — BIGINT partition key.
2300    BigInt(i64),
2301    /// v7.37.16 (16.6) — INTEGER partition key (also covers
2302    /// `SERIAL` since SPG decomposes it to INTEGER + sequence).
2303    Int(i32),
2304    /// v7.37.16 (16.6) — SMALLINT partition key.
2305    SmallInt(i16),
2306    /// v7.37.16 (16.6) — DATE partition key. Stored as days
2307    /// since the Unix epoch (matches `Value::Date`).
2308    Date(i32),
2309    /// v7.37.16 (16.6) — TEXT / VARCHAR partition key.
2310    Text(alloc::string::String),
2311}
2312
2313impl PartitionBound {
2314    /// v7.37.16 (16.6) — true iff this bound's underlying value
2315    /// equals `other`'s. Used for LIST partition membership
2316    /// checks. Returns false for `MinValue` / `MaxValue`
2317    /// (sentinels — never literal equality).
2318    #[must_use]
2319    pub fn equals_value(&self, other: &Value<'_>) -> bool {
2320        match (self, other) {
2321            (PartitionBound::TimestampTz(a), Value::Timestamp(b)) => a == b,
2322            (PartitionBound::BigInt(a), Value::BigInt(b)) => a == b,
2323            (PartitionBound::Int(a), Value::Int(b)) => a == b,
2324            (PartitionBound::SmallInt(a), Value::SmallInt(b)) => a == b,
2325            (PartitionBound::Date(a), Value::Date(b)) => a == b,
2326            (PartitionBound::Text(a), Value::Text(b)) => a.as_str() == b.as_ref(),
2327            _ => false,
2328        }
2329    }
2330}
2331
2332/// v7.9.19 — composite UNIQUE / PRIMARY KEY constraint persisted
2333/// on the table schema. The leading column always has a BTree
2334/// index (created at CREATE TABLE time); INSERT enforcement
2335/// scans that index for collisions on the full column tuple.
2336/// v7.39 (read01 round 48) — a `CHECK` constraint: the SQL name the user
2337/// gave it (via `ADD CONSTRAINT <name> CHECK (...)` or the inline
2338/// `CONSTRAINT <name> CHECK (...)` form) plus the predicate source. `None`
2339/// name = unnamed, in which case `pg_constraint` synthesises PG's
2340/// `<table>_<col>_check` form. Names are persisted in the constraint-name
2341/// appendix (FILE_VERSION 60+); older catalogs deserialise with `None`.
2342#[derive(Debug, Clone, PartialEq, Eq)]
2343pub struct CheckConstraint {
2344    pub name: Option<String>,
2345    /// The AST Expr's `Display` form, re-parsed on every INSERT/UPDATE.
2346    pub expr: String,
2347    /// v7.39 (round 652) — `false` for a constraint added `NOT VALID`: the
2348    /// rows already in the table were never scanned against it, and
2349    /// `pg_constraint.convalidated` says so. It does NOT weaken the check on
2350    /// new rows — INSERT and UPDATE enforce it either way, as in PG.
2351    /// `VALIDATE CONSTRAINT` does the deferred scan and flips it. Persisted
2352    /// by the FILE_VERSION 87 appendix; older catalogs deserialise as `true`,
2353    /// which is what every constraint they could hold actually was.
2354    pub validated: bool,
2355}
2356
2357#[derive(Debug, Clone, PartialEq, Eq)]
2358pub struct UniquenessConstraint {
2359    /// `true` when this constraint was declared as `PRIMARY KEY`
2360    /// (vs `UNIQUE`). Semantically PK implies NOT NULL on all
2361    /// referenced columns; the engine enforces that at CREATE
2362    /// TABLE time.
2363    pub is_primary_key: bool,
2364    /// Column positions on the parent table. ≥ 1 element. For
2365    /// single-column UNIQUE this is exactly one position; the
2366    /// BTree index alone enforces it.
2367    pub columns: Vec<usize>,
2368    /// v7.13.0 — `UNIQUE NULLS NOT DISTINCT` modifier
2369    /// (mailrs round-5 G10; PG 15+ surface). When `true`, two
2370    /// rows whose constrained columns are all NULL collide on
2371    /// the constraint. Default (`false`) is the SQL-standard
2372    /// `NULLS DISTINCT` behaviour where any NULL passes.
2373    /// Persisted in catalog FILE_VERSION 23+.
2374    pub nulls_not_distinct: bool,
2375    /// v7.39 (read01 round 48) — the constraint's SQL name when the user
2376    /// supplied one (`ADD CONSTRAINT <name> PRIMARY KEY/UNIQUE (...)`, or
2377    /// the inline `CONSTRAINT <name>` form). `None` = unnamed, in which
2378    /// case `pg_constraint` synthesises PG's `<table>_pkey` /
2379    /// `<table>_<col>_key` form. DROP CONSTRAINT resolves the stored name
2380    /// first and falls back to the synthesised one, so catalogs written
2381    /// before this field (< FILE_VERSION 60) keep working unchanged.
2382    pub name: Option<String>,
2383    /// v7.39 (round 711) — `[NOT] DEFERRABLE`. Round 621 taught the parser
2384    /// to CONSUME the clause on PK/UNIQUE (the FK path had stored it since
2385    /// round 288); this is the storing half. Persisted in the v89 timing
2386    /// appendix.
2387    pub deferrable: bool,
2388    /// `INITIALLY DEFERRED`: the check belongs to COMMIT, not the
2389    /// statement, unless `SET CONSTRAINTS … IMMEDIATE` pulls it in.
2390    pub initially_deferred: bool,
2391}
2392
2393/// v7.39 (round 210) — an `EXCLUDE` constraint. Forbids two distinct live
2394/// rows from satisfying, for EVERY element, `new.col <op> existing.col`
2395/// (e.g. `EXCLUDE USING gist (during WITH &&)` = no two `during` ranges
2396/// overlap). Unlike a uniqueness constraint the operator is not equality,
2397/// so enforcement is a full live-row scan re-checking the operator (a real
2398/// GiST index that answers overlap in O(log n) is a later perf phase). A
2399/// NULL in any element column exempts the row (matching PG / UNIQUE NULL
2400/// semantics). Persisted in catalog FILE_VERSION 72+.
2401#[derive(Debug, Clone, PartialEq, Eq)]
2402pub struct ExclusionConstraint {
2403    /// The constraint's SQL name. PG auto-names an unnamed EXCLUDE
2404    /// `<table>_<leading-col>_excl`; the engine synthesises that at CREATE
2405    /// TABLE time so this is always populated.
2406    pub name: String,
2407    /// Access method spelled after `USING` (`gist`, `spgist`, …), lower-cased.
2408    /// `None` = no `USING` clause. Purely cosmetic for enforcement; it round-
2409    /// trips into `pg_get_constraintdef`.
2410    pub method: Option<String>,
2411    /// One `(column-position, operator-spelling)` pair per element, in
2412    /// declaration order. The operator spelling is the wire token (`&&`,
2413    /// `=`, `@>`, `<@`, `&<`, `&>`) evaluated against each existing row.
2414    pub elements: Vec<(usize, String)>,
2415}
2416
2417/// v7.6.1 — Storage-layer mirror of `spg_sql::ast::ForeignKeyConstraint`.
2418/// The engine's CREATE TABLE path translates between the two; keeping
2419/// them separate preserves the no-deps boundary between
2420/// `spg-storage` and `spg-sql`.
2421#[derive(Debug, Clone, PartialEq, Eq)]
2422pub struct ForeignKeyConstraint {
2423    /// Optional user-supplied constraint name (`CONSTRAINT <name>`
2424    /// prefix). Used by `ALTER TABLE DROP CONSTRAINT <name>` in
2425    /// v7.6.8; ignored by enforcement.
2426    pub name: Option<String>,
2427    /// Positions of local columns in this table's column list.
2428    /// Same arity as `parent_columns`.
2429    pub local_columns: Vec<usize>,
2430    /// Referenced parent table name.
2431    pub parent_table: String,
2432    /// Positions of parent columns in the parent's column list.
2433    /// Engine resolves these at CREATE TABLE time (after the parent
2434    /// schema is known) so enforcement paths can skip the name
2435    /// lookup on every row.
2436    pub parent_columns: Vec<usize>,
2437    /// Referential action when a parent row is deleted.
2438    pub on_delete: FkAction,
2439    /// Referential action when a parent row's referenced columns
2440    /// are updated.
2441    pub on_update: FkAction,
2442    /// v7.38 (read01, T29) — `MATCH SIMPLE | FULL`. Defaults to `Simple`.
2443    pub match_type: MatchType,
2444    /// v7.39 (round 288) — `[NOT] DEFERRABLE`.
2445    pub deferrable: bool,
2446    /// `INITIALLY DEFERRED`: the check runs at COMMIT rather than at
2447    /// the statement, unless `SET CONSTRAINTS … IMMEDIATE` pulls it in.
2448    pub initially_deferred: bool,
2449}
2450
2451/// v7.38 (read01, T29) — FK MATCH type. Mirrors `spg_sql::ast::MatchType`.
2452#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
2453pub enum MatchType {
2454    #[default]
2455    Simple,
2456    Full,
2457}
2458
2459impl MatchType {
2460    /// On-disk tag byte (catalog appendix, `FILE_VERSION` 55+).
2461    pub const fn tag(self) -> u8 {
2462        match self {
2463            Self::Simple => 0,
2464            Self::Full => 1,
2465        }
2466    }
2467    pub const fn from_tag(b: u8) -> Option<Self> {
2468        Some(match b {
2469            0 => Self::Simple,
2470            1 => Self::Full,
2471            _ => return None,
2472        })
2473    }
2474}
2475
2476/// v7.6.1 — referential action tag. Mirrors `spg_sql::ast::FkAction`.
2477#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2478pub enum FkAction {
2479    Restrict,
2480    Cascade,
2481    SetNull,
2482    SetDefault,
2483    NoAction,
2484}
2485
2486impl FkAction {
2487    /// On-disk tag byte (v13 catalog appendix).
2488    pub const fn tag(self) -> u8 {
2489        match self {
2490            Self::Restrict => 0,
2491            Self::Cascade => 1,
2492            Self::SetNull => 2,
2493            Self::SetDefault => 3,
2494            Self::NoAction => 4,
2495        }
2496    }
2497    pub const fn from_tag(b: u8) -> Option<Self> {
2498        Some(match b {
2499            0 => Self::Restrict,
2500            1 => Self::Cascade,
2501            2 => Self::SetNull,
2502            3 => Self::SetDefault,
2503            4 => Self::NoAction,
2504            _ => return None,
2505        })
2506    }
2507}
2508
2509impl TableSchema {
2510    pub fn column_position(&self, name: &str) -> Option<usize> {
2511        self.columns.iter().position(|c| c.name == name)
2512    }
2513}
2514
2515/// Key type accepted by secondary indices. Float / NULL / Vector values
2516/// can't participate in a B-tree index — `f64` is only `PartialOrd`, NULL
2517/// has SQL-three-valued semantics, and Vector belongs to the (future) HNSW
2518/// path. Index lookups on those columns fall back to full scan.
2519#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
2520pub enum IndexKey {
2521    Int(i64),
2522    Text(String),
2523    Bool(bool),
2524    /// v7.17.0 — `Value::Uuid` index key. Comparison is byte-wise
2525    /// (RFC 4122 byte order) so PRIMARY KEY UUID lookups land on
2526    /// the same fast-path as Int / Text.
2527    Uuid([u8; 16]),
2528    /// r1039 — `Value::Bytes` (bytea). PG orders bytea by plain byte
2529    /// comparison, shorter-prefix first (`'' < \x00 < \x0000 < \x01ff <
2530    /// \xff`, measured on 18.4), which is exactly `Vec<u8>`'s `Ord`.
2531    Bytes(Vec<u8>),
2532    /// r1039 — exact decimal, in the canonical form described on
2533    /// [`NumericKey`].
2534    ///
2535    /// r1040 — BOXED, and the box is load-bearing for every OTHER index.
2536    /// A `NumericKey` is 48 bytes against `Text(String)`'s 24, so inline
2537    /// it set the size of the whole enum and every B-tree node in every
2538    /// index grew with it: 32 bytes per key to 48, align 8 to 16.
2539    /// Measured through the release sweep, `SELECT pad FROM t ORDER BY
2540    /// id` over 400,000 rows — a walk of the primary key's index — went
2541    /// 39.4-40.6 ms to 42.3-44.1, in both leg orders. The indirection is
2542    /// charged to numeric keys, which are new, instead of to every index
2543    /// that existed already.
2544    Numeric(alloc::boxed::Box<NumericKey>),
2545    /// v7.38.1 (L12) — a NULL component INSIDE a composite key, and
2546    /// nothing else. `IndexKey::from_value(Value::Null)` still returns
2547    /// `None`, so single-column B-trees never hold one, and no probe
2548    /// path ever BUILDS one (`col = NULL` is not a match in SQL) — the
2549    /// variant is only reachable through a composite key's component
2550    /// list, where it exists so that a row like `(2, 3, NULL)` stays
2551    /// findable by a PREFIX probe on `(w, d)`. Declared last: slice
2552    /// `Ord` then sorts NULL components after every value, PG's
2553    /// NULLS LAST.
2554    Null,
2555}
2556
2557/// r1039 — an exact-decimal index key, canonical so that representation
2558/// equality IS value equality.
2559///
2560/// That property is the whole reason this is a struct rather than the
2561/// `(scaled, scale)` pair the value carries. `1.5` and `1.50` are the
2562/// same NUMERIC (PG18.4: `1.5::numeric = 1.50::numeric` is true) and
2563/// arrive here as `(15, 1)` and `(150, 2)`. A B-tree keyed on the raw
2564/// pair would file them apart, so `WHERE n = 1.5` would miss a row stored
2565/// as `1.50` — an index changing the answer, which is the one thing an
2566/// index may never do. `BigNumeric::cmp` carries the same warning and
2567/// declines to implement `Ord` for exactly this reason; a KEY cannot
2568/// decline, so it normalizes instead.
2569///
2570/// Canonical form: significant decimal digits with no leading and no
2571/// trailing zeros, most significant first, plus the decimal exponent of
2572/// the leading digit. Zero is the empty digit vector with `neg == false`
2573/// and `exp == 0`, so there is no `-0`.
2574///
2575/// Ordering is PG's, measured: `-Infinity < -1 < 0 < 1 < Infinity < NaN`,
2576/// and `NaN = NaN`.
2577#[derive(Debug, Clone, PartialEq, Eq)]
2578pub struct NumericKey {
2579    /// 0 = -Infinity, 1 = finite, 2 = +Infinity, 3 = NaN. Ordering the
2580    /// classes by this byte is what puts NaN on top, where PG keeps it.
2581    class: u8,
2582    /// Finite only, and never set for zero.
2583    neg: bool,
2584    /// Decimal exponent of the leading significant digit; 0 for zero.
2585    exp: i32,
2586    /// r1040 — the first [`HEAD_DIGITS`] significant digits, LEFT-ALIGNED
2587    /// (multiplied up so the leading digit always sits at 10^36). That
2588    /// alignment is what makes an integer comparison of two heads the same
2589    /// answer as a digit-by-digit one: `12` and `1` become 1.2e36 and
2590    /// 1.0e36, which order the way the digit strings do, where the bare
2591    /// integers 12 and 1 would not.
2592    ///
2593    /// Zero for the value zero and for every special.
2594    ///
2595    /// This started as a `Vec<u8>` of digits, which is correct and cost
2596    /// an allocation per key and a slice comparison per sort comparison.
2597    /// `ORDER BY <numeric>` builds one key per row and compares n log n
2598    /// times: 200,000 rows measured 65.4 ms against 39.6 for the f64
2599    /// projection that had been returning rows in the wrong order.
2600    head: u128,
2601    /// Significant digits past the 37th, one per byte, no trailing zeros.
2602    /// Empty for everything an `i128` mantissa can hold with room to
2603    /// spare — and an empty `Vec` does not allocate, which is the point.
2604    tail: Vec<u8>,
2605}
2606
2607/// Significant digits carried in [`NumericKey::head`]. 37 is the most
2608/// that can be left-aligned inside a `u128`: the largest such value is
2609/// 9.99…e36, and `u128::MAX` is 3.4e38.
2610const HEAD_DIGITS: u32 = 37;
2611/// `10^36` — where a left-aligned leading digit sits.
2612const HEAD_SCALE: u128 = 1_000_000_000_000_000_000_000_000_000_000_000_000;
2613
2614/// The `class` byte of [`NumericKey`], in PG's order.
2615const NUM_CLASS_NEG_INF: u8 = 0;
2616const NUM_CLASS_FINITE: u8 = 1;
2617const NUM_CLASS_POS_INF: u8 = 2;
2618const NUM_CLASS_NAN: u8 = 3;
2619
2620impl NumericKey {
2621    /// The key for a `Value::Numeric`'s three fields.
2622    ///
2623    /// Public because the ORDER BY key wants the same canonical form the
2624    /// index key uses: two sort keys that disagree about which of two
2625    /// NUMERICs is larger is the same class of defect as an index that
2626    /// disagrees with a scan, and one definition is how they stay honest.
2627    #[must_use]
2628    pub fn from_numeric(scaled: i128, scale: u16, kind: NumericKind) -> Self {
2629        match kind {
2630            NumericKind::Finite => {
2631                let mut buf = [0u8; 40];
2632                let n = digits_of_u128(scaled.unsigned_abs(), &mut buf);
2633                Self::finite(scaled < 0, &buf[..n], i32::from(scale))
2634            }
2635            NumericKind::NaN => Self::special(NUM_CLASS_NAN),
2636            NumericKind::PosInf => Self::special(NUM_CLASS_POS_INF),
2637            NumericKind::NegInf => Self::special(NUM_CLASS_NEG_INF),
2638        }
2639    }
2640
2641    /// The key for an exact integer — no scale, so no rounding.
2642    #[must_use]
2643    pub fn from_i128(n: i128) -> Self {
2644        let mut buf = [0u8; 40];
2645        let len = digits_of_u128(n.unsigned_abs(), &mut buf);
2646        Self::finite(n < 0, &buf[..len], 0)
2647    }
2648
2649    /// The key for a mantissa that overflowed `i128`. The two
2650    /// representations of one value land on one key.
2651    #[must_use]
2652    pub fn from_big(b: &crate::bignum::BigNumeric) -> Self {
2653        let (neg, limbs, scale) = b.parts();
2654        Self::finite(neg, &digits_of_limbs(limbs), i32::from(scale))
2655    }
2656
2657    /// The `f64` this key means, for the one comparison PG defines that
2658    /// way: `numeric` against `float8` demotes the numeric.
2659    ///
2660    /// Lossy by construction — that is the point, and it is why nothing
2661    /// else uses it.
2662    #[must_use]
2663    #[allow(clippy::cast_precision_loss)]
2664    pub fn to_f64(&self) -> f64 {
2665        match self.class {
2666            NUM_CLASS_NAN => return f64::NAN,
2667            NUM_CLASS_POS_INF => return f64::INFINITY,
2668            NUM_CLASS_NEG_INF => return f64::NEG_INFINITY,
2669            _ => {}
2670        }
2671        if self.head == 0 {
2672            return 0.0;
2673        }
2674        // `head` is `d.ddd… × 10^36`; the value is that leading digit and
2675        // its followers at `exp`. The tail is below f64's resolution by
2676        // construction (it starts at the 38th significant digit).
2677        let mantissa = self.head as f64 / HEAD_SCALE as f64;
2678        let out = mantissa * pow10_f64(self.exp);
2679        if self.neg { -out } else { out }
2680    }
2681
2682    /// The significant decimal digits, most significant first — the form
2683    /// the catalog codec writes, and the one `from_parts` reads back.
2684    #[must_use]
2685    pub fn digits(&self) -> Vec<u8> {
2686        let mut out = Vec::new();
2687        if self.head != 0 {
2688            let mut h = self.head;
2689            for _ in 0..HEAD_DIGITS {
2690                let d = u8::try_from(h / HEAD_SCALE).unwrap_or(0);
2691                out.push(d);
2692                h = (h % HEAD_SCALE) * 10;
2693            }
2694            while out.last() == Some(&0) {
2695                out.pop();
2696            }
2697        }
2698        out.extend_from_slice(&self.tail);
2699        out
2700    }
2701
2702    /// The wire parts, for the catalog codec.
2703    #[must_use]
2704    pub fn parts(&self) -> (u8, bool, i32) {
2705        (self.class, self.neg, self.exp)
2706    }
2707
2708    /// Rebuild from the wire parts. Returns `None` on parts that are not
2709    /// canonical, so a corrupt catalog cannot smuggle in a key whose `Eq`
2710    /// and `Ord` disagree.
2711    #[must_use]
2712    pub fn from_parts(class: u8, neg: bool, exp: i32, digits: &[u8]) -> Option<Self> {
2713        if class > NUM_CLASS_NAN || digits.iter().any(|d| *d > 9) {
2714            return None;
2715        }
2716        if class != NUM_CLASS_FINITE && (neg || exp != 0 || !digits.is_empty()) {
2717            return None;
2718        }
2719        if digits.is_empty() {
2720            if neg || exp != 0 {
2721                return None;
2722            }
2723            return Some(Self::special(class));
2724        }
2725        if digits[0] == 0 || digits[digits.len() - 1] == 0 {
2726            return None;
2727        }
2728        Some(Self {
2729            class,
2730            neg,
2731            exp,
2732            head: head_of(digits),
2733            tail: digits.iter().skip(HEAD_DIGITS as usize).copied().collect(),
2734        })
2735    }
2736
2737    /// Canonicalize `(-1)^neg · <digits as an integer> · 10^-scale`.
2738    ///
2739    /// `digits` is most-significant-first and may carry leading and
2740    /// trailing zeros; both are stripped, which is what makes `1.5` and
2741    /// `1.50` land on the same key.
2742    fn finite(neg: bool, digits: &[u8], scale: i32) -> Self {
2743        let lead = digits.iter().position(|d| *d != 0).unwrap_or(digits.len());
2744        let digits = &digits[lead..];
2745        if digits.is_empty() {
2746            return Self::special(NUM_CLASS_FINITE);
2747        }
2748        // The leading digit's exponent, taken BEFORE trailing zeros go:
2749        // dropping low-order digits does not move the leading one.
2750        let exp = i32::try_from(digits.len()).unwrap_or(i32::MAX) - 1 - scale;
2751        let mut end = digits.len();
2752        while end > 0 && digits[end - 1] == 0 {
2753            end -= 1;
2754        }
2755        let digits = &digits[..end];
2756        Self {
2757            class: NUM_CLASS_FINITE,
2758            neg,
2759            exp,
2760            head: head_of(digits),
2761            tail: digits.iter().skip(HEAD_DIGITS as usize).copied().collect(),
2762        }
2763    }
2764
2765    fn special(class: u8) -> Self {
2766        Self {
2767            class,
2768            neg: false,
2769            exp: 0,
2770            head: 0,
2771            tail: Vec::new(),
2772        }
2773    }
2774}
2775
2776/// The first [`HEAD_DIGITS`] of `digits`, left-aligned so the leading one
2777/// sits at `10^36`.
2778fn head_of(digits: &[u8]) -> u128 {
2779    let mut head: u128 = 0;
2780    let take = (HEAD_DIGITS as usize).min(digits.len());
2781    for d in &digits[..take] {
2782        head = head * 10 + u128::from(*d);
2783    }
2784    for _ in take..HEAD_DIGITS as usize {
2785        head *= 10;
2786    }
2787    head
2788}
2789
2790/// Decimal digits of `mag` into `buf`, most significant first; returns how
2791/// many were written. Zero writes none.
2792///
2793/// r1040 — split at `u64` on purpose. A `u128` divide is a called routine,
2794/// not an instruction, and this loop runs once per digit per key.
2795fn digits_of_u128(mag: u128, buf: &mut [u8; 40]) -> usize {
2796    if mag == 0 {
2797        return 0;
2798    }
2799    let mut rev = [0u8; 40];
2800    let mut n = 0usize;
2801    let mut big = mag;
2802    // Peel nineteen digits at a time — the most a `u64` holds — so the
2803    // wide divide runs at most twice.
2804    while big > u128::from(u64::MAX) {
2805        let mut chunk = u64::try_from(big % 10_000_000_000_000_000_000_u128).unwrap_or(0);
2806        big /= 10_000_000_000_000_000_000_u128;
2807        for _ in 0..19 {
2808            rev[n] = u8::try_from(chunk % 10).unwrap_or(0);
2809            chunk /= 10;
2810            n += 1;
2811        }
2812    }
2813    let mut small = u64::try_from(big).unwrap_or(0);
2814    while small > 0 {
2815        rev[n] = u8::try_from(small % 10).unwrap_or(0);
2816        small /= 10;
2817        n += 1;
2818    }
2819    for i in 0..n {
2820        buf[i] = rev[n - 1 - i];
2821    }
2822    n
2823}
2824
2825/// Decimal digits of a base-10^9 little-endian limb vector, most
2826/// significant first. Every limb but the leading one is padded to its
2827/// full nine digits — that padding is the whole point, since a limb of 5
2828/// in the middle of a number means `000000005`.
2829fn digits_of_limbs(limbs: &[u32]) -> Vec<u8> {
2830    let mut out = Vec::new();
2831    let mut buf = [0u8; 40];
2832    for (i, limb) in limbs.iter().enumerate().rev() {
2833        let n = digits_of_u128(u128::from(*limb), &mut buf);
2834        if i + 1 == limbs.len() {
2835            out.extend_from_slice(&buf[..n]);
2836        } else {
2837            out.extend(core::iter::repeat_n(0u8, 9 - n));
2838            out.extend_from_slice(&buf[..n]);
2839        }
2840    }
2841    out
2842}
2843
2844/// `10^e` as an `f64`, for any `e` a canonical key can carry.
2845#[allow(clippy::cast_precision_loss)]
2846fn pow10_f64(e: i32) -> f64 {
2847    let mut out = 1.0_f64;
2848    let mag = e.unsigned_abs();
2849    for _ in 0..mag {
2850        out *= 10.0;
2851    }
2852    if e < 0 { 1.0 / out } else { out }
2853}
2854
2855impl Ord for NumericKey {
2856    fn cmp(&self, other: &Self) -> core::cmp::Ordering {
2857        use core::cmp::Ordering;
2858        if self.class != other.class {
2859            return self.class.cmp(&other.class);
2860        }
2861        if self.class != NUM_CLASS_FINITE {
2862            // Each of the three specials is a single value, and PG holds
2863            // `'NaN'::numeric = 'NaN'::numeric` true.
2864            return Ordering::Equal;
2865        }
2866        // Zero first: it is stored with `neg == false` and `exp == 0`, so
2867        // the magnitude comparison below would put it above every value
2868        // smaller than 1 rather than between the negatives and positives.
2869        match (self.head == 0, other.head == 0) {
2870            (true, true) => return Ordering::Equal,
2871            (true, false) => {
2872                return if other.neg {
2873                    Ordering::Greater
2874                } else {
2875                    Ordering::Less
2876                };
2877            }
2878            (false, true) => {
2879                return if self.neg {
2880                    Ordering::Less
2881                } else {
2882                    Ordering::Greater
2883                };
2884            }
2885            (false, false) => {}
2886        }
2887        match (self.neg, other.neg) {
2888            (false, true) => return Ordering::Greater,
2889            (true, false) => return Ordering::Less,
2890            _ => {}
2891        }
2892        // Same sign, both non-zero: more integer digits is bigger, and at
2893        // equal exponent the left-aligned heads compare as one integer —
2894        // the alignment is what makes that the same answer as comparing
2895        // the digit strings. The tail only speaks when the first 37
2896        // significant digits are identical.
2897        let mag = self
2898            .exp
2899            .cmp(&other.exp)
2900            .then_with(|| self.head.cmp(&other.head))
2901            .then_with(|| self.tail.cmp(&other.tail));
2902        if self.neg { mag.reverse() } else { mag }
2903    }
2904}
2905
2906impl PartialOrd for NumericKey {
2907    fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
2908        Some(self.cmp(other))
2909    }
2910}
2911
2912impl IndexKey {
2913    /// v7.37.43 (INSUBQ B-4) — inline-friendly BigInt fast path.
2914    /// `try_count_star_pk_in_subquery_fast` (and any other hot loop
2915    /// probing an integer PK) already holds an `i64`; this builds the
2916    /// `IndexKey` without going through the generic `from_value`
2917    /// dispatch tree.
2918    #[inline]
2919    pub fn from_i64(n: i64) -> Self {
2920        Self::Int(n)
2921    }
2922
2923    /// r1039 — the key a value takes when the INDEXED COLUMN is `ty`, or
2924    /// `None` when it takes none (→ the caller falls back to a scan).
2925    ///
2926    /// Every key under one index comes from one column, so they all live
2927    /// in one key SPACE. A probe built in a different space finds nothing
2928    /// — and "nothing" is indistinguishable from "no matching rows",
2929    /// which is how round 564 and r1037 both turned an index into a wrong
2930    /// answer (a TEXT key sought against a DATE-keyed and a UUID-keyed
2931    /// index).
2932    ///
2933    /// The two spaces this round adds make that trap reachable again from
2934    /// a new direction: `WHERE n = 2` on a NUMERIC column produces
2935    /// `Value::Int`, and an integer key would look in a space nothing
2936    /// lives in. So NUMERIC columns take integers by converting them
2937    /// exactly, and refuse anything they cannot convert; BYTEA columns
2938    /// take only `Value::Bytes`; and no other column may be keyed in
2939    /// either of the two new spaces.
2940    ///
2941    /// Use this wherever the key comes from a LITERAL or from another
2942    /// table's value. [`IndexKey::from_value`] stays right for building
2943    /// the index itself, where the value is the column's own.
2944    pub fn from_value_for_column(v: &Value<'_>, ty: DataType) -> Option<Self> {
2945        match ty {
2946            DataType::Numeric { .. } => match v {
2947                Value::SmallInt(n) => Some(Self::exact_int_key(i128::from(*n))),
2948                Value::Int(n) => Some(Self::exact_int_key(i128::from(*n))),
2949                Value::BigInt(n) => Some(Self::exact_int_key(i128::from(*n))),
2950                Value::Numeric { .. } | Value::NumericBig(_) => Self::from_value(v),
2951                // Float included: `2.0::float8` and `2.0::numeric` are not
2952                // the same value to a B-tree, and rounding one into the
2953                // other's space is how a seek reaches the wrong row.
2954                _ => None,
2955            },
2956            DataType::Bytes => match v {
2957                Value::Bytes(b) => Some(Self::Bytes(b.to_vec())),
2958                _ => None,
2959            },
2960            _ => match Self::from_value(v) {
2961                Some(Self::Numeric(_) | Self::Bytes(_)) => None,
2962                other => other,
2963            },
2964        }
2965    }
2966
2967    /// An integer as a NUMERIC key. Exact by construction — no scale, no
2968    /// rounding — which is why the conversion is allowed at all.
2969    fn exact_int_key(n: i128) -> Self {
2970        Self::Numeric(alloc::boxed::Box::new(NumericKey::from_i128(n)))
2971    }
2972
2973    pub fn from_value(v: &Value<'_>) -> Option<Self> {
2974        match v {
2975            // v7.37.43 (INSUBQ B-4) — BigInt hits first (the dominant
2976            // INSUBQ shape probes PK as BigInt). Tiny micro-win.
2977            Value::BigInt(n) => Some(Self::Int(*n)),
2978            Value::SmallInt(n) => Some(Self::Int(i64::from(*n))),
2979            Value::Int(n) => Some(Self::Int(i64::from(*n))),
2980            Value::Text(s) => Some(Self::Text(s.clone().into_owned())),
2981            // v7.38 (read01, T11) — bpchar keys compare blank-insensitively.
2982            Value::BpChar(s) => Some(Self::Text(s.trim_end_matches(' ').to_string())),
2983            Value::Bool(b) => Some(Self::Bool(*b)),
2984            // Date/Timestamp use their integer storage repr as the
2985            // index key — same order semantics, same comparison.
2986            Value::Date(d) => Some(Self::Int(i64::from(*d))),
2987            Value::Timestamp(t) => Some(Self::Int(*t)),
2988            // v7.17.0: UUID indexable via byte-wise ordering. Lookup
2989            // on `id = '...'::uuid` resolves through the secondary
2990            // index rather than full-scan.
2991            Value::Uuid(b) => Some(Self::Uuid(*b)),
2992            // v7.17.0 Phase 3.P0-32: TIME indexable via i64 — same
2993            // order semantics as Date/Timestamp.
2994            Value::Time(us) => Some(Self::Int(*us)),
2995            // v7.17.0 Phase 3.P0-33: YEAR indexable as i64 — u16
2996            // widens losslessly and gives the natural calendar
2997            // ordering.
2998            Value::Year(y) => Some(Self::Int(i64::from(*y))),
2999            // v7.17.0 Phase 3.P0-34: TIMETZ indexable by its
3000            // UTC-equivalent microseconds (local wall - offset).
3001            // Without normalising, two values for the same
3002            // physical instant in different zones would sort
3003            // wrong. Matches PG's TIMETZ index behaviour.
3004            Value::TimeTz { us, offset_secs } => {
3005                Some(Self::Int(us - i64::from(*offset_secs) * 1_000_000))
3006            }
3007            // v7.17.0 Phase 3.P0-35: MONEY indexable as i64 cents
3008            // (no scaling needed — natural numeric ordering).
3009            Value::Money(c) => Some(Self::Int(*c)),
3010            // v7.17.0 Phase 3.P0-38: ranges are NOT indexable in
3011            // v7.17.0 — they'd need a custom comparator (PG uses
3012            // SP-GiST for this). Skip.
3013            Value::Range { .. } => None,
3014            // v7.17.0 Phase 3.P0-39: hstore is NOT indexable in
3015            // v7.17.0 — map columns need GIN with bespoke ops.
3016            Value::Hstore(_) => None,
3017            // r1039 — exact decimals index through the canonical
3018            // [`NumericKey`], which is what makes `1.5` and `1.50` one key.
3019            Value::NumericBig(b) => Some(Self::Numeric(alloc::boxed::Box::new(NumericKey::from_big(b)))),
3020            Value::Numeric {
3021                scaled,
3022                scale,
3023                kind,
3024            } => Some(Self::Numeric(alloc::boxed::Box::new(
3025                NumericKey::from_numeric(*scaled, *scale, *kind),
3026            ))),
3027            // r1039 — bytea orders by plain byte comparison, which is
3028            // `Vec<u8>`'s own.
3029            Value::Bytes(b) => Some(Self::Bytes(b.to_vec())),
3030            // v7.17.0 Phase 3.P0-40: 2D arrays aren't indexable.
3031            Value::IntArray2D(_)
3032            | Value::BigIntArray2D(_)
3033            | Value::TextArray2D(_)
3034            | Value::BoolArray2D(_) => None,
3035            // v7.37.5 β-P4: INTERVAL[] isn't indexable (PG uses
3036            // GIN/intarray for array-contains queries; SPG plans
3037            // that as a separate axis under v7.37.8 GIN-on-jsonb).
3038            Value::IntervalArray(_) => None,
3039            // v7.37.5 γ — none of the array-of-scalar family is
3040            // B-tree indexable. Same reason as IntervalArray: PG
3041            // serves array-contains / array-overlap queries via
3042            // GIN, and SPG's GIN axis lands in v7.37.8.
3043            Value::BoolArray(_)
3044            | Value::SmallIntArray(_)
3045            | Value::FloatArray(_)
3046            | Value::NumericArray(_)
3047            | Value::DateArray(_)
3048            | Value::TimestampArray(_)
3049            | Value::TimestamptzArray(_)
3050            | Value::UuidArray(_)
3051            | Value::JsonArray(_)
3052            | Value::JsonbArray(_)
3053            | Value::BytesArray(_)
3054            | Value::VarcharArray(_)
3055            | Value::CharArray(_)
3056            // v7.37.5 δ — multirange not indexable (PG uses GiST/
3057            // SP-GiST + a custom operator class; SPG plans the same
3058            // axis under v7.37.8 with ranges).
3059            | Value::Multirange { .. }
3060            // v7.37.5 ε — geometric scalars not B-tree indexable
3061            // (PG uses GiST/SP-GiST for these too; SPG plans the
3062            // same axis under v7.37.8).
3063            | Value::Point(_)
3064            | Value::Lseg(_, _)
3065            | Value::Path { .. }
3066            | Value::PgBox(_, _)
3067            | Value::Polygon(_)
3068            | Value::Line { .. }
3069            | Value::Circle { .. }
3070            // v7.37.5 ζ-A — network / bit / xml / "char" / money[].
3071            // INET / CIDR / MACADDR / MACADDR8 could be B-tree
3072            // indexable (PG does this), but the byte-wise compare
3073            // family-blind would mis-order IPv4 vs IPv6; left as
3074            // a follow-up under v7.37.8 GIN window.
3075            | Value::Inet { .. }
3076            | Value::Cidr { .. }
3077            | Value::Macaddr(_)
3078            | Value::Macaddr8(_)
3079            | Value::PgLsn(_)
3080            | Value::BitString { .. }
3081            | Value::Xml(_)
3082            | Value::Char1(_)
3083            | Value::MoneyArray(_)
3084            | Value::Composite(_)
3085            | Value::Tid(..)
3086            | Value::Xid(_)
3087            | Value::Cid(_)
3088            | Value::RegClass(..)
3089            | Value::RegProc(..)
3090            | Value::RegType(..) => None,
3091            // Interval isn't index-eligible (and can't reach this path
3092            // through column storage anyway). Float / Real stay out
3093            // because `f64` is only `PartialOrd`.
3094            Value::Null
3095            | Value::Float(_)
3096            | Value::Vector(_)
3097            | Value::Sq8Vector(_)
3098            | Value::HalfVector(_)
3099            | Value::Interval { .. }
3100            | Value::Json(_)
3101            | Value::TextArray(_)
3102            | Value::IntArray(_)
3103            | Value::BigIntArray(_)
3104            | Value::TsVector(_)
3105            | Value::TsQuery(_)
3106            | Value::Real(_) => None,
3107        }
3108    }
3109}
3110
3111/// A single-column secondary index. v2.0 carries either a B-tree map
3112/// (the default — used for equality / range lookups on scalar columns)
3113/// or a navigable-small-world graph (used for kNN over vector
3114/// columns).
3115#[derive(Debug, Clone)]
3116pub struct Index {
3117    pub name: String,
3118    pub column_position: usize,
3119    pub kind: IndexKind,
3120    /// v6.8.0 — column positions of `INCLUDE (col1, col2, …)`
3121    /// non-key columns. Carries the planner's "this query is
3122    /// covered by the index" signal; lookup paths still resolve
3123    /// via the `RowLocator` to fetch the row body, but EXPLAIN
3124    /// surfaces the covered-scan annotation so operators can
3125    /// confirm the planner sees the coverage.
3126    ///
3127    /// Empty `Vec` = no `INCLUDE` clause (the legacy shape). v12
3128    /// catalog snapshots deserialise with an empty vec.
3129    pub included_columns: Vec<usize>,
3130    /// v6.8.1 — partial-index predicate stored as its canonical
3131    /// Display form (the engine re-parses it on the maintenance
3132    /// path). `None` = unconditional index (the legacy shape).
3133    /// Persisted as `[u8 has_pred][u16 LE len][bytes]` on the
3134    /// catalog snapshot (FILE_VERSION 12, appended after
3135    /// `included_columns`).
3136    pub partial_predicate: Option<String>,
3137    /// v6.8.2 — expression-index key, stored as the expression's
3138    /// canonical Display form. `None` = bare column-reference
3139    /// index (the legacy shape). Persisted alongside
3140    /// `partial_predicate` on the v12 catalog snapshot.
3141    pub expression: Option<String>,
3142    /// v7.39 (read01 round 52) — `CREATE UNIQUE INDEX … NULLS NOT DISTINCT`
3143    /// (PG 15+): a NULL in the key no longer exempts the row, so two
3144    /// all-NULL keys collide. Default `false` = SQL-standard NULLS DISTINCT.
3145    /// Persisted in the index appendix (FILE_VERSION 62+); older catalogs
3146    /// deserialise with `false`.
3147    pub nulls_not_distinct: bool,
3148    /// v7.39 (round 537) — the key column's ordering clause, as written.
3149    ///
3150    /// SPG's index does not scan in a direction, so this changes no
3151    /// lookup; `pg_indexes.indexdef` is a reproduction of the DDL and
3152    /// dropping the clause made `CREATE INDEX i ON t (a DESC NULLS
3153    /// LAST)` read back as `(a)` — a dump lost it and a schema diff saw
3154    /// drift every run. `nulls_first` is `None` when the statement did
3155    /// not say, in which case PG's default applies and neither word is
3156    /// rendered.
3157    pub descending: bool,
3158    pub nulls_first: Option<bool>,
3159    /// v7.39 (round 538) — an explicit `COLLATE` on the key, as written.
3160    /// SPG orders text by bytes, so it changes no comparison; PG prints
3161    /// it because a named collation and an inherited one are different
3162    /// objects even where they sort identically.
3163    pub collation: Option<String>,
3164    /// v7.9.29 — `CREATE UNIQUE INDEX …`. When true the engine
3165    /// rejects INSERTs whose key already appears in this index
3166    /// (combined with `partial_predicate` when present — only
3167    /// rows matching the predicate enter the uniqueness check).
3168    /// Catalog FILE_VERSION 16+; older snapshots deserialise
3169    /// with `false`. mailrs K1.
3170    pub is_unique: bool,
3171    /// v7.9.29 — extra (non-leading) column positions for
3172    /// multi-column indexes (`CREATE INDEX … (a, b, c)`). The
3173    /// planner today still only uses the leading
3174    /// `column_position` for index seeks, but UNIQUE INDEX
3175    /// enforcement walks the full tuple so partial-unique
3176    /// invariants like CalDAV `(calendar_id, uid,
3177    /// recurrence_id)` are enforced correctly. Catalog
3178    /// FILE_VERSION 16+; older snapshots deserialise empty.
3179    pub extra_column_positions: Vec<usize>,
3180}
3181
3182/// Default neighbor degree (M) for the NSW graph. Picked at construction
3183/// time and persisted with the index.
3184pub const NSW_DEFAULT_M: usize = 16;
3185
3186/// v5.2.2: outcome of a successful [`Catalog::freeze_oldest_to_cold`]
3187/// call. The catalog state has already been mutated by the time this
3188/// is returned (hot rows dropped + segment registered + Cold locators
3189/// flipped). The caller's only remaining concern is `segment_bytes` —
3190/// persist them to disk under `<db>.spg/segments/seg_<id>.spg` so a
3191/// future restart can reload via the v5.1 `SPG_PRELOAD_COLD_SEGMENT`
3192/// path. (v5.3's manifest will subsume this manual step.)
3193#[derive(Debug, Clone)]
3194pub struct FreezeReport {
3195    /// Id allocated by [`Catalog::load_segment_bytes`] for the new
3196    /// cold-tier segment. Stable across the call's success path.
3197    pub segment_id: u32,
3198    /// Number of rows that moved hot → cold. Equals the `max_rows`
3199    /// the caller asked for (the API is strict on the count).
3200    pub frozen_rows: usize,
3201    /// Hot-tier bytes reclaimed by the freeze — the
3202    /// [`Table::hot_bytes`] delta before vs after. Useful to feed
3203    /// back into the freezer's budget check on the next tick.
3204    pub bytes_freed: u64,
3205    /// Encoded segment bytes, byte-identical to what
3206    /// [`encode_segment`] produced. The catalog already owns a
3207    /// copy inside `cold_segments`; this hand-off lets the caller
3208    /// persist them without re-encoding.
3209    pub segment_bytes: Vec<u8>,
3210}
3211
3212/// v6.7.4 — read-only output of [`Catalog::prepare_freeze_slice`].
3213/// Carries every row body + key in a contiguous hot-row range,
3214/// already encoded and sorted by PK so the coordinator's merge
3215/// step is a k-way merge over already-sorted streams.
3216///
3217/// `Vec<FreezeSlice>` from N independent workers feeds
3218/// [`Catalog::commit_freeze_slices`], which concats + encodes the
3219/// merged segment + atomically swaps the catalog state.
3220#[derive(Debug, Clone)]
3221pub struct FreezeSlice {
3222    /// Hot-row index range this slice covered (half-open, in the
3223    /// table's `rows: PersistentVec` ordering at call time). The
3224    /// commit step uses this to compute the union range that
3225    /// gets passed to [`Table::delete_rows`].
3226    pub row_range: core::ops::Range<usize>,
3227    /// `(pk_u64, encoded_row_body, IndexKey)` triples, sorted
3228    /// ascending by `pk_u64`. Per-slice sort happens inside
3229    /// `prepare_freeze_slice`; the coordinator does only a
3230    /// k-way merge to reach the global PK ordering
3231    /// [`encode_segment`] requires.
3232    pub rows: Vec<(u64, Vec<u8>, IndexKey)>,
3233}
3234
3235/// v6.7.3 — outcome of a [`Catalog::compact_cold_segments`] call.
3236/// The catalog state has already been mutated when this is returned:
3237/// the merged segment is loaded into `cold_segments`, the source
3238/// segment slots are tombstoned (`None`), and every BTree-index
3239/// `RowLocator::Cold` that previously pointed at a source now
3240/// points at the merged segment. The caller's remaining job is to
3241/// persist `merged_segment_bytes` under
3242/// `<db>.spg/segments/seg_<merged_segment_id>.spg` and update the
3243/// in-memory `segment_id → path` map (remove the source ids, add
3244/// the merged id) so the next CHECKPOINT writes a manifest that
3245/// no longer lists the retired sources.
3246///
3247/// On a no-op (fewer than 2 candidate segments under the threshold),
3248/// `merged_segment_id` is `None` and `sources` is empty; the
3249/// catalog was not mutated.
3250#[derive(Debug, Clone)]
3251pub struct CompactReport {
3252    /// Source segment ids that were merged + tombstoned.
3253    pub sources: Vec<u32>,
3254    /// Id allocated for the merged segment. `None` on no-op.
3255    pub merged_segment_id: Option<u32>,
3256    /// Encoded merged-segment bytes (empty on no-op).
3257    pub merged_segment_bytes: Vec<u8>,
3258    /// Number of rows that landed in the merged segment.
3259    pub merged_rows: usize,
3260    /// `Σ source.num_rows − merged_rows`. Rows present in source
3261    /// segment payloads but unreferenced by any live BTree
3262    /// `Cold` locator — DELETE'd-but-still-frozen rows that
3263    /// compaction GC'd during the merge.
3264    pub deleted_rows_pruned: usize,
3265    /// `Σ source.bytes() − merged.bytes()`. Estimate of on-disk
3266    /// space the merge will reclaim once the source segment files
3267    /// are GC'd. Saturating subtract — never negative.
3268    pub bytes_reclaimed_estimate: u64,
3269}
3270
3271#[derive(Debug, Clone)]
3272pub enum IndexKind {
3273    /// v4.40: structural-sharing B-tree over `IndexKey`. Replaces the v0.8
3274    /// `BTreeMap<IndexKey, Vec<usize>>` — `Index::clone` is now an `Arc`
3275    /// bump regardless of index size, so `Catalog::clone` inside the
3276    /// v4.34 auto-commit wrap stays O(1) even for tables with secondary
3277    /// indices (the case that bottlenecked v4.39 at 1M rows in the
3278    /// sweep).
3279    ///
3280    /// v5.1: value type widened from `Vec<usize>` to `Vec<RowLocator>` so
3281    /// a single key can point to a mix of hot-tier rows (`RowLocator::Hot`,
3282    /// equivalent to the pre-v5 `usize` row index) and cold-tier rows
3283    /// (`RowLocator::Cold { segment_id, page_offset }`) once the v5.2
3284    /// freezer starts producing them. Pre-v5.2 only `Hot` entries appear
3285    /// — the on-disk encoding stays at `FILE_VERSION` 8 (raw u64 row index)
3286    /// because every locator round-trips through `RowLocator::from_legacy_v8_u64`
3287    /// without information loss. `FILE_VERSION` 9 with tagged encoding lands
3288    /// alongside the first freezer commit (v5.1 step 2b / v5.2).
3289    BTree(PersistentBTreeMap<IndexKey, crate::posting::PostingList>),
3290    /// Navigable-small-world graph for vector kNN search.
3291    Nsw(NswGraph),
3292    /// v6.7.1 — BRIN (Block Range INdex). Pure metadata: BRIN
3293    /// indexes carry NO in-memory key→locator map. The (min,
3294    /// max) summaries live in each cold-tier segment's v2
3295    /// envelope sidecar; the BRIN entry in `Table.indices` only
3296    /// records THAT a BRIN index exists on this column so the
3297    /// segment encoder + planner can opt into the summary path.
3298    Brin {
3299        /// The cell type at `column_position` at CREATE INDEX time.
3300        /// Used by the planner to type-check WHERE-clause range
3301        /// predicates against the BRIN-indexed column.
3302        column_type: DataType,
3303        /// v7.38.11 — one `(min, max)` per [`BRIN_RANGE_ROWS`] slots of
3304        /// the hot tier, so a range predicate can skip the ranges that
3305        /// cannot contain a match.
3306        ///
3307        /// Maintenance is WIDEN-ONLY and that is the whole safety
3308        /// argument: an insert widens its range, an update widens, and
3309        /// a delete leaves the range alone. A range left wider than the
3310        /// rows it now covers is correct and merely less selective —
3311        /// which is exactly PG's contract for a lossy index, since the
3312        /// predicate is re-checked on every row the summary lets
3313        /// through. A summary may over-report; it can never
3314        /// under-report, so no matching row can be skipped.
3315        ///
3316        /// `None` for a range whose rows carry no comparable key (all
3317        /// NULL, say), and such a range is never skipped.
3318        summaries: alloc::vec::Vec<Option<(i64, i64)>>,
3319    },
3320    /// v7.12.3 — GIN inverted index over a `tsvector` column.
3321    ///
3322    /// Storage shape: `lexeme word → Vec<RowLocator>`. The posting
3323    /// list per word is appended in row-order, so range scans are
3324    /// O(matching rows) once the per-word lookup is done. Multi-
3325    /// term queries intersect / union posting lists.
3326    ///
3327    /// `IndexKey::from_value(TsVector)` returns `None` — GIN doesn't
3328    /// participate in `try_index_seek` (which is BTree-equality-keyed).
3329    /// The engine consults this index through `try_gin_lookup` on
3330    /// `WHERE col @@ tsquery` predicates instead.
3331    ///
3332    /// Backed by a `PersistentBTreeMap` so `Catalog::clone` (the
3333    /// per-write snapshot) stays O(1) — same structural-sharing
3334    /// invariant as BTree.
3335    Gin(PersistentBTreeMap<alloc::string::String, crate::posting::PostingList>),
3336    /// v7.15.0 — `USING gin (col gin_trgm_ops)` over a `TEXT`
3337    /// column. Posting lists map `trigram` (PG-compatible 3-byte
3338    /// shingle on the lower-cased + space-padded input) to row
3339    /// locators. The planner uses this index to accelerate
3340    /// `WHERE col LIKE '…'` / `ILIKE '…'` / `similarity(col, q) >
3341    /// t` — every literal run of length ≥ 1 in the pattern
3342    /// produces a trigram set, the engine intersects the posting
3343    /// lists, and the LIKE / similarity predicate is re-evaluated
3344    /// per candidate row to filter the over-approximation.
3345    /// Persisted via tag-4 index payload in `FILE_VERSION` 24+.
3346    GinTrgm(PersistentBTreeMap<alloc::string::String, crate::posting::PostingList>),
3347    /// v7.17.0 Phase 2.2 — MySQL `FULLTEXT KEY (col)` over a
3348    /// `TEXT` / `VARCHAR` column. Posting lists map
3349    /// `tsvector('simple') lexeme` to row locators. At insert /
3350    /// build time the engine derives the lexemes from the cell
3351    /// via the same lower-case tokenisation rule as
3352    /// `to_tsvector('simple', ...)` — the column itself stays a
3353    /// plain text type on disk (mysqldump round-trips would be
3354    /// broken otherwise). The planner uses this index to
3355    /// accelerate MySQL-shape `MATCH(col) AGAINST('term')`
3356    /// queries by mapping them onto the existing tsquery `@@`
3357    /// walker. Persisted via tag-5 index payload in
3358    /// `FILE_VERSION` 33+.
3359    GinFulltext(PersistentBTreeMap<alloc::string::String, crate::posting::PostingList>),
3360    /// v7.37.8(sentori Epic 5 P2)— `USING gin (col)` over a
3361    /// `JSON` / `JSONB` column. Posting lists map a canonical
3362    /// `(path, leaf)` token(see [`crate::jsonb_gin::extract_tokens`])
3363    /// to row locators so the planner can resolve
3364    /// `<col> @> <jsonb_literal>` to a candidate row set via
3365    /// posting-list intersection + per-row `json::contains`
3366    /// re-verification. Pre-7.37.8 the same DDL loaded as a
3367    /// BTree fallback so `pg_dump` JSONB-GIN scripts kept loading
3368    /// without query-time acceleration. Persisted via tag-6 index
3369    /// payload in `FILE_VERSION` 51+.
3370    GinJsonb(PersistentBTreeMap<alloc::string::String, crate::posting::PostingList>),
3371    /// v7.38.1 (L12) — a REAL multi-column B-tree: the key is the whole
3372    /// column tuple, `[leading, extras…]`, ordered lexicographically by
3373    /// slice `Ord`. That ordering is the entire design: every key
3374    /// sharing a prefix is contiguous, so an equality on a PREFIX of
3375    /// the columns is one `O(log N)` descent plus a bounded walk, and a
3376    /// full-tuple equality is a point `get`. The single-column `BTree`
3377    /// kind used to stand in for multi-column DDL by keying on the
3378    /// leading column only and carrying the rest as metadata — TPC-C's
3379    /// `customer (c_w_id, c_d_id, c_last, c_first)` then answered a
3380    /// three-column equality with every row of one warehouse and a
3381    /// per-row filter over 30 000 candidates.
3382    ///
3383    /// Rows where any component column is NULL (or of an unkeyable
3384    /// type) are NOT entered: this index serves `=` probes, and in SQL
3385    /// `col = v` never selects a NULL. Uniqueness keeps its own
3386    /// full-tuple walk with NULLS-DISTINCT semantics on the
3387    /// enforcement path, exactly as before.
3388    ///
3389    /// Persisted via tag-7 index payload in `FILE_VERSION` 91+.
3390    BTreeMulti(PersistentBTreeMap<alloc::boxed::Box<[IndexKey]>, crate::posting::PostingList>),
3391}
3392
3393impl IndexKind {
3394    /// v7.31 (memory campaign, C2) — bytes this index variant holds
3395    /// resident in RAM, computed by walking its OWN structure rather
3396    /// than a parametric guess made by the engine. Replaces the old
3397    /// `spg_admin::memory_stats` inline match, which charged NSW with
3398    /// a stale `m_max_0 * 8` per node (neighbour slots are `u32` = 4 B
3399    /// since v6.1.x, and most nodes never fill `m_max_0`) and lumped
3400    /// every GIN family index into a flat 1 KiB token — a gross
3401    /// undercount for the text-heavy posting lists that dominate
3402    /// mailrs' footprint. Per-entry container overhead uses the
3403    /// 3-word (24 B on 64-bit) `Vec`/`String` header as the charge.
3404    ///
3405    /// O(index entries): operator/monitoring surface (`memory_stats` /
3406    /// `spg_memory_stats`), not a query path.
3407    #[must_use]
3408    pub fn approx_resident_bytes(&self) -> u64 {
3409        const HEADER: usize = 24; // Vec/String 3-word header on 64-bit.
3410        let loc = core::mem::size_of::<RowLocator>();
3411        match self {
3412            IndexKind::BTree(map) => {
3413                let key = core::mem::size_of::<IndexKey>();
3414                map.iter()
3415                    .map(|(_, locs)| (key + HEADER + locs.len() * loc) as u64)
3416                    .sum()
3417            }
3418            // v7.38.1 (L12) — multi keys own a boxed slice of components.
3419            IndexKind::BTreeMulti(map) => {
3420                let key = core::mem::size_of::<IndexKey>();
3421                map.iter()
3422                    .map(|(k, locs)| (HEADER + k.len() * key + HEADER + locs.len() * loc) as u64)
3423                    .sum()
3424            }
3425            IndexKind::Nsw(g) => {
3426                // `levels` is one byte per node; each layer's adjacency
3427                // is a `Vec<u32>` per node whose actual length we walk
3428                // (the dense layer-0 list dominates, but upper layers
3429                // are sparse — the old estimate ignored that).
3430                let mut b = g.levels.len() as u64;
3431                for layer in &g.layers {
3432                    for nbrs in layer.iter() {
3433                        b += (HEADER + nbrs.len() * core::mem::size_of::<u32>()) as u64;
3434                    }
3435                }
3436                b
3437            }
3438            // BRIN carries NO in-memory key→locator map (the (min,max)
3439            // summaries live in cold-segment sidecars on disk); the
3440            // resident footprint is just the column-type token.
3441            IndexKind::Brin { .. } => core::mem::size_of::<DataType>() as u64,
3442            IndexKind::Gin(map)
3443            | IndexKind::GinTrgm(map)
3444            | IndexKind::GinFulltext(map)
3445            | IndexKind::GinJsonb(map) => map
3446                .iter()
3447                .map(|(word, postings)| {
3448                    (word.len() + HEADER + HEADER + postings.len() * loc) as u64
3449                })
3450                .sum(),
3451        }
3452    }
3453}
3454
3455/// Multi-layer HNSW graph (v2.13). Each node is assigned a `top_level`;
3456/// it appears in layers `0..=top_level`. Higher layers are sparser, so
3457/// search starts from the entry at the top layer, greedy-descends to
3458/// layer 0, and beam-searches there. Layer 0 keeps a larger neighbour
3459/// budget (`m_max_0 = 2 * m` per the HNSW paper); upper layers cap at
3460/// `m`. The struct name stays `NswGraph` so external users / on-disk
3461/// callers don't have to track a rename — the algorithm changed, the
3462/// data slot didn't.
3463#[derive(Debug, Clone)]
3464pub struct NswGraph {
3465    /// Max neighbours per node on layers ≥ 1.
3466    pub m: usize,
3467    /// Max neighbours on layer 0 (the dense bottom layer). HNSW
3468    /// convention: `m_max_0 = 2 * m`.
3469    pub m_max_0: usize,
3470    /// Entry point — the node that sits on the topmost layer. Search
3471    /// always starts here.
3472    pub entry: Option<usize>,
3473    /// Top layer of the entry node (== `layers.len() - 1` when populated).
3474    pub entry_level: u8,
3475    /// `levels[i]` = top layer of node `i`. Nodes whose vector cell is
3476    /// NULL / non-Vector have `levels[i] = 0` and no neighbour entries.
3477    ///
3478    /// v5.5.0: backed by `PersistentVec` so `NswGraph::clone` (and the
3479    /// `Catalog::clone` on every group-commit write that contains it) is O(1)
3480    /// structural-sharing instead of an O(N) element copy.
3481    pub levels: PersistentVec<u8>,
3482    /// `layers[l][i]` = neighbours of node `i` at layer `l`. Inner vec
3483    /// is empty when node `i` doesn't reach layer `l`.
3484    ///
3485    /// v5.5.0: the per-node middle dimension (the O(N) one) is a
3486    /// `PersistentVec`; the outer layer dimension stays a plain `Vec`
3487    /// (layer count ≤ 8, so its clone is O(1) in practice) and the inner
3488    /// neighbour list stays a `Vec` (bounded by `m_max_0`).
3489    ///
3490    /// v6.1.x: neighbour slot widened from `usize` (8 B on 64-bit) to
3491    /// `u32` (4 B). Row indices are catalog-bounded by `u32::MAX` (4G
3492    /// rows per table); the cast at the NSW boundary asserts this. At
3493    /// 1M dim-128 SQ8, layer 0 adjacency alone shrinks by ~128 MiB
3494    /// — the largest single contribution to the v6.0.5-measured
3495    /// 624 MiB ambition gap. On-disk format already used u32 LE, so
3496    /// this is a pure in-memory layout change; no `FILE_VERSION` bump.
3497    pub layers: Vec<PersistentVec<Vec<u32>>>,
3498}
3499
3500impl NswGraph {
3501    fn new(m: usize) -> Self {
3502        Self {
3503            m,
3504            m_max_0: m.saturating_mul(2),
3505            entry: None,
3506            entry_level: 0,
3507            levels: PersistentVec::new(),
3508            layers: alloc::vec![PersistentVec::new()],
3509        }
3510    }
3511
3512    /// Max-neighbour budget for layer `l`.
3513    pub const fn cap_for_layer(&self, layer: u8) -> usize {
3514        if layer == 0 { self.m_max_0 } else { self.m }
3515    }
3516}
3517
3518/// Deterministic level assignment, seeded on the row index so the same
3519/// insert order reproduces the same topology. Distribution is roughly
3520/// HNSW-flavoured with `mL ≈ 1/ln(M) ≈ 0.36` for M=16: each 4-bit
3521/// chunk that comes up zero promotes the node one layer (so P(level ≥
3522/// L) ≈ (1/16)^L).
3523#[allow(clippy::verbose_bit_mask)] // clippy suggests trailing_zeros(); we need an explicit MAX cap and a stable distribution shape.
3524pub fn nsw_assign_level(row_idx: usize) -> u8 {
3525    const MAX_LEVEL: u8 = 7; // 7 ⇒ ~16^7 ≈ 2.7e8 expected nodes between promotions; ample.
3526    // SplitMix-style mixer — cheap and seedable.
3527    let mut x = (row_idx as u64).wrapping_mul(0x9E37_79B9_7F4A_7C15);
3528    x ^= x >> 30;
3529    x = x.wrapping_mul(0xBF58_476D_1CE4_E5B9);
3530    x ^= x >> 27;
3531    x = x.wrapping_mul(0x94D0_49BB_1331_11EB);
3532    x ^= x >> 31;
3533    // Count contiguous low-end zero nibbles (4-bit chunks). Each zero
3534    // nibble has probability 1/16, mirroring HNSW's `mL ≈ 1/ln(M)` for
3535    // M=16. `trailing_zeros / 4` would lose the ordering when x = 0, so
3536    // a plain loop with a cap is clearer.
3537    let mut level: u8 = 0;
3538    while x & 0xF == 0 && level < MAX_LEVEL {
3539        level += 1;
3540        x >>= 4;
3541    }
3542    level
3543}
3544
3545/// v7.38.1 (L12) — the composite key `values` takes in a multi-column
3546/// B-tree over `[lead, extras…]`. A NULL component keys as
3547/// [`IndexKey::Null`] (declared to sort last, PG's NULLS LAST) so the
3548/// row stays findable by prefix probes on the columns before it. `None`
3549/// = some non-null component has no key form; the row is then not
3550/// entered, which is why creation gates every component column's type
3551/// through [`multi_component_type_ok`].
3552pub(crate) fn compose_multi_key(
3553    values: &[Value<'_>],
3554    lead: usize,
3555    extras: &[usize],
3556) -> Option<alloc::boxed::Box<[IndexKey]>> {
3557    let mut comps: Vec<IndexKey> = Vec::with_capacity(1 + extras.len());
3558    for pos in core::iter::once(lead).chain(extras.iter().copied()) {
3559        let v = values.get(pos)?;
3560        if matches!(v, Value::Null) {
3561            comps.push(IndexKey::Null);
3562        } else {
3563            comps.push(IndexKey::from_value(v)?);
3564        }
3565    }
3566    Some(comps.into_boxed_slice())
3567}
3568
3569/// v7.38.1 (L12) — component-type gate for multi-column B-trees: every
3570/// NON-NULL value of these types keys through `IndexKey::from_value`,
3571/// so a row can only be absent from the index when creation raced a
3572/// type this list does not name. Deliberately conservative — a type
3573/// outside the list simply keeps its index on the leading-column path.
3574pub(crate) fn multi_component_type_ok(ty: DataType) -> bool {
3575    matches!(
3576        ty,
3577        DataType::SmallInt
3578            | DataType::Int
3579            | DataType::BigInt
3580            | DataType::Text
3581            | DataType::Varchar(_)
3582            | DataType::Char(_)
3583            | DataType::Bool
3584            | DataType::Uuid
3585            | DataType::Date
3586            | DataType::Timestamp
3587    )
3588}
3589
3590impl Index {
3591    /// Any key this B-tree currently holds, or `None` if it holds none.
3592    ///
3593    /// A probe built from a query literal has to be the same SHAPE as the
3594    /// keys the maintenance side made, or `lookup_eq` misses every row and
3595    /// the caller reads the empty answer as "no rows match". One stored
3596    /// key settles it: an index keys one expression, whose values are one
3597    /// type.
3598    pub fn sample_key(&self) -> Option<&IndexKey> {
3599        match &self.kind {
3600            IndexKind::BTree(map) => map.iter().next().map(|(k, _)| k),
3601            _ => None,
3602        }
3603    }
3604
3605    /// v7.38.19 — the largest integer key this index holds.
3606    ///
3607    /// For the one question it answers — what number comes next for a
3608    /// `serial` column — a tree already knows, and knew all along.
3609    /// [`Table::next_auto_value`] read every row instead:
3610    ///
3611    /// ```text
3612    ///   rows in the table    one INSERT      PostgreSQL 18
3613    ///      1,000              1.831 ms          1.245
3614    ///     10,000              1.814             1.289
3615    ///     50,000              2.703             1.386
3616    ///    200,000              3.666             1.375
3617    /// ```
3618    ///
3619    /// Theirs is flat because a sequence is a counter. Ours grew with
3620    /// the table, so an ingest workload got slower the longer it ran.
3621    ///
3622    /// A dead row version's key is still in the tree, so this can be
3623    /// HIGHER than the maximum over live rows. That is the safe
3624    /// direction — it hands out a value no row has ever held — and it
3625    /// is the direction PostgreSQL goes too, which never reuses a
3626    /// number a deleted row was given.
3627    ///
3628    /// `None` = no B-tree, or its keys are not integers, and the caller
3629    /// falls back to the scan.
3630    pub fn max_int_key(&self) -> Option<i64> {
3631        let IndexKind::BTree(map) = &self.kind else {
3632            return None;
3633        };
3634        match map.iter_rev().next()? {
3635            (IndexKey::Int(n), _) => Some(*n),
3636            _ => None,
3637        }
3638    }
3639
3640    fn new_btree(name: String, column_position: usize) -> Self {
3641        Self {
3642            name,
3643            column_position,
3644            kind: IndexKind::BTree(PersistentBTreeMap::new()),
3645            included_columns: Vec::new(),
3646            partial_predicate: None,
3647            expression: None,
3648            is_unique: false,
3649            nulls_not_distinct: false,
3650            descending: false,
3651            nulls_first: None,
3652            collation: None,
3653            extra_column_positions: Vec::new(),
3654        }
3655    }
3656
3657    /// v7.38.1 (L12) — a real multi-column B-tree shell. The caller
3658    /// sets `extra_column_positions` before the first row enters; the
3659    /// key arity is `1 + extras` from then on.
3660    fn new_btree_multi(name: String, column_position: usize) -> Self {
3661        Self {
3662            kind: IndexKind::BTreeMulti(PersistentBTreeMap::new()),
3663            ..Self::new_btree(name, column_position)
3664        }
3665    }
3666
3667    /// v7.38.1 (L12) — the composite key this row takes in a
3668    /// [`IndexKind::BTreeMulti`] index. NULL components key as
3669    /// [`IndexKey::Null`] so prefix probes still find the row; `None`
3670    /// only when a non-null component produces no key, which creation's
3671    /// component-type gate makes unreachable for well-formed indexes.
3672    pub fn multi_key_for_row(&self, values: &[Value<'_>]) -> Option<alloc::boxed::Box<[IndexKey]>> {
3673        compose_multi_key(values, self.column_position, &self.extra_column_positions)
3674    }
3675
3676    fn new_nsw(name: String, column_position: usize, m: usize) -> Self {
3677        Self {
3678            name,
3679            column_position,
3680            kind: IndexKind::Nsw(NswGraph::new(m)),
3681            included_columns: Vec::new(),
3682            partial_predicate: None,
3683            expression: None,
3684            is_unique: false,
3685            nulls_not_distinct: false,
3686            descending: false,
3687            nulls_first: None,
3688            collation: None,
3689            extra_column_positions: Vec::new(),
3690        }
3691    }
3692
3693    /// v6.7.1 — BRIN index constructor. BRIN carries no in-memory
3694    /// data; the `column_type` snapshot is used by the segment
3695    /// encoder + planner for type-checking range predicates.
3696    fn new_brin(name: String, column_position: usize, column_type: DataType) -> Self {
3697        Self {
3698            name,
3699            column_position,
3700            kind: IndexKind::Brin {
3701                column_type,
3702                summaries: alloc::vec::Vec::new(),
3703            },
3704            included_columns: Vec::new(),
3705            partial_predicate: None,
3706            expression: None,
3707            is_unique: false,
3708            nulls_not_distinct: false,
3709            descending: false,
3710            nulls_first: None,
3711            collation: None,
3712            extra_column_positions: Vec::new(),
3713        }
3714    }
3715
3716    /// v7.12.3 — GIN inverted-index constructor. Empty posting-list
3717    /// map; caller (typically [`Table::add_gin_index`] or
3718    /// [`Table::restore_gin_index`]) populates it from existing rows
3719    /// or from a deserialised snapshot.
3720    fn new_gin(name: String, column_position: usize) -> Self {
3721        Self {
3722            name,
3723            column_position,
3724            kind: IndexKind::Gin(PersistentBTreeMap::new()),
3725            included_columns: Vec::new(),
3726            partial_predicate: None,
3727            expression: None,
3728            is_unique: false,
3729            nulls_not_distinct: false,
3730            descending: false,
3731            nulls_first: None,
3732            collation: None,
3733            extra_column_positions: Vec::new(),
3734        }
3735    }
3736
3737    /// v7.15.0 — `gin_trgm_ops`-flavoured GIN constructor. Same
3738    /// shape as `new_gin` but the posting-list keys are 3-byte
3739    /// trigram shingles (`pg_trgm`-compatible) and the column
3740    /// type is `TEXT` / `VARCHAR` (not `TSVECTOR`).
3741    fn new_gin_trgm(name: String, column_position: usize) -> Self {
3742        Self {
3743            name,
3744            column_position,
3745            kind: IndexKind::GinTrgm(PersistentBTreeMap::new()),
3746            included_columns: Vec::new(),
3747            partial_predicate: None,
3748            expression: None,
3749            is_unique: false,
3750            nulls_not_distinct: false,
3751            descending: false,
3752            nulls_first: None,
3753            collation: None,
3754            extra_column_positions: Vec::new(),
3755        }
3756    }
3757
3758    /// v7.17.0 Phase 2.2 — MySQL `FULLTEXT KEY` GIN constructor.
3759    /// Same shape as `new_gin_trgm` but the posting-list keys
3760    /// are lower-cased word lexemes (`to_tsvector('simple', col)`
3761    /// equivalent) instead of trigrams, and the column type is
3762    /// `TEXT` / `VARCHAR` (not `TSVECTOR`).
3763    fn new_gin_fulltext(name: String, column_position: usize) -> Self {
3764        Self {
3765            name,
3766            column_position,
3767            kind: IndexKind::GinFulltext(PersistentBTreeMap::new()),
3768            included_columns: Vec::new(),
3769            partial_predicate: None,
3770            expression: None,
3771            is_unique: false,
3772            nulls_not_distinct: false,
3773            descending: false,
3774            nulls_first: None,
3775            collation: None,
3776            extra_column_positions: Vec::new(),
3777        }
3778    }
3779
3780    /// v7.37.8(sentori Epic 5 P2)— JSONB-GIN constructor. Same
3781    /// shape as the other GIN-family indexes; posting-list keys
3782    /// are the canonical `(path, leaf)` tokens emitted by
3783    /// `crate::jsonb_gin::extract_tokens`. Maintains posting
3784    /// lists from `Value::Json` cells(JSONB is a synonym for the
3785    /// same in-memory string-backed Value).
3786    fn new_gin_jsonb(name: String, column_position: usize) -> Self {
3787        Self {
3788            name,
3789            column_position,
3790            kind: IndexKind::GinJsonb(PersistentBTreeMap::new()),
3791            included_columns: Vec::new(),
3792            partial_predicate: None,
3793            expression: None,
3794            is_unique: false,
3795            nulls_not_distinct: false,
3796            descending: false,
3797            nulls_first: None,
3798            collation: None,
3799            extra_column_positions: Vec::new(),
3800        }
3801    }
3802
3803    /// v7.34.4 — descending-order iterator over `(IndexKey, locators)`
3804    /// pairs for a BTree index, with O(log N) descent to the rightmost
3805    /// leaf and lazy emission thereafter. Returns an empty iterator
3806    /// for non-BTree index kinds — callers handle both uniformly.
3807    /// Used by the ORDER BY `<indexed col>` DESC + LIMIT N executor
3808    /// path: walking only the first N matches off the rightmost leaf
3809    /// avoids the per-row materialisation + partial-sort cost on
3810    /// large tables (mailrs `content_worker` at 250 k rows).
3811    pub fn iter_desc(
3812        &self,
3813    ) -> alloc::boxed::Box<dyn Iterator<Item = (&IndexKey, &crate::posting::PostingList)> + '_>
3814    {
3815        match &self.kind {
3816            IndexKind::BTree(m) => alloc::boxed::Box::new(m.iter_rev()),
3817            // v7.38.1 (L12) — projecting the leading component of a
3818            // composite key preserves order: keys sort by the whole
3819            // tuple, so the leading component is non-increasing here
3820            // (non-decreasing in iter_asc), exactly what an ORDER BY
3821            // on the leading column needs.
3822            IndexKind::BTreeMulti(m) => {
3823                alloc::boxed::Box::new(m.iter_rev().map(|(k, l)| (&k[0], l)))
3824            }
3825            IndexKind::Nsw(_)
3826            | IndexKind::Brin { .. }
3827            | IndexKind::Gin(_)
3828            | IndexKind::GinTrgm(_)
3829            | IndexKind::GinFulltext(_)
3830            | IndexKind::GinJsonb(_) => alloc::boxed::Box::new(core::iter::empty()),
3831        }
3832    }
3833
3834    /// v7.34.4 — ascending-order iterator over `(IndexKey, locators)`
3835    /// pairs. Mirror of `iter_desc` for ORDER BY ... ASC + LIMIT N.
3836    pub fn iter_asc(
3837        &self,
3838    ) -> alloc::boxed::Box<dyn Iterator<Item = (&IndexKey, &crate::posting::PostingList)> + '_>
3839    {
3840        match &self.kind {
3841            IndexKind::BTree(m) => alloc::boxed::Box::new(m.iter()),
3842            // v7.38.1 (L12) — see iter_desc: the leading component of
3843            // a tuple-sorted walk is itself in order.
3844            IndexKind::BTreeMulti(m) => alloc::boxed::Box::new(m.iter().map(|(k, l)| (&k[0], l))),
3845            IndexKind::Nsw(_)
3846            | IndexKind::Brin { .. }
3847            | IndexKind::Gin(_)
3848            | IndexKind::GinTrgm(_)
3849            | IndexKind::GinFulltext(_)
3850            | IndexKind::GinJsonb(_) => alloc::boxed::Box::new(core::iter::empty()),
3851        }
3852    }
3853
3854    /// Look up the locators stored under `key` (B-tree only). Returns
3855    /// an empty slice when the key is absent or the index isn't a
3856    /// BTree — callers can treat both cases uniformly.
3857    ///
3858    /// v5.1: return type widened from `&[usize]` to `&[RowLocator]`.
3859    /// Pre-v5.2 callers can read the slice and `.as_hot().unwrap()`
3860    /// each entry (no `Cold` variants exist until the freezer lands);
3861    /// post-v5.2 callers dispatch hot vs. cold per locator.
3862    pub fn lookup_eq(&self, key: &IndexKey) -> &crate::posting::PostingList {
3863        match &self.kind {
3864            IndexKind::BTree(m) => m.get(key).map_or(&EMPTY_POSTINGS, |l| l),
3865            // BRIN / NSW / GIN / trigram-GIN / fulltext-GIN have
3866            // no IndexKey-keyed map; lookup is a no-op. GIN uses
3867            // [`Index::gin_lookup_word`] instead.
3868            IndexKind::Nsw(_)
3869            | IndexKind::Brin { .. }
3870            | IndexKind::Gin(_)
3871            | IndexKind::GinTrgm(_)
3872            | IndexKind::GinFulltext(_)
3873            | IndexKind::GinJsonb(_)
3874            | IndexKind::BTreeMulti(_) => &EMPTY_POSTINGS,
3875        }
3876    }
3877
3878    /// v7.37.43 (INSUBQ B-2) — specialised lookup for integer-PK probes.
3879    /// `try_count_star_pk_in_subquery_fast` already holds an `i64` (the
3880    /// inner survivor key); skip the `IndexKey::from_value` enum-dispatch
3881    /// trip and build the key inline. ~20 ns × N_survivors saved on
3882    /// the INSUBQ hot loop.
3883    #[inline]
3884    pub fn lookup_eq_i64(&self, n: i64) -> &crate::posting::PostingList {
3885        match &self.kind {
3886            IndexKind::BTree(m) => m.get(&IndexKey::Int(n)).map_or(&EMPTY_POSTINGS, |l| l),
3887            IndexKind::Nsw(_)
3888            | IndexKind::Brin { .. }
3889            | IndexKind::Gin(_)
3890            | IndexKind::GinTrgm(_)
3891            | IndexKind::GinFulltext(_)
3892            | IndexKind::GinJsonb(_)
3893            | IndexKind::BTreeMulti(_) => &EMPTY_POSTINGS,
3894        }
3895    }
3896
3897    /// v7.38 (perf, index range scan) — flatten the row locators for every key
3898    /// in `[lo, hi]` (bounds per `core::ops::Bound`) via the BTree's `O(log N +
3899    /// k)` range walk. Returns `None` once more than `cap` locators accumulate
3900    /// — a "this range isn't selective enough, seq-scan instead" signal that
3901    /// stops a wide range from materialising a near-full table's worth of rows
3902    /// through the index. BTree only (other kinds → None).
3903    pub fn lookup_range_capped(
3904        &self,
3905        lo: core::ops::Bound<&IndexKey>,
3906        hi: core::ops::Bound<&IndexKey>,
3907        cap: usize,
3908    ) -> Option<Vec<RowLocator>> {
3909        self.lookup_range_capped_by(lo, hi, cap, |_| true)
3910    }
3911
3912    /// v7.39 (round 490) — the same range walk, but the caller decides
3913    /// which locators are worth carrying, and the cap counts only those.
3914    ///
3915    /// A BTree index holds one locator per row VERSION. On a churned table
3916    /// the dead versions are still in there: round 490 measured a
3917    /// 1000-row range handing back 61 000 locators after 60
3918    /// delete-and-reinsert cycles with the background vacuum switched off.
3919    /// Every caller then dropped the dead ones — the mutation paths and the
3920    /// SELECT range path all test `is_row_visible` and `continue` — but only
3921    /// after they had been collected into a `Vec`, sorted, and walked.
3922    ///
3923    /// Handing the predicate down means the walk keeps ~1000, and the cap
3924    /// (which exists so an index walk never costs more than the scan it
3925    /// replaces) is once again measured in rows a caller will actually look
3926    /// at. Round 461 had to add the dead count to the budget to stop the
3927    /// seek being refused outright; with the filter here that compensation
3928    /// is no longer needed.
3929    pub fn lookup_range_capped_by(
3930        &self,
3931        lo: core::ops::Bound<&IndexKey>,
3932        hi: core::ops::Bound<&IndexKey>,
3933        cap: usize,
3934        keep: impl Fn(RowLocator) -> bool,
3935    ) -> Option<Vec<RowLocator>> {
3936        match &self.kind {
3937            IndexKind::BTree(m) => {
3938                let mut out: Vec<RowLocator> = Vec::new();
3939                for (_, locs) in m.range(lo, hi) {
3940                    out.extend(locs.iter().copied().filter(|l| keep(*l)));
3941                    if out.len() > cap {
3942                        return None;
3943                    }
3944                }
3945                Some(out)
3946            }
3947            IndexKind::Nsw(_)
3948            | IndexKind::Brin { .. }
3949            | IndexKind::Gin(_)
3950            | IndexKind::GinTrgm(_)
3951            | IndexKind::GinFulltext(_)
3952            | IndexKind::GinJsonb(_)
3953            | IndexKind::BTreeMulti(_) => None,
3954        }
3955    }
3956
3957    /// v7.38.1 (L12) — full-tuple point lookup on a [`IndexKind::BTreeMulti`]
3958    /// index. `key` must carry exactly as many components as the index
3959    /// has columns; anything else (including a probe against a
3960    /// non-multi index) finds nothing, and "nothing" here is safe
3961    /// because the caller falls back to a scan, never to an answer.
3962    pub fn lookup_eq_multi(&self, key: &[IndexKey]) -> &crate::posting::PostingList {
3963        match &self.kind {
3964            IndexKind::BTreeMulti(m) if key.len() == 1 + self.extra_column_positions.len() => {
3965                m.get_by(key).map_or(&EMPTY_POSTINGS, |l| l)
3966            }
3967            _ => &EMPTY_POSTINGS,
3968        }
3969    }
3970
3971    /// v7.38.1 (L12) — locators for every key whose leading components
3972    /// equal `prefix`, on a [`IndexKind::BTreeMulti`] index. Slice
3973    /// ordering keeps a prefix's keys contiguous, so this is one
3974    /// descent to `[prefix]` and a walk that stops at the first key
3975    /// leaving the prefix. Same cap/keep contract as
3976    /// [`Index::lookup_range_capped_by`]: `None` = not selective
3977    /// enough (or not a multi index), fall back.
3978    pub fn lookup_prefix_capped_by(
3979        &self,
3980        prefix: &[IndexKey],
3981        cap: usize,
3982        keep: impl Fn(RowLocator) -> bool,
3983    ) -> Option<Vec<RowLocator>> {
3984        let IndexKind::BTreeMulti(m) = &self.kind else {
3985            return None;
3986        };
3987        if prefix.is_empty() || prefix.len() > 1 + self.extra_column_positions.len() {
3988            return None;
3989        }
3990        let lo: alloc::boxed::Box<[IndexKey]> = prefix.to_vec().into_boxed_slice();
3991        let mut out: Vec<RowLocator> = Vec::new();
3992        for (k, locs) in m.range(core::ops::Bound::Included(&lo), core::ops::Bound::Unbounded) {
3993            if k.len() < prefix.len() || k[..prefix.len()] != *prefix {
3994                break;
3995            }
3996            out.extend(locs.iter().copied().filter(|l| keep(*l)));
3997            if out.len() > cap {
3998                return None;
3999            }
4000        }
4001        Some(out)
4002    }
4003
4004    /// v7.38.19 — a RANGE on the composite tree's leading column.
4005    ///
4006    /// Tuples order lexicographically, so every key whose first
4007    /// component is `x` sorts at or after the one-element tuple `[x]`
4008    /// and before `[x']` for any larger `x'`. That makes a leading-
4009    /// column range one contiguous run, walked exactly like the
4010    /// single-column range walk — the only difference is that the
4011    /// comparison is against `k[0]` rather than the whole key.
4012    ///
4013    /// Without this, `WHERE project_id > 90` on a table whose only
4014    /// index was `(project_id, kind)` read every row: 4.067 ms against
4015    /// PostgreSQL 18's 0.220, on a predicate matching nothing. The same
4016    /// query with a single-column index took 0.165, which is what says
4017    /// the range was never the problem.
4018    pub fn lookup_leading_range_capped_by(
4019        &self,
4020        lo: core::ops::Bound<&IndexKey>,
4021        hi: core::ops::Bound<&IndexKey>,
4022        cap: usize,
4023        keep: impl Fn(RowLocator) -> bool,
4024    ) -> Option<Vec<RowLocator>> {
4025        let IndexKind::BTreeMulti(m) = &self.kind else {
4026            return None;
4027        };
4028        // The start of the run. An EXCLUDED lower bound cannot be
4029        // handed to the map as-is: `[x]` sorts BEFORE `[x, y]`, so
4030        // excluding `[x]` would still admit every tuple that begins
4031        // with `x`. Start at `[x]` included and drop those tuples by
4032        // the per-key test below, which compares the component.
4033        let lo_key: Option<alloc::boxed::Box<[IndexKey]>> = match lo {
4034            core::ops::Bound::Included(k) | core::ops::Bound::Excluded(k) => {
4035                Some(alloc::vec![k.clone()].into_boxed_slice())
4036            }
4037            core::ops::Bound::Unbounded => None,
4038        };
4039        let start = match &lo_key {
4040            Some(k) => core::ops::Bound::Included(k),
4041            None => core::ops::Bound::Unbounded,
4042        };
4043        let mut out: Vec<RowLocator> = Vec::new();
4044        for (k, locs) in m.range(start, core::ops::Bound::Unbounded) {
4045            let Some(first) = k.first() else { continue };
4046            match lo {
4047                core::ops::Bound::Excluded(b) if first == b => continue,
4048                _ => {}
4049            }
4050            match hi {
4051                core::ops::Bound::Included(b) if first > b => break,
4052                core::ops::Bound::Excluded(b) if first >= b => break,
4053                _ => {}
4054            }
4055            out.extend(locs.iter().copied().filter(|l| keep(*l)));
4056            if out.len() > cap {
4057                return None;
4058            }
4059        }
4060        Some(out)
4061    }
4062
4063    /// v7.39 (round 560) — the index range as (key, locator) pairs.
4064    ///
4065    /// `lookup_range_capped_by` throws the KEY away and returns only
4066    /// locators, so a query whose projection is exactly the indexed
4067    /// column still goes to the row store for a value the walk already
4068    /// had in hand — paying per row for something the index knows.
4069    ///
4070    /// Uncapped on purpose: an index-only walk touches no row, so the
4071    /// selectivity ceiling that keeps a seek from being worse than the
4072    /// scan it replaces does not apply to it.
4073    ///
4074    /// v7.39 (round 562) — and it does not collect, either. This
4075    /// returned a `Vec<(IndexKey, RowLocator)>`: for a 100k-row range,
4076    /// 100k key clones into a `Vec::new()` that doubles its way up to
4077    /// several MB, all to be walked once and dropped. A profile of the
4078    /// server serving that query put 20% of the connection thread's CPU
4079    /// on the collect alone, with another 18% in the allocator beside
4080    /// it. The caller consumes the pairs in order and needs the key
4081    /// only by reference, so it can have the walk itself.
4082    pub fn range_keyed(
4083        &self,
4084        lo: core::ops::Bound<&IndexKey>,
4085        hi: core::ops::Bound<&IndexKey>,
4086    ) -> Option<impl Iterator<Item = (&IndexKey, RowLocator)> + '_> {
4087        match &self.kind {
4088            IndexKind::BTree(m) => Some(
4089                m.range(lo, hi)
4090                    .flat_map(|(k, locs)| locs.iter().map(move |l| (k, *l))),
4091            ),
4092            IndexKind::Nsw(_)
4093            | IndexKind::Brin { .. }
4094            | IndexKind::Gin(_)
4095            | IndexKind::GinTrgm(_)
4096            | IndexKind::GinFulltext(_)
4097            | IndexKind::GinJsonb(_)
4098            | IndexKind::BTreeMulti(_) => None,
4099        }
4100    }
4101
4102    /// v7.12.3 — GIN posting-list lookup. Returns the row locators
4103    /// whose `tsvector` cell contains `word`. Empty when the word is
4104    /// absent from the index or this isn't a GIN index.
4105    pub fn gin_lookup_word(&self, word: &str) -> &crate::posting::PostingList {
4106        match &self.kind {
4107            // v7.17.0 Phase 2.2 — fulltext-GIN shares the same
4108            // lexeme-keyed posting list shape as the
4109            // tsvector-typed GIN, so the same lookup applies.
4110            IndexKind::Gin(m) | IndexKind::GinFulltext(m) => {
4111                m.get(&String::from(word)).map_or(&EMPTY_POSTINGS, |l| l)
4112            }
4113            IndexKind::BTree(_)
4114            | IndexKind::Nsw(_)
4115            | IndexKind::Brin { .. }
4116            | IndexKind::GinTrgm(_)
4117            | IndexKind::GinJsonb(_)
4118            | IndexKind::BTreeMulti(_) => &EMPTY_POSTINGS,
4119        }
4120    }
4121
4122    /// v7.15.0 — trigram-GIN posting-list lookup. Returns the row
4123    /// locators whose indexed `TEXT` cell contains the trigram
4124    /// `tri`. Empty when the trigram is absent or this isn't a
4125    /// trigram-GIN index.
4126    pub fn gin_trgm_lookup(&self, tri: &str) -> &crate::posting::PostingList {
4127        match &self.kind {
4128            IndexKind::GinTrgm(m) => m.get(&String::from(tri)).map_or(&EMPTY_POSTINGS, |l| l),
4129            IndexKind::BTree(_)
4130            | IndexKind::Nsw(_)
4131            | IndexKind::Brin { .. }
4132            | IndexKind::Gin(_)
4133            | IndexKind::GinFulltext(_)
4134            | IndexKind::GinJsonb(_)
4135            | IndexKind::BTreeMulti(_) => &EMPTY_POSTINGS,
4136        }
4137    }
4138
4139    /// v7.37.8(sentori Epic 5 P2)— JSONB-GIN posting-list lookup.
4140    /// Returns the row locators whose indexed JSONB cell carries
4141    /// the canonical `token`(see [`crate::jsonb_gin::extract_tokens`]).
4142    /// Empty when the token is absent or this isn't a JSONB-GIN
4143    /// index. Planners drive `<col> @> <jsonb_literal>` through here.
4144    pub fn gin_jsonb_lookup(&self, token: &str) -> &crate::posting::PostingList {
4145        match &self.kind {
4146            IndexKind::GinJsonb(m) => m.get(&String::from(token)).map_or(&EMPTY_POSTINGS, |l| l),
4147            IndexKind::BTree(_)
4148            | IndexKind::Nsw(_)
4149            | IndexKind::Brin { .. }
4150            | IndexKind::Gin(_)
4151            | IndexKind::GinTrgm(_)
4152            | IndexKind::GinFulltext(_)
4153            | IndexKind::BTreeMulti(_) => &EMPTY_POSTINGS,
4154        }
4155    }
4156
4157    /// Borrow the NSW graph (if this is an NSW index). Callers that need
4158    /// the graph for a kNN search go through here.
4159    pub const fn nsw(&self) -> Option<&NswGraph> {
4160        match &self.kind {
4161            IndexKind::Nsw(g) => Some(g),
4162            IndexKind::BTree(_)
4163            | IndexKind::Brin { .. }
4164            | IndexKind::Gin(_)
4165            | IndexKind::GinTrgm(_)
4166            | IndexKind::GinFulltext(_)
4167            | IndexKind::GinJsonb(_)
4168            | IndexKind::BTreeMulti(_) => None,
4169        }
4170    }
4171
4172    /// v6.7.1 — true when this index is a BRIN (block range) index.
4173    /// Used by the segment encoder to opt into BRIN sidecar emission
4174    /// at freeze time, and by the planner to opt into page-skipping
4175    /// on range predicates.
4176    pub const fn is_brin(&self) -> bool {
4177        matches!(self.kind, IndexKind::Brin { .. })
4178    }
4179
4180    /// v7.15.0 — true when this index is a trigram GIN
4181    /// (`gin_trgm_ops`-flavoured). Used by the LIKE planner to
4182    /// opt into trigram acceleration.
4183    pub const fn is_gin_trgm(&self) -> bool {
4184        matches!(self.kind, IndexKind::GinTrgm(_))
4185    }
4186
4187    /// v7.12.3 — true when this index is a GIN inverted index.
4188    /// Used by the planner to opt into posting-list acceleration on
4189    /// `WHERE col @@ tsquery` predicates.
4190    pub const fn is_gin(&self) -> bool {
4191        matches!(self.kind, IndexKind::Gin(_))
4192    }
4193
4194    /// v7.17.0 Phase 2.2 — true when this index is a fulltext
4195    /// GIN over a TEXT / VARCHAR column (MySQL `FULLTEXT KEY`
4196    /// surface). Used by the planner to opt the FULLTEXT-indexed
4197    /// column into MATCH AGAINST acceleration.
4198    pub const fn is_gin_fulltext(&self) -> bool {
4199        matches!(self.kind, IndexKind::GinFulltext(_))
4200    }
4201
4202    /// v7.37.8(sentori Epic 5 P2)— true when this index is a
4203    /// real JSONB-GIN(posting-list backed). Used by the planner
4204    /// to opt `<col> @> <jsonb_literal>` into posting-list seek.
4205    pub const fn is_gin_jsonb(&self) -> bool {
4206        matches!(self.kind, IndexKind::GinJsonb(_))
4207    }
4208}
4209
4210/// In-memory table: schema + a persistent row vector + secondary indices.
4211///
4212/// v4.39: `rows` is a [`PersistentVec`] (Bitmapped Vector Trie, 32-way) so
4213/// `Table::clone()` is `O(1)` — the whole reason for v4.39's existence is
4214/// to make `Catalog::clone()` cheap inside the v4.34 auto-commit wrap.
4215///
4216/// v5.2.1: `hot_bytes` tracks the encoded byte size of every row currently
4217/// in [`Self::rows`], summed over rows. Updated incrementally by `insert`
4218/// (+= encoded row size), `delete_rows` (-= removed rows' encoded sizes),
4219/// and `update_row` (-= old size, += new size). The value is what the
4220/// v5.2 freezer reads to decide when to demote cold rows — when the
4221/// catalog-wide sum crosses `SPG_HOT_TIER_BYTES` (default 4 GiB) the
4222/// freezer thread wakes. v5.2.1 ships measurement only; the freezer
4223/// itself lands in v5.2.2. Stored as `u64` so a single field clone in
4224/// `Catalog::clone` stays at the O(1) invariant v4.39 built.
4225/// v7.34 (crash-recovery P0 #2) — one row-level physical redo record.
4226/// Row-level redo replaces statement-based WAL replay (which re-executes
4227/// each SQL through the full engine — O(records × catalog_rows), the
4228/// superlinear recovery hang root-caused on the mailrs crash-recovery
4229/// P0). A `RowChange` is the exact storage mutation the engine applied
4230/// (`Table::insert` / `update_row` / `delete_rows`); replaying it on a
4231/// catalog restored from the matching checkpoint reproduces the state
4232/// WITHOUT re-validating uniqueness/FK/parse/plan — O(changed rows).
4233///
4234/// Positions are physical, not key-based: `serialize`/`deserialize`
4235/// preserve row order exactly (rows written + read back in `self.rows`
4236/// order) and the mutation ops are deterministic, so the same op sequence
4237/// replayed from the same checkpoint reproduces the same positions. This
4238/// matches PostgreSQL's physical redo and supports tables with no primary
4239/// key. (Caveat handled at replay integration: a post-checkpoint cold-tier
4240/// freeze shifts hot positions and must itself be logged or fenced by a
4241/// checkpoint — see `row-level-redo-design`.)
4242/// ## v7.37.15 (Epic W slice 1) — additive MVCC identity metadata
4243///
4244/// Each variant now also carries, additively, the stable
4245/// [`RowId`](row_header::RowId) of the affected row(s) and the
4246/// **writer version** (`xmin` for an insert, `xmax` for a
4247/// delete/update). This is the codec foundation for making
4248/// in-place MVCC tombstones durable across crash/upgrade recovery.
4249///
4250/// Two important properties for the durability path:
4251///
4252/// 1. **Replay resolution is UNCHANGED.** `apply_redo_run_on_table`
4253///    still resolves every change by physical `pos`/`positions`
4254///    exactly as before. The new metadata is *carried but unused*
4255///    by replay in this slice; resolving-by-`RowId` and
4256///    header-preserving replay are later slices.
4257/// 2. **Backward compatibility.** A redo payload written by
4258///    pre-Epic-W code carries no metadata; [`decode_redo_log`]
4259///    fills `rowid`/`rowids` with [`RowId::UNASSIGNED`](row_header::RowId::UNASSIGNED)
4260///    (empty for `Delete`) and `writer_version` with `0`. See the
4261///    codec version gate in [`encode_redo_log`]/[`decode_redo_log`].
4262///
4263/// The `writer_version` is captured as `0` at the storage layer
4264/// (`Table::insert`/`delete_rows`/`update_row` don't have the
4265/// committing `TxId`), then **stamped with the real committing
4266/// version by the engine** after it drains the statement's changes
4267/// (Epic W slice 2 — [`RowChange::set_writer_version`], driven from
4268/// `Engine::writer_version_for_current_stmt`). All changes from one
4269/// statement share the one version. Replay still resolves by
4270/// physical position and does not read `writer_version` — that is a
4271/// later slice (header-preserving replay).
4272#[derive(Debug, Clone, PartialEq)]
4273pub enum RowChange {
4274    /// Append `row` to `table`.
4275    Insert {
4276        table: String,
4277        row: Row<'static>,
4278        /// Epic W: stable id the appended row will receive.
4279        /// [`RowId::UNASSIGNED`](row_header::RowId::UNASSIGNED) when
4280        /// decoded from a pre-Epic-W redo payload.
4281        rowid: row_header::RowId,
4282        /// Epic W: writer version (`xmin`). `0` until the writing
4283        /// `TxId` is threaded to the storage layer (later slice).
4284        writer_version: u64,
4285    },
4286    /// Replace the row at physical `pos` in `table` with `new_row`.
4287    Update {
4288        table: String,
4289        pos: usize,
4290        new_row: Vec<Value<'static>>,
4291        /// Epic W: stable id of the row at `pos`.
4292        /// [`RowId::UNASSIGNED`](row_header::RowId::UNASSIGNED) when
4293        /// decoded from a pre-Epic-W redo payload.
4294        rowid: row_header::RowId,
4295        /// Epic W: writer version (`xmax` of the superseded tuple).
4296        /// `0` until the writing `TxId` is threaded (later slice).
4297        writer_version: u64,
4298    },
4299    /// Remove the rows at the given physical `positions` from `table`.
4300    Delete {
4301        table: String,
4302        positions: Vec<usize>,
4303        /// Epic W: stable ids parallel to `positions` (same length,
4304        /// [`RowId::UNASSIGNED`](row_header::RowId::UNASSIGNED) for an
4305        /// out-of-bounds input position). **Empty** when decoded from
4306        /// a pre-Epic-W redo payload (no metadata was recorded).
4307        rowids: Vec<row_header::RowId>,
4308        /// Epic W: writer version (`xmax`). `0` until the writing
4309        /// `TxId` is threaded to the storage layer (later slice).
4310        writer_version: u64,
4311    },
4312    /// v7.37.15 (Epic W durable-tombstone slice) — an **in-place MVCC
4313    /// delete**: the row(s) named by `rowids` are NOT physically
4314    /// removed; their header `xmax` is stamped so newer snapshots stop
4315    /// seeing them (vacuum reclaims later). This is the redo shape of
4316    /// the gate-on (`SPG_MVCC_INPLACE`) DELETE / UPDATE-old-version /
4317    /// ON-CONFLICT paths, which call [`Table::mark_row_deleted`]
4318    /// instead of `delete_rows`.
4319    ///
4320    /// Unlike `Delete`, the target is named by **stable `RowId`**, not
4321    /// physical position: a tombstone keeps the slot, so position would
4322    /// be ambiguous after later compaction, and the header-preserving
4323    /// replay must re-find the exact row the writer tombstoned. On
4324    /// replay the id is matched against the ids the same redo run
4325    /// produced (an `Insert`'s `rowid`, or the table's ids snapshotted
4326    /// at run start); an id that cannot be resolved is skipped and
4327    /// counted (see `apply_redo_run_on_table`) — this is the documented
4328    /// cross-checkpoint limitation until the V6 envelope persists ids.
4329    Tombstone {
4330        table: String,
4331        /// Stable ids of the tombstoned rows (from `self.rowids()[pos]`
4332        /// at capture). Never empty for a recorded tombstone.
4333        rowids: Vec<row_header::RowId>,
4334        /// The version stamped into each target row's header `xmax`
4335        /// (the deleting statement's writer version).
4336        xmax: u64,
4337    },
4338}
4339
4340impl RowChange {
4341    /// v7.39 (round 736) — which table this change applies to.
4342    #[must_use]
4343    pub fn table_name(&self) -> &str {
4344        match self {
4345            Self::Insert { table, .. }
4346            | Self::Update { table, .. }
4347            | Self::Delete { table, .. }
4348            | Self::Tombstone { table, .. } => table,
4349        }
4350    }
4351
4352    /// v7.37.15 (Epic W slice 2) — stamp the committing writer
4353    /// version onto this change. Every change drained from a single
4354    /// statement shares one version (the statement's `xmin`/`xmax`),
4355    /// so the engine calls this on each drained change with the value
4356    /// from [`Engine::writer_version_for_current_stmt`]. Additive
4357    /// metadata only: replay still resolves by physical position and
4358    /// does not read `writer_version` (that is a later slice).
4359    pub fn set_writer_version(&mut self, v: u64) {
4360        match self {
4361            RowChange::Insert { writer_version, .. }
4362            | RowChange::Update { writer_version, .. }
4363            | RowChange::Delete { writer_version, .. } => *writer_version = v,
4364            // A tombstone captures `xmax` directly from the deleting
4365            // statement's version at record time (via
4366            // `mark_row_deleted`), so it already equals `v`. Keep the
4367            // "one statement, one version" invariant mechanical by
4368            // asserting agreement in debug builds rather than silently
4369            // overwriting a possibly-different value.
4370            RowChange::Tombstone { xmax, .. } => {
4371                debug_assert_eq!(
4372                    *xmax, v,
4373                    "tombstone xmax must match the statement writer version"
4374                );
4375                *xmax = v;
4376            }
4377        }
4378    }
4379}
4380
4381/// v7.37.15 (Epic W slice 1) — leading marker byte of the
4382/// metadata-carrying redo layout. A **pre-Epic-W** redo payload leads
4383/// with `FILE_VERSION` (8..=52 today, rising ~1 per release); this
4384/// marker is `0xFF` and can therefore never collide with a real
4385/// `FILE_VERSION`, so [`decode_redo_log`] tells the two layouts apart
4386/// by inspecting the first byte alone. The compile-time assertion
4387/// below makes the "never collide" invariant a hard build gate: if
4388/// `FILE_VERSION` ever climbs toward `0xFF` the build breaks and forces
4389/// a redesign long before an ambiguity could ship.
4390const REDO_META_MARKER: u8 = 0xFF;
4391/// v7.37.15 (Epic W slice 1) — version of the metadata-carrying redo
4392/// layout that follows [`REDO_META_MARKER`]. Bumped when the per-change
4393/// metadata shape changes; an unknown value is a hard decode error.
4394const REDO_META_VERSION: u8 = 1;
4395
4396/// v7.37.15 (Epic W durable-tombstone slice) — process-wide count of
4397/// [`RowChange::Tombstone`] targets that `apply_redo` could NOT resolve
4398/// to a row by `RowId`. A non-zero value is expected only across a
4399/// checkpoint boundary (the table's ids are reassigned on deserialize
4400/// and the V6 envelope does not yet persist them), where a tombstone
4401/// naming a pre-checkpoint row is left visible rather than mis-applied.
4402/// Surfaced for observability; never affects correctness of the resolved
4403/// tombstones. Read via [`unresolved_tombstone_count`].
4404static UNRESOLVED_TOMBSTONES: core::sync::atomic::AtomicU64 = core::sync::atomic::AtomicU64::new(0);
4405
4406/// v7.39 (flip crash-replay P0) — observability read for the replay
4407/// tombstones that could not be resolved to a row (each one is a
4408/// resurrected delete).
4409#[must_use]
4410pub fn unresolved_tombstones() -> u64 {
4411    UNRESOLVED_TOMBSTONES.load(core::sync::atomic::Ordering::Relaxed)
4412}
4413
4414/// v7.37.15 (Epic W durable-tombstone slice) — read the process-wide
4415/// count of redo tombstones that could not be resolved to a row by
4416/// `RowId` during `apply_redo`. See [`UNRESOLVED_TOMBSTONES`].
4417#[must_use]
4418pub fn unresolved_tombstone_count() -> u64 {
4419    UNRESOLVED_TOMBSTONES.load(core::sync::atomic::Ordering::Relaxed)
4420}
4421// Provably-unambiguous old/new distinction: the pre-Epic-W layout's
4422// first byte is `FILE_VERSION`, which must stay strictly below the
4423// marker forever.
4424const _: () = assert!(FILE_VERSION < REDO_META_MARKER);
4425
4426/// v7.34 (crash-recovery P0 #2), extended v7.37.15 (Epic W slice 1) —
4427/// encode a row-level redo log to bytes for a WAL record.
4428///
4429/// ## Layout (Epic W metadata-carrying form, always emitted now)
4430///
4431/// `[u8 REDO_META_MARKER=0xFF][u8 REDO_META_VERSION][u8 FILE_VERSION]
4432/// [u32 count]` then per change `[u8 op][str table]` and, per op:
4433/// - `Insert [u32 n][value×n][u64 rowid][u64 writer_version]`
4434/// - `Update [u32 pos][u32 n][value×n][u64 rowid][u64 writer_version]`
4435/// - `Delete [u32 n][u32 pos×n][u64 rowid×n][u64 writer_version]`
4436/// - `Tombstone [u32 n][u64 rowid×n][u64 xmax]` (op byte 3; only ever
4437///   emitted under the metadata-carrying layout — the pre-Epic-W layout
4438///   had no in-place tombstone, so a legacy stream can never carry it)
4439///
4440/// Positions are physical (u32 ≤ 4 G rows). The `FILE_VERSION` byte
4441/// still rides along (now the 3rd byte) so the value codec decodes
4442/// string / BYTEA escapes exactly as before.
4443///
4444/// ## Backward compatibility
4445///
4446/// The **pre-Epic-W** layout was `[u8 FILE_VERSION][u32 count]…` with
4447/// no per-change metadata. [`decode_redo_log`] still decodes that form
4448/// (first byte < `0xFF`) byte-for-byte identically — every WAL file
4449/// written by released code replays unchanged.
4450#[must_use]
4451pub fn encode_redo_log(changes: &[RowChange]) -> Vec<u8> {
4452    let mut out = Vec::new();
4453    out.push(REDO_META_MARKER);
4454    out.push(REDO_META_VERSION);
4455    out.push(FILE_VERSION);
4456    codec::write_u32(&mut out, changes.len() as u32);
4457    let write_values = |out: &mut Vec<u8>, vals: &[Value<'static>]| {
4458        codec::write_u32(out, vals.len() as u32);
4459        for v in vals {
4460            codec::write_value(out, v);
4461        }
4462    };
4463    for change in changes {
4464        match change {
4465            RowChange::Insert {
4466                table,
4467                row,
4468                rowid,
4469                writer_version,
4470            } => {
4471                out.push(0);
4472                codec::write_str(&mut out, table);
4473                write_values(&mut out, &row.values);
4474                codec::write_u64(&mut out, rowid.0);
4475                codec::write_u64(&mut out, *writer_version);
4476            }
4477            RowChange::Update {
4478                table,
4479                pos,
4480                new_row,
4481                rowid,
4482                writer_version,
4483            } => {
4484                out.push(1);
4485                codec::write_str(&mut out, table);
4486                codec::write_u32(&mut out, *pos as u32);
4487                write_values(&mut out, new_row);
4488                codec::write_u64(&mut out, rowid.0);
4489                codec::write_u64(&mut out, *writer_version);
4490            }
4491            RowChange::Delete {
4492                table,
4493                positions,
4494                rowids,
4495                writer_version,
4496            } => {
4497                out.push(2);
4498                codec::write_str(&mut out, table);
4499                codec::write_u32(&mut out, positions.len() as u32);
4500                for p in positions {
4501                    codec::write_u32(&mut out, *p as u32);
4502                }
4503                // Epic W: one RowId per position (parallel). Capture
4504                // sites always produce `rowids.len() == positions.len()`;
4505                // this assertion pins that invariant at encode time so a
4506                // mismatch is a loud bug, not a silently short payload.
4507                debug_assert_eq!(
4508                    rowids.len(),
4509                    positions.len(),
4510                    "redo Delete: rowids must be parallel to positions"
4511                );
4512                for rid in rowids {
4513                    codec::write_u64(&mut out, rid.0);
4514                }
4515                codec::write_u64(&mut out, *writer_version);
4516            }
4517            RowChange::Tombstone {
4518                table,
4519                rowids,
4520                xmax,
4521            } => {
4522                out.push(3);
4523                codec::write_str(&mut out, table);
4524                codec::write_u32(&mut out, rowids.len() as u32);
4525                for rid in rowids {
4526                    codec::write_u64(&mut out, rid.0);
4527                }
4528                codec::write_u64(&mut out, *xmax);
4529            }
4530        }
4531    }
4532    out
4533}
4534
4535/// v7.34, extended v7.37.15 (Epic W slice 1) — decode a row-level redo
4536/// log written by [`encode_redo_log`].
4537///
4538/// Decodes **both** the Epic W metadata-carrying layout (first byte
4539/// `REDO_META_MARKER = 0xFF`) and the pre-Epic-W layout (first byte is
4540/// `FILE_VERSION`, always `< 0xFF`). For the old layout the per-change
4541/// metadata is absent, so `rowid`/`rowids` come back
4542/// [`RowId::UNASSIGNED`](row_header::RowId::UNASSIGNED) (empty for
4543/// `Delete`) and `writer_version` comes back `0`.
4544///
4545/// A truncated / corrupt buffer is a hard error — never a panic — the
4546/// embedding layer frames each record with its own length + CRC, so a
4547/// frame that decodes short is corruption, not a torn tail.
4548pub fn decode_redo_log(bytes: &[u8]) -> Result<Vec<RowChange>, StorageError> {
4549    let first = *bytes
4550        .first()
4551        .ok_or_else(|| StorageError::Corrupt("redo log: empty".into()))?;
4552    // Epic W: `0xFF` marker ⇒ metadata-carrying layout; anything else
4553    // is a pre-Epic-W `FILE_VERSION` byte (old layout, no metadata).
4554    let has_meta = first == REDO_META_MARKER;
4555    let (codec_version, header_len) = if has_meta {
4556        let meta_version = *bytes
4557            .get(1)
4558            .ok_or_else(|| StorageError::Corrupt("redo log: short header".into()))?;
4559        if meta_version != REDO_META_VERSION {
4560            return Err(StorageError::Corrupt(alloc::format!(
4561                "redo log: unknown metadata version {meta_version}"
4562            )));
4563        }
4564        let file_version = *bytes
4565            .get(2)
4566            .ok_or_else(|| StorageError::Corrupt("redo log: short header".into()))?;
4567        // header = [marker][meta_version][file_version]
4568        (file_version, 3usize)
4569    } else {
4570        // Old layout: the first byte IS the FILE_VERSION.
4571        (first, 1usize)
4572    };
4573    let mut cur = codec::Cursor::new(bytes).with_codec_version(codec_version);
4574    for _ in 0..header_len {
4575        cur.read_u8()?;
4576    }
4577    let count = cur.read_u32()? as usize;
4578    let mut read_values =
4579        |cur: &mut codec::Cursor<'_>| -> Result<Vec<Value<'static>>, StorageError> {
4580            let n = cur.read_u32()? as usize;
4581            let mut vals = Vec::with_capacity(n);
4582            for _ in 0..n {
4583                vals.push(cur.read_value()?);
4584            }
4585            Ok(vals)
4586        };
4587    let mut changes = Vec::with_capacity(count);
4588    for _ in 0..count {
4589        let op = cur.read_u8()?;
4590        let table = cur.read_str()?;
4591        let change = match op {
4592            0 => {
4593                let row = Row::new(read_values(&mut cur)?);
4594                let (rowid, writer_version) = if has_meta {
4595                    (row_header::RowId(cur.read_u64()?), cur.read_u64()?)
4596                } else {
4597                    (row_header::RowId::UNASSIGNED, 0)
4598                };
4599                RowChange::Insert {
4600                    table,
4601                    row,
4602                    rowid,
4603                    writer_version,
4604                }
4605            }
4606            1 => {
4607                let pos = cur.read_u32()? as usize;
4608                let new_row = read_values(&mut cur)?;
4609                let (rowid, writer_version) = if has_meta {
4610                    (row_header::RowId(cur.read_u64()?), cur.read_u64()?)
4611                } else {
4612                    (row_header::RowId::UNASSIGNED, 0)
4613                };
4614                RowChange::Update {
4615                    table,
4616                    pos,
4617                    new_row,
4618                    rowid,
4619                    writer_version,
4620                }
4621            }
4622            2 => {
4623                let n = cur.read_u32()? as usize;
4624                let mut positions = Vec::with_capacity(n);
4625                for _ in 0..n {
4626                    positions.push(cur.read_u32()? as usize);
4627                }
4628                let (rowids, writer_version) = if has_meta {
4629                    let mut rowids = Vec::with_capacity(n);
4630                    for _ in 0..n {
4631                        rowids.push(row_header::RowId(cur.read_u64()?));
4632                    }
4633                    (rowids, cur.read_u64()?)
4634                } else {
4635                    // Old layout carried no RowId metadata.
4636                    (Vec::new(), 0)
4637                };
4638                RowChange::Delete {
4639                    table,
4640                    positions,
4641                    rowids,
4642                    writer_version,
4643                }
4644            }
4645            // Op 3 is the Epic W in-place tombstone — it only exists in
4646            // the metadata-carrying layout. Guarding on `has_meta` means
4647            // a legacy stream that happens to contain a `3` byte here is
4648            // reported as an unknown op (corruption), never mis-decoded.
4649            3 if has_meta => {
4650                let n = cur.read_u32()? as usize;
4651                let mut rowids = Vec::with_capacity(n);
4652                for _ in 0..n {
4653                    rowids.push(row_header::RowId(cur.read_u64()?));
4654                }
4655                let xmax = cur.read_u64()?;
4656                RowChange::Tombstone {
4657                    table,
4658                    rowids,
4659                    xmax,
4660                }
4661            }
4662            other => {
4663                return Err(StorageError::Corrupt(alloc::format!(
4664                    "redo log: unknown op {other}"
4665                )));
4666            }
4667        };
4668        changes.push(change);
4669    }
4670    Ok(changes)
4671}
4672
4673/// v7.39 (pg_stat knife B) — per-table scan counters, bumped from
4674/// `&self` read paths. Clone (tx shadow catalogs clone tables) copies
4675/// the current values; the counters are volatile like PG's cumulative
4676/// stats.
4677#[derive(Debug, Default)]
4678pub struct ScanStats {
4679    pub seq_scan: core::sync::atomic::AtomicU64,
4680    pub seq_tup_read: core::sync::atomic::AtomicU64,
4681    pub idx_scan: core::sync::atomic::AtomicU64,
4682    pub idx_tup_fetch: core::sync::atomic::AtomicU64,
4683}
4684
4685impl Clone for ScanStats {
4686    fn clone(&self) -> Self {
4687        use core::sync::atomic::{AtomicU64, Ordering};
4688        Self {
4689            seq_scan: AtomicU64::new(self.seq_scan.load(Ordering::Relaxed)),
4690            seq_tup_read: AtomicU64::new(self.seq_tup_read.load(Ordering::Relaxed)),
4691            idx_scan: AtomicU64::new(self.idx_scan.load(Ordering::Relaxed)),
4692            idx_tup_fetch: AtomicU64::new(self.idx_tup_fetch.load(Ordering::Relaxed)),
4693        }
4694    }
4695}
4696
4697/// v7.39 (round 215) — the lower-bound sort key for a range value, used by
4698/// the range-exclusion index. The bound as an `i128` (unbounded lower =
4699/// `i128::MIN`, sorting first) plus an inclusivity rank (inclusive lower
4700/// sorts before exclusive at the same value, `[3` before `(3`). Returns
4701/// `None` for range kinds whose bound isn't an integer scalar (numrange's
4702/// numeric/bignum), for empty ranges, and for non-range values — the caller
4703/// then keeps the O(n) scan rather than risk an unsound order. Int4/Int8/
4704/// Date/Ts/TsTz all reduce here (tstzrange bounds are `Value::Timestamp`).
4705/// Maintenance (index build) and query (overlap probe) MUST agree on this
4706/// key, so both sides call exactly this function.
4707#[must_use]
4708pub fn range_excl_index_key(v: &Value<'_>) -> Option<(i128, u8)> {
4709    let Value::Range {
4710        lower,
4711        lower_inc,
4712        empty,
4713        ..
4714    } = v
4715    else {
4716        return None;
4717    };
4718    if *empty {
4719        return None;
4720    }
4721    let key = match lower {
4722        None => i128::MIN,
4723        Some(b) => match b.as_ref() {
4724            Value::SmallInt(n) => i128::from(*n),
4725            Value::Int(n) => i128::from(*n),
4726            Value::BigInt(n) => i128::from(*n),
4727            Value::Date(n) => i128::from(*n),
4728            Value::Timestamp(n) => i128::from(*n),
4729            _ => return None,
4730        },
4731    };
4732    Some((key, u8::from(!*lower_inc)))
4733}
4734
4735/// v7.39 (round 215) — a per-table range-exclusion index: an incrementally
4736/// maintained map from a range column's lower-bound key
4737/// ([`range_excl_index_key`]) to the physical row locators carrying that
4738/// bound. Lets EXCLUDE enforcement find the few candidate rows a new range
4739/// might overlap in O(log n) instead of scanning every row (measured O(N²),
4740/// r213). Because the stored ranges under a valid `EXCLUDE (col WITH &&)`
4741/// are pairwise disjoint, a candidate overlaps only its predecessor or the
4742/// successors whose lower bound precedes its upper — a handful of probes.
4743///
4744/// NOT persisted: rebuilt from the (persisted) exclusion constraints + rows
4745/// on catalog load, exactly like BRIN re-derives. Backed by a
4746/// `PersistentBTreeMap` so `Table::clone` (the per-write snapshot) stays
4747/// O(1). Locators to tombstoned rows are left in place and filtered by the
4748/// consumer via `is_deleted()` at query time — the established index pattern.
4749#[derive(Debug, Clone)]
4750pub struct ExclRangeIndex {
4751    /// The constrained range column's position in the table.
4752    pub column_position: usize,
4753    /// Lower-bound key → row locators. A key maps to a `Vec` because a
4754    /// tombstoned-then-reinserted bound can transiently collide; live rows
4755    /// under the constraint are disjoint so each key has one live locator.
4756    pub map: PersistentBTreeMap<(i128, u8), crate::posting::PostingList>,
4757}
4758
4759/// v7.38.2 (R2) — see [`Table::tx_write_track`]. Positions are the
4760/// insert-time slots (verified against the header's version at
4761/// extraction, so a shifted slot falls back to the scan); tombstones
4762/// carry the stable RowId, which is what the write-set wants anyway.
4763#[derive(Debug, Clone, Default)]
4764struct TxWriteTrack {
4765    version: u64,
4766    inserted: Vec<(usize, row_header::RowId)>,
4767    tombstoned: Vec<row_header::RowId>,
4768}
4769
4770/// v7.38.11 — hot-tier BRIN granularity: slots per summarised range.
4771///
4772/// 1024 keeps the summary vector three orders of magnitude smaller
4773/// than the table while staying fine enough that a one-day window over
4774/// a 90-day table skips ~99 % of it. A tuning constant, not a format:
4775/// summaries are rebuilt from the rows on load, so changing it costs
4776/// nothing on disk.
4777pub const BRIN_RANGE_ROWS: usize = 1024;
4778
4779/// The comparable scalar a BRIN summary tracks, or `None` for a value
4780/// with no ordering this index can use.
4781///
4782/// Deliberately narrow: only types whose ordering IS the i64 ordering
4783/// of this number. A type added here whose comparison is not that —
4784/// text under a collation, say — would make the summary under-report
4785/// and skip matching rows, which is the one failure this design must
4786/// not have.
4787#[must_use]
4788pub fn brin_scalar(v: &Value<'_>) -> Option<i64> {
4789    match v {
4790        Value::SmallInt(n) => Some(i64::from(*n)),
4791        Value::Int(n) => Some(i64::from(*n)),
4792        Value::BigInt(n) | Value::Timestamp(n) => Some(*n),
4793        Value::Date(d) => Some(i64::from(*d)),
4794        Value::Bool(b) => Some(i64::from(*b)),
4795        _ => None,
4796    }
4797}
4798
4799#[derive(Debug, Clone)]
4800pub struct Table {
4801    schema: TableSchema,
4802    /// v7.38.18 (S2) — the DATABASE's collation, copied in by the
4803    /// catalog that owns this table.
4804    ///
4805    /// A text column that declares no collation inherits it, which is
4806    /// what PostgreSQL does and what `information_schema.columns`
4807    /// reports as NULL. Runtime only, never serialised: it belongs to
4808    /// the catalog, and a table that has been handed around outside one
4809    /// falls back to `C`, which is the answer for every database written
4810    /// before this existed.
4811    db_collation: Option<String>,
4812    /// v7.38.16 — names of the expression indexes whose B-tree currently
4813    /// holds keys derived from the EXPRESSION.
4814    ///
4815    /// Every catalog written before this version stored, under an
4816    /// expression index, the values of its leading column — keys no
4817    /// lookup could ever match, which is why every read path guarded
4818    /// itself with `expression.is_none()` and the index bought nothing
4819    /// while costing 1.9x a plain insert to maintain.
4820    ///
4821    /// Deliberately NOT persisted: a table read off disk starts with the
4822    /// set empty, so those old wrong keys can never answer a query. The
4823    /// engine, which owns the expression evaluator, refills it.
4824    expr_index_complete: alloc::collections::BTreeSet<String>,
4825    /// v7.37.15 (Phase C.1) — stable per-catalog relation identity.
4826    /// [`RelId::UNASSIGNED`](row_header::RelId::UNASSIGNED) until
4827    /// `Catalog::create_table` (or the deserialize dense-assign pass)
4828    /// stamps a real id. Keys the Phase C.4 row-lock table and the
4829    /// Phase C.5 `RelationStore`; survives `DROP TABLE` slot shifts.
4830    rel_id: row_header::RelId,
4831    rows: PersistentVec<Row<'static>>,
4832    /// v7.37.15 (Phase A.2) — per-row MVCC visibility headers
4833    /// parallel to `rows`. `headers.len() == rows.len()` is the
4834    /// load-bearing invariant; debug builds assert it on every
4835    /// scan boundary, release builds rely on it from
4836    /// disciplined insert / delete / update paths.
4837    ///
4838    /// Pre-v7.37.15-loaded tables (every row currently in the
4839    /// fleet) start as `RowHeader::frozen()` — `is_all_visible_fast()`
4840    /// returns `true`, so the per-row visibility gate Phase B
4841    /// adds is a no-op against any snapshot.
4842    ///
4843    /// Headers are NOT yet serialised into the envelope at this
4844    /// commit — on snapshot deserialize every row gets a fresh
4845    /// `RowHeader::frozen()`. Phase D adds the visibility-map
4846    /// + segment-freeze story which makes serialisation
4847    /// meaningful; until then the on-disk story is "the catalog
4848    /// is the set of visible rows."
4849    headers: PersistentVec<row_header::RowHeader>,
4850    /// v7.37.15 (Phase C.1) — stable per-relation row identity
4851    /// parallel to `rows` / `headers`. `rowids[i]` is the never-
4852    /// reused [`RowId`](row_header::RowId) of the row physically at
4853    /// slot `i`; `rowids.len() == rows.len()` joins the same load-
4854    /// bearing lock-step invariant as `headers`. Compaction (delete
4855    /// / vacuum) rebuilds all three vecs together so the id travels
4856    /// with the row while the slot shifts.
4857    ///
4858    /// Introduced additively: allocated + kept lock-step, but index
4859    /// locators still address rows by physical slot at this commit.
4860    /// Later phases migrate the lock table (C.4), HOT chains (D),
4861    /// and the WAL (Epic W) to address by `RowId`.
4862    ///
4863    /// Not yet serialised into the envelope — on load every row is
4864    /// assigned a fresh dense id `1..=len` (see `next_rowid`), which
4865    /// is sufficient while the id is process-local bookkeeping. The
4866    /// V6 envelope (Phase C.6) will persist ids so a WAL redo can
4867    /// name a row across restart.
4868    rowids: PersistentVec<row_header::RowId>,
4869    /// v7.37.15 (Phase C.1) — per-relation monotonic allocator for
4870    /// `rowids`. Starts at 1 (0 is the `RowId::UNASSIGNED` sentinel);
4871    /// every append takes `next_rowid` then increments. Never reused
4872    /// even after the row is deleted / vacuumed, so a stale lock /
4873    /// redo reference can be detected rather than silently aliasing a
4874    /// later row that reused the slot.
4875    ///
4876    /// 7.38.1 (S2.4, MATRIX #20 root cause) — the allocator is SHARED
4877    /// across every `clone()` of the relation (`Arc`), because the
4878    /// monotonic-never-reused promise is a LINEAGE invariant: each
4879    /// open transaction's shadow catalog is a clone, and when clones
4880    /// carried private counters two concurrent shadows minted the
4881    /// same id — duplicate rids in the base after both committed,
4882    /// aliasing every rid-addressed mechanism (locks, tombstones,
4883    /// redo, the rebase unique pre-check).
4884    next_rowid: alloc::sync::Arc<core::sync::atomic::AtomicU64>,
4885    /// v7.37.16 (autovacuum) — live count of tombstoned-but-present hot
4886    /// rows (`headers[i].xmax != XMAX_ALIVE`). Maintained incrementally:
4887    /// `mark_row_deleted` / `mark_rows_deleted` increment (the only
4888    /// tombstone producers), `delete_rows_no_index` recomputes over the
4889    /// survivors (it is the compaction hub every physical removal —
4890    /// including vacuum — flows through), and the v53 snapshot loader
4891    /// recounts verbatim-restored headers. Drives the engine's
4892    /// autovacuum threshold; not persisted (recomputed on load).
4893    dead_rows: u64,
4894    /// v7.39 (pg_stat knife A) — volatile per-table write counters
4895    /// backing `pg_stat_user_tables.n_tup_ins/upd/del`. Not persisted
4896    /// (PG's cumulative stats are shared-memory-volatile too — a
4897    /// restart zeroes them).
4898    stat_tup_ins: u64,
4899    stat_tup_upd: u64,
4900    stat_tup_del: u64,
4901    /// v7.39 (pg_stat knife B) — volatile scan counters
4902    /// (`seq_scan/seq_tup_read/idx_scan/idx_tup_fetch`). Atomics: the
4903    /// read paths that bump them hold only `&Table`.
4904    scan_stats: ScanStats,
4905    /// v7.39 (pg_stat knife C) — wall-clock stamps (unix µs, from the
4906    /// host ClockFn) for pg_stat_user_tables' last_autovacuum /
4907    /// last_analyze. Volatile, like PG's cumulative stats. SPG has no
4908    /// manual-VACUUM statement semantics, so last_vacuum stays NULL.
4909    last_autovacuum_us: Option<i64>,
4910    last_analyze_us: Option<i64>,
4911    indices: Vec<Index>,
4912    hot_bytes: u64,
4913    /// v6.7.0 — cached count of rows currently materialised in the
4914    /// cold tier via `RowLocator::Cold` entries across THIS table's
4915    /// indices. Populated by `ANALYZE` (walks every BTree index and
4916    /// counts Cold locators); the count survives until the next
4917    /// ANALYZE recomputes it. Surfaced via `spg_statistic.cold_row_count`
4918    /// and `spg_stat_segment.table_name`.
4919    ///
4920    /// Honest scope: this is a CACHED count, not a live one.
4921    /// Freezer / promote / DELETE don't currently update the cache
4922    /// incrementally — they invalidate it by setting the
4923    /// `cold_row_count_stale` flag, and the next ANALYZE re-walks.
4924    /// Incremental maintenance is a v6.7.x candidate if observation
4925    /// shows the ANALYZE walk cost dominates.
4926    cold_row_count: u64,
4927    /// v6.7.0 — set when the cached `cold_row_count` may be wrong
4928    /// because rows moved into / out of the cold tier since the last
4929    /// ANALYZE. The virtual-table surface reports the cached value
4930    /// regardless (operators run ANALYZE to refresh).
4931    cold_row_count_stale: bool,
4932    /// v7.34 (crash-recovery P0 #2) — row-level redo capture buffer.
4933    /// `None` (default, in-memory mode) captures nothing — zero overhead.
4934    /// `Some` (set by the engine when persistence is on, before a
4935    /// mutating call) makes `insert` / `update_row` / `delete_rows`
4936    /// record the physical [`RowChange`] they applied, which the engine
4937    /// drains after the statement and writes to the WAL in place of the
4938    /// SQL text. Transient: never serialized; a `Catalog::clone` between
4939    /// enable and drain copies it (cheap — empty in the steady state).
4940    redo_log: Option<Vec<RowChange>>,
4941    /// v7.39 (round 215) — per-`EXCLUDE`-constraint range-overlap indexes,
4942    /// one per single-`&&` constraint on an integer-keyable range column.
4943    /// Maintained incrementally on insert / update / rebuild (mirroring the
4944    /// BTree secondary indexes); NOT serialized — rebuilt from the schema's
4945    /// exclusion constraints on load. Empty for tables with no EXCLUDE
4946    /// constraint (the common case), so `Table::clone` pays nothing.
4947    excl_indexes: Vec<ExclRangeIndex>,
4948    /// v7.38.2 (R2) — incremental write-set track for the RC rebase.
4949    /// `extract_tx_writeset` used to full-scan every header per call —
4950    /// ~200 µs on a 20k-row table, per in-transaction statement, every
4951    /// time a concurrent COMMIT moved the epoch; on tpcb's 100k-row
4952    /// accounts that scan was the c2 concurrency cliff itself. The
4953    /// three version-marking funnels (`insert_with_xmin`,
4954    /// `mark_row_deleted`, `mark_rows_deleted`) record here instead.
4955    ///
4956    /// One track per table, keyed by the LAST writer version: a shadow
4957    /// belongs to one transaction, so a different version claiming the
4958    /// table simply replaces the track (on the committed base that
4959    /// makes memory bounded by the last writer's footprint). Extraction
4960    /// verifies every recorded position still carries the version —
4961    /// any mismatch (compaction, inherited track, pre-track rows)
4962    /// falls back to the full scan, so the fast path can be wrong
4963    /// about NOTHING, only slow.
4964    tx_write_track: Option<TxWriteTrack>,
4965    /// v7.39 (round 493) — the snapshot floor below which a deleted row
4966    /// version is invisible to everyone, as of the statement now running.
4967    ///
4968    /// Runtime only: never serialised, and `0` (the default) prunes
4969    /// nothing, so any path that forgets to set it is merely slower, not
4970    /// wrong. The engine sets it from `vacuum_oldest_active()` — the same
4971    /// floor `vacuum` itself takes — before the statement's inserts.
4972    prune_horizon: u64,
4973}
4974
4975/// Catalog: insertion-ordered `Vec<Table>` for stable iter / serialize,
4976/// plus a `BTreeMap<String, usize>` sidecar index so `get` / `get_mut`
4977/// run in O(log n) instead of the old linear scan with per-element
4978/// string compares.
4979///
4980/// A pure `BTreeMap<String, Table>` was tried in an interim version
4981/// of v3.1.2 and regressed the single-table catalog benches by ~10%
4982/// (the per-element `BTreeMap` overhead outweighs the lookup win
4983/// when n is small). The sidecar shape preserves the insertion-order
4984/// iteration the on-disk encoding relies on and keeps `last_mut`
4985/// (used by the deserialize hot path) cheap.
4986/// v7.39 (pg_stat blks knife) — catalog-wide cold-tier read counter
4987/// backing pg_stat_database.blks_read. Row-granular (SPG has no 8 KB
4988/// page notion): one cold-segment row resolution = one "block read",
4989/// one hot row access = one "block hit" — the hit RATIO monitoring
4990/// dashboards compute keeps its meaning. Volatile like PG's stats.
4991#[derive(Debug, Default)]
4992pub struct ColdReadStats {
4993    pub cold_reads: core::sync::atomic::AtomicU64,
4994}
4995
4996impl Clone for ColdReadStats {
4997    fn clone(&self) -> Self {
4998        Self {
4999            cold_reads: core::sync::atomic::AtomicU64::new(
5000                self.cold_reads.load(core::sync::atomic::Ordering::Relaxed),
5001            ),
5002        }
5003    }
5004}
5005
5006/// 7.38.1 S3.1 (D4) — the non-table catalog families that carry a
5007/// per-transaction dirty window (see `Catalog::dirty_nontable`). One
5008/// entry class per side-map the poisoned-commit merge reconciles.
5009#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
5010pub enum NonTableKind {
5011    Sequence,
5012    View,
5013    MaterializedView,
5014    EnumType,
5015    DomainType,
5016    CompositeType,
5017}
5018
5019#[derive(Debug, Clone, Default)]
5020pub struct Catalog {
5021    /// v7.39 (pg_stat blks knife) — see [`ColdReadStats`].
5022    pub cold_read_stats: ColdReadStats,
5023    tables: Vec<Table>,
5024    /// `name → tables[index]`. Kept in lock-step with `tables`.
5025    /// `create_table` is the only write path.
5026    by_name: BTreeMap<String, usize>,
5027    /// v7.39 (round 436) — the current session's temporary-table namespace.
5028    /// A temp table is stored under `<prefix><name>`, and every lookup tries
5029    /// that first: exactly PG's `pg_temp` search-path rule, and MySQL's
5030    /// "a TEMPORARY table shadows a permanent one of the same name".
5031    ///
5032    /// Process-local, never serialised: the engine sets it per session, and
5033    /// a catalog read back from disk starts with none. Kept here rather than
5034    /// at each of the ~170 engine call sites because `by_name` is private —
5035    /// this is the ONE place a table name becomes an index.
5036    temp_prefix: Option<String>,
5037    /// v7.39.2 — see [`Catalog::set_case_insensitive_names`].
5038    case_insensitive_names: bool,
5039    /// v7.39 (round 496) — the names of tables this catalog handle has had
5040    /// changed since the set was last cleared.
5041    ///
5042    /// Runtime only, never serialised. A transaction's shadow catalog
5043    /// clears it at BEGIN, so at COMMIT the set is exactly the tables the
5044    /// transaction changed — which is what lets a commit that cannot use
5045    /// the row-level merge install only those tables instead of the whole
5046    /// catalog, leaving another session's concurrent work in place.
5047    ///
5048    /// Recorded where the change actually happens (`get_mut`,
5049    /// `create_table`, `drop_table`) rather than from the statement
5050    /// classifier: round 494 tried classification for a correctness gate
5051    /// and it was wrong, because `SELECT lo_write(…)` reads as read-only.
5052    dirty_tables: alloc::collections::BTreeSet<String>,
5053    /// 7.38.1 S3.1 (D4) — the non-table twin of `dirty_tables`: which
5054    /// sequences / views / matviews / enum / domain / composite types
5055    /// THIS window created, altered, renamed or dropped. Counter
5056    /// advances (`nextval`) deliberately do NOT record — counter
5057    /// values merge via `sequence_counters` / `restore_sequence_
5058    /// counters`, and a tx that only consumed ids must not shadow a
5059    /// neighbour's ALTER SEQUENCE. Cleared by `clear_dirty_tables`
5060    /// (one window, both records).
5061    dirty_nontable: alloc::collections::BTreeSet<(NonTableKind, String)>,
5062    /// v7.37.15 (Phase C.1) — monotonic allocator for stable
5063    /// [`RelId`](row_header::RelId)s. Pre-incremented on each
5064    /// `create_table` so real ids start at 1 (0 is `UNASSIGNED`);
5065    /// never reused even after `DROP TABLE`, so a stale lock / redo
5066    /// reference is detectable. Process-local bookkeeping — not yet
5067    /// serialised; `deserialize` re-assigns dense ids on load (the
5068    /// V6 envelope, Phase C.6, will round-trip real ids).
5069    next_rel_id: u64,
5070    /// v5.1: in-memory cold-tier segments. Side-loaded via
5071    /// [`Catalog::load_segment_bytes`] — they live outside the
5072    /// catalog snapshot (caller persists them as separate files
5073    /// and re-loads on boot, until v5.3's `CatalogManifest` makes
5074    /// that wiring automatic). `RowLocator::Cold { segment_id, .. }`
5075    /// indexes this `Vec`. Cleared on `Catalog::new` / fresh
5076    /// `deserialize`.
5077    ///
5078    /// `Arc` wrap keeps `Catalog::clone` at O(N segments) bumps
5079    /// (rather than O(total segment bytes) memcpy) so the v4.42
5080    /// group-commit pre-image rollback invariant — clone is
5081    /// effectively free — survives the cold-tier addition.
5082    ///
5083    /// v6.7.3 — slots became `Option<…>` so cold-segment compaction
5084    /// can tombstone merged sources without breaking the
5085    /// `segment_id = index_into_vec` contract that on-disk
5086    /// `RowLocator::Cold { segment_id }` already serialized.
5087    /// `None` slot = the segment was retired by compaction; the
5088    /// physical file may still be on disk (next CHECKPOINT writes
5089    /// a manifest that no longer lists it, and the file becomes
5090    /// an orphan eligible for offline cleanup).
5091    cold_segments: Vec<Option<Arc<OwnedSegment>>>,
5092    /// v7.12.4 — user-defined functions (PL/pgSQL + SQL).
5093    /// Keyed by function name (PG overloading is out of scope).
5094    /// Bodies are stored as the raw source text the parser saw
5095    /// between `$$ ... $$`; the engine re-parses on each
5096    /// invocation. This keeps `spg-storage` free of `spg-sql`
5097    /// dependency — same pattern as partial-index predicates.
5098    functions: BTreeMap<String, FunctionDef>,
5099    /// v7.12.4 — triggers in insertion order. PG18-measured (round
5100    /// 753): PG fires same-event triggers in NAME order (a_trig
5101    /// before z_trig regardless of creation order); SPG fires in
5102    /// insertion order — a real divergence, ledgered as F31-B2.
5103    triggers: Vec<TriggerDef>,
5104    /// v7.39 (round 139) — query-rewrite RULEs, flat like triggers.
5105    rules: Vec<RuleDef>,
5106    /// v7.39 (round 280) — extended-statistics objects. Recorded so a
5107    /// pg_dump restores them and reflection reports them; the planner
5108    /// does not consult them yet.
5109    statistics_ext: Vec<StatisticsExtDef>,
5110    /// v7.39 (round 287) — server-side large objects, keyed by OID.
5111    /// PG stores them as 2 KB pages in `pg_largeobject`; the page split
5112    /// is a storage detail of ITS heap, so SPG holds the whole byte
5113    /// string and renders the pages on read. What must match is the
5114    /// observable surface: the OIDs, the bytes, and the page rows.
5115    large_objects: alloc::collections::BTreeMap<u32, Vec<u8>>,
5116    /// v7.17.0 — catalogued SEQUENCE objects (Phase 1.1). Each
5117    /// `nextval(name)` reaches in here, atomically increments
5118    /// `last_value` / flips `is_called`, returns the new value.
5119    /// Persisted in catalog FILE_VERSION 26+; older catalogs
5120    /// deserialise with an empty map.
5121    sequences: BTreeMap<String, SequenceDef>,
5122    /// v7.39 (read01 round 60) — the `public` schema's ACL (PG
5123    /// `pg_namespace.nspacl`). EMPTY = PG's default, which is not "nothing":
5124    /// PUBLIC holds USAGE and the owner holds USAGE + CREATE. Materialised on
5125    /// the first GRANT / REVOKE, exactly like a table's relacl.
5126    schema_acl: Vec<AclItem>,
5127    /// v7.39 (read01 round 60) — the database's ACL. EMPTY = PG's default:
5128    /// PUBLIC holds CONNECT + TEMPORARY, the owner holds all three.
5129    database_acl: Vec<AclItem>,
5130    /// v7.17.0 — catalogued VIEW objects (Phase 1.2). Each
5131    /// `SELECT FROM v` at engine exec-time looks up `v` here and
5132    /// prepends the view body as a synthetic CTE. Persisted in
5133    /// catalog FILE_VERSION 27+; older catalogs deserialise with
5134    /// an empty map.
5135    views: BTreeMap<String, ViewDef>,
5136    /// v7.17.0 — catalogued MATERIALIZED VIEW source registry
5137    /// (Phase 1.3). Maps name → SELECT source. The materialised
5138    /// rows themselves live as a regular `Table` with the same
5139    /// name; REFRESH re-parses + re-executes the source against
5140    /// the table. Persisted in catalog FILE_VERSION 28+;
5141    /// older catalogs deserialise with an empty map.
5142    materialized_views: BTreeMap<String, String>,
5143    /// v7.17.0 — catalogued user-defined ENUM types (Phase 1.4).
5144    /// Maps name → label list. Columns reference these by name
5145    /// via `ColumnSchema.user_enum_type`. Persisted in catalog
5146    /// FILE_VERSION 29+; older catalogs deserialise with an empty
5147    /// map.
5148    enum_types: BTreeMap<String, EnumDef>,
5149    /// v7.17.0 — catalogued user-defined DOMAIN types (Phase 1.5).
5150    /// Maps name → base + CHECK constraints. Columns reference
5151    /// these by name via `ColumnSchema.user_domain_type`.
5152    /// Persisted in catalog FILE_VERSION 30+; older catalogs
5153    /// deserialise with an empty map.
5154    domain_types: BTreeMap<String, DomainDef>,
5155    /// v7.39 (read01 round 50) — `COMMENT ON <kind> <obj> IS '…'` store.
5156    /// Keyed by a canonical `"<kind>:<name>"` string (`"table:t"`,
5157    /// `"column:t.c"`, `"index:i"`, `"view:v"`, …) so a new commentable
5158    /// object kind needs no schema change. `COMMENT … IS NULL` removes the
5159    /// entry. Persisted in catalog FILE_VERSION 61+; older catalogs
5160    /// deserialise with an empty map. Read back by obj_description /
5161    /// col_description and the pg_description view.
5162    comments: BTreeMap<String, String>,
5163    /// v7.39 (round 547) — PG's `pg_db_role_setting`: the GUC defaults
5164    /// `ALTER ROLE … SET` / `ALTER DATABASE … SET` record, applied when
5165    /// a session starts.
5166    ///
5167    /// Keyed exactly as PG keys it — `(database, role)` where an empty
5168    /// name is PG's oid 0, meaning "all". So `ALTER ROLE ALL SET` is
5169    /// `("", "")`, `ALTER DATABASE d SET` is `(d, "")`, `ALTER ROLE r
5170    /// SET` is `("", r)` and `ALTER ROLE r IN DATABASE d SET` is
5171    /// `(d, r)`. The value is that scope's parameter list.
5172    db_role_settings: BTreeMap<(String, String), BTreeMap<String, String>>,
5173    /// v7.39 (round 550) — replication slots, by name.
5174    ///
5175    /// A slot in PG is two things: a named record, and a reservation
5176    /// that holds WAL back. SPG keeps the record — which is what every
5177    /// setup script and monitoring query reads — and reports
5178    /// `wal_status = 'unreserved'`, PG's own word for a slot that no
5179    /// longer holds WAL. The whole family used to answer NULL and
5180    /// report success, so `pg_drop_replication_slot('nosuchslot')` said
5181    /// it worked and a setup script created nothing.
5182    ///
5183    /// Value: (plugin, slot_type). `plugin` is empty for a physical slot.
5184    replication_slots: BTreeMap<String, (String, String)>,
5185    /// v7.38.18 (S1) — the collation this database was CREATED with, and
5186    /// the one every text column that declares none is compared under.
5187    ///
5188    /// `None` means `C`, which is what every database written by every
5189    /// earlier version was built with — so an upgrade changes no answer
5190    /// and rebuilds no index. That is the whole migration story, and it
5191    /// is why this is an `Option` rather than a `String` defaulting to
5192    /// `"C"`.
5193    ///
5194    /// Set once, at creation, and never after. PostgreSQL refuses
5195    /// `ALTER DATABASE … LC_COLLATE` and the reason is the one that
5196    /// matters here too: every index key in this database was built
5197    /// under this collation, so it cannot move out from under them.
5198    /// See `docs/DESIGN-2026-08-23-collation.md`.
5199    db_collation: Option<String>,
5200    /// v7.38.19 — every name a `CREATE DATABASE` has asked for.
5201    ///
5202    /// SPG serves one database and answers to any name, so the statement
5203    /// has always been a no-op for naming. `pg_database` then listed one
5204    /// row -- whatever name the current session connected with -- so a
5205    /// database that had just been created, and could be connected to,
5206    /// was absent from the catalogue. `psql \l`, a migration tool asking
5207    /// "does this database exist", and a backup script that enumerates
5208    /// all read that table.
5209    ///
5210    /// Reported by sentori against 7.38.18. Runtime only, like
5211    /// `db_collation`: the statement is audited whenever it records a
5212    /// name, so replay rebuilds the set.
5213    created_databases: alloc::collections::BTreeSet<String>,
5214    /// v7.37.42-T2 ζ-B — catalogued user-defined COMPOSITE types
5215    /// (`CREATE TYPE name AS (field_name field_type, …)`). Columns
5216    /// reference these by name via
5217    /// `ColumnSchema.user_composite_type` (parallel to
5218    /// `user_enum_type` / `user_domain_type`). Persisted in catalog
5219    /// FILE_VERSION 52+; older catalogs deserialise with an empty
5220    /// map.
5221    composite_types: BTreeMap<String, CompositeDef>,
5222    /// v7.17.0 — schema-namespace registry (Phase 1.6). Tracks
5223    /// which schemas exist. `public`, `pg_catalog`, and
5224    /// `information_schema` are built-in and always present.
5225    /// Schema-qualified table references still strip the prefix
5226    /// at lookup time per v7.16-and-earlier — full
5227    /// schema-as-isolation is v7.18+ scope. Persisted in catalog
5228    /// FILE_VERSION 31+; older catalogs deserialise with just
5229    /// the built-ins.
5230    schemas: alloc::collections::BTreeSet<String>,
5231}
5232
5233/// v7.12.4 — catalogued user-defined function. `body` is the raw
5234/// source text between `$$ ... $$`; the engine re-parses it on
5235/// invocation. This keeps the storage codec stable when the
5236/// PL/pgSQL surface grows (no breaking-change risk on the disk
5237/// format).
5238// v7.39 (round 322, V46) — no longer `Eq`: COST / ROWS are f64, as in PG.
5239#[derive(Debug, Clone, PartialEq)]
5240pub struct FunctionDef {
5241    pub name: String,
5242    /// Display form of the argument list, e.g.
5243    /// `"(name TEXT, ts TIMESTAMP)"`. Empty `"()"` for the trigger
5244    /// function shape. Parser-side canonicalised before storage.
5245    pub args_repr: String,
5246    /// Display form of the return type, e.g. `"TRIGGER"` /
5247    /// `"INT"` / `"SETOF text"`. The engine special-cases
5248    /// `"TRIGGER"` (case-insensitive) to gate trigger-only
5249    /// semantics (NEW/OLD).
5250    pub returns: String,
5251    /// `LANGUAGE` clause, lowercased. `"plpgsql"` / `"sql"`.
5252    pub language: String,
5253    /// Source body of the function. PL/pgSQL: includes the
5254    /// surrounding `BEGIN ... END;`. SQL: includes the
5255    /// statement(s). The engine re-parses on invocation; bad
5256    /// bodies surface as a parse error at CALL time, not CREATE.
5257    pub body: String,
5258    /// v7.39 (read01 round 61) — the role that ran CREATE FUNCTION.
5259    pub owner: Option<String>,
5260    /// v7.39 (read01 round 61) — explicit GRANTs (PG `pg_proc.proacl`). EMPTY
5261    /// is NOT "nobody may call it": PG grants EXECUTE to PUBLIC by default, and
5262    /// leaves proacl NULL to say so. The list materialises on the first
5263    /// GRANT / REVOKE.
5264    pub acl: Vec<AclItem>,
5265    /// v7.39 (round 322, V46) — `IMMUTABLE` / `STRICT` / `PARALLEL SAFE` /
5266    /// `SECURITY DEFINER` / `LEAKPROOF` / `COST` / `ROWS`. `strict` is the
5267    /// only one with execution semantics today (a NULL argument yields a
5268    /// NULL result without running the body); the rest are recorded so
5269    /// `pg_get_functiondef` and `pg_proc` report what was declared.
5270    pub volatility: u8,
5271    pub strict: bool,
5272    pub security_definer: bool,
5273    pub leakproof: bool,
5274    pub parallel: u8,
5275    pub cost: Option<f64>,
5276    pub rows: Option<f64>,
5277}
5278
5279/// v7.39 (round 322, V46) — `FunctionDef.volatility` codes: PG's
5280/// `pg_proc.provolatile` letters.
5281pub const FN_VOLATILE: u8 = b'v';
5282pub const FN_IMMUTABLE: u8 = b'i';
5283pub const FN_STABLE: u8 = b's';
5284
5285/// v7.39 (round 322, V46) — `FunctionDef.parallel` codes: PG's
5286/// `pg_proc.proparallel` letters.
5287pub const FN_PARALLEL_UNSAFE: u8 = b'u';
5288pub const FN_PARALLEL_RESTRICTED: u8 = b'r';
5289pub const FN_PARALLEL_SAFE: u8 = b's';
5290
5291/// v7.39 (round 315, V19) — which catalogued function does a persisted
5292/// ACL key refer to?
5293///
5294/// The key was computed by whichever formula was current when the image
5295/// was written, and the multi-word fix changed that formula for bare
5296/// types like `double precision`. A miss therefore does NOT mean "no
5297/// such function": an older image's key would land nowhere and its owner
5298/// and grants would be dropped in silence. Exact match first, then the
5299/// pre-fix formula.
5300#[must_use]
5301pub fn resolve_stored_function_key(
5302    functions: &BTreeMap<String, FunctionDef>,
5303    stored: &str,
5304) -> Option<String> {
5305    if functions.contains_key(stored) {
5306        return Some(stored.to_string());
5307    }
5308    functions
5309        .values()
5310        .find(|f| function_signature_key_legacy(&f.name, &f.args_repr) == stored)
5311        .map(|f| function_signature_key(&f.name, &f.args_repr))
5312}
5313
5314/// v7.39 (round 344, V49) — re-exported from [`spg_sql`], which owns the
5315/// SQL type spellings. This crate carried a byte-identical copy because
5316/// the two were siblings that did not depend on each other; spg-sql is a
5317/// dependency-free leaf, so the dependency is acyclic and the publish
5318/// order already puts it first. One list, one place to keep it right.
5319pub use spg_sql::parser::is_multiword_type_phrase;
5320
5321/// v7.39 (round 315, V19) — the signature key as computed BEFORE the
5322/// multi-word fix, used only to recognise what an older image wrote.
5323///
5324/// The function catalogue recomputes its keys from the stored name and
5325/// argument text on load, so it needs no migration. The ACL block does
5326/// not: it persists the computed key as a string and matches on it. A
5327/// key that changed shape would simply fail to match, and the owner and
5328/// grants would be dropped without a word — so the loader falls back to
5329/// this when the stored key finds nothing.
5330#[must_use]
5331pub fn function_signature_key_legacy(name: &str, args_repr: &str) -> String {
5332    let inner = args_repr
5333        .trim()
5334        .trim_start_matches('(')
5335        .trim_end_matches(')');
5336    let types: Vec<String> = if inner.trim().is_empty() {
5337        Vec::new()
5338    } else {
5339        inner
5340            .split(',')
5341            .map(|part| {
5342                let mut words: Vec<&str> = part.split_whitespace().collect();
5343                if !words.is_empty()
5344                    && (words[0].eq_ignore_ascii_case("OUT")
5345                        || words[0].eq_ignore_ascii_case("INOUT"))
5346                {
5347                    words.remove(0);
5348                }
5349                let ty = if words.len() >= 2 {
5350                    words[1..].join(" ")
5351                } else {
5352                    words.first().map_or(String::new(), |w| (*w).to_string())
5353                };
5354                normalize_type_name(&ty)
5355            })
5356            .collect()
5357    };
5358    format!("{}({})", name.to_ascii_lowercase(), types.join(","))
5359}
5360
5361pub fn function_signature_key(name: &str, args_repr: &str) -> String {
5362    let types = function_arg_types(args_repr);
5363    format!("{}({})", name.to_ascii_lowercase(), types.join(","))
5364}
5365
5366/// The declared argument TYPES of a function, out of its `args_repr`
5367/// (`"(x INT, y DOUBLE PRECISION)"` → `["int", "float"]`). An entry may be a
5368/// bare type with no name (`"(INT)"`).
5369#[must_use]
5370pub fn function_arg_types(args_repr: &str) -> Vec<String> {
5371    let inner = args_repr
5372        .trim()
5373        .trim_start_matches('(')
5374        .trim_end_matches(')');
5375    if inner.trim().is_empty() {
5376        return Vec::new();
5377    }
5378    inner
5379        .split(',')
5380        .map(|part| {
5381            let mut words: Vec<&str> = part.split_whitespace().collect();
5382            // `OUT x INT` / `INOUT x INT` — the mode is not part of the type.
5383            if !words.is_empty()
5384                && (words[0].eq_ignore_ascii_case("OUT") || words[0].eq_ignore_ascii_case("INOUT"))
5385            {
5386                words.remove(0);
5387            }
5388            // v7.39 (round 315, V19) — two or more words is USUALLY
5389            // `name TYPE`, but not when the type itself is spelled in
5390            // several words. `double precision` was read as a parameter
5391            // named "double" of type "precision", so it keyed differently
5392            // from `x double precision` — the same signature written two
5393            // ways did not resolve to the same function. Decide by asking
5394            // whether the whole phrase names a type first; only then is
5395            // the leading word a parameter name.
5396            let whole = words.join(" ");
5397            let ty = if words.len() >= 2 && !is_multiword_type_phrase(&whole) {
5398                words[1..].join(" ")
5399            } else {
5400                whole
5401            };
5402            normalize_type_name(&ty)
5403        })
5404        .collect()
5405}
5406
5407/// v7.39 (read01 round 65) — the declared argument NAMES of a function (`""` for
5408/// a bare type with no name).
5409#[must_use]
5410pub fn function_arg_names(args_repr: &str) -> Vec<String> {
5411    let inner = args_repr
5412        .trim()
5413        .trim_start_matches('(')
5414        .trim_end_matches(')');
5415    if inner.trim().is_empty() {
5416        return Vec::new();
5417    }
5418    inner
5419        .split(',')
5420        .map(|part| {
5421            let mut words: Vec<&str> = part.split_whitespace().collect();
5422            if !words.is_empty()
5423                && (words[0].eq_ignore_ascii_case("OUT") || words[0].eq_ignore_ascii_case("INOUT"))
5424            {
5425                words.remove(0);
5426            }
5427            if words.len() >= 2 {
5428                words[0].to_string()
5429            } else {
5430                String::new()
5431            }
5432        })
5433        .collect()
5434}
5435
5436/// Fold PG's type aliases so a signature key is stable across spellings.
5437/// Unknown names pass through lower-cased — consistency is what the key needs.
5438#[must_use]
5439pub fn normalize_type_name(ty: &str) -> String {
5440    let t = ty.trim().to_ascii_lowercase();
5441    // Peel a precision/length modifier: `numeric(10,2)`, `varchar(64)`.
5442    let base = t.split_once('(').map_or(t.as_str(), |(h, _)| h).trim();
5443    match base {
5444        "int" | "int4" | "integer" => "int",
5445        "bigint" | "int8" => "bigint",
5446        "smallint" | "int2" => "smallint",
5447        "text" | "varchar" | "character varying" | "char" | "character" | "bpchar" => "text",
5448        "bool" | "boolean" => "bool",
5449        "float" | "float8" | "double precision" => "float",
5450        "real" | "float4" => "real",
5451        "numeric" | "decimal" => "numeric",
5452        "timestamptz" | "timestamp with time zone" => "timestamptz",
5453        "timestamp" | "timestamp without time zone" => "timestamp",
5454        other => other,
5455    }
5456    .to_string()
5457}
5458
5459/// v7.12.4 — catalogued trigger. References its function by
5460/// name; the function must exist at TRIGGER creation time
5461/// (forward references are deferred to v7.12.5+).
5462#[derive(Debug, Clone, PartialEq, Eq)]
5463pub struct TriggerDef {
5464    pub name: String,
5465    /// Watched table. Trigger is dropped when the table drops.
5466    pub table: String,
5467    /// `"BEFORE"` / `"AFTER"` / `"INSTEAD OF"`. Stored as the
5468    /// uppercased keyword so deserialised catalogs round-trip
5469    /// without canonicalisation surprises.
5470    pub timing: String,
5471    /// Each entry is one of `"INSERT"` / `"UPDATE"` / `"DELETE"`
5472    /// / `"TRUNCATE"`. `INSERT OR UPDATE` parses to two entries.
5473    pub events: Vec<String>,
5474    /// `"ROW"` / `"STATEMENT"`. v7.12.4 ships `"ROW"` only;
5475    /// `"STATEMENT"` parses and persists but the executor
5476    /// refuses it at trigger fire time.
5477    pub for_each: String,
5478    /// Name of the PL/pgSQL function to invoke.
5479    pub function: String,
5480    /// v7.13.0 — `UPDATE OF col, col, …` column-list filter
5481    /// (mailrs round-5 G7). Non-empty means the trigger fires
5482    /// only when at least one of these columns appears in the
5483    /// UPDATE's SET list. Empty = no column filter. Stored in
5484    /// catalog FILE_VERSION 23+; older catalogs deserialise with
5485    /// an empty vec.
5486    pub update_columns: Vec<String>,
5487    /// v7.16.1 — whether the trigger fires when its watched
5488    /// event occurs. Toggled by `ALTER TABLE … { ENABLE |
5489    /// DISABLE } TRIGGER …`; pg_dump --disable-triggers wraps
5490    /// every data block with a DISABLE/ENABLE pair so the
5491    /// rows already-computed in prod don't get re-rewritten.
5492    /// Defaults to `true` at CREATE TRIGGER time. Stored in
5493    /// catalog FILE_VERSION 25+; older catalogs deserialise
5494    /// with `enabled = true`.
5495    pub enabled: bool,
5496    /// v7.39 (round 138) — the deparsed `WHEN ( condition )` predicate text
5497    /// (re-parsed at fire time to filter row triggers). Empty = no WHEN.
5498    /// Persisted from FILE_VERSION 70; older catalogs read back empty.
5499    pub when_condition: String,
5500}
5501
5502/// v7.39 (round 280) — one `CREATE STATISTICS` object.
5503#[derive(Debug, Clone, PartialEq, Eq)]
5504pub struct StatisticsExtDef {
5505    pub name: String,
5506    pub table: String,
5507    /// PG's single-letter kinds: `d` ndistinct, `f` dependencies,
5508    /// `m` mcv. PG's default set is all three.
5509    pub kinds: Vec<String>,
5510    pub columns: Vec<String>,
5511}
5512
5513/// v7.39 (round 139) — a catalogued query-rewrite RULE. Stored flat like
5514/// `TriggerDef`, keyed by `(name, table)`. Command / WHEN text is deparsed SQL
5515/// re-parsed at rewrite time (the same round-trip trick as
5516/// `TriggerDef.when_condition`). Persisted from FILE_VERSION 71.
5517#[derive(Debug, Clone, PartialEq, Eq)]
5518pub struct RuleDef {
5519    pub name: String,
5520    pub table: String,
5521    /// Event keyword, uppercased: `INSERT` / `UPDATE` / `DELETE` / `SELECT`.
5522    pub event: String,
5523    /// `true` = `DO INSTEAD`, `false` = `DO ALSO`.
5524    pub instead: bool,
5525    /// Deparsed `WHERE` predicate text; empty = unconditional.
5526    pub when_condition: String,
5527    /// Deparsed DO command statements; empty = `NOTHING`.
5528    pub commands: Vec<String>,
5529}
5530
5531/// v7.17.0 — catalogued SEQUENCE. PG semantics: a counter object
5532/// returning monotonically increasing values via `nextval(name)`.
5533/// `last_value` is the most recent value handed out; `is_called`
5534/// is false until the first `nextval`/`setval`. Stored separately
5535/// from tables in the catalog.
5536#[derive(Debug, Clone, PartialEq, Eq)]
5537pub struct SequenceDef {
5538    pub name: String,
5539    /// Data type — narrows the i64 range. PG default BIGINT.
5540    pub data_type: SequenceDataType,
5541    pub start: i64,
5542    pub increment: i64,
5543    pub min_value: i64,
5544    pub max_value: i64,
5545    pub cache: i64,
5546    pub cycle: bool,
5547    /// `OWNED BY` target — `(table, column)` or NONE.
5548    pub owned_by: Option<(String, String)>,
5549    /// Most recently handed-out value. Meaningless when
5550    /// `is_called == false`; in that case the NEXT `nextval`
5551    /// will return `start`.
5552    pub last_value: i64,
5553    pub is_called: bool,
5554    /// v7.39 (read01 round 60) — the role that ran CREATE SEQUENCE. `None` = an
5555    /// image written before FILE_VERSION 66, which predates sequence owners.
5556    pub owner: Option<String>,
5557    /// v7.39 (read01 round 60) — explicit GRANTs on this sequence. A sequence's
5558    /// meaningful privileges are SELECT (`currval`), UPDATE (`setval`) and
5559    /// USAGE (`nextval`).
5560    pub acl: Vec<AclItem>,
5561}
5562
5563/// v7.17.0 — sequence integer width.
5564#[derive(Debug, Clone, Copy, PartialEq, Eq)]
5565pub enum SequenceDataType {
5566    SmallInt,
5567    Int,
5568    BigInt,
5569}
5570
5571/// v7.17.0 Phase 1.6 — built-in schema names that every Catalog
5572/// understands without an explicit CREATE SCHEMA. Used by
5573/// [`Catalog::schema_exists`] and the engine's schema-qualified
5574/// lookup path.
5575#[must_use]
5576pub fn is_builtin_schema(name: &str) -> bool {
5577    name.eq_ignore_ascii_case("public")
5578        || name.eq_ignore_ascii_case("pg_catalog")
5579        || name.eq_ignore_ascii_case("information_schema")
5580}
5581
5582/// v7.17.0 — parse a PG-canonical UUID text representation into the
5583/// 16-byte network-order layout used by `Value::Uuid`. Accepted input
5584/// shapes (all case-insensitive):
5585///   * Canonical hyphenated 8-4-4-4-12 (`550e8400-e29b-41d4-a716-446655440000`)
5586///   * Unhyphenated 32-char hex (`550e8400e29b41d4a716446655440000`)
5587///   * Either form wrapped in `{ ... }`
5588///
5589/// Returns `None` for any malformed input (wrong length, non-hex
5590/// characters, misplaced hyphens). The caller surfaces a SQL error
5591/// at coercion time — silent acceptance of garbage would mask
5592/// application bugs and is exactly the divergence from PG that
5593/// breaks the 0-change cutover promise.
5594#[must_use]
5595pub fn parse_uuid_str(input: &str) -> Option<[u8; 16]> {
5596    let s = input.trim();
5597    // Strip surrounding braces if present.
5598    let s = if let Some(inner) = s.strip_prefix('{').and_then(|x| x.strip_suffix('}')) {
5599        inner
5600    } else {
5601        s
5602    };
5603    // Two valid shapes after braces are stripped: 32 hex chars or
5604    // the canonical 36-char hyphenated form.
5605    let hex: String = match s.len() {
5606        32 => s.to_ascii_lowercase(),
5607        36 => {
5608            // Hyphens must be exactly at positions 8, 13, 18, 23.
5609            let b = s.as_bytes();
5610            if b[8] != b'-' || b[13] != b'-' || b[18] != b'-' || b[23] != b'-' {
5611                return None;
5612            }
5613            let mut out = String::with_capacity(32);
5614            out.push_str(&s[0..8]);
5615            out.push_str(&s[9..13]);
5616            out.push_str(&s[14..18]);
5617            out.push_str(&s[19..23]);
5618            out.push_str(&s[24..36]);
5619            out.make_ascii_lowercase();
5620            out
5621        }
5622        _ => return None,
5623    };
5624    let bytes = hex.as_bytes();
5625    let mut out = [0u8; 16];
5626    for i in 0..16 {
5627        let hi = hex_nibble(bytes[i * 2])?;
5628        let lo = hex_nibble(bytes[i * 2 + 1])?;
5629        out[i] = (hi << 4) | lo;
5630    }
5631    Some(out)
5632}
5633
5634fn hex_nibble(b: u8) -> Option<u8> {
5635    match b {
5636        b'0'..=b'9' => Some(b - b'0'),
5637        b'a'..=b'f' => Some(10 + b - b'a'),
5638        b'A'..=b'F' => Some(10 + b - b'A'),
5639        _ => None,
5640    }
5641}
5642
5643/// v7.17.0 — render a `Value::Uuid` payload as the canonical
5644/// lowercase 8-4-4-4-12 hyphenated form PG `text` cast surfaces.
5645#[must_use]
5646pub fn format_uuid(b: &[u8; 16]) -> String {
5647    const HEX: &[u8; 16] = b"0123456789abcdef";
5648    let mut out = String::with_capacity(36);
5649    for (i, byte) in b.iter().enumerate() {
5650        if matches!(i, 4 | 6 | 8 | 10) {
5651            out.push('-');
5652        }
5653        out.push(HEX[(byte >> 4) as usize] as char);
5654        out.push(HEX[(byte & 0x0f) as usize] as char);
5655    }
5656    out
5657}
5658
5659/// v7.17.0 Phase 1.5 — catalogued user-defined DOMAIN. A domain
5660/// is a named CHECK-constrained alias over a built-in type;
5661/// columns bound to it inherit the base type plus the CHECK
5662/// predicates + NOT NULL + DEFAULT at INSERT/UPDATE time.
5663/// v7.37.17 (Phase E RC rebase) — the write-set one writer version left
5664/// on a table, addressed by stable [`row_header::RowId`]s so it can be
5665/// replayed onto a fresher clone of the relation whose physical slots
5666/// differ. Produced by [`Table::extract_tx_writeset`], consumed by
5667/// [`Table::replay_tx_writeset`].
5668#[derive(Debug, Clone, Default)]
5669pub struct TxWriteSet {
5670    /// INSERTs and UPDATE-new-versions (`header.xmin == v`).
5671    pub inserted: Vec<(row_header::RowId, Row<'static>)>,
5672    /// DELETE / UPDATE-old-version targets (`header.xmax == v`).
5673    pub tombstoned: Vec<row_header::RowId>,
5674}
5675
5676impl TxWriteSet {
5677    #[must_use]
5678    pub fn is_empty(&self) -> bool {
5679        self.inserted.is_empty() && self.tombstoned.is_empty()
5680    }
5681}
5682
5683/// v7.39 (round 260) — one named CHECK on a domain. PG auto-names an
5684/// unnamed one `<domain>_check`, then `_check1`, `_check2`, … (probed).
5685#[derive(Debug, Clone, PartialEq, Eq)]
5686pub struct DomainCheck {
5687    pub name: String,
5688    /// The predicate source, referencing the pseudo-column `VALUE`.
5689    pub expr: String,
5690}
5691
5692/// `default` / `checks` are stored as Display-form source so
5693/// `spg-storage` stays free of `spg-sql` dependency — same
5694/// pattern as FunctionDef / ViewDef.
5695#[derive(Debug, Clone, PartialEq, Eq)]
5696pub struct DomainDef {
5697    pub name: String,
5698    pub base_type: DataType,
5699    pub nullable: bool,
5700    pub default: Option<String>,
5701    /// v7.39 (round 260) — each CHECK carries its constraint NAME, so
5702    /// `ALTER DOMAIN … DROP CONSTRAINT <name>` can find it and the
5703    /// violation message can report the constraint that actually failed.
5704    /// PG's auto-naming for an unnamed check is `<domain>_check`, then
5705    /// `_check1`, `_check2`, … (probed).
5706    pub checks: Vec<DomainCheck>,
5707    /// v7.39 (round 258/259) — when this domain was declared over ANOTHER
5708    /// domain (`CREATE DOMAIN child AS parent CHECK (…)`), the parent's
5709    /// name. `base_type` is the ultimate scalar type either way, so
5710    /// without this the parent's constraints were invisible and a value
5711    /// violating them was silently accepted. PG checks the whole chain,
5712    /// base-first, and an `ALTER DOMAIN` on the parent takes effect for
5713    /// the child immediately (probed) — so the chain is walked at check
5714    /// time rather than copied at CREATE time. Catalog FILE_VERSION 74+.
5715    pub base_domain: Option<String>,
5716}
5717
5718/// v7.17.0 Phase 1.4 — catalogued user-defined ENUM type. The
5719/// label vector is order-preserving (PG enum ordering follows the
5720/// declared order). At INSERT/UPDATE on a column bound to this
5721/// enum, the engine looks up the value against `labels` and
5722/// rejects non-members.
5723#[derive(Debug, Clone, PartialEq, Eq)]
5724pub struct EnumDef {
5725    pub name: String,
5726    pub labels: Vec<String>,
5727}
5728
5729/// v7.37.42-T2 ζ-B — catalogued user-defined COMPOSITE type
5730/// (`CREATE TYPE name AS (field_name field_type, ...)`). Order
5731/// matters: PG composite literals are positional, and SPG mirrors
5732/// that. Stored as ordered `(name, DataType)` pairs to keep the
5733/// codec straightforward and to allow eventual `Value::Composite`
5734/// bodies to encode positionally. Persisted in catalog FILE_VERSION
5735/// 52+; older catalogs deserialise with an empty composite_types
5736/// map. Composite types can be used as a column type by spelling
5737/// the composite's name; the resolution from
5738/// `ColumnSchema.user_composite_type = Some(name)` happens at the
5739/// engine boundary (parallel to `user_enum_type` /
5740/// `user_domain_type`). The dense storage shape — JSON-text body
5741/// keyed by the composite's field list — keeps the codec free of
5742/// recursive `Value` bodies until the full Value::Composite arena
5743/// migration in a later phase.
5744#[derive(Debug, Clone, PartialEq, Eq)]
5745pub struct CompositeDef {
5746    pub name: String,
5747    /// Ordered `(field_name, field_type)` pairs. PG composite
5748    /// literals are positional, so order is part of the type's
5749    /// identity.
5750    pub fields: Vec<(String, DataType)>,
5751    /// v7.39 (round 264) — parallel to `fields`: the USER type name of
5752    /// each field when it is itself a composite (or another named user
5753    /// type). `DataType` has no room for one, so a nested composite
5754    /// field resolved to the parser's Text placeholder and the inner
5755    /// record stayed TEXT — `(x).inner.street` errored, `pg_typeof`
5756    /// said text, and `row_to_json` nested a string instead of an
5757    /// object. Same shape as `ColumnSchema.user_composite_type` and
5758    /// `DomainDef.base_domain`. Catalog FILE_VERSION 76+; an older
5759    /// catalog reads all-None, which is what it meant.
5760    pub field_user_types: Vec<Option<String>>,
5761}
5762
5763/// v7.17.0 Phase 1.2 — catalogued VIEW. The body is stored as the
5764/// raw source text the parser saw between `AS` and the statement
5765/// terminator; the engine re-parses on each invocation. Same
5766/// pattern as `FunctionDef` — keeps `spg-storage` free of
5767/// `spg-sql` dependency.
5768#[derive(Debug, Clone, PartialEq, Eq)]
5769pub struct ViewDef {
5770    pub name: String,
5771    /// Optional `(col, col, …)` rename list. Empty when the body's
5772    /// projected names are used directly.
5773    pub columns: Vec<String>,
5774    /// Raw SELECT source. Display-rendered at storage time so the
5775    /// catalog round-trips a deterministic form regardless of
5776    /// whitespace / comments in the original input. Re-parsed at
5777    /// SELECT-from-view time to materialise as a synthetic CTE.
5778    pub body: String,
5779    /// v7.39 (round 132) — `WITH CHECK OPTION`: 0 = none, 1 = LOCAL,
5780    /// 2 = CASCADED. A storage-local u8 (no dependency on the SQL AST).
5781    /// Persisted from FILE_VERSION 69; older catalogs read back as 0.
5782    pub check_option: u8,
5783}
5784
5785impl SequenceDataType {
5786    /// PG default min/max per AS clause.
5787    pub fn default_bounds(self, increment_positive: bool) -> (i64, i64) {
5788        match self {
5789            Self::SmallInt => {
5790                if increment_positive {
5791                    (1, i64::from(i16::MAX))
5792                } else {
5793                    (i64::from(i16::MIN), -1)
5794                }
5795            }
5796            Self::Int => {
5797                if increment_positive {
5798                    (1, i64::from(i32::MAX))
5799                } else {
5800                    (i64::from(i32::MIN), -1)
5801                }
5802            }
5803            Self::BigInt => {
5804                if increment_positive {
5805                    (1, i64::MAX)
5806                } else {
5807                    (i64::MIN, -1)
5808                }
5809            }
5810        }
5811    }
5812}
5813
5814impl Catalog {
5815    /// v7.37.15 (Phase D) — fleet-wide vacuum pass. Walks every
5816    /// user table and reclaims rows whose delete-commit version is
5817    /// older than `oldest_active_snapshot`. Returns an aggregated
5818    /// report with per-table breakdown so hosts can emit metrics.
5819    ///
5820    /// `dry_run = true` reports the work without doing it. Use it
5821    /// to estimate the cost before scheduling a real pass.
5822    pub fn vacuum_all(
5823        &mut self,
5824        oldest_active_snapshot: u64,
5825        dry_run: bool,
5826    ) -> vacuum::VacuumReport {
5827        let mut total = vacuum::VacuumReport::default();
5828        // Snapshot the table names so we don't hold an immutable
5829        // borrow during the get_mut loop.
5830        let names: Vec<String> = self
5831            .tables
5832            .iter()
5833            .map(|t| t.schema().name.clone())
5834            .collect();
5835        for name in names {
5836            let Some(t) = self.get_mut(&name) else {
5837                continue;
5838            };
5839            let r = t.vacuum(oldest_active_snapshot, dry_run);
5840            if r.rows_reclaimed > 0 {
5841                total.per_table.push((name, r.rows_reclaimed));
5842            }
5843            total.rows_reclaimed += r.rows_reclaimed;
5844            total.rows_examined += r.rows_examined;
5845        }
5846        total
5847    }
5848
5849    pub const fn new() -> Self {
5850        Self {
5851            cold_read_stats: ColdReadStats {
5852                cold_reads: core::sync::atomic::AtomicU64::new(0),
5853            },
5854            tables: Vec::new(),
5855            by_name: BTreeMap::new(),
5856            temp_prefix: None,
5857            case_insensitive_names: false,
5858            dirty_tables: alloc::collections::BTreeSet::new(),
5859            dirty_nontable: alloc::collections::BTreeSet::new(),
5860            next_rel_id: 0,
5861            cold_segments: Vec::new(),
5862            functions: BTreeMap::new(),
5863            triggers: Vec::new(),
5864            rules: Vec::new(),
5865            statistics_ext: Vec::new(),
5866            large_objects: alloc::collections::BTreeMap::new(),
5867            sequences: BTreeMap::new(),
5868            schema_acl: Vec::new(),
5869            database_acl: Vec::new(),
5870            views: BTreeMap::new(),
5871            materialized_views: BTreeMap::new(),
5872            enum_types: BTreeMap::new(),
5873            domain_types: BTreeMap::new(),
5874            comments: BTreeMap::new(),
5875            db_role_settings: BTreeMap::new(),
5876            replication_slots: BTreeMap::new(),
5877            db_collation: None,
5878            created_databases: alloc::collections::BTreeSet::new(),
5879            composite_types: BTreeMap::new(),
5880            schemas: alloc::collections::BTreeSet::new(),
5881        }
5882    }
5883
5884    /// v7.12.4 — read-only view of catalogued user-defined
5885    /// functions. Engine callers go through here to look up the
5886    /// function body before re-parsing it for invocation.
5887    pub const fn functions(&self) -> &BTreeMap<String, FunctionDef> {
5888        &self.functions
5889    }
5890
5891    /// v7.12.4 — register a new user-defined function. With
5892    /// `or_replace = false`, errors if the name is taken. The
5893    /// engine validates the body before passing it here.
5894    pub fn create_function(
5895        &mut self,
5896        def: FunctionDef,
5897        or_replace: bool,
5898    ) -> Result<(), StorageError> {
5899        // v7.39 (read01 round 62) — functions are keyed by SIGNATURE, not by
5900        // name: `f(int)` and `f(text)` are two functions, as in PG. Keying by
5901        // name alone made a second overload an "already exists" error — so a
5902        // pg_dump carrying an overload set could not restore — and, worse, a
5903        // call to one overload silently ran the other.
5904        let key = function_signature_key(&def.name, &def.args_repr);
5905        if !or_replace && self.functions.contains_key(&key) {
5906            return Err(StorageError::Corrupt(format!(
5907                "function {:?} already exists (drop or use CREATE OR REPLACE)",
5908                def.name
5909            )));
5910        }
5911        self.functions.insert(key, def);
5912        Ok(())
5913    }
5914
5915    /// v7.39 (read01 round 62) — every overload of `name`.
5916    #[must_use]
5917    pub fn functions_named(&self, name: &str) -> Vec<&FunctionDef> {
5918        self.functions
5919            .values()
5920            .filter(|f| f.name.eq_ignore_ascii_case(name))
5921            .collect()
5922    }
5923
5924    /// v7.39 (read01 round 62) — one overload, by its signature key.
5925    #[must_use]
5926    pub fn function_by_key(&self, key: &str) -> Option<&FunctionDef> {
5927        self.functions.get(key)
5928    }
5929
5930    /// v7.39 (read01 round 62) — drop ONE overload. `true` if it was there.
5931    pub fn drop_function_by_key(&mut self, key: &str) -> bool {
5932        self.functions.remove(key).is_some()
5933    }
5934
5935    /// v7.12.4 — remove a user-defined function by name. Returns
5936    /// `true` if a function was removed, `false` if none matched.
5937    /// Caller decides whether to surface `if_exists` semantics.
5938    /// v7.39 (read01 round 62) — with no signature, PG drops the function only
5939    /// when the name is unambiguous. SPG mirrors that: this removes EVERY
5940    /// overload of `name`, and the caller (ddl.rs) refuses the ambiguous case
5941    /// before getting here.
5942    pub fn drop_function(&mut self, name: &str) -> bool {
5943        let keys: Vec<String> = self
5944            .functions
5945            .iter()
5946            .filter(|(_, f)| f.name.eq_ignore_ascii_case(name))
5947            .map(|(k, _)| k.clone())
5948            .collect();
5949        let hit = !keys.is_empty();
5950        for k in keys {
5951            self.functions.remove(&k);
5952        }
5953        hit
5954    }
5955
5956    /// v7.17.0 — read-only handle to catalogued sequences.
5957    /// v7.39 (read01 round 60) — the `public` schema's ACL (PG nspacl).
5958    #[must_use]
5959    pub fn schema_acl(&self) -> &[AclItem] {
5960        &self.schema_acl
5961    }
5962
5963    pub fn schema_acl_mut(&mut self) -> &mut Vec<AclItem> {
5964        &mut self.schema_acl
5965    }
5966
5967    /// v7.39 (read01 round 60) — the database's ACL.
5968    #[must_use]
5969    pub fn database_acl(&self) -> &[AclItem] {
5970        &self.database_acl
5971    }
5972
5973    pub fn database_acl_mut(&mut self) -> &mut Vec<AclItem> {
5974        &mut self.database_acl
5975    }
5976
5977    /// v7.39 (read01 round 60) — mutable sequence access, for GRANT.
5978    /// v7.39 (round 469) — resolves the session's temporary sequence
5979    /// first, like its read-only twin. `nextval` and `setval` reach the
5980    /// map through here, so a temporary sequence shadowing a permanent one
5981    /// advances the temporary one — measured against PG18, where the
5982    /// permanent sequence's counter is untouched while the temp exists.
5983    pub fn sequence_mut(&mut self, name: &str) -> Option<&mut SequenceDef> {
5984        let key = self.sequence_key(name);
5985        self.sequences.get_mut(&key)
5986    }
5987
5988    /// v7.39 (read01 round 61) — mutable function access, for GRANT.
5989    pub fn function_mut(&mut self, name: &str) -> Option<&mut FunctionDef> {
5990        self.functions.get_mut(name)
5991    }
5992
5993    /// Every catalogued sequence, temp ones included under their mangled
5994    /// storage names. Listing code filters these through
5995    /// [`Self::listed_name`]; anything resolving ONE name by its logical
5996    /// spelling wants [`Self::sequence`] instead.
5997    pub const fn sequences_all(&self) -> &BTreeMap<String, SequenceDef> {
5998        &self.sequences
5999    }
6000
6001    /// v7.39 (round 469) — resolve one sequence by its logical name, the
6002    /// session's temporary one winning over a permanent one of the same
6003    /// name. The same rule [`Self::resolve_index`] applies to tables.
6004    #[must_use]
6005    pub fn sequence(&self, name: &str) -> Option<&SequenceDef> {
6006        if let Some(mangled) = self.temp_name_for(name)
6007            && let Some(def) = self.sequences.get(&mangled)
6008        {
6009            return Some(def);
6010        }
6011        self.sequences.get(name)
6012    }
6013
6014    /// Does a sequence of this logical name exist for this session?
6015    #[must_use]
6016    pub fn has_sequence(&self, name: &str) -> bool {
6017        self.sequence(name).is_some()
6018    }
6019
6020    /// The storage key a sequence of this logical name resolves to — the
6021    /// session's temp mangling when it has one, else the name itself.
6022    #[must_use]
6023    pub fn sequence_key(&self, name: &str) -> String {
6024        if let Some(mangled) = self.temp_name_for(name)
6025            && self.sequences.contains_key(&mangled)
6026        {
6027            return mangled;
6028        }
6029        name.into()
6030    }
6031
6032    /// v7.17.0 — register a new SEQUENCE. Errors if `name`
6033    /// collides with an existing sequence and `if_not_exists`
6034    /// is false.
6035    pub fn create_sequence(
6036        &mut self,
6037        def: SequenceDef,
6038        if_not_exists: bool,
6039    ) -> Result<(), StorageError> {
6040        if self.sequences.contains_key(&def.name) {
6041            if if_not_exists {
6042                return Ok(());
6043            }
6044            // v7.39 (read01 round 47) — a sequence is a relation to PG (42P07).
6045            return Err(StorageError::Corrupt(format!(
6046                "relation {:?} already exists",
6047                def.name
6048            )));
6049        }
6050        self.mark_nontable_dirty(NonTableKind::Sequence, &def.name);
6051        self.sequences.insert(def.name.clone(), def);
6052        Ok(())
6053    }
6054
6055    /// v7.17.0 — remove a SEQUENCE by name. Returns `true` if a
6056    /// sequence was removed, `false` if none matched. Caller
6057    /// surfaces IF EXISTS semantics.
6058    /// v7.39 (read01 round 49) — `ALTER SEQUENCE old RENAME TO new`.
6059    /// Errors when `old` is missing or `new` is taken; the SequenceDef's own
6060    /// `name` field is rewritten so it stays self-describing.
6061    pub fn rename_sequence(&mut self, old: &str, new: &str) -> Result<(), StorageError> {
6062        if !self.sequences.contains_key(old) {
6063            return Err(StorageError::Corrupt(format!(
6064                "relation {old:?} does not exist"
6065            )));
6066        }
6067        if self.sequences.contains_key(new) {
6068            return Err(StorageError::Corrupt(format!(
6069                "relation {new:?} already exists"
6070            )));
6071        }
6072        self.mark_nontable_dirty(NonTableKind::Sequence, old);
6073        self.mark_nontable_dirty(NonTableKind::Sequence, new);
6074        if let Some(mut def) = self.sequences.remove(old) {
6075            def.name = new.to_string();
6076            self.sequences.insert(new.to_string(), def);
6077        }
6078        Ok(())
6079    }
6080
6081    pub fn drop_sequence(&mut self, name: &str) -> bool {
6082        self.mark_nontable_dirty(NonTableKind::Sequence, name);
6083        self.sequences.remove(name).is_some()
6084    }
6085
6086    /// v7.17.0 — atomic nextval. Increments `last_value` per
6087    /// `increment`, returns the new value, sets `is_called`.
6088    /// Returns an error on CYCLE-less overflow.
6089    /// v7.39 (round 497) — the counter state of every sequence, for
6090    /// carrying across a commit install.
6091    ///
6092    /// A sequence's VALUE is not transactional in PG: `nextval` advances
6093    /// shared state that a rollback does not give back, because two
6094    /// sessions must never receive the same number. SPG keeps sequences in
6095    /// the catalog, and a transaction works on a catalog CLONE, so
6096    /// installing that clone at COMMIT would restore whatever the counter
6097    /// was at BEGIN. These two let the install put the live counters back.
6098    #[must_use]
6099    pub fn sequence_counters(&self) -> Vec<(String, i64, bool)> {
6100        self.sequences
6101            .iter()
6102            .map(|(k, d)| (k.clone(), d.last_value, d.is_called))
6103            .collect()
6104    }
6105
6106    /// Restore counters saved by [`Self::sequence_counters`], for the
6107    /// sequences that still exist. A sequence the transaction CREATED is
6108    /// absent from the saved set and keeps the value it was given.
6109    pub fn restore_sequence_counters(&mut self, saved: &[(String, i64, bool)]) {
6110        for (k, last, called) in saved {
6111            if let Some(d) = self.sequences.get_mut(k) {
6112                d.last_value = *last;
6113                d.is_called = *called;
6114            }
6115        }
6116    }
6117
6118    pub fn sequence_next_value(&mut self, name: &str) -> Result<i64, StorageError> {
6119        let key = self.sequence_key(name);
6120        let Some(seq) = self.sequences.get_mut(&key) else {
6121            return Err(StorageError::TableNotFound { name: name.into() });
6122        };
6123        // PG semantics: when !is_called (fresh sequence or
6124        // setval(_, false)), the next nextval returns the stored
6125        // `last_value`. When is_called, it advances by `increment`
6126        // and CYCLE-wraps on overflow.
6127        let candidate = if seq.is_called {
6128            let next = seq.last_value.checked_add(seq.increment).ok_or_else(|| {
6129                StorageError::Corrupt(format!("sequence {name:?} arithmetic overflow"))
6130            })?;
6131            if seq.increment > 0 {
6132                if next > seq.max_value {
6133                    if seq.cycle {
6134                        seq.min_value
6135                    } else {
6136                        // v7.39 (round 220) — PG's 2200H wording, not a
6137                        // Corrupt-classed error.
6138                        return Err(StorageError::SequenceExhausted {
6139                            name: name.into(),
6140                            limit: seq.max_value,
6141                            is_max: true,
6142                        });
6143                    }
6144                } else {
6145                    next
6146                }
6147            } else if next < seq.min_value {
6148                if seq.cycle {
6149                    seq.max_value
6150                } else {
6151                    return Err(StorageError::SequenceExhausted {
6152                        name: name.into(),
6153                        limit: seq.min_value,
6154                        is_max: false,
6155                    });
6156                }
6157            } else {
6158                next
6159            }
6160        } else {
6161            seq.last_value
6162        };
6163        seq.last_value = candidate;
6164        seq.is_called = true;
6165        Ok(candidate)
6166    }
6167
6168    /// v7.17.0 — currval. Errors if the session has never called
6169    /// nextval on this sequence (PG semantics). At the catalog
6170    /// level we approximate "session" with "is_called persisted";
6171    /// the engine session-tracking layer can wrap this for the
6172    /// strict per-session semantics later.
6173    pub fn sequence_current_value(&self, name: &str) -> Result<i64, StorageError> {
6174        let Some(seq) = self.sequences.get(name) else {
6175            return Err(StorageError::TableNotFound { name: name.into() });
6176        };
6177        if !seq.is_called {
6178            return Err(StorageError::Corrupt(format!(
6179                "currval of sequence {name:?} is not yet defined in this session"
6180            )));
6181        }
6182        Ok(seq.last_value)
6183    }
6184
6185    /// v7.17.0 — setval(name, value [, is_called]). PG returns
6186    /// `value` regardless. `is_called=true` means the NEXT
6187    /// nextval will return `value + increment`; `is_called=false`
6188    /// means the next nextval will return `value`.
6189    pub fn sequence_set_value(
6190        &mut self,
6191        name: &str,
6192        value: i64,
6193        is_called: bool,
6194    ) -> Result<i64, StorageError> {
6195        let key = self.sequence_key(name);
6196        let Some(seq) = self.sequences.get_mut(&key) else {
6197            return Err(StorageError::TableNotFound { name: name.into() });
6198        };
6199        // v7.39 (round 244) — PG refuses a value outside the sequence's
6200        // range (22003); SPG accepted it silently, leaving last_value out
6201        // of bounds.
6202        if value < seq.min_value || value > seq.max_value {
6203            return Err(StorageError::Unsupported(format!(
6204                "setval: value {value} is out of bounds for sequence \"{name}\" ({}..{})",
6205                seq.min_value, seq.max_value
6206            )));
6207        }
6208        seq.last_value = value;
6209        seq.is_called = is_called;
6210        Ok(value)
6211    }
6212
6213    /// v7.17.0 Phase 1.2 — read-only handle to catalogued views. Temp ones
6214    /// are in here under their mangled storage names; listing code filters
6215    /// through [`Self::listed_name`], and anything resolving ONE name by
6216    /// its logical spelling wants [`Self::view`].
6217    pub const fn views_all(&self) -> &BTreeMap<String, ViewDef> {
6218        &self.views
6219    }
6220
6221    /// v7.39 (round 469) — resolve one view by its logical name, the
6222    /// session's temporary one winning over a permanent one of the same
6223    /// name.
6224    #[must_use]
6225    pub fn view(&self, name: &str) -> Option<&ViewDef> {
6226        if let Some(mangled) = self.temp_name_for(name)
6227            && let Some(def) = self.views.get(&mangled)
6228        {
6229            return Some(def);
6230        }
6231        self.views.get(name)
6232    }
6233
6234    /// Does a view of this logical name exist for this session?
6235    #[must_use]
6236    pub fn has_view(&self, name: &str) -> bool {
6237        self.view(name).is_some()
6238    }
6239
6240    /// The storage key a view of this logical name resolves to.
6241    #[must_use]
6242    pub fn view_key(&self, name: &str) -> String {
6243        if let Some(mangled) = self.temp_name_for(name)
6244            && self.views.contains_key(&mangled)
6245        {
6246            return mangled;
6247        }
6248        name.into()
6249    }
6250
6251    /// v7.17.0 Phase 1.2 — install a VIEW. `or_replace=true`
6252    /// overwrites an existing entry; `if_not_exists=true` is a
6253    /// silent no-op when the name is taken. Errors if both flags
6254    /// are off and the name collides.
6255    pub fn create_view(
6256        &mut self,
6257        def: ViewDef,
6258        or_replace: bool,
6259        if_not_exists: bool,
6260    ) -> Result<(), StorageError> {
6261        if self.views.contains_key(&def.name) {
6262            if or_replace {
6263                self.mark_nontable_dirty(NonTableKind::View, &def.name);
6264                self.mark_nontable_dirty(NonTableKind::View, &def.name);
6265                self.views.insert(def.name.clone(), def);
6266                return Ok(());
6267            }
6268            if if_not_exists {
6269                return Ok(());
6270            }
6271            // v7.39 (read01 round 47) — a view is a relation to PG (42P07).
6272            return Err(StorageError::Corrupt(format!(
6273                "relation {:?} already exists",
6274                def.name
6275            )));
6276        }
6277        // Reject name collision with tables / sequences — same
6278        // namespace per PG.
6279        if self.by_name.contains_key(&def.name) {
6280            return Err(StorageError::Corrupt(format!(
6281                "view {:?} would shadow an existing table",
6282                def.name
6283            )));
6284        }
6285        if self.sequences.contains_key(&def.name) {
6286            return Err(StorageError::Corrupt(format!(
6287                "view {:?} would shadow an existing sequence",
6288                def.name
6289            )));
6290        }
6291        self.views.insert(def.name.clone(), def);
6292        Ok(())
6293    }
6294
6295    /// v7.17.0 Phase 1.2 — remove a view by name. Returns true if
6296    /// a view was removed.
6297    pub fn drop_view(&mut self, name: &str) -> bool {
6298        self.mark_nontable_dirty(NonTableKind::View, name);
6299        self.views.remove(name).is_some()
6300    }
6301
6302    /// v7.17.0 Phase 1.3 — read-only handle to the materialised-
6303    /// view source registry. Each entry pairs with a regular
6304    /// table of the same name that holds the cached rows.
6305    pub const fn materialized_views(&self) -> &BTreeMap<String, String> {
6306        &self.materialized_views
6307    }
6308
6309    /// v7.17.0 Phase 1.3 — register a source for a materialised
6310    /// view. Caller has already created the backing table.
6311    pub fn register_materialized_view(&mut self, name: String, body: String) {
6312        self.mark_nontable_dirty(NonTableKind::MaterializedView, &name);
6313        self.materialized_views.insert(name, body);
6314    }
6315
6316    /// v7.17.0 Phase 1.3 — drop the source registry entry. Returns
6317    /// true if a source was unregistered. Caller separately drops
6318    /// the backing table.
6319    pub fn drop_materialized_view_source(&mut self, name: &str) -> bool {
6320        self.mark_nontable_dirty(NonTableKind::MaterializedView, name);
6321        self.materialized_views.remove(name).is_some()
6322    }
6323
6324    /// v7.17.0 Phase 1.4 — read-only handle to user-defined ENUM
6325    /// catalog.
6326    pub const fn enum_types(&self) -> &BTreeMap<String, EnumDef> {
6327        &self.enum_types
6328    }
6329
6330    /// v7.17.0 Phase 1.4 — install a new ENUM type. Errors if
6331    /// `name` collides with an existing enum (no IF NOT EXISTS
6332    /// per PG semantics for CREATE TYPE).
6333    pub fn create_enum_type(&mut self, def: EnumDef) -> Result<(), StorageError> {
6334        if self.enum_types.contains_key(&def.name) {
6335            return Err(StorageError::Corrupt(format!(
6336                "type {:?} already exists",
6337                def.name
6338            )));
6339        }
6340        self.mark_nontable_dirty(NonTableKind::EnumType, &def.name);
6341        self.enum_types.insert(def.name.clone(), def);
6342        Ok(())
6343    }
6344
6345    /// v7.17.0 Phase 1.4 — drop an ENUM type by name. Returns
6346    /// true if a type was removed.
6347    /// v7.37 D.55 — `ALTER TYPE … ADD VALUE`. Appends `label` to an existing
6348    /// enum's ordered label list, or inserts it before/after an existing label.
6349    /// `if_not_exists` makes a duplicate a no-op; otherwise a duplicate errors.
6350    /// Returns `Ok(true)` if a label was added, `Ok(false)` if it already existed
6351    /// (only possible under `if_not_exists`).
6352    /// v7.39 (read01 round 49) — `ALTER TYPE t RENAME VALUE 'old' TO 'new'`.
6353    /// The parser used to swallow this form as a no-op, so the rename was
6354    /// accepted and silently ignored. Renaming in place keeps the label's
6355    /// sort position, which is what PG does (enumsortorder is untouched).
6356    pub fn rename_enum_value(
6357        &mut self,
6358        type_name: &str,
6359        old: &str,
6360        new: &str,
6361    ) -> Result<(), StorageError> {
6362        let def = self
6363            .enum_types
6364            .get_mut(type_name)
6365            .ok_or_else(|| StorageError::Corrupt(format!("type {type_name:?} does not exist")))?;
6366        if def.labels.iter().any(|l| l == new) {
6367            return Err(StorageError::Corrupt(format!(
6368                "enum label {new:?} already exists"
6369            )));
6370        }
6371        let at = def.labels.iter().position(|l| l == old).ok_or_else(|| {
6372            StorageError::Corrupt(format!("{old:?} is not an existing enum label"))
6373        })?;
6374        def.labels[at] = new.to_string();
6375        Ok(())
6376    }
6377
6378    /// v7.39 (read01 round 50) — set (or, with `None`, remove) the comment on
6379    /// an object. `key` is the canonical `"<kind>:<name>"` form.
6380    pub fn set_comment(&mut self, key: &str, text: Option<&str>) {
6381        match text {
6382            Some(t) => {
6383                self.comments.insert(key.to_string(), t.to_string());
6384            }
6385            None => {
6386                self.comments.remove(key);
6387            }
6388        }
6389    }
6390
6391    /// v7.39 (read01 round 50) — the comment on an object, if any.
6392    #[must_use]
6393    pub fn comment(&self, key: &str) -> Option<&str> {
6394        self.comments.get(key).map(String::as_str)
6395    }
6396
6397    /// v7.39 (round 547) — record a GUC default for a scope. An empty
6398    /// database or role name is PG's oid 0 ("all"). `None` value
6399    /// removes just that parameter, as PG's RESET does.
6400    pub fn set_db_role_setting(
6401        &mut self,
6402        database: &str,
6403        role: &str,
6404        param: &str,
6405        value: Option<&str>,
6406    ) {
6407        let key = (database.to_string(), role.to_string());
6408        match value {
6409            Some(v) => {
6410                self.db_role_settings
6411                    .entry(key)
6412                    .or_default()
6413                    .insert(param.to_ascii_lowercase(), v.to_string());
6414            }
6415            None => {
6416                if let Some(m) = self.db_role_settings.get_mut(&key) {
6417                    m.remove(&param.to_ascii_lowercase());
6418                    if m.is_empty() {
6419                        self.db_role_settings.remove(&key);
6420                    }
6421                }
6422            }
6423        }
6424    }
6425
6426    /// v7.39 (round 550) — create a replication slot. `Err` carries
6427    /// PG's own message for a duplicate.
6428    ///
6429    /// # Errors
6430    /// When a slot of that name already exists.
6431    pub fn create_replication_slot(
6432        &mut self,
6433        name: &str,
6434        plugin: &str,
6435        slot_type: &str,
6436    ) -> Result<(), String> {
6437        if self.replication_slots.contains_key(name) {
6438            return Err(alloc::format!("replication slot \"{name}\" already exists"));
6439        }
6440        self.replication_slots.insert(
6441            name.to_string(),
6442            (plugin.to_string(), slot_type.to_string()),
6443        );
6444        Ok(())
6445    }
6446
6447    /// # Errors
6448    /// When no slot of that name exists — PG's message, and the case
6449    /// that used to report success.
6450    pub fn drop_replication_slot(&mut self, name: &str) -> Result<(), String> {
6451        if self.replication_slots.remove(name).is_none() {
6452            return Err(alloc::format!("replication slot \"{name}\" does not exist"));
6453        }
6454        Ok(())
6455    }
6456
6457    #[must_use]
6458    /// v7.38.18 (S1) — the collation this database was created with.
6459    /// `"C"` when nothing was recorded, which is what an older catalog
6460    /// and a default `initdb`-less start both mean.
6461    pub fn db_collation(&self) -> &str {
6462        self.db_collation.as_deref().unwrap_or("C")
6463    }
6464
6465    /// Record the creation collation. Refused once one is set, because
6466    /// every index key already in this database was built under it —
6467    /// the same refusal PostgreSQL gives `ALTER DATABASE … LC_COLLATE`,
6468    /// and for the same reason.
6469    ///
6470    /// `Ok(false)` when the value asked for is the one already in force,
6471    /// so a host that passes its environment on every start is not an
6472    /// error.
6473    pub fn set_db_collation(&mut self, name: &str) -> Result<bool, StorageError> {
6474        if self.db_collation.as_deref() == Some(name) {
6475            return Ok(false);
6476        }
6477        if self.db_collation.is_none() && name.eq_ignore_ascii_case("C") {
6478            return Ok(false);
6479        }
6480        if self.db_collation.is_some() || !self.tables.is_empty() {
6481            return Err(StorageError::Corrupt(format!(
6482                "database collation is already {:?} and cannot be changed; \
6483                 PostgreSQL refuses this too, because every index key here \
6484                 was built under it",
6485                self.db_collation()
6486            )));
6487        }
6488        self.db_collation = Some(name.into());
6489        Ok(true)
6490    }
6491
6492    /// The user said so, in SQL: `CREATE DATABASE … LC_COLLATE 'x'`.
6493    ///
6494    /// Differs from [`Self::set_db_collation`] in one way, and the
6495    /// difference is the whole point: this REPLACES a collation the
6496    /// database already has, as long as no table has been created yet.
6497    /// The refusal in `set_db_collation` exists because index keys were
6498    /// built under the old collation — with no tables, none were.
6499    ///
6500    /// The case it is for: a server stamps the container's `LANG` on a
6501    /// fresh database at startup, and the customer's bootstrap script
6502    /// then says `CREATE DATABASE app LC_COLLATE 'de_DE.utf8'`. What the
6503    /// script asked for beats what the container happened to export.
6504    ///
6505    /// `Ok(false)` when a table already exists — the caller warns rather
6506    /// than failing, because PostgreSQL would have made a SEPARATE
6507    /// database here and returned success, and failing a bootstrap
6508    /// script is a customer change.
6509    pub fn declare_db_collation(&mut self, name: &str) -> bool {
6510        if self.db_collation.as_deref() == Some(name) {
6511            return true;
6512        }
6513        if !self.tables.is_empty() {
6514            return false;
6515        }
6516        self.db_collation = Some(name.into());
6517        true
6518    }
6519
6520    /// Record a name a `CREATE DATABASE` asked for; `true` when new.
6521    pub fn record_created_database(&mut self, name: &str) -> bool {
6522        self.created_databases.insert(name.to_string())
6523    }
6524
6525    /// The names `CREATE DATABASE` has been asked for.
6526    pub const fn created_databases(&self) -> &alloc::collections::BTreeSet<String> {
6527        &self.created_databases
6528    }
6529
6530    pub const fn replication_slots(&self) -> &BTreeMap<String, (String, String)> {
6531        &self.replication_slots
6532    }
6533
6534    /// PG's RESET ALL: drops this scope's whole entry, leaving the
6535    /// other scopes alone — measured on PG18, where `ALTER ROLE r RESET
6536    /// ALL` left the ALL, the database and the role-in-database rows.
6537    pub fn reset_db_role_settings(&mut self, database: &str, role: &str) {
6538        self.db_role_settings
6539            .remove(&(database.to_string(), role.to_string()));
6540    }
6541
6542    #[must_use]
6543    pub const fn db_role_settings(&self) -> &BTreeMap<(String, String), BTreeMap<String, String>> {
6544        &self.db_role_settings
6545    }
6546
6547    /// v7.39 (read01 round 50) — every `(key, text)` pair, for the
6548    /// pg_description view.
6549    #[must_use]
6550    pub const fn comments(&self) -> &BTreeMap<String, String> {
6551        &self.comments
6552    }
6553
6554    /// v7.39 (read01 round 50) — drop every comment whose key names `obj`
6555    /// (the object itself and, for a table, its columns). Called when the
6556    /// object is dropped so a later object of the same name doesn't inherit
6557    /// a stale comment.
6558    pub fn drop_comments_for(&mut self, kind: &str, name: &str) {
6559        let exact = alloc::format!("{kind}:{name}");
6560        let col_prefix = alloc::format!("column:{name}.");
6561        self.comments
6562            .retain(|k, _| *k != exact && !k.starts_with(&col_prefix));
6563    }
6564
6565    pub fn add_enum_value(
6566        &mut self,
6567        type_name: &str,
6568        label: &str,
6569        if_not_exists: bool,
6570        position: Option<(bool, String)>,
6571    ) -> Result<bool, StorageError> {
6572        self.mark_nontable_dirty(NonTableKind::EnumType, type_name);
6573        let def = self
6574            .enum_types
6575            .get_mut(type_name)
6576            .ok_or_else(|| StorageError::Corrupt(format!("type {type_name:?} does not exist")))?;
6577        if def.labels.iter().any(|l| l == label) {
6578            if if_not_exists {
6579                return Ok(false);
6580            }
6581            // v7.39 (read01 round 49) — PG wording (42710 at the wire).
6582            return Err(StorageError::Corrupt(format!(
6583                "enum label {label:?} already exists"
6584            )));
6585        }
6586        match position {
6587            None => def.labels.push(label.to_string()),
6588            Some((is_before, anchor)) => {
6589                let at = def
6590                    .labels
6591                    .iter()
6592                    .position(|l| l == &anchor)
6593                    .ok_or_else(|| {
6594                        StorageError::Corrupt(format!(
6595                            "enum label {anchor:?} does not exist in type {type_name:?}"
6596                        ))
6597                    })?;
6598                let idx = if is_before { at } else { at + 1 };
6599                def.labels.insert(idx, label.to_string());
6600            }
6601        }
6602        Ok(true)
6603    }
6604
6605    pub fn drop_enum_type(&mut self, name: &str) -> bool {
6606        self.mark_nontable_dirty(NonTableKind::EnumType, name);
6607        self.enum_types.remove(name).is_some()
6608    }
6609
6610    /// v7.17.0 Phase 1.5 — read-only handle to DOMAIN catalog.
6611    pub const fn domain_types(&self) -> &BTreeMap<String, DomainDef> {
6612        &self.domain_types
6613    }
6614
6615    /// v7.17.0 Phase 1.5 — install a DOMAIN. Errors on collision
6616    /// with an existing domain.
6617    pub fn create_domain_type(&mut self, def: DomainDef) -> Result<(), StorageError> {
6618        if self.domain_types.contains_key(&def.name) {
6619            return Err(StorageError::Corrupt(format!(
6620                "domain {:?} already exists",
6621                def.name
6622            )));
6623        }
6624        self.mark_nontable_dirty(NonTableKind::DomainType, &def.name);
6625        self.domain_types.insert(def.name.clone(), def);
6626        Ok(())
6627    }
6628
6629    /// v7.17.0 Phase 1.5 — drop a DOMAIN by name.
6630    pub fn drop_domain_type(&mut self, name: &str) -> bool {
6631        self.mark_nontable_dirty(NonTableKind::DomainType, name);
6632        self.domain_types.remove(name).is_some()
6633    }
6634
6635    /// v7.37.42-T2 ζ-B — read-only handle to user-defined COMPOSITE
6636    /// catalog. Used by the engine to resolve
6637    /// `ColumnSchema.user_composite_type` lookups + by
6638    /// information_schema-style introspection.
6639    pub const fn composite_types(&self) -> &BTreeMap<String, CompositeDef> {
6640        &self.composite_types
6641    }
6642
6643    /// v7.37.42-T2 ζ-B — install a new COMPOSITE type. Errors if
6644    /// `name` already exists in the composite registry (PG forbids
6645    /// IF NOT EXISTS on CREATE TYPE composite; the engine surfaces
6646    /// the collision with the existing name).
6647    pub fn create_composite_type(&mut self, def: CompositeDef) -> Result<(), StorageError> {
6648        if self.composite_types.contains_key(&def.name) {
6649            return Err(StorageError::Corrupt(format!(
6650                "type {:?} already exists",
6651                def.name
6652            )));
6653        }
6654        self.mark_nontable_dirty(NonTableKind::CompositeType, &def.name);
6655        self.composite_types.insert(def.name.clone(), def);
6656        Ok(())
6657    }
6658
6659    /// v7.37.42-T2 ζ-B — drop a COMPOSITE type by name. Returns
6660    /// true if a type was removed.
6661    pub fn drop_composite_type(&mut self, name: &str) -> bool {
6662        self.mark_nontable_dirty(NonTableKind::CompositeType, name);
6663        self.composite_types.remove(name).is_some()
6664    }
6665
6666    /// v7.17.0 Phase 1.6 — read-only handle to the user-created
6667    /// schema registry. Built-in schemas (`public`, `pg_catalog`,
6668    /// `information_schema`) are NOT included here; use
6669    /// [`schema_exists`](Self::schema_exists) for the full
6670    /// check.
6671    pub const fn user_schemas(&self) -> &alloc::collections::BTreeSet<String> {
6672        &self.schemas
6673    }
6674
6675    /// v7.17.0 Phase 1.6 — schema-name resolver. Returns true
6676    /// for built-in schemas + every user-CREATEd one. Used by
6677    /// CREATE SCHEMA collision checks and (future) by
6678    /// information_schema.schemata.
6679    pub fn schema_exists(&self, name: &str) -> bool {
6680        is_builtin_schema(name) || self.schemas.contains(name)
6681    }
6682
6683    /// v7.17.0 Phase 1.6 — register a new schema. Errors if the
6684    /// name already exists and `if_not_exists=false`. Built-in
6685    /// names cannot be redeclared.
6686    pub fn create_schema(&mut self, name: String, if_not_exists: bool) -> Result<(), StorageError> {
6687        if is_builtin_schema(&name) {
6688            if if_not_exists {
6689                return Ok(());
6690            }
6691            return Err(StorageError::Corrupt(format!(
6692                "schema {name:?} is built-in and cannot be redeclared"
6693            )));
6694        }
6695        if self.schemas.contains(&name) {
6696            if if_not_exists {
6697                return Ok(());
6698            }
6699            return Err(StorageError::Corrupt(format!(
6700                "schema {name:?} already exists"
6701            )));
6702        }
6703        self.schemas.insert(name);
6704        Ok(())
6705    }
6706
6707    /// v7.17.0 Phase 1.6 — drop a user-created schema. Returns
6708    /// true if a schema was removed. Built-in names always
6709    /// return false (cannot be dropped). Tables that previously
6710    /// used the schema as a prefix keep their bare name and stay
6711    /// queryable — this is the "prefix routing, not isolation"
6712    /// posture documented in v7.17 Phase 1.6.
6713    pub fn drop_schema(&mut self, name: &str) -> Result<bool, StorageError> {
6714        if is_builtin_schema(name) {
6715            return Err(StorageError::Corrupt(format!(
6716                "schema {name:?} is built-in and cannot be dropped"
6717            )));
6718        }
6719        Ok(self.schemas.remove(name))
6720    }
6721
6722    /// v7.17.0 — ALTER SEQUENCE option merge. Caller-provided
6723    /// updates overwrite the matching fields; unset fields keep
6724    /// their stored values. RESTART variants update last_value
6725    /// directly per PG: `RESTART` resets to current `start`;
6726    /// `RESTART WITH n` resets to `n`.
6727    #[allow(clippy::too_many_arguments)]
6728    pub fn alter_sequence(
6729        &mut self,
6730        name: &str,
6731        increment: Option<i64>,
6732        min_value: Option<i64>,
6733        max_value: Option<i64>,
6734        start: Option<i64>,
6735        restart: Option<Option<i64>>,
6736        cache: Option<i64>,
6737        cycle: Option<bool>,
6738        owned_by: Option<Option<(String, String)>>,
6739    ) -> Result<(), StorageError> {
6740        self.mark_nontable_dirty(NonTableKind::Sequence, name);
6741        let Some(seq) = self.sequences.get_mut(name) else {
6742            return Err(StorageError::TableNotFound { name: name.into() });
6743        };
6744        if let Some(v) = increment {
6745            seq.increment = v;
6746        }
6747        if let Some(v) = min_value {
6748            seq.min_value = v;
6749        }
6750        if let Some(v) = max_value {
6751            seq.max_value = v;
6752        }
6753        if let Some(v) = start {
6754            seq.start = v;
6755        }
6756        if let Some(restart_value) = restart {
6757            seq.last_value = restart_value.unwrap_or(seq.start);
6758            seq.is_called = false;
6759        }
6760        if let Some(v) = cache {
6761            seq.cache = v;
6762        }
6763        if let Some(v) = cycle {
6764            seq.cycle = v;
6765        }
6766        if let Some(v) = owned_by {
6767            seq.owned_by = v;
6768        }
6769        Ok(())
6770    }
6771
6772    /// v7.12.4 — read-only slice of all catalogued triggers.
6773    /// Engine row-write paths filter this by (table, event,
6774    /// timing) and fire matches in slice order.
6775    pub fn triggers(&self) -> &[TriggerDef] {
6776        &self.triggers
6777    }
6778
6779    /// v7.15.0 — mutable handle to the trigger slice for
6780    /// `ALTER TABLE … RENAME COLUMN`, which rewrites every
6781    /// `update_columns` entry that referenced the renamed
6782    /// column.
6783    pub fn triggers_mut(&mut self) -> &mut Vec<TriggerDef> {
6784        &mut self.triggers
6785    }
6786
6787    /// v7.12.4 — register a new trigger. With `or_replace = false`,
6788    /// errors when a trigger with the same name already exists on
6789    /// the same table (PG scoping rule — trigger names are
6790    /// per-table, not global). Trigger function must already
6791    /// exist in the catalog at registration time.
6792    pub fn create_trigger(
6793        &mut self,
6794        def: TriggerDef,
6795        or_replace: bool,
6796    ) -> Result<(), StorageError> {
6797        // v7.39 (round 137) — a trigger may target a base table (BEFORE / AFTER)
6798        // or a view (INSTEAD OF). The engine enforces the timing↔target rule;
6799        // storage only requires the relation to exist as one or the other.
6800        if !self.by_name.contains_key(&def.table) && !self.views.contains_key(&def.table) {
6801            return Err(StorageError::TableNotFound {
6802                name: def.table.clone(),
6803            });
6804        }
6805        // v7.39 (read01 round 62) — functions are keyed by SIGNATURE now. A
6806        // trigger names its function by NAME (a trigger function takes no
6807        // arguments), so the existence check goes through the name index.
6808        if self.functions_named(&def.function).is_empty() {
6809            // v7.39 (round 710) — PG's wording: the FUNCTION is what does
6810            // not exist (`function nosuch_fn() does not exist`), and the
6811            // old message rode `Corrupt`'s on-disk banner besides.
6812            return Err(StorageError::Corrupt(format!(
6813                "function {}() does not exist",
6814                def.function
6815            )));
6816        }
6817        let dup = self
6818            .triggers
6819            .iter()
6820            .position(|t| t.name == def.name && t.table == def.table);
6821        match (dup, or_replace) {
6822            (Some(_), false) => Err(StorageError::Corrupt(format!(
6823                "trigger {:?} already exists on table {:?}",
6824                def.name, def.table
6825            ))),
6826            (Some(i), true) => {
6827                self.triggers[i] = def;
6828                Ok(())
6829            }
6830            (None, _) => {
6831                self.triggers.push(def);
6832                Ok(())
6833            }
6834        }
6835    }
6836
6837    /// v7.12.4 — remove a trigger by `(name, table)`. Returns
6838    /// `true` if one was removed.
6839    pub fn drop_trigger(&mut self, name: &str, table: &str) -> bool {
6840        let before = self.triggers.len();
6841        self.triggers
6842            .retain(|t| !(t.name == name && t.table == table));
6843        before != self.triggers.len()
6844    }
6845
6846    /// v7.39 (round 139) — the catalogued query-rewrite RULEs.
6847    pub fn rules(&self) -> &[RuleDef] {
6848        &self.rules
6849    }
6850
6851    /// v7.39 (round 280) — the catalogued extended-statistics objects.
6852    #[must_use]
6853    pub fn statistics_ext(&self) -> &[StatisticsExtDef] {
6854        &self.statistics_ext
6855    }
6856
6857    /// v7.39 (round 287) — every large object, ascending by OID.
6858    #[must_use]
6859    pub fn large_objects(&self) -> &alloc::collections::BTreeMap<u32, Vec<u8>> {
6860        &self.large_objects
6861    }
6862
6863    /// The bytes of one large object, or `None` when no such OID exists.
6864    #[must_use]
6865    pub fn large_object(&self, oid: u32) -> Option<&[u8]> {
6866        self.large_objects.get(&oid).map(Vec::as_slice)
6867    }
6868
6869    /// Create a large object. `oid` of 0 means "pick one" — PG's
6870    /// `lo_create(0)` / `lo_creat(-1)` spelling. Errors when the
6871    /// requested OID is taken.
6872    pub fn create_large_object(&mut self, oid: u32, bytes: Vec<u8>) -> Result<u32, String> {
6873        let id = if oid == 0 {
6874            self.next_large_object_oid()
6875        } else {
6876            oid
6877        };
6878        if self.large_objects.contains_key(&id) {
6879            return Err(format!("large object {id} already exists"));
6880        }
6881        self.large_objects.insert(id, bytes);
6882        Ok(id)
6883    }
6884
6885    /// Overwrite `len` bytes at `offset` (0-based), growing the object
6886    /// with zero bytes if the write starts past the end — PG's
6887    /// `lo_put` semantics.
6888    pub fn put_large_object(&mut self, oid: u32, offset: usize, data: &[u8]) -> Result<(), String> {
6889        let Some(buf) = self.large_objects.get_mut(&oid) else {
6890            return Err(format!("large object {oid} does not exist"));
6891        };
6892        let end = offset.saturating_add(data.len());
6893        if buf.len() < end {
6894            buf.resize(end, 0);
6895        }
6896        buf[offset..end].copy_from_slice(data);
6897        Ok(())
6898    }
6899
6900    /// v7.39 (round 306) — `lo_truncate`. PG's truncate sets the object
6901    /// to exactly `len` bytes in BOTH directions: it shortens, and it
6902    /// GROWS with zero fill when `len` exceeds the current size
6903    /// (measured — `lo_truncate(fd, 8)` over a 4-byte object leaves
6904    /// eight bytes, the last four zero).
6905    pub fn truncate_large_object(&mut self, oid: u32, len: usize) -> Result<(), String> {
6906        let Some(buf) = self.large_objects.get_mut(&oid) else {
6907            return Err(format!("large object {oid} does not exist"));
6908        };
6909        buf.resize(len, 0);
6910        Ok(())
6911    }
6912
6913    /// Remove a large object. `false` when the OID was not there.
6914    pub fn unlink_large_object(&mut self, oid: u32) -> bool {
6915        self.large_objects.remove(&oid).is_some()
6916    }
6917
6918    /// The next free OID in PG's user band.
6919    /// v7.39 (round 343, V40) — large objects have their own oid band.
6920    /// It used to start at 16_384, which is where user TABLES start, so
6921    /// the first large object and the first table shared an oid — and
6922    /// `pg_largeobject_metadata.oid` is joinable against `pg_class.oid`,
6923    /// so a join across them matched a row that has nothing to do with
6924    /// it. (PG cannot collide: every oid there comes off one counter.)
6925    /// An object already stored keeps the oid it was given; only new
6926    /// ones land in the band.
6927    fn next_large_object_oid(&self) -> u32 {
6928        self.large_objects
6929            .keys()
6930            .next_back()
6931            .map_or(500_000, |m| m.saturating_add(1))
6932    }
6933
6934    /// Register one. `Err(name)` when the name is taken.
6935    pub fn create_statistics_ext(&mut self, def: StatisticsExtDef) -> Result<(), String> {
6936        if self.statistics_ext.iter().any(|s| s.name == def.name) {
6937            return Err(def.name);
6938        }
6939        self.statistics_ext.push(def);
6940        Ok(())
6941    }
6942
6943    /// Drop one by name; false when absent.
6944    pub fn drop_statistics_ext(&mut self, name: &str) -> bool {
6945        let before = self.statistics_ext.len();
6946        self.statistics_ext.retain(|s| s.name != name);
6947        before != self.statistics_ext.len()
6948    }
6949
6950    /// v7.39 (round 139) — register a RULE. Its target relation (table or view)
6951    /// must exist; `or_replace` overwrites a same-(name,table) rule.
6952    pub fn create_rule(&mut self, def: RuleDef, or_replace: bool) -> Result<(), StorageError> {
6953        if !self.by_name.contains_key(&def.table) && !self.views.contains_key(&def.table) {
6954            return Err(StorageError::TableNotFound {
6955                name: def.table.clone(),
6956            });
6957        }
6958        let dup = self
6959            .rules
6960            .iter()
6961            .position(|r| r.name == def.name && r.table == def.table);
6962        match (dup, or_replace) {
6963            (Some(_), false) => Err(StorageError::Corrupt(format!(
6964                "rule {:?} for relation {:?} already exists",
6965                def.name, def.table
6966            ))),
6967            (Some(i), true) => {
6968                self.rules[i] = def;
6969                Ok(())
6970            }
6971            (None, _) => {
6972                self.rules.push(def);
6973                Ok(())
6974            }
6975        }
6976    }
6977
6978    /// v7.39 (round 139) — drop a RULE by `(name, table)`.
6979    pub fn drop_rule(&mut self, name: &str, table: &str) -> bool {
6980        let before = self.rules.len();
6981        self.rules.retain(|r| !(r.name == name && r.table == table));
6982        before != self.rules.len()
6983    }
6984
6985    pub fn create_table(&mut self, schema: TableSchema) -> Result<(), StorageError> {
6986        if self.by_name.contains_key(&schema.name) {
6987            return Err(StorageError::DuplicateTable {
6988                name: schema.name.clone(),
6989            });
6990        }
6991        let idx = self.tables.len();
6992        let name = schema.name.clone();
6993        let mut t = Table::new(schema);
6994        // v7.38.18 (S2) — the table inherits the database's collation,
6995        // which is what its undeclared text columns compare under.
6996        t.set_db_collation(self.db_collation());
6997        self.tables.push(t);
6998        self.by_name.insert(name.clone(), idx);
6999        // v7.39 (round 496) — see `dirty_tables`.
7000        self.dirty_tables.insert(name);
7001        // v7.37.15 (Phase C.1) — stamp the new relation with a stable,
7002        // monotonic, never-reused RelId. Pre-increment so ids start at
7003        // 1 (0 = UNASSIGNED); a later DROP TABLE frees the slot but not
7004        // the id.
7005        self.next_rel_id += 1;
7006        let rid = row_header::RelId(self.next_rel_id);
7007        self.tables[idx].set_rel_id(rid);
7008        Ok(())
7009    }
7010
7011    /// v7.39 (round 436) — the session's temporary table of this name wins
7012    /// over a permanent one, as `pg_temp` does in PG's search path and as
7013    /// MySQL's TEMPORARY shadowing does. Every name → index resolution in
7014    /// this catalog goes through here.
7015    fn resolve_index(&self, name: &str) -> Option<usize> {
7016        if let Some(prefix) = &self.temp_prefix {
7017            let mut mangled = String::with_capacity(prefix.len() + name.len());
7018            mangled.push_str(prefix);
7019            mangled.push_str(name);
7020            if let Some(idx) = self.by_name.get(&mangled) {
7021                return Some(*idx);
7022            }
7023            if self.case_insensitive_names
7024                && let Some(idx) = self.index_ignoring_case(&mangled)
7025            {
7026                return Some(idx);
7027            }
7028        }
7029        if let Some(idx) = self.by_name.get(name) {
7030            return Some(*idx);
7031        }
7032        // v7.39.2 — a MySQL session finds the relation under any
7033        // spelling of its name.
7034        //
7035        // The lexer folds an unquoted identifier and leaves a backticked
7036        // one alone, so `CREATE TABLE MyTable` stored `mytable` while
7037        // ``SELECT 1 FROM `MyTable` `` looked for `MyTable` and found
7038        // nothing: the two spellings of one name were two tables.
7039        // `mysqldump` backticks every identifier, so a dump restored
7040        // here and an application that writes the name unquoted were
7041        // looking at different relations.
7042        //
7043        // This is MySQL's `lower_case_table_names = 1` — names compare
7044        // without case — which is what SPG has always half-done, and
7045        // what it now reports. Exact match first, so a catalog that
7046        // already holds two names differing only in case keeps
7047        // answering the way it did.
7048        //
7049        // PostgreSQL sessions never set this: `"MyTable"` and `mytable`
7050        // are two relations there, and the flag is off.
7051        if self.case_insensitive_names {
7052            return self.index_ignoring_case(name);
7053        }
7054        None
7055    }
7056
7057    /// The single relation whose name matches `name` without regard to
7058    /// case, or `None` when there is none — or more than one, which the
7059    /// exact lookup above has already failed to settle.
7060    fn index_ignoring_case(&self, name: &str) -> Option<usize> {
7061        let mut found = None;
7062        for (k, idx) in &self.by_name {
7063            if k.len() == name.len() && k.eq_ignore_ascii_case(name) {
7064                if found.is_some() {
7065                    return None;
7066                }
7067                found = Some(*idx);
7068            }
7069        }
7070        found
7071    }
7072
7073    /// v7.39.2 — does this session compare relation names without case?
7074    ///
7075    /// Per SESSION, and the catalog is shared, so the engine installs it
7076    /// the way it installs `temp_prefix`: on every session switch, into
7077    /// the main catalog and into every open transaction's shadow.
7078    pub fn set_case_insensitive_names(&mut self, on: bool) {
7079        self.case_insensitive_names = on;
7080    }
7081
7082    /// v7.39 (round 436) — install the calling session's temp namespace.
7083    /// `None` disables temp resolution entirely (a session that never made
7084    /// one pays a single `Option` check per lookup).
7085    pub fn set_temp_prefix(&mut self, prefix: Option<String>) {
7086        self.temp_prefix = prefix;
7087    }
7088
7089    /// The mangled storage name a temp table of `name` takes in this
7090    /// session, or `None` when the session has no temp namespace.
7091    #[must_use]
7092    pub fn temp_name_for(&self, name: &str) -> Option<String> {
7093        self.temp_prefix
7094            .as_ref()
7095            .map(|p| alloc::format!("{p}{name}"))
7096    }
7097
7098    pub fn get(&self, name: &str) -> Option<&Table> {
7099        let idx = self.resolve_index(name)?;
7100        self.tables.get(idx)
7101    }
7102
7103    pub fn get_mut(&mut self, name: &str) -> Option<&mut Table> {
7104        let idx = self.resolve_index(name)?;
7105        // v7.39 (round 496) — the choke point for changing a table, so the
7106        // record is taken here. Over-approximate on purpose: a caller that
7107        // takes the handle and writes nothing merely carries that table
7108        // through a commit, which is the old behaviour.
7109        let recorded = self.tables.get(idx).map(|t| t.schema().name.clone());
7110        if let Some(n) = recorded {
7111            self.dirty_tables.insert(n);
7112        }
7113        self.tables.get_mut(idx)
7114    }
7115
7116    /// v7.39 (round 496) — the tables changed through this handle since
7117    /// [`Self::clear_dirty_tables`]. See `dirty_tables`.
7118    #[must_use]
7119    pub fn dirty_tables(&self) -> &alloc::collections::BTreeSet<String> {
7120        &self.dirty_tables
7121    }
7122
7123    /// r1059 — mark one table dirty without taking its handle. The
7124    /// rebase/merge paths replace a tx's shadow with a fresh base
7125    /// clone and must carry the tx's OWN dirty window across (the
7126    /// base's set is an ever-growing history, never cleared).
7127    pub fn mark_table_dirty(&mut self, name: &str) {
7128        self.dirty_tables.insert(name.into());
7129    }
7130
7131    /// v7.39 (round 496) — start a fresh recording window. A transaction's
7132    /// shadow calls this at BEGIN so the set means "changed by this tx".
7133    /// 7.38.1 S3.1 — one window covers both records (tables and the
7134    /// non-table families).
7135    pub fn clear_dirty_tables(&mut self) {
7136        self.dirty_tables.clear();
7137        self.dirty_nontable.clear();
7138    }
7139
7140    /// 7.38.1 S3.1 (D4) — record a non-table object as changed by this
7141    /// window. Called from every create/alter/rename/drop of the six
7142    /// [`NonTableKind`] families; a rename records BOTH names.
7143    fn mark_nontable_dirty(&mut self, kind: NonTableKind, name: &str) {
7144        self.dirty_nontable.insert((kind, name.into()));
7145    }
7146
7147    /// 7.38.1 S3.1 (D4) — reconcile the six non-table families with
7148    /// `base` (the latest committed catalog): every entry this window
7149    /// did NOT touch is taken from base — existence, definition and
7150    /// absence alike — so a neighbour's CREATE / ALTER / DROP of a
7151    /// sequence, view, matview, enum, domain or composite type
7152    /// survives a poisoned transaction's COMMIT. Entries this window
7153    /// DID touch keep the shadow's version (the tx's own DDL wins its
7154    /// own objects, exactly like the dirty-table merge above it).
7155    pub fn merge_nontable_objects_from(&mut self, base: &Catalog) {
7156        use NonTableKind as K;
7157        fn merge_map<V: Clone>(
7158            kind: NonTableKind,
7159            dirty: &alloc::collections::BTreeSet<(NonTableKind, String)>,
7160            mine: &mut BTreeMap<String, V>,
7161            theirs: &BTreeMap<String, V>,
7162        ) {
7163            let names: alloc::vec::Vec<String> =
7164                mine.keys().chain(theirs.keys()).cloned().collect();
7165            for n in names {
7166                if dirty.contains(&(kind, n.clone())) {
7167                    continue;
7168                }
7169                match theirs.get(&n) {
7170                    Some(v) => {
7171                        mine.insert(n, v.clone());
7172                    }
7173                    None => {
7174                        mine.remove(&n);
7175                    }
7176                }
7177            }
7178        }
7179        let dirty = self.dirty_nontable.clone();
7180        merge_map(K::Sequence, &dirty, &mut self.sequences, &base.sequences);
7181        merge_map(K::View, &dirty, &mut self.views, &base.views);
7182        merge_map(
7183            K::MaterializedView,
7184            &dirty,
7185            &mut self.materialized_views,
7186            &base.materialized_views,
7187        );
7188        merge_map(K::EnumType, &dirty, &mut self.enum_types, &base.enum_types);
7189        merge_map(
7190            K::DomainType,
7191            &dirty,
7192            &mut self.domain_types,
7193            &base.domain_types,
7194        );
7195        merge_map(
7196            K::CompositeType,
7197            &dirty,
7198            &mut self.composite_types,
7199            &base.composite_types,
7200        );
7201    }
7202
7203    /// v7.39 (round 496) — put `table` in at `name`, replacing any table
7204    /// already there and keeping the rest of the catalog untouched.
7205    ///
7206    /// The commit-time table-granularity merge needs exactly this: take
7207    /// the latest committed catalog, then overwrite only the tables the
7208    /// transaction changed.
7209    pub fn install_table(&mut self, name: &str, table: Table) {
7210        match self.by_name.get(name).copied() {
7211            Some(idx) => self.tables[idx] = table,
7212            None => {
7213                let idx = self.tables.len();
7214                self.tables.push(table);
7215                self.by_name.insert(name.into(), idx);
7216            }
7217        }
7218        self.dirty_tables.insert(name.into());
7219    }
7220
7221    /// v7.37.42 (docker-fair SCALARSQ attack) — resolve a table name to
7222    /// its insertion-order index ONCE, so callers that need to fetch the
7223    /// same table many times (per-row PK probes in correlated scalar
7224    /// subqueries) can avoid the per-call `BTreeMap<String, usize>` string
7225    /// descent. The returned index is stable for the lifetime of the
7226    /// catalog snapshot the caller holds (same engine read guard).
7227    pub fn tables_position_of(&self, name: &str) -> Option<usize> {
7228        self.resolve_index(name)
7229    }
7230
7231    /// Direct positional fetch counterpart to [`tables_position_of`].
7232    /// `idx` must come from `tables_position_of` against the same catalog
7233    /// snapshot — out-of-range returns `None`.
7234    pub fn tables_at(&self, idx: usize) -> Option<&Table> {
7235        self.tables.get(idx)
7236    }
7237
7238    /// v7.34 (crash-recovery P0 #2) — replay a row-level redo log onto
7239    /// this catalog (the [`RowChange`] physical-redo apply primitive that
7240    /// row-level WAL recovery will use in place of statement re-execution).
7241    /// Applies each change in order via the same `Table` mutators the
7242    /// engine used — no uniqueness/FK/parse/plan: the original execution
7243    /// already validated, replay trusts and applies. Positions are
7244    /// physical and only valid when replayed from the matching checkpoint
7245    /// baseline in original order (see [`RowChange`] docs).
7246    ///
7247    /// A change naming an absent table, or whose position is out of range,
7248    /// is a corrupt/misaligned log and surfaces as an error rather than a
7249    /// silent skip.
7250    pub fn apply_redo(&mut self, changes: &[RowChange]) -> Result<(), StorageError> {
7251        // v7.37.5 (mailrs crash-recovery Ask 3) — true batched replay.
7252        // Pre-v7.37.5 each `RowChange::Delete` record ran a fresh
7253        // O(N) PersistentVec rebuild + O(N × indices × log N)
7254        // `rebuild_indices()` — 5000 records × 100k rows × 13 indices
7255        // ≈ 27 min on the mailrs prod-shape WAL.
7256        //
7257        // The strategy: group consecutive changes by table, and for
7258        // each run, compose all the row-level mutations through a
7259        // single "live" tracking vector + a per-table operation log,
7260        // then apply rows + indices ONCE at the end. The result:
7261        //  - DELETE blow-up: O(records × rows × indices × log rows)
7262        //    → O(rows × indices × log rows) — one rebuild per run.
7263        //  - Row-position semantics preserved: positions in a later
7264        //    `Delete` / `Update` record reference the layout produced
7265        //    by every earlier change; we walk the live-vector
7266        //    forward as each change is processed so positions
7267        //    translate correctly to the ORIGINAL row index space.
7268        //
7269        // For correctness, even with this batching `apply_redo`
7270        // remains in-order: a single per-table run only batches
7271        // a contiguous slice of changes targeting that table; a
7272        // mid-run change targeting a DIFFERENT table forces a
7273        // flush of the current run.
7274        let mut runs: alloc::vec::Vec<(String, alloc::vec::Vec<&RowChange>)> =
7275            alloc::vec::Vec::new();
7276        for change in changes {
7277            // v7.39 (flip crash-replay P0) — a replayed tombstone carries
7278            // the xmax the CRASHED process allocated, but this process's
7279            // version cursor restarted; without advancing it past every
7280            // replayed version, `Snapshot::visible`'s "deletion is in the
7281            // future" branch (xmax > snapshot.version) resurrects every
7282            // replayed delete. Same recovery contract as the snapshot
7283            // loader (`observe_persisted_version`, the pg_control-style
7284            // nextXid recovery).
7285            if let RowChange::Tombstone { xmax, .. } = change {
7286                row_header::observe_persisted_version(*xmax);
7287            }
7288            let table = match change {
7289                RowChange::Insert { table, .. }
7290                | RowChange::Update { table, .. }
7291                | RowChange::Delete { table, .. }
7292                | RowChange::Tombstone { table, .. } => table.clone(),
7293            };
7294            if runs.last().map(|(t, _)| t.as_str()) != Some(table.as_str()) {
7295                runs.push((table, alloc::vec::Vec::new()));
7296            }
7297            runs.last_mut().unwrap().1.push(change);
7298        }
7299        for (table_name, run) in runs {
7300            self.apply_redo_run_on_table(&table_name, &run)?;
7301        }
7302        Ok(())
7303    }
7304
7305    /// v7.37.5 — apply a contiguous slice of `RowChange`s all
7306    /// targeting the same `table_name`. Composes row mutations
7307    /// through a single live-tracking vector + a single tail
7308    /// for appended `Insert`s + a single in-place edit set for
7309    /// `Update`s, then writes the final row layout to
7310    /// `self.rows` and rebuilds indices ONCE.
7311    fn apply_redo_run_on_table(
7312        &mut self,
7313        table_name: &str,
7314        run: &[&RowChange],
7315    ) -> Result<(), StorageError> {
7316        // Look up the table once; the unchecked unwrap is safe
7317        // because the caller just resolved `table_name` for each
7318        // change.
7319        let table = self.get_mut(table_name).ok_or_else(|| {
7320            StorageError::Corrupt(alloc::format!("redo: unknown table {table_name:?}"))
7321        })?;
7322        // Live-tracking over both pre-existing rows and tail-
7323        // appended Insert rows. `live[i] = true` initially for
7324        // every existing row. Appended Inserts extend with `true`.
7325        // A `Delete` flips entries to `false` (using the position
7326        // mapping that walks live indices in order). An `Update`
7327        // edits in place — collected into an overlay map keyed by
7328        // ORIGINAL row position so later Updates win.
7329        let original_rows: alloc::vec::Vec<Row<'static>> = table.rows().iter().cloned().collect();
7330        let mut live: alloc::vec::Vec<bool> = alloc::vec![true; original_rows.len()];
7331        let mut tail: alloc::vec::Vec<Row<'static>> = alloc::vec::Vec::new();
7332        // Overlay: index into ORIGINAL row space (existing rows
7333        // 0..original_rows.len()) or into tail (offset
7334        // original_rows.len()). Map -> new values.
7335        let mut overlay: alloc::collections::BTreeMap<usize, alloc::vec::Vec<Value<'static>>> =
7336            alloc::collections::BTreeMap::new();
7337        // v7.37.15 (Epic W durable-tombstone slice) — extra bookkeeping
7338        // ONLY when this run actually carries an in-place `Tombstone`.
7339        // A tombstone keeps its row physically present but stamps `xmax`
7340        // on the header; the run finalizer `set_rows_and_rebuild_indices`
7341        // freezes every header (and reassigns ids), so we must re-stamp
7342        // in a post-pass keyed by RowId. When the run has no tombstone
7343        // (every default gate-off replay) this is all skipped and the
7344        // path below stays byte-for-byte the legacy one.
7345        let has_tomb = run.iter().any(|c| matches!(c, RowChange::Tombstone { .. }));
7346        // Ids of the pre-existing rows, snapshotted parallel to
7347        // `original_rows`, and ids of the tail rows filled from each
7348        // `Insert`'s carried `rowid`. Together they let a tombstone name
7349        // the exact row the writer stamped, independent of the ids the
7350        // finalizer will hand out. (When `!has_tomb`, both stay empty.)
7351        // v7.39 (flip crash-replay P0) — ids are tracked UNCONDITIONALLY
7352        // now: the finalizer preserves them so a later WAL record's
7353        // tombstone can still name rows this record produced.
7354        let orig_rowids: alloc::vec::Vec<row_header::RowId> =
7355            table.rowids().iter().copied().collect();
7356        // Headers snapshotted in lock-step: the finalizer preserves
7357        // them so earlier records' tombstone stamps survive.
7358        let orig_headers: alloc::vec::Vec<row_header::RowHeader> =
7359            table.headers().iter().copied().collect();
7360        let mut tail_rowids: alloc::vec::Vec<row_header::RowId> = alloc::vec::Vec::new();
7361        // (RowId, xmax) of every row this run tombstones.
7362        let mut tomb_targets: alloc::vec::Vec<(row_header::RowId, u64)> = alloc::vec::Vec::new();
7363        // Helper: given a "current" position (i.e. position in
7364        // the post-prior-deletes layout), translate to the
7365        // ABSOLUTE position in the unified live + tail space
7366        // by walking the live vector + tail. Returns None when
7367        // the position is out of range.
7368        fn translate(live: &[bool], tail_len: usize, current_pos: usize) -> Option<usize> {
7369            // Walk live[..] counting live entries until we hit
7370            // current_pos. Then if not yet matched, dip into tail.
7371            let mut seen = 0usize;
7372            for (i, &alive) in live.iter().enumerate() {
7373                if alive {
7374                    if seen == current_pos {
7375                        return Some(i);
7376                    }
7377                    seen += 1;
7378                }
7379            }
7380            // Position lives in tail. tail_len rows in the tail
7381            // are all live (we haven't deleted any tail rows in
7382            // this simplification; if we did, we'd extend `live`).
7383            let off = current_pos - seen;
7384            if off < tail_len {
7385                Some(live.len() + off)
7386            } else {
7387                None
7388            }
7389        }
7390        for change in run {
7391            match *change {
7392                RowChange::Insert { row, rowid, .. } => {
7393                    // Validate against schema before recording the
7394                    // change so a corrupt log surfaces as an error
7395                    // rather than silently mis-applying.
7396                    if row.len() != table.schema().columns.len() {
7397                        return Err(StorageError::ArityMismatch {
7398                            expected: table.schema().columns.len(),
7399                            actual: row.len(),
7400                        });
7401                    }
7402                    tail.push(row.clone());
7403                    // Keep the id lock-step with `tail` so a later
7404                    // tombstone (this run or a later WAL record) can
7405                    // find the row by the id the writer captured.
7406                    tail_rowids.push(*rowid);
7407                }
7408                RowChange::Update { pos, new_row, .. } => {
7409                    if new_row.len() != table.schema().columns.len() {
7410                        return Err(StorageError::ArityMismatch {
7411                            expected: table.schema().columns.len(),
7412                            actual: new_row.len(),
7413                        });
7414                    }
7415                    let abs = translate(&live, tail.len(), *pos).ok_or_else(|| {
7416                        StorageError::Corrupt(alloc::format!(
7417                            "redo: update_row position {pos} out of bounds in table {table_name:?}",
7418                        ))
7419                    })?;
7420                    // Tail edits are applied directly to `tail`
7421                    // (we own it); existing-row edits land in
7422                    // the overlay map keyed by original index.
7423                    if abs < live.len() {
7424                        overlay.insert(abs, new_row.clone());
7425                    } else {
7426                        tail[abs - live.len()] = Row::new(new_row.clone());
7427                    }
7428                }
7429                RowChange::Delete { positions, .. } => {
7430                    // De-dup + sort so the translate walk stays
7431                    // monotone (the second translate doesn't have
7432                    // to redo work the first one did, in principle;
7433                    // we keep it simple here and re-walk per
7434                    // position). Bounds-filter silently mirrors
7435                    // `Table::delete_rows`.
7436                    let mut sorted: alloc::vec::Vec<usize> = positions.clone();
7437                    sorted.sort_unstable();
7438                    sorted.dedup();
7439                    // Walk live[] once per Delete record to
7440                    // translate all positions in this record's
7441                    // post-prior-deletes layout to absolute
7442                    // indices. We MUST defer the live[] flip
7443                    // until after all positions are translated
7444                    // so two positions in the same record
7445                    // (e.g. [3, 7]) reference the same layout.
7446                    let mut to_flip_live: alloc::vec::Vec<usize> = alloc::vec::Vec::new();
7447                    let mut to_flip_tail: alloc::vec::Vec<usize> = alloc::vec::Vec::new();
7448                    // Two-pointer walk: live[i] scanned monotonically,
7449                    // sorted positions consumed in order.
7450                    let mut seen = 0usize;
7451                    let mut sp = sorted.iter().peekable();
7452                    for (i, &alive) in live.iter().enumerate() {
7453                        if !alive {
7454                            continue;
7455                        }
7456                        while let Some(&&p) = sp.peek() {
7457                            if seen == p {
7458                                to_flip_live.push(i);
7459                                sp.next();
7460                            } else {
7461                                break;
7462                            }
7463                        }
7464                        if sp.peek().is_none() {
7465                            break;
7466                        }
7467                        seen += 1;
7468                    }
7469                    // Remaining positions fall into the tail.
7470                    for &p in sp {
7471                        // p >= seen and refers to the (p - seen)-th
7472                        // entry in tail. Filter out-of-bounds.
7473                        let off = p - seen;
7474                        if off < tail.len() {
7475                            to_flip_tail.push(off);
7476                        }
7477                    }
7478                    for i in to_flip_live {
7479                        live[i] = false;
7480                        // Any pending overlay edit for this
7481                        // index is moot — the row is gone.
7482                        overlay.remove(&i);
7483                    }
7484                    // Tail deletes: remove in REVERSE order so
7485                    // shifting indices stay valid.
7486                    to_flip_tail.sort_unstable();
7487                    to_flip_tail.dedup();
7488                    for off in to_flip_tail.into_iter().rev() {
7489                        tail.remove(off);
7490                        {
7491                            // Keep the id vector lock-step with `tail`.
7492                            tail_rowids.remove(off);
7493                        }
7494                        // Re-key tail-relative overlay entries that
7495                        // were past `off` — in practice tail edits
7496                        // are applied directly so the overlay map
7497                        // only holds existing-row keys; nothing to
7498                        // do here.
7499                    }
7500                }
7501                RowChange::Tombstone { rowids, xmax, .. } => {
7502                    // An in-place tombstone leaves the row physically
7503                    // present — it does not touch `live` / `tail` /
7504                    // `overlay`. Record the (id, xmax) targets; the
7505                    // post-finalizer pass re-stamps `xmax` onto the
7506                    // matching row's (otherwise-frozen) header.
7507                    for rid in rowids {
7508                        tomb_targets.push((*rid, *xmax));
7509                    }
7510                }
7511            }
7512        }
7513        // Compose the final row layout: keep existing rows where
7514        // live[i] = true, applying overlay edits in place; then
7515        // append the surviving tail.
7516        let mut new_rows: PersistentVec<Row> = PersistentVec::new();
7517        let mut new_hot_bytes: u64 = 0;
7518        let schema_snapshot = table.schema().clone();
7519        // Parallel to `new_rows` (only built when `has_tomb`): the RowId
7520        // of each row in its FINAL slot, so the post-pass can map a
7521        // tombstone target id → the slot to re-stamp `xmax` on.
7522        let mut final_rowids: alloc::vec::Vec<row_header::RowId> = alloc::vec::Vec::new();
7523        let mut final_headers: alloc::vec::Vec<row_header::RowHeader> = alloc::vec::Vec::new();
7524        for (i, row) in original_rows.into_iter().enumerate() {
7525            if !live[i] {
7526                continue;
7527            }
7528            let final_row = if let Some(new_values) = overlay.remove(&i) {
7529                Row::new(new_values)
7530            } else {
7531                row
7532            };
7533            new_hot_bytes = new_hot_bytes
7534                .saturating_add(row_body_encoded_len(&final_row, &schema_snapshot) as u64);
7535            new_rows.push_mut(final_row);
7536            final_rowids.push(
7537                orig_rowids
7538                    .get(i)
7539                    .copied()
7540                    .unwrap_or(row_header::RowId::UNASSIGNED),
7541            );
7542            final_headers.push(
7543                orig_headers
7544                    .get(i)
7545                    .copied()
7546                    .unwrap_or_else(row_header::RowHeader::frozen),
7547            );
7548        }
7549        for (off, row) in tail.into_iter().enumerate() {
7550            new_hot_bytes =
7551                new_hot_bytes.saturating_add(row_body_encoded_len(&row, &schema_snapshot) as u64);
7552            new_rows.push_mut(row);
7553            final_rowids.push(
7554                tail_rowids
7555                    .get(off)
7556                    .copied()
7557                    .unwrap_or(row_header::RowId::UNASSIGNED),
7558            );
7559            final_headers.push(row_header::RowHeader::frozen());
7560        }
7561        // v7.39 (flip crash-replay P0) — id-preserving finalizer, so a
7562        // LATER WAL record's tombstone still resolves rows this record
7563        // produced (per-statement replay used to reassign ids between
7564        // records, orphaning every cross-record tombstone target).
7565        table.set_rows_and_rebuild_indices_with_rowids(
7566            new_rows,
7567            new_hot_bytes,
7568            &final_rowids,
7569            &final_headers,
7570        );
7571        // v7.37.15 (Epic W durable-tombstone slice) — header-preserving
7572        // re-stamp. `set_rows_and_rebuild_indices` above froze every
7573        // header, so any row this run tombstoned is currently all-
7574        // visible again. Re-apply the `xmax` stamp by matching the
7575        // tombstone's target RowId against the final-slot id map. This
7576        // is what makes a gate-on DELETE durable across replay without
7577        // changing the on-disk snapshot format (headers/ids are still
7578        // NOT serialised — that is the deferred V6 coupling; see below).
7579        if has_tomb && !tomb_targets.is_empty() {
7580            let mut id_to_slot: alloc::collections::BTreeMap<row_header::RowId, usize> =
7581                alloc::collections::BTreeMap::new();
7582            for (slot, rid) in final_rowids.iter().enumerate() {
7583                if *rid != row_header::RowId::UNASSIGNED {
7584                    id_to_slot.insert(*rid, slot);
7585                }
7586            }
7587            let table = self.get_mut(table_name).ok_or_else(|| {
7588                StorageError::Corrupt(alloc::format!("redo: unknown table {table_name:?}"))
7589            })?;
7590            for (rid, xmax) in &tomb_targets {
7591                match id_to_slot.get(rid) {
7592                    Some(&slot) => {
7593                        // First-deleter-wins + bounds handled inside.
7594                        let _ = table.mark_row_deleted(slot, *xmax);
7595                    }
7596                    None => {
7597                        // The target row was not produced by THIS redo
7598                        // run and its id was not in the run-start
7599                        // snapshot — the documented cross-checkpoint
7600                        // limitation: after a checkpoint restore the
7601                        // table's ids are reassigned (not yet persisted
7602                        // in the envelope), so a tombstone naming a
7603                        // pre-checkpoint row cannot be resolved by id.
7604                        // Skipping leaves the row visible (identical to
7605                        // the pre-Epic-W non-durable behaviour); it is
7606                        // never a correctness regression, only an
7607                        // unclosed durability gap the V6 envelope slice
7608                        // closes. Counted for observability.
7609                        UNRESOLVED_TOMBSTONES.fetch_add(1, core::sync::atomic::Ordering::Relaxed);
7610                    }
7611                }
7612            }
7613        }
7614        Ok(())
7615    }
7616
7617    fn table_for_redo(&mut self, name: &str) -> Result<&mut Table, StorageError> {
7618        self.get_mut(name)
7619            .ok_or_else(|| StorageError::Corrupt(alloc::format!("redo: unknown table {name:?}")))
7620    }
7621
7622    /// v7.34 (crash-recovery P0 #2) — enable row-level redo capture on
7623    /// every table (the engine calls this before a mutating statement
7624    /// when persistence is on; idempotent, keeps any in-flight capture).
7625    pub fn enable_redo_all(&mut self) {
7626        for t in &mut self.tables {
7627            t.enable_redo();
7628        }
7629    }
7630
7631    /// v7.34 — drain the row-level redo captured across all tables, in
7632    /// table order then per-table apply order, and stop capturing. The
7633    /// engine calls this after a successful mutating statement and writes
7634    /// the returned [`RowChange`]s to the WAL in place of the SQL text.
7635    pub fn drain_redo(&mut self) -> Vec<RowChange> {
7636        let mut all = Vec::new();
7637        for t in &mut self.tables {
7638            all.extend(t.take_redo());
7639        }
7640        all
7641    }
7642
7643    pub fn table_count(&self) -> usize {
7644        self.tables.len()
7645    }
7646
7647    /// v7.14.0 — remove a table by name. Returns `true` when the
7648    /// table existed (and is now gone), `false` when it didn't.
7649    /// Used by `DROP TABLE` from pg_dump / mysqldump preambles
7650    /// where the dump re-creates schema and starts with
7651    /// `DROP TABLE IF EXISTS`.
7652    pub fn drop_table(&mut self, name: &str) -> bool {
7653        // v7.39 (round 436) — resolve through the session's temp namespace
7654        // first, exactly as a read would: MariaDB's plain `DROP TABLE tmp`
7655        // drops the TEMPORARY one and leaves a permanent namesake standing
7656        // (measured). Removing by the raw name would have dropped the
7657        // permanent table out from under every other session.
7658        let key = match self.temp_prefix.as_ref() {
7659            Some(p) => {
7660                let mangled = alloc::format!("{p}{name}");
7661                if self.by_name.contains_key(&mangled) {
7662                    mangled
7663                } else {
7664                    name.into()
7665                }
7666            }
7667            None => name.into(),
7668        };
7669        let Some(idx) = self.by_name.remove(&key) else {
7670            return false;
7671        };
7672        // v7.39 (round 496) — see `dirty_tables`. Recorded under the
7673        // RESOLVED key, which is what a commit-time merge looks up.
7674        self.dirty_tables.insert(key.clone());
7675        // swap_remove invalidates the trailing index → rebuild
7676        // by_name for affected entries.
7677        self.tables.swap_remove(idx);
7678        // Re-stamp moved table's index slot in by_name.
7679        if idx < self.tables.len() {
7680            let moved_name = self.tables[idx].schema.name.clone();
7681            self.by_name.insert(moved_name, idx);
7682        }
7683        true
7684    }
7685
7686    /// v7.16.2 — rename a table (mailrs round-10 A.5). Updates
7687    /// the schema name, the catalog name → index map, and
7688    /// rewrites every reference dangling at the table name:
7689    ///   * every FK on every OTHER table whose `parent_table`
7690    ///     pointed at the old name now points at the new
7691    ///     name, so FK enforcement keeps working
7692    ///   * every trigger watching the table updates its `table`
7693    ///     field
7694    /// Returns `Ok` on success; `Err(StorageError::TableNotFound)`
7695    /// when the old name isn't in the catalog and
7696    /// `Err(StorageError::DuplicateTable)` when the new name is
7697    /// already taken.
7698    pub fn rename_table(&mut self, old: &str, new: &str) -> Result<(), StorageError> {
7699        if old == new {
7700            return Ok(());
7701        }
7702        if self.by_name.contains_key(new) {
7703            return Err(StorageError::Corrupt(format!(
7704                "rename_table: target name {new:?} already exists"
7705            )));
7706        }
7707        let idx = self
7708            .by_name
7709            .remove(old)
7710            .ok_or_else(|| StorageError::TableNotFound { name: old.into() })?;
7711        self.tables[idx].schema.name = new.to_string();
7712        self.by_name.insert(new.to_string(), idx);
7713        for t in &mut self.tables {
7714            for fk in &mut t.schema.foreign_keys {
7715                if fk.parent_table == old {
7716                    fk.parent_table = new.to_string();
7717                }
7718            }
7719        }
7720        for trig in &mut self.triggers {
7721            if trig.table == old {
7722                trig.table = new.to_string();
7723            }
7724        }
7725        Ok(())
7726    }
7727
7728    /// v7.16.2 — rename an index by name. Walks every table
7729    /// since the index lives on its owning table; updates the
7730    /// name in place. Errors with `IndexNotFound` when no
7731    /// index matches. mailrs round-10 A.5.
7732    pub fn rename_index(&mut self, old: &str, new: &str) -> Result<(), StorageError> {
7733        if old == new {
7734            return Ok(());
7735        }
7736        // Reject the new name if it already exists anywhere.
7737        for t in &self.tables {
7738            if t.indices.iter().any(|i| i.name == new) {
7739                return Err(StorageError::Corrupt(format!(
7740                    "rename_index: target name {new:?} already exists"
7741                )));
7742            }
7743        }
7744        for t in &mut self.tables {
7745            for i in &mut t.indices {
7746                if i.name == old {
7747                    i.name = new.to_string();
7748                    return Ok(());
7749                }
7750            }
7751        }
7752        Err(StorageError::IndexNotFound { name: old.into() })
7753    }
7754
7755    /// v7.14.0 — remove a named index across the catalog.
7756    /// Returns `true` when found + dropped.
7757    pub fn drop_named_index(&mut self, name: &str) -> bool {
7758        for t in &mut self.tables {
7759            let before = t.indices.len();
7760            t.indices.retain(|i| i.name != name);
7761            if t.indices.len() != before {
7762                return true;
7763            }
7764        }
7765        false
7766    }
7767
7768    /// v7.39.7 — the same drop, scoped to ONE table.
7769    ///
7770    /// MySQL keys an index name inside its table, and `DROP INDEX i ON t`
7771    /// says which. `None` means the table itself is missing, which is a
7772    /// different error from the index being missing — MySQL answers 1146
7773    /// for the first and 1091 for the second.
7774    pub fn drop_named_index_on(&mut self, table: &str, name: &str) -> Option<bool> {
7775        let t = self
7776            .tables
7777            .iter_mut()
7778            .find(|t| t.schema.name.eq_ignore_ascii_case(table))?;
7779        let before = t.indices.len();
7780        t.indices.retain(|i| i.name != name);
7781        Some(t.indices.len() != before)
7782    }
7783
7784    /// Borrow-free copy of every table's name in catalog order
7785    /// (= insertion order, matching the on-disk encoding).
7786    pub fn table_names(&self) -> Vec<String> {
7787        self.tables.iter().map(|t| t.schema.name.clone()).collect()
7788    }
7789
7790    /// v7.39 (round 436) — the marker every session's temporary-table
7791    /// namespace starts with. Public so the catalog synths can tell a
7792    /// temp table from an ordinary one without knowing the session id.
7793    pub const TEMP_NAME_MARKER: &'static str = "__spg_temp_";
7794
7795    /// v7.39 (round 437) — how a stored table name should appear to the
7796    /// CALLING session in a catalog listing (SHOW TABLES, pg_class,
7797    /// information_schema, …):
7798    ///   * an ordinary table → its own name
7799    ///   * this session's temporary table → its logical name, prefix stripped
7800    ///   * another session's temporary table → `None`, i.e. not listed
7801    ///
7802    /// Measured on both oracles: MariaDB 11 and PG 18 each list the calling
7803    /// session's own temporary tables and neither lists anybody else's.
7804    /// Round 436 stored temp tables under a prefix without teaching the
7805    /// listings about it, so the mangled names leaked to every client.
7806    #[must_use]
7807    pub fn listed_name<'a>(&self, stored: &'a str) -> Option<&'a str> {
7808        if !stored.starts_with(Self::TEMP_NAME_MARKER) {
7809            return Some(stored);
7810        }
7811        let prefix = self.temp_prefix.as_ref()?;
7812        stored.strip_prefix(prefix.as_str())
7813    }
7814
7815    /// The listing names of every table this session may see, in catalog
7816    /// order. See [`Catalog::listed_name`].
7817    #[must_use]
7818    pub fn visible_table_names(&self) -> Vec<String> {
7819        self.tables
7820            .iter()
7821            .filter_map(|t| self.listed_name(&t.schema.name).map(String::from))
7822            .collect()
7823    }
7824
7825    /// v5.1: register a cold-tier segment that already lives in
7826    /// memory (caller did the file read). Returns the
7827    /// `segment_id` that `RowLocator::Cold { segment_id, .. }`
7828    /// will reference — currently this is just the index into
7829    /// `cold_segments`, but treat it as an opaque token.
7830    ///
7831    /// Storage is `no_std`, so file I/O is the caller's
7832    /// responsibility — `spg-server` reads the file and forwards
7833    /// the bytes here. The bytes stay resident in the catalog
7834    /// for the life of the `Catalog`, parsed only once.
7835    pub fn load_segment_bytes(&mut self, bytes: Vec<u8>) -> Result<u32, StorageError> {
7836        let id = u32::try_from(self.cold_segments.len()).map_err(|_| {
7837            StorageError::Corrupt("cold segment count would exceed u32::MAX".into())
7838        })?;
7839        let seg = OwnedSegment::from_bytes(bytes)
7840            .map_err(|e| StorageError::Corrupt(format!("cold segment parse failed: {e}")))?;
7841        self.cold_segments.push(Some(Arc::new(seg)));
7842        Ok(id)
7843    }
7844
7845    /// v6.7.3 — register a cold-tier segment at a specific id. Used
7846    /// by the spg-server manifest-boot path so segments whose
7847    /// neighbouring ids were retired by compaction still get back
7848    /// the same `segment_id` they had pre-restart (the
7849    /// `RowLocator::Cold { segment_id }` baked into the BTree-index
7850    /// snapshot persists across restart and must continue to
7851    /// resolve).
7852    ///
7853    /// Pads the Vec with `None` slots up to `target_id` if needed.
7854    /// Errors when the target slot is already occupied (would
7855    /// stomp another segment), the parse fails, or `target_id`
7856    /// exceeds `u32::MAX`.
7857    pub fn load_segment_bytes_at(
7858        &mut self,
7859        target_id: u32,
7860        bytes: Vec<u8>,
7861    ) -> Result<(), StorageError> {
7862        let seg = OwnedSegment::from_bytes(bytes)
7863            .map_err(|e| StorageError::Corrupt(format!("cold segment parse failed: {e}")))?;
7864        let idx = target_id as usize;
7865        while self.cold_segments.len() <= idx {
7866            self.cold_segments.push(None);
7867        }
7868        if self.cold_segments[idx].is_some() {
7869            return Err(StorageError::Corrupt(format!(
7870                "load_segment_bytes_at: segment_id {target_id} already occupied"
7871            )));
7872        }
7873        self.cold_segments[idx] = Some(Arc::new(seg));
7874        Ok(())
7875    }
7876
7877    /// v6.7.3 — retire a cold-tier segment slot (compaction-driven).
7878    /// The physical file is the caller's concern (typically kept
7879    /// on disk until the next CHECKPOINT writes a manifest that
7880    /// no longer lists it); this just flips the in-memory slot
7881    /// to `None` so later cold lookups for `segment_id` resolve
7882    /// as "unknown" instead of returning a stale row.
7883    ///
7884    /// No-op when the slot is already `None`. Errors only when
7885    /// `segment_id` is out of bounds.
7886    pub fn tombstone_segment(&mut self, segment_id: u32) -> Result<(), StorageError> {
7887        let idx = segment_id as usize;
7888        if idx >= self.cold_segments.len() {
7889            return Err(StorageError::Corrupt(format!(
7890                "tombstone_segment: segment_id {segment_id} out of bounds (len={})",
7891                self.cold_segments.len()
7892            )));
7893        }
7894        self.cold_segments[idx] = None;
7895        Ok(())
7896    }
7897
7898    /// Number of *active* (non-tombstoned) cold segments.
7899    #[must_use]
7900    pub fn cold_segment_count(&self) -> usize {
7901        self.cold_segments.iter().filter(|s| s.is_some()).count()
7902    }
7903
7904    /// v7.37.42 (docker-fair SCALARSQ attack 3) — short-circuit guard
7905    /// for scan loops that conditionally walk the cold tier. Returns
7906    /// `false` when the catalog has never loaded a cold segment (or all
7907    /// segments are tombstoned), so callers can skip the per-table cold
7908    /// PK-index walk entirely on hot-only databases. O(N segments);
7909    /// typical N is small (single-digit) so the check is sub-µs.
7910    #[must_use]
7911    pub fn has_any_cold_segments(&self) -> bool {
7912        self.cold_segments.iter().any(Option::is_some)
7913    }
7914
7915    /// Slot count including tombstones (= the next id the
7916    /// no-arg `load_segment_bytes` would allocate).
7917    #[must_use]
7918    pub fn cold_segment_slot_count(&self) -> usize {
7919        self.cold_segments.len()
7920    }
7921
7922    /// v6.2.7 — list every *active* cold-tier segment id known to
7923    /// this catalog (skips compaction tombstones since v6.7.3).
7924    /// Used by EXPLAIN ANALYZE to annotate scan nodes with the
7925    /// segments they could have walked.
7926    #[must_use]
7927    pub fn cold_segment_ids_global(&self) -> Vec<u32> {
7928        self.cold_segments
7929            .iter()
7930            .enumerate()
7931            .filter_map(|(i, s)| s.as_ref().map(|_| i as u32))
7932            .collect()
7933    }
7934
7935    /// v5.2.1: sum of `Table::hot_bytes` across every table. The v5.2
7936    /// freezer compares this against `SPG_HOT_TIER_BYTES` (parsed at
7937    /// server startup; default 4 GiB) and wakes when the budget is
7938    /// crossed. Pre-freezer (v5.2.1) this is measurement-only — the
7939    /// counter exposes whether the budget is being approached without
7940    /// triggering any demotion.
7941    #[must_use]
7942    pub fn hot_tier_bytes(&self) -> u64 {
7943        self.tables
7944            .iter()
7945            .map(Table::hot_bytes)
7946            .fold(0u64, u64::saturating_add)
7947    }
7948
7949    /// v5.2.2: freeze the **first** `max_rows` rows of `table_name`'s
7950    /// hot tier into a brand-new cold-tier segment. The named `BTree`
7951    /// index supplies the per-row PK (its column must be an integer
7952    /// type — v5.2.2 only supports `IndexKey::Int` PKs, matching the
7953    /// `index_key_as_u64` constraint used by the cold-tier lookup
7954    /// path). On success returns a [`FreezeReport`] with the
7955    /// freshly-allocated segment id, the count of rows that moved,
7956    /// the encoded segment bytes (so the caller can persist them to
7957    /// disk for later reload via `SPG_PRELOAD_COLD_SEGMENT`), and the
7958    /// hot-tier byte delta that was reclaimed.
7959    ///
7960    /// **Semantics**:
7961    /// 1. The first `max_rows` rows (by hot-tier position — same as
7962    ///    insertion order under v4.39 `PersistentVec`) are read.
7963    /// 2. Rows are sorted ascending by PK and serialised into a new
7964    ///    segment via [`encode_segment`].
7965    /// 3. The hot rows are dropped via [`Table::delete_rows`]; the
7966    ///    `rebuild_indices` it triggers regenerates `Hot` locators
7967    ///    for every remaining row (their positions shift down by
7968    ///    `max_rows`). Existing `Cold` locators in this index — from
7969    ///    a previous freeze — are also rebuilt **but with empty
7970    ///    payload** since rebuild reads only `self.rows`; this
7971    ///    routine re-registers them at the end of the call so the
7972    ///    user-visible state preserves all prior cold locators.
7973    /// 4. The new segment is loaded into `self.cold_segments` via
7974    ///    [`Catalog::load_segment_bytes`] (allocating a fresh
7975    ///    `segment_id`). New `Cold` locators are registered on the
7976    ///    named index — one per frozen row.
7977    ///
7978    /// **v5.2.2 limits** (relaxed in later sub-versions):
7979    /// - INSERT-only flow: subsequent UPDATE/DELETE on a frozen row
7980    ///   returns a stale-locator error (no promote-on-write until
7981    ///   v5.2.3).
7982    /// - Single-table scope: callers iterate tables themselves.
7983    /// - All-or-nothing: returns `Err` and leaves catalog unchanged
7984    ///   if any step fails before the atomic swap point.
7985    ///
7986    /// Errors:
7987    /// - [`StorageError::Corrupt`] for missing table/index, non-`BTree`
7988    ///   index, non-integer PK column, `max_rows == 0`, or
7989    ///   `max_rows > row_count`.
7990    /// - The encoder's [`SegmentError`] surfaces as `Corrupt` (the
7991    ///   only realistic source is "a single row is larger than the
7992    ///   page size"; SPG schemas don't hit it in practice).
7993    pub fn freeze_oldest_to_cold(
7994        &mut self,
7995        table_name: &str,
7996        index_name: &str,
7997        max_rows: usize,
7998    ) -> Result<FreezeReport, StorageError> {
7999        // --- validation phase: never mutates ---------------------
8000        if max_rows == 0 {
8001            return Err(StorageError::Corrupt(
8002                "freeze_oldest_to_cold: max_rows must be > 0".into(),
8003            ));
8004        }
8005        let table = self.get(table_name).ok_or_else(|| {
8006            StorageError::Corrupt(format!(
8007                "freeze_oldest_to_cold: table {table_name:?} not found"
8008            ))
8009        })?;
8010        if max_rows > table.rows.len() {
8011            return Err(StorageError::Corrupt(format!(
8012                "freeze_oldest_to_cold: max_rows {max_rows} > row_count {}",
8013                table.rows.len()
8014            )));
8015        }
8016        let idx = table
8017            .indices
8018            .iter()
8019            .find(|i| i.name == index_name)
8020            .ok_or_else(|| {
8021                StorageError::Corrupt(format!(
8022                    "freeze_oldest_to_cold: index {index_name:?} not found on {table_name:?}"
8023                ))
8024            })?;
8025        if !matches!(idx.kind, IndexKind::BTree(_)) {
8026            return Err(StorageError::Corrupt(format!(
8027                "freeze_oldest_to_cold: index {index_name:?} is NSW; only BTree indices may freeze"
8028            )));
8029        }
8030        let column_position = idx.column_position;
8031
8032        // --- segment build phase: reads only --------------------
8033        let schema = table.schema.clone();
8034        let mut to_freeze: Vec<(u64, Vec<u8>, IndexKey)> = Vec::with_capacity(max_rows);
8035        for row_idx in 0..max_rows {
8036            let row = table.rows.get(row_idx).expect("bounds-checked above");
8037            let key = IndexKey::from_value(&row.values[column_position]).ok_or_else(|| {
8038                StorageError::Corrupt(format!(
8039                    "freeze_oldest_to_cold: row {row_idx} has NULL / non-key value in index column"
8040                ))
8041            })?;
8042            let pk_u64 = index_key_as_u64(&key).ok_or_else(|| {
8043                StorageError::Corrupt(format!(
8044                    "freeze_oldest_to_cold: index {index_name:?} column type is non-integer; \
8045                     v5.2.2 cold tier requires IndexKey::Int (Text PK lands in v5.5+)"
8046                ))
8047            })?;
8048            to_freeze.push((pk_u64, encode_row_body_dense(row, &schema), key));
8049        }
8050        // encode_segment requires ascending u64 keys. Sort by PK
8051        // before encoding; the caller's row-position order is not
8052        // necessarily PK order (e.g. workloads that insert random
8053        // PKs).
8054        to_freeze.sort_by_key(|(k, _, _)| *k);
8055        // Reject duplicate PKs — encode_segment also rejects them
8056        // (`SegmentError::UnsortedKey`), but the resulting error
8057        // message there is misleading. Surface a clearer one.
8058        for w in to_freeze.windows(2) {
8059            if w[0].0 == w[1].0 {
8060                return Err(StorageError::Corrupt(format!(
8061                    "freeze_oldest_to_cold: duplicate PK {} in freeze batch",
8062                    w[0].0
8063                )));
8064            }
8065        }
8066        // Snapshot the (key, locator) pairs that will be registered
8067        // post-swap. Cloning the IndexKey out before the move makes
8068        // the registration loop borrow-free.
8069        let post_swap_keys: Vec<IndexKey> = to_freeze.iter().map(|(_, _, k)| k.clone()).collect();
8070        // Segment encode is now infallible w.r.t. ordering. Map the
8071        // `SegmentError` into a `StorageError::Corrupt` so the
8072        // public surface stays one error type.
8073        let seg_rows: Vec<(u64, Vec<u8>)> = to_freeze
8074            .into_iter()
8075            .map(|(k, body, _)| (k, body))
8076            .collect();
8077        let frozen_rows = seg_rows.len();
8078        let (seg_bytes, _meta) = encode_segment(seg_rows.into_iter(), 0.01, SEGMENT_PAGE_BYTES)
8079            .map_err(|e| StorageError::Corrupt(format!("freeze_oldest_to_cold: encode: {e}")))?;
8080
8081        // --- atomic swap phase: mutations only past this point ---
8082        // v5.2.3 made `Table::rebuild_indices` preserve every Cold
8083        // locator across the per-table rebuild, so `delete_rows`
8084        // below no longer wipes prior-freeze cold entries. The pre-
8085        // v5.2.3 capture-then-re-register that used to live here
8086        // was removed in v5.3.1 — keeping it would double-count
8087        // every prior-frozen key's Cold locator on each subsequent
8088        // freeze.
8089        let bytes_before = self.get(table_name).expect("just validated").hot_bytes();
8090        let positions: Vec<usize> = (0..max_rows).collect();
8091        let t_mut = self
8092            .get_mut(table_name)
8093            .expect("just validated; still present");
8094        let removed = t_mut.delete_rows(&positions);
8095        debug_assert_eq!(removed, max_rows, "delete_rows count matches request");
8096        let bytes_after = t_mut.hot_bytes();
8097        let bytes_freed = bytes_before.saturating_sub(bytes_after);
8098
8099        let segment_id = self
8100            .load_segment_bytes(seg_bytes.clone())
8101            .map_err(|e| StorageError::Corrupt(format!("freeze_oldest_to_cold: load: {e}")))?;
8102        let new_cold = post_swap_keys.into_iter().map(|k| {
8103            (
8104                k,
8105                RowLocator::Cold {
8106                    segment_id,
8107                    page_offset: 0,
8108                },
8109            )
8110        });
8111        let t_mut = self.get_mut(table_name).expect("still present");
8112        t_mut.register_cold_locators(index_name, new_cold)?;
8113        // r944 — a freeze has to say that it froze something.
8114        //
8115        // `has_cold_rows_fast()` reads the cached count, and neither
8116        // freeze path touched it, so afterwards it answered "no cold
8117        // rows" while cold rows existed. That predicate gates four join
8118        // paths, and a gate that wrongly declines the cold-aware path
8119        // drops the frozen rows from the answer.
8120        //
8121        // Marking it stale rather than adding to it: stale reads as
8122        // true, which is the safe direction, and this function cannot
8123        // know the exact total (rows may already have been cold). ANALYZE
8124        // recomputes the number.
8125        t_mut.mark_cold_row_count_stale();
8126
8127        Ok(FreezeReport {
8128            segment_id,
8129            frozen_rows,
8130            bytes_freed,
8131            segment_bytes: seg_bytes,
8132        })
8133    }
8134
8135    /// v5.1: borrow the cold segment at `segment_id`. Used by the
8136    /// spg-server preload path to enumerate (key, locator) pairs
8137    /// after loading a segment, so it can call
8138    /// [`Table::register_cold_locators`] without re-parsing the
8139    /// bytes.
8140    #[must_use]
8141    pub fn cold_segment(&self, segment_id: u32) -> Option<&OwnedSegment> {
8142        self.cold_segments
8143            .get(segment_id as usize)
8144            .and_then(|s| s.as_deref())
8145    }
8146
8147    /// v5.1: resolve a single `RowLocator::Cold` to its underlying
8148    /// `Row`. Decoupled from [`Catalog::lookup_by_pk`] so callers
8149    /// iterating a multi-locator slice (e.g. the engine's index
8150    /// seek path) can dispatch per locator instead of getting back
8151    /// only the first row for a key. Returns `None` when the
8152    /// segment isn't registered, the key isn't `u64`-coercible, or
8153    /// the segment doesn't actually carry the key (bloom or page-
8154    /// index reject).
8155    pub fn resolve_cold_locator(
8156        &self,
8157        table_name: &str,
8158        segment_id: u32,
8159        key: &IndexKey,
8160    ) -> Option<Row<'static>> {
8161        let t = self.get(table_name)?;
8162        let u64_key = index_key_as_u64(key)?;
8163        let seg = self.cold_segments.get(segment_id as usize)?.as_ref()?;
8164        let payload = seg.lookup(u64_key)?;
8165        let (row, _) = decode_row_body_dense(&payload, &t.schema, seg.codec_version()).ok()?;
8166        // v7.39 (pg_stat blks knife) — one cold-tier "block read".
8167        self.cold_read_stats
8168            .cold_reads
8169            .fetch_add(1, core::sync::atomic::Ordering::Relaxed);
8170        Some(row)
8171    }
8172
8173    /// v5.1: indexed PK lookup that dispatches per locator,
8174    /// returning the first matching row from either the hot tier
8175    /// (`Table::rows`) or a registered cold segment.
8176    ///
8177    /// The cold path requires the index column to be coercible to
8178    /// a `u64` (the segment's PK type) and the segment payload to
8179    /// be a [`encode_row_body_dense`]-encoded row body for the
8180    /// same schema. v5.1 ships this for BIGINT / INT / SMALLINT
8181    /// PKs; other types fall through to hot-only behavior.
8182    ///
8183    /// Returns `None` if (a) the table or index doesn't exist,
8184    /// (b) the key isn't in the index at all, or (c) the key was
8185    /// resolved to a stale locator (Hot index out of range, Cold
8186    /// segment id unknown, segment lookup miss). Does not surface
8187    /// segment-decode errors — those would indicate corrupted
8188    /// cold-tier files and should be caught at
8189    /// [`Catalog::load_segment_bytes`] time.
8190    pub fn lookup_by_pk(&self, table: &str, index_name: &str, key: &IndexKey) -> Option<Row<'_>> {
8191        let t = self.get(table)?;
8192        let idx = t.indices.iter().find(|i| i.name == index_name)?;
8193        let locators = idx.lookup_eq(key);
8194        let cold_u64_key = index_key_as_u64(key);
8195        for loc in locators {
8196            match *loc {
8197                RowLocator::Hot(i) => {
8198                    if let Some(row) = t.rows.get(i) {
8199                        return Some(row.clone());
8200                    }
8201                }
8202                RowLocator::Cold {
8203                    segment_id,
8204                    page_offset: _,
8205                } => {
8206                    let Some(u64_key) = cold_u64_key else {
8207                        // Key type not coercible to u64 — cold tier
8208                        // only handles BIGINT/INT/SMALLINT in v5.1.
8209                        continue;
8210                    };
8211                    let Some(seg) = self
8212                        .cold_segments
8213                        .get(segment_id as usize)
8214                        .and_then(|s| s.as_deref())
8215                    else {
8216                        // v6.7.3 — `None` slot = compaction
8217                        // retired this segment; the live locator
8218                        // on a freshly-compacted index points to
8219                        // the merged segment_id, so a Cold hit
8220                        // here against a tombstone means the BTree
8221                        // entry hasn't been swapped yet (mid-
8222                        // compaction reader race) or the caller is
8223                        // looking up a stale snapshot. Skip — the
8224                        // next locator in the list, if any, is
8225                        // typically the merged segment.
8226                        continue;
8227                    };
8228                    let Some(payload) = seg.lookup(u64_key) else {
8229                        continue;
8230                    };
8231                    let (row, _) =
8232                        decode_row_body_dense(&payload, &t.schema, seg.codec_version()).ok()?;
8233                    return Some(row);
8234                }
8235            }
8236        }
8237        None
8238    }
8239
8240    /// v5.2.3: promote a frozen row back to the hot tier so an
8241    /// UPDATE / DELETE can mutate it. Reads the cold-tier row body
8242    /// (decoded from its registered segment), pushes it into
8243    /// `table.rows` via [`Table::insert`] (which also adds a fresh
8244    /// `Hot(new_idx)` locator on `index_name`), then retires the
8245    /// shadowed `Cold` locator via
8246    /// [`Table::remove_cold_locators_for_key`]. The cold-tier row
8247    /// in the segment file becomes garbage — recoverable when a
8248    /// future cold-segment compaction job lands.
8249    ///
8250    /// Returns:
8251    /// - `Ok(Some(new_hot_idx))` when the key resolved through a
8252    ///   cold locator and the promote completed. `new_hot_idx` is
8253    ///   the position the row now occupies in `table.rows`.
8254    /// - `Ok(None)` when the key has no Cold locator on the index
8255    ///   (already hot, or wasn't present at all). Callers treat this
8256    ///   as "nothing to do here, fall back to the hot-only path".
8257    ///
8258    /// Errors when the table / index doesn't exist, the index isn't
8259    /// `BTree`, the cold segment is missing / can't decode the row,
8260    /// or the inferred row body fails `Table::insert` validation.
8261    pub fn promote_cold_row(
8262        &mut self,
8263        table_name: &str,
8264        index_name: &str,
8265        key: &IndexKey,
8266    ) -> Result<Option<usize>, StorageError> {
8267        let cold_loc = self.find_cold_locator(table_name, index_name, key)?;
8268        let Some((segment_id, _page_offset)) = cold_loc else {
8269            return Ok(None);
8270        };
8271        let u64_key = index_key_as_u64(key).ok_or_else(|| {
8272            StorageError::Corrupt(
8273                "promote_cold_row: key type not coercible to u64 (cold tier requires integer PK)"
8274                    .into(),
8275            )
8276        })?;
8277        // Read the row body from the segment. Borrow the segment +
8278        // schema short-term so we can then take `&mut self` for the
8279        // hot-side insert.
8280        let schema = self
8281            .get(table_name)
8282            .ok_or_else(|| {
8283                StorageError::Corrupt(format!("promote_cold_row: table {table_name:?} not found"))
8284            })?
8285            .schema
8286            .clone();
8287        let seg = self
8288            .cold_segments
8289            .get(segment_id as usize)
8290            .and_then(|s| s.as_ref())
8291            .ok_or_else(|| {
8292                StorageError::Corrupt(format!(
8293                    "promote_cold_row: segment {segment_id} not registered on catalog"
8294                ))
8295            })?;
8296        let payload = seg.lookup(u64_key).ok_or_else(|| {
8297            StorageError::Corrupt(format!(
8298                "promote_cold_row: key {u64_key} resolves to segment {segment_id} \
8299                 but the segment's bloom/page lookup didn't return a row"
8300            ))
8301        })?;
8302        let (row, _consumed) = decode_row_body_dense(&payload, &schema, seg.codec_version())?;
8303        // Insert the promoted row into the hot tier. `Table::insert`
8304        // appends to `self.rows`, adds a `Hot(new_idx)` locator to
8305        // every BTree index covering the row's keyed columns, and
8306        // increments `hot_bytes`.
8307        let t = self
8308            .get_mut(table_name)
8309            .expect("table existed at lookup time");
8310        t.insert(row)?;
8311        let new_hot_idx =
8312            t.rows.len().checked_sub(1).ok_or_else(|| {
8313                StorageError::Corrupt("promote_cold_row: empty after insert".into())
8314            })?;
8315        // The hot insert added Hot(new_idx) alongside the still-
8316        // present Cold locator. Drop the Cold entry so future
8317        // lookups return only the fresh hot row.
8318        t.remove_cold_locators_for_key(index_name, key)?;
8319        Ok(Some(new_hot_idx))
8320    }
8321
8322    /// v5.2.3: shadow a frozen row's index entry. Used by DELETE
8323    /// when the row to remove lives in a cold-tier segment — the
8324    /// row body stays in the segment file (becoming garbage) but
8325    /// every `Cold` locator for `key` on `index_name` is removed
8326    /// so PK lookups stop returning it.
8327    ///
8328    /// Returns the number of cold locators retired (0 when the key
8329    /// has no cold entries — the DELETE fell on a hot row or a
8330    /// key that was already absent). Errors when the table /
8331    /// index doesn't exist or the index isn't `BTree`.
8332    ///
8333    /// Cold-segment compaction (which merges shadowed-heavy
8334    /// segments and reclaims their disk footprint) lands in a
8335    /// later v5.x sub-version; until then, repeated UPDATE/DELETE
8336    /// of cold rows can amplify cold-segment disk usage by up to
8337    /// 1-2× — still well under typical LSM-tree shadowing because
8338    /// SPG segments are bulk-baked, not write-merged.
8339    pub fn shadow_cold_row(
8340        &mut self,
8341        table_name: &str,
8342        index_name: &str,
8343        key: &IndexKey,
8344    ) -> Result<usize, StorageError> {
8345        let t = self.get_mut(table_name).ok_or_else(|| {
8346            StorageError::Corrupt(format!("shadow_cold_row: table {table_name:?} not found"))
8347        })?;
8348        t.remove_cold_locators_for_key(index_name, key)
8349    }
8350
8351    /// v6.7.4 — read-only slice preparation for the parallel
8352    /// freezer. Walks rows in `row_range`, builds the
8353    /// `(pk_u64, encoded_body, IndexKey)` triples that the
8354    /// coordinator's k-way merge consumes, sorts the slice by
8355    /// `pk_u64`, and returns a [`FreezeSlice`].
8356    ///
8357    /// Caller invariants:
8358    /// - `row_range.end <= table.rows.len()` (caller's job to
8359    ///   compute the partition).
8360    /// - All slices passed to `commit_freeze_slices` must cover a
8361    ///   contiguous half-open range `[0, total_max_rows)` with no
8362    ///   gaps and no overlaps. The coordinator validates this
8363    ///   invariant before committing.
8364    ///
8365    /// `&self`-only — multiple workers can run this concurrently
8366    /// against the same `Catalog` reference under the engine's
8367    /// write lock (workers don't mutate; the coordinator does).
8368    pub fn prepare_freeze_slice(
8369        &self,
8370        table_name: &str,
8371        index_name: &str,
8372        row_range: core::ops::Range<usize>,
8373    ) -> Result<FreezeSlice, StorageError> {
8374        let table = self.get(table_name).ok_or_else(|| {
8375            StorageError::Corrupt(format!(
8376                "prepare_freeze_slice: table {table_name:?} not found"
8377            ))
8378        })?;
8379        let idx = table
8380            .indices
8381            .iter()
8382            .find(|i| i.name == index_name)
8383            .ok_or_else(|| {
8384                StorageError::Corrupt(format!(
8385                    "prepare_freeze_slice: index {index_name:?} not found on {table_name:?}"
8386                ))
8387            })?;
8388        if !matches!(idx.kind, IndexKind::BTree(_)) {
8389            return Err(StorageError::Corrupt(format!(
8390                "prepare_freeze_slice: index {index_name:?} is NSW; only BTree indices may freeze"
8391            )));
8392        }
8393        if row_range.end > table.rows.len() {
8394            return Err(StorageError::Corrupt(format!(
8395                "prepare_freeze_slice: row_range end {} > row_count {}",
8396                row_range.end,
8397                table.rows.len()
8398            )));
8399        }
8400        let column_position = idx.column_position;
8401        let schema = table.schema.clone();
8402        let mut rows: Vec<(u64, Vec<u8>, IndexKey)> = Vec::with_capacity(row_range.len());
8403        for row_idx in row_range.clone() {
8404            let row = table.rows.get(row_idx).expect("bounds-checked above");
8405            let key = IndexKey::from_value(&row.values[column_position]).ok_or_else(|| {
8406                StorageError::Corrupt(format!(
8407                    "prepare_freeze_slice: row {row_idx} has NULL / non-key value in index column"
8408                ))
8409            })?;
8410            let pk_u64 = index_key_as_u64(&key).ok_or_else(|| {
8411                StorageError::Corrupt(format!(
8412                    "prepare_freeze_slice: index {index_name:?} column type is non-integer; \
8413                     v5.2.2 cold tier requires IndexKey::Int (Text PK lands in v5.5+)"
8414                ))
8415            })?;
8416            rows.push((pk_u64, encode_row_body_dense(row, &schema), key));
8417        }
8418        rows.sort_by_key(|(k, _, _)| *k);
8419        Ok(FreezeSlice { row_range, rows })
8420    }
8421
8422    /// v6.7.4 — coordinator commit step. Merges N
8423    /// [`FreezeSlice`]s into one segment via the standard
8424    /// [`encode_segment`] path, atomically swaps the catalog
8425    /// state (delete the union row range + register Cold
8426    /// locators + load the segment).
8427    ///
8428    /// Validates that the slices cover a contiguous, gap-free,
8429    /// overlap-free half-open range starting at index 0 (the
8430    /// freezer always freezes "oldest first" — same semantics as
8431    /// the single-threaded [`Catalog::freeze_oldest_to_cold`]).
8432    ///
8433    /// Empty `slices` → no-op success (returns a zero-row report
8434    /// without mutating). Total row count = `Σ slice.rows.len()`.
8435    pub fn commit_freeze_slices(
8436        &mut self,
8437        table_name: &str,
8438        index_name: &str,
8439        slices: Vec<FreezeSlice>,
8440    ) -> Result<FreezeReport, StorageError> {
8441        // --- validation phase: never mutates ---------------------
8442        let table = self.get(table_name).ok_or_else(|| {
8443            StorageError::Corrupt(format!(
8444                "commit_freeze_slices: table {table_name:?} not found"
8445            ))
8446        })?;
8447        let idx = table
8448            .indices
8449            .iter()
8450            .find(|i| i.name == index_name)
8451            .ok_or_else(|| {
8452                StorageError::Corrupt(format!(
8453                    "commit_freeze_slices: index {index_name:?} not found on {table_name:?}"
8454                ))
8455            })?;
8456        if !matches!(idx.kind, IndexKind::BTree(_)) {
8457            return Err(StorageError::Corrupt(format!(
8458                "commit_freeze_slices: index {index_name:?} is NSW; only BTree indices may freeze"
8459            )));
8460        }
8461        // Validate slice coverage: contiguous from 0, no gaps, no
8462        // overlaps. Allow the caller to pass slices in any order —
8463        // sort by row_range.start first.
8464        let mut ordered = slices;
8465        ordered.sort_by_key(|s| s.row_range.start);
8466        // Drop fully-empty slices that fell out of an uneven
8467        // partition; they carry no data but contribute to the
8468        // contiguity check, so keep them in line.
8469        let mut expected_start = 0usize;
8470        for s in &ordered {
8471            if s.row_range.start != expected_start {
8472                return Err(StorageError::Corrupt(format!(
8473                    "commit_freeze_slices: gap/overlap at row {}; expected start {}",
8474                    s.row_range.start, expected_start
8475                )));
8476            }
8477            expected_start = s.row_range.end;
8478        }
8479        let max_rows = expected_start;
8480        if max_rows > table.rows.len() {
8481            return Err(StorageError::Corrupt(format!(
8482                "commit_freeze_slices: total row range {} exceeds row_count {}",
8483                max_rows,
8484                table.rows.len()
8485            )));
8486        }
8487        if max_rows == 0 {
8488            return Ok(FreezeReport {
8489                segment_id: u32::MAX,
8490                frozen_rows: 0,
8491                bytes_freed: 0,
8492                segment_bytes: Vec::new(),
8493            });
8494        }
8495
8496        // --- segment build phase: reads only --------------------
8497        // K-way merge of already-sorted slices. Each slice's rows
8498        // are ascending by pk_u64; we keep a per-slice cursor and
8499        // pull the next-smallest head until every cursor drains.
8500        let total_rows: usize = ordered.iter().map(|s| s.rows.len()).sum();
8501        if total_rows != max_rows {
8502            return Err(StorageError::Corrupt(format!(
8503                "commit_freeze_slices: total slice rows {total_rows} ≠ row_range coverage {max_rows}"
8504            )));
8505        }
8506        let mut cursors: Vec<usize> = alloc::vec![0; ordered.len()];
8507        let mut merged: Vec<(u64, Vec<u8>, IndexKey)> = Vec::with_capacity(total_rows);
8508        loop {
8509            // Pick the slice whose head row has the smallest key
8510            // and isn't yet exhausted.
8511            let mut pick: Option<usize> = None;
8512            for (i, c) in cursors.iter().enumerate() {
8513                let slice = &ordered[i];
8514                if *c >= slice.rows.len() {
8515                    continue;
8516                }
8517                match pick {
8518                    None => pick = Some(i),
8519                    Some(j) => {
8520                        if slice.rows[*c].0 < ordered[j].rows[cursors[j]].0 {
8521                            pick = Some(i);
8522                        }
8523                    }
8524                }
8525            }
8526            let Some(i) = pick else { break };
8527            let row = ordered[i].rows[cursors[i]].clone();
8528            cursors[i] += 1;
8529            merged.push(row);
8530        }
8531        // Reject duplicate PKs — same error as the single-threaded
8532        // path so callers get a uniform surface.
8533        for w in merged.windows(2) {
8534            if w[0].0 == w[1].0 {
8535                return Err(StorageError::Corrupt(format!(
8536                    "commit_freeze_slices: duplicate PK {} across slices",
8537                    w[0].0
8538                )));
8539            }
8540        }
8541        let post_swap_keys: Vec<IndexKey> = merged.iter().map(|(_, _, k)| k.clone()).collect();
8542        let seg_rows: Vec<(u64, Vec<u8>)> =
8543            merged.into_iter().map(|(k, body, _)| (k, body)).collect();
8544        let frozen_rows = seg_rows.len();
8545        let (seg_bytes, _meta) = encode_segment(seg_rows.into_iter(), 0.01, SEGMENT_PAGE_BYTES)
8546            .map_err(|e| StorageError::Corrupt(format!("commit_freeze_slices: encode: {e}")))?;
8547
8548        // --- atomic swap phase: mutations only past this point ---
8549        let bytes_before = self.get(table_name).expect("just validated").hot_bytes();
8550        let positions: Vec<usize> = (0..max_rows).collect();
8551        let t_mut = self
8552            .get_mut(table_name)
8553            .expect("just validated; still present");
8554        let removed = t_mut.delete_rows(&positions);
8555        debug_assert_eq!(removed, max_rows, "delete_rows count matches request");
8556        let bytes_after = t_mut.hot_bytes();
8557        let bytes_freed = bytes_before.saturating_sub(bytes_after);
8558
8559        let segment_id = self
8560            .load_segment_bytes(seg_bytes.clone())
8561            .map_err(|e| StorageError::Corrupt(format!("commit_freeze_slices: load: {e}")))?;
8562        let new_cold = post_swap_keys.into_iter().map(|k| {
8563            (
8564                k,
8565                RowLocator::Cold {
8566                    segment_id,
8567                    page_offset: 0,
8568                },
8569            )
8570        });
8571        let t_mut = self.get_mut(table_name).expect("still present");
8572        t_mut.register_cold_locators(index_name, new_cold)?;
8573        // r944 — a freeze has to say that it froze something.
8574        //
8575        // `has_cold_rows_fast()` reads the cached count, and neither
8576        // freeze path touched it, so afterwards it answered "no cold
8577        // rows" while cold rows existed. That predicate gates four join
8578        // paths, and a gate that wrongly declines the cold-aware path
8579        // drops the frozen rows from the answer.
8580        //
8581        // Marking it stale rather than adding to it: stale reads as
8582        // true, which is the safe direction, and this function cannot
8583        // know the exact total (rows may already have been cold). ANALYZE
8584        // recomputes the number.
8585        t_mut.mark_cold_row_count_stale();
8586
8587        Ok(FreezeReport {
8588            segment_id,
8589            frozen_rows,
8590            bytes_freed,
8591            segment_bytes: seg_bytes,
8592        })
8593    }
8594
8595    /// v6.7.3 — compact every cold segment on `(table, index)` whose
8596    /// `OwnedSegment::bytes().len()` is below `target_segment_bytes`
8597    /// into a single larger merged segment. Rows present in source
8598    /// segment payloads but no longer referenced by any
8599    /// `RowLocator::Cold` on the index (DELETE'd + frozen rows
8600    /// retired via [`Catalog::shadow_cold_row`]) are GC'd in the
8601    /// merge.
8602    ///
8603    /// **Semantics**:
8604    /// 1. Walk the BTree index to collect every Cold locator that
8605    ///    targets a small (< threshold) segment. Each such
8606    ///    `(key, segment_id)` becomes a row in the merged segment;
8607    ///    payload is looked up from the source segment in-place.
8608    /// 2. Encode the collected rows into one new segment via
8609    ///    [`encode_segment`]; register it via
8610    ///    [`Catalog::load_segment_bytes`] (allocating a fresh
8611    ///    `merged_segment_id` at the end of `cold_segments`).
8612    /// 3. Rewrite the BTree index in one pass: every
8613    ///    `RowLocator::Cold { segment_id ∈ sources }` becomes
8614    ///    `RowLocator::Cold { segment_id = merged_id, page_offset = 0 }`.
8615    ///    Hot locators are untouched.
8616    /// 4. Tombstone every source slot via
8617    ///    [`Catalog::tombstone_segment`]. Source segment payloads
8618    ///    are no longer reachable through the catalog; the on-disk
8619    ///    files are the caller's concern.
8620    ///
8621    /// On fewer than 2 candidate segments the catalog is **not**
8622    /// mutated and a no-op report (`merged_segment_id: None`,
8623    /// `sources: []`) is returned. This is the routine case — a
8624    /// freshly-frozen table has at most 1 small segment, no merge
8625    /// possible.
8626    ///
8627    /// Atomicity: every mutating step runs after the read-only
8628    /// gather phase, so a panic before the merge encode leaves the
8629    /// catalog unchanged. The mutation block itself (load + rewrite +
8630    /// tombstone) takes only `&mut self` — callers serialise the
8631    /// engine write lock outside this function.
8632    ///
8633    /// Errors when the table / index doesn't exist, the index isn't
8634    /// `BTree`, the index column type isn't u64-coercible (cold-tier
8635    /// pre-condition), or a source segment fails its in-place
8636    /// row-body lookup (would indicate prior catalog corruption).
8637    pub fn compact_cold_segments(
8638        &mut self,
8639        table_name: &str,
8640        index_name: &str,
8641        target_segment_bytes: u64,
8642    ) -> Result<CompactReport, StorageError> {
8643        // --- validation phase ----------------------------------
8644        let t = self.get(table_name).ok_or_else(|| {
8645            StorageError::Corrupt(format!(
8646                "compact_cold_segments: table {table_name:?} not found"
8647            ))
8648        })?;
8649        let idx = t
8650            .indices
8651            .iter()
8652            .find(|i| i.name == index_name)
8653            .ok_or_else(|| {
8654                StorageError::Corrupt(format!(
8655                    "compact_cold_segments: index {index_name:?} not found on {table_name:?}"
8656                ))
8657            })?;
8658        let map = match &idx.kind {
8659            IndexKind::BTree(m) => m,
8660            IndexKind::Nsw(_)
8661            | IndexKind::Brin { .. }
8662            | IndexKind::Gin(_)
8663            | IndexKind::GinTrgm(_)
8664            | IndexKind::GinFulltext(_)
8665            | IndexKind::GinJsonb(_)
8666            | IndexKind::BTreeMulti(_) => {
8667                return Err(StorageError::Corrupt(format!(
8668                    "compact_cold_segments: index {index_name:?} is not BTree; \
8669                     compaction applies only to BTree cold-tier indices"
8670                )));
8671            }
8672        };
8673
8674        // --- gather phase --------------------------------------
8675        // Step A: every segment_id this BTree index Cold-references.
8676        let mut referenced_ids: BTreeSet<u32> = BTreeSet::new();
8677        for (_key, locators) in map.iter() {
8678            for loc in locators {
8679                if let RowLocator::Cold { segment_id, .. } = loc {
8680                    referenced_ids.insert(*segment_id);
8681                }
8682            }
8683        }
8684        // Step B: keep only the small + still-active ones.
8685        let candidate_set: BTreeSet<u32> = referenced_ids
8686            .into_iter()
8687            .filter(|id| {
8688                self.cold_segments
8689                    .get(*id as usize)
8690                    .and_then(|s| s.as_deref())
8691                    .is_some_and(|s| (s.bytes().len() as u64) < target_segment_bytes)
8692            })
8693            .collect();
8694        if candidate_set.len() < 2 {
8695            return Ok(CompactReport {
8696                sources: Vec::new(),
8697                merged_segment_id: None,
8698                merged_segment_bytes: Vec::new(),
8699                merged_rows: 0,
8700                deleted_rows_pruned: 0,
8701                bytes_reclaimed_estimate: 0,
8702            });
8703        }
8704        // Step C: pre-count source rows for the deleted-pruned metric.
8705        let mut source_row_count: usize = 0;
8706        let mut source_byte_total: u64 = 0;
8707        for &id in &candidate_set {
8708            let seg = self.cold_segments[id as usize]
8709                .as_ref()
8710                .expect("candidate selected only when slot is Some");
8711            source_row_count = source_row_count.saturating_add(seg.meta().num_rows as usize);
8712            source_byte_total = source_byte_total.saturating_add(seg.bytes().len() as u64);
8713        }
8714        // Step D: collect (key, body) pairs from every live Cold
8715        // locator pointing at a candidate. dedupe by key — one
8716        // BTree key resolves to at most one cold payload (the
8717        // freezer + promote/shadow flow keeps Cold locators
8718        // unique per key).
8719        let mut collected: BTreeMap<u64, (Vec<u8>, IndexKey)> = BTreeMap::new();
8720        for (key, locators) in map.iter() {
8721            for loc in locators {
8722                let RowLocator::Cold { segment_id, .. } = loc else {
8723                    continue;
8724                };
8725                if !candidate_set.contains(segment_id) {
8726                    continue;
8727                }
8728                let u64_key = index_key_as_u64(key).ok_or_else(|| {
8729                    StorageError::Corrupt(format!(
8730                        "compact_cold_segments: index {index_name:?} has non-integer Cold key; \
8731                         cold tier requires IndexKey::Int (Text PK lands in v5.5+)"
8732                    ))
8733                })?;
8734                let seg = self.cold_segments[*segment_id as usize]
8735                    .as_ref()
8736                    .expect("candidate slot guaranteed Some above");
8737                let payload = seg.lookup(u64_key).ok_or_else(|| {
8738                    StorageError::Corrupt(format!(
8739                        "compact_cold_segments: BTree {index_name:?} points key={u64_key} \
8740                         at segment {segment_id} but the segment lookup missed"
8741                    ))
8742                })?;
8743                collected.insert(u64_key, (payload, key.clone()));
8744                break;
8745            }
8746        }
8747        let merged_rows = collected.len();
8748        let deleted_rows_pruned = source_row_count.saturating_sub(merged_rows);
8749
8750        // Step E: encode the merged segment. `BTreeMap<u64, _>`
8751        // iteration is ascending by key, which is what
8752        // `encode_segment` requires.
8753        let seg_rows: Vec<(u64, Vec<u8>)> = collected
8754            .iter()
8755            .map(|(k, (body, _))| (*k, body.clone()))
8756            .collect();
8757        let (seg_bytes, _meta) = encode_segment(seg_rows.into_iter(), 0.01, SEGMENT_PAGE_BYTES)
8758            .map_err(|e| StorageError::Corrupt(format!("compact_cold_segments: encode: {e}")))?;
8759        let merged_bytes_len = seg_bytes.len() as u64;
8760
8761        // --- atomic mutation phase ------------------------------
8762        let merged_segment_id = self
8763            .load_segment_bytes(seg_bytes.clone())
8764            .map_err(|e| StorageError::Corrupt(format!("compact_cold_segments: load: {e}")))?;
8765
8766        // Rewrite the BTree index: every Cold locator pointing at
8767        // a candidate source becomes a Cold locator pointing at
8768        // the merged segment. Use a flat collect-then-replace
8769        // pattern so we never hold a `&self` borrow across the
8770        // `&mut self` write.
8771        let entries: Vec<(IndexKey, crate::posting::PostingList)> = {
8772            let t = self
8773                .get(table_name)
8774                .expect("table existed at the start of this fn");
8775            let idx = t
8776                .indices
8777                .iter()
8778                .find(|i| i.name == index_name)
8779                .expect("index existed at the start of this fn");
8780            let IndexKind::BTree(map) = &idx.kind else {
8781                unreachable!("validated above");
8782            };
8783            map.iter().map(|(k, v)| (k.clone(), v.clone())).collect()
8784        };
8785        let t_mut = self
8786            .get_mut(table_name)
8787            .expect("table existed at the start of this fn");
8788        let idx_mut = t_mut
8789            .indices
8790            .iter_mut()
8791            .find(|i| i.name == index_name)
8792            .expect("index existed at the start of this fn");
8793        let IndexKind::BTree(map_mut) = &mut idx_mut.kind else {
8794            unreachable!("validated above");
8795        };
8796        for (key, locators) in entries {
8797            let mut new_locs = crate::posting::PostingList::new();
8798            let mut changed = false;
8799            for loc in &locators {
8800                match *loc {
8801                    RowLocator::Cold {
8802                        segment_id,
8803                        page_offset: _,
8804                    } if candidate_set.contains(&segment_id) => {
8805                        let replacement = RowLocator::Cold {
8806                            segment_id: merged_segment_id,
8807                            page_offset: 0,
8808                        };
8809                        if !new_locs.contains(replacement) {
8810                            new_locs.push(replacement);
8811                        }
8812                        changed = true;
8813                    }
8814                    other => new_locs.push(other),
8815                }
8816            }
8817            if changed {
8818                map_mut.insert_mut(key, new_locs);
8819            }
8820        }
8821
8822        // Tombstone every source slot. Last step — failures here
8823        // would leave the segment double-referenced in both
8824        // memory + manifest, but `tombstone_segment` only errors
8825        // on out-of-bounds, which we've already validated.
8826        for &id in &candidate_set {
8827            self.tombstone_segment(id)?;
8828        }
8829
8830        let bytes_reclaimed_estimate = source_byte_total.saturating_sub(merged_bytes_len);
8831        Ok(CompactReport {
8832            sources: candidate_set.into_iter().collect(),
8833            merged_segment_id: Some(merged_segment_id),
8834            merged_segment_bytes: seg_bytes,
8835            merged_rows,
8836            deleted_rows_pruned,
8837            bytes_reclaimed_estimate,
8838        })
8839    }
8840
8841    /// Internal helper: scan `(table, index)` for a `Cold` locator
8842    /// keyed by `key`. Returns `Ok(Some((segment_id, page_offset)))`
8843    /// when found, `Ok(None)` when the key has only hot entries
8844    /// or no entries at all, `Err` on the same input-validation
8845    /// errors as the public `promote_cold_row` / `shadow_cold_row`.
8846    fn find_cold_locator(
8847        &self,
8848        table_name: &str,
8849        index_name: &str,
8850        key: &IndexKey,
8851    ) -> Result<Option<(u32, u32)>, StorageError> {
8852        let t = self.get(table_name).ok_or_else(|| {
8853            StorageError::Corrupt(format!("find_cold_locator: table {table_name:?} not found"))
8854        })?;
8855        let idx = t
8856            .indices
8857            .iter()
8858            .find(|i| i.name == index_name)
8859            .ok_or_else(|| {
8860                StorageError::Corrupt(format!(
8861                    "find_cold_locator: index {index_name:?} not found on {table_name:?}"
8862                ))
8863            })?;
8864        if !matches!(idx.kind, IndexKind::BTree(_)) {
8865            return Err(StorageError::Corrupt(format!(
8866                "find_cold_locator: index {index_name:?} is NSW; promote-on-write only applies to BTree indices"
8867            )));
8868        }
8869        for loc in idx.lookup_eq(key) {
8870            if let RowLocator::Cold {
8871                segment_id,
8872                page_offset,
8873            } = *loc
8874            {
8875                return Ok(Some((segment_id, page_offset)));
8876            }
8877        }
8878        Ok(None)
8879    }
8880}
8881
8882/// Coerce an [`IndexKey`] to the `u64` that v5.1 cold-tier
8883/// segments use as their on-disk PK. Returns `None` for keys that
8884/// aren't representable as `u64` — Text PKs need a hash mapping
8885/// the segment writer baked in (deferred to v5.2+), Bool PKs are
8886/// almost never wide enough to be sharded into a cold tier.
8887fn index_key_as_u64(key: &IndexKey) -> Option<u64> {
8888    match key {
8889        // Reinterpret the i64 bit pattern as u64. Cold-tier segments
8890        // are sorted by this u64 view, so the chosen interpretation
8891        // only has to match between insert (bake_segment / freezer)
8892        // and lookup — using cast_unsigned keeps both sides honest
8893        // and silences clippy::cast_sign_loss.
8894        IndexKey::Int(n) => Some(n.cast_unsigned()),
8895        // Text / Bool / Uuid / Bytes / Numeric PKs aren't representable
8896        // as u64 and so can't participate in the u64-sorted cold-tier
8897        // segment PK layout. Same deferral story as Text — lookup falls
8898        // through the in-memory btree.
8899        IndexKey::Text(_)
8900        | IndexKey::Bool(_)
8901        | IndexKey::Uuid(_)
8902        | IndexKey::Bytes(_)
8903        | IndexKey::Numeric(_)
8904        | IndexKey::Null => None,
8905    }
8906}
8907
8908#[derive(Debug, Clone, PartialEq, Eq)]
8909#[non_exhaustive]
8910pub enum StorageError {
8911    DuplicateTable {
8912        name: String,
8913    },
8914    TableNotFound {
8915        name: String,
8916    },
8917    ArityMismatch {
8918        expected: usize,
8919        actual: usize,
8920    },
8921    TypeMismatch {
8922        column: String,
8923        expected: DataType,
8924        actual: DataType,
8925        position: usize,
8926    },
8927    NullInNotNull {
8928        column: String,
8929    },
8930    /// Index with this name already exists on the table.
8931    DuplicateIndex {
8932        name: String,
8933    },
8934    /// Column referenced by an index doesn't exist on the table.
8935    ColumnNotFound {
8936        column: String,
8937    },
8938    /// On-disk format failed to parse — corrupted file, wrong magic, truncated
8939    /// payload, or unknown tag bytes.
8940    Corrupt(String),
8941    /// v6.0.4 — ALTER INDEX targeted an index name that doesn't
8942    /// exist on any table in this catalog.
8943    IndexNotFound {
8944        name: String,
8945    },
8946    /// v6.0.4 — operation requested isn't supported on this index
8947    /// kind / column type (e.g. ALTER INDEX REBUILD on a `BTree`
8948    /// index, or REBUILD WITH (encoding=…) on a non-vector column).
8949    Unsupported(String),
8950    /// v7.39 (round 220) — a CYCLE-less sequence ran past its bound.
8951    /// PG's 2200H phrasing: `nextval: reached maximum value of
8952    /// sequence "s" (n)` (`is_max: false` = the MINVALUE direction).
8953    SequenceExhausted {
8954        name: String,
8955        limit: i64,
8956        is_max: bool,
8957    },
8958}
8959
8960impl fmt::Display for StorageError {
8961    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
8962        match self {
8963            // v7.39 (read01 round 47) — PG's 42P07 wording.
8964            Self::DuplicateTable { name } => write!(f, "relation \"{name}\" already exists"),
8965            // v7.39 (read01 round 47) — PG's wording for a missing relation
8966            // (42P01). DROP TABLE says "table" and raises its own error at
8967            // the engine; every other path (SELECT / ALTER / …) says
8968            // "relation", which is what this carries.
8969            Self::TableNotFound { name } => write!(f, "relation \"{name}\" does not exist"),
8970            Self::ArityMismatch { expected, actual } => write!(
8971                f,
8972                "row arity mismatch: expected {expected} columns, got {actual}"
8973            ),
8974            Self::TypeMismatch {
8975                column,
8976                expected,
8977                actual,
8978                position,
8979            } => write!(
8980                f,
8981                "type mismatch in column {column:?} (position {position}): expected {expected}, got {actual}"
8982            ),
8983            Self::NullInNotNull { column } => {
8984                // v7.39 (SQLSTATE fidelity) — PG's 23502 phrasing (the
8985                // relation-qualified long form is added by engine call
8986                // sites that know the table name).
8987                write!(
8988                    f,
8989                    "null value in column \"{column}\" violates not-null constraint"
8990                )
8991            }
8992            // v7.39 (read01 round 47) — an index is a relation to PG (42P07).
8993            Self::DuplicateIndex { name } => write!(f, "relation \"{name}\" already exists"),
8994            // v7.39 (round 701) — PG's wording, and the same fix `EvalError::
8995            // ColumnNotFound` took in read01 round 81 with the same reason:
8996            // "column not found: x" matches none of the wire layer's `does
8997            // not exist` patterns, so a missing column reached the client as
8998            // the generic error class. The eval-side variant was changed and
8999            // the storage-side one was not, so which sentence you got
9000            // depended on which layer noticed — `CREATE INDEX ix ON t(nope)`
9001            // came out of storage and kept the old spelling.
9002            Self::ColumnNotFound { column } => write!(f, "column \"{column}\" does not exist"),
9003            Self::Corrupt(detail) => write!(f, "corrupt on-disk format: {detail}"),
9004            Self::IndexNotFound { name } => write!(f, "index \"{name}\" does not exist"),
9005            Self::Unsupported(detail) => write!(f, "unsupported: {detail}"),
9006            // v7.39 (round 220) — PG's exact 2200H wording.
9007            Self::SequenceExhausted {
9008                name,
9009                limit,
9010                is_max,
9011            } => write!(
9012                f,
9013                "nextval: reached {} value of sequence \"{name}\" ({limit})",
9014                if *is_max { "maximum" } else { "minimum" }
9015            ),
9016        }
9017    }
9018}
9019
9020impl ColumnSchema {
9021    pub fn new(name: impl Into<String>, ty: DataType, nullable: bool) -> Self {
9022        Self {
9023            name: name.into(),
9024            ty,
9025            nullable,
9026            collation_name: None,
9027            default: None,
9028            runtime_default: None,
9029            auto_increment: false,
9030            user_enum_type: None,
9031            user_domain_type: None,
9032            user_composite_type: None,
9033            acl: Vec::new(),
9034            on_update_runtime: None,
9035            collation: Collation::Binary,
9036            is_unsigned: false,
9037            inline_enum_variants: None,
9038            inline_set_variants: None,
9039            generated_stored_expr: None,
9040            identity_always: false,
9041            default_text: None,
9042            auto_restart: None,
9043            scalar_row_source: false,
9044            mysql_int_width: None,
9045            mysql_fsp: None,
9046            mysql_declared_timestamp: false,
9047            mysql_float_md: None,
9048        }
9049    }
9050
9051    /// v7.38.14 — the SAME column, re-described.
9052    ///
9053    /// `ColumnSchema::new` is for SYNTHESISING a column: a catalog row, an
9054    /// admin view, a computed output. It sets twenty-two fields to their
9055    /// defaults, which is right when there is no source column to speak of.
9056    ///
9057    /// It is wrong, and quietly so, when there IS one -- a join's combined
9058    /// schema, an aggregate's synthetic keys, a derived table's output. Those
9059    /// sites re-describe an existing column under a new name or type, and
9060    /// have each been written as `new(..)` followed by hand-picking a few
9061    /// attributes to copy across. They all pick differently and none picks
9062    /// them all.
9063    ///
9064    /// Five fields have been lost through that shape so far -- enum identity,
9065    /// MySQL fsp, the PG collation name, `ProjectedItem::fold_exempt`, and
9066    /// the `collation` enum -- and v7.38.14 alone found four sites dropping
9067    /// the last of those. The failure is never loud: `collation` defaults to
9068    /// `Binary`, which downstream reads as "byte-wise ON PURPOSE" rather than
9069    /// as "unknown", so a dropped declaration presents as a deliberate one.
9070    ///
9071    /// This constructor copies everything by construction. A field added to
9072    /// `ColumnSchema` therefore reaches every re-describe site without anyone
9073    /// having to remember, which is the property the hand-written copy lists
9074    /// never had.
9075    ///
9076    /// The two fields a re-describe legitimately changes -- name and
9077    /// nullability -- are parameters. Callers that also retype the column
9078    /// assign `ty` afterwards.
9079    #[must_use]
9080    pub fn rederive(source: &Self, name: impl Into<String>, nullable: bool) -> Self {
9081        Self {
9082            name: name.into(),
9083            nullable,
9084            ..source.clone()
9085        }
9086    }
9087
9088    /// Builder-style helper to attach a default value to an otherwise
9089    /// plain column schema. Used by the engine when CREATE TABLE
9090    /// specifies `column TYPE DEFAULT <expr>`.
9091    #[must_use]
9092    pub fn with_default(mut self, default: Value<'static>) -> Self {
9093        self.default = Some(default);
9094        self
9095    }
9096
9097    /// v7.9.21 — builder for runtime-evaluated defaults
9098    /// (`DEFAULT now()`, `DEFAULT CURRENT_TIMESTAMP`, …).
9099    /// `expr` is the Expr's `Display` form, re-parsed by the
9100    /// engine at each INSERT.
9101    #[must_use]
9102    pub fn with_runtime_default(mut self, expr: impl Into<String>) -> Self {
9103        self.runtime_default = Some(expr.into());
9104        self
9105    }
9106
9107    /// Builder-style helper to mark a column as `AUTO_INCREMENT`.
9108    #[must_use]
9109    pub const fn with_auto_increment(mut self) -> Self {
9110        self.auto_increment = true;
9111        self
9112    }
9113}
9114
9115impl TableSchema {
9116    pub fn new(name: impl Into<String>, columns: Vec<ColumnSchema>) -> Self {
9117        Self {
9118            name: name.into(),
9119            columns,
9120            hot_tier_bytes: None,
9121            foreign_keys: Vec::new(),
9122            uniqueness_constraints: Vec::new(),
9123            exclusion_constraints: Vec::new(),
9124            checks: Vec::new(),
9125            partition_role: None,
9126            policies: Vec::new(),
9127            row_security: false,
9128            force_row_security: false,
9129            owner: None,
9130            acl: Vec::new(),
9131        }
9132    }
9133}
9134
9135// =========================================================================
9136// Persistent binary format for the catalog.
9137//
9138// Layout (little-endian throughout):
9139//
9140//   [magic "SPGDB001" 8 bytes][version u8]
9141//   [table_count u32]
9142//   for each table:
9143//       [name_len u16][name bytes]
9144//       [col_count u16]
9145//       for each col:
9146//           [name_len u16][name bytes]
9147//           [type_tag u8 + optional payload]
9148//               1=Int 2=BigInt 3=Float 4=Text 5=Bool
9149//               6=Vector(u32 dim)
9150//               7=SmallInt
9151//               8=Varchar(u32 max)
9152//               9=Char(u32 size)
9153//               10=Numeric(u8 precision, u8 scale)
9154//               11=Date
9155//               12=Timestamp
9156//           [nullable u8]   0/1
9157//           [default_tag u8] 0=none 1=value (followed by [value_tag u8] + bytes)
9158//       [row_count u32]
9159//       for each row, for each col, one [value_tag u8] + value bytes:
9160//           tag 0 (Null)     → no body
9161//           tag 1 (Int)      → i32 LE
9162//           tag 2 (BigInt)   → i64 LE
9163//           tag 3 (Float)    → f64 LE
9164//           tag 4 (Text)     → u16 LE len + UTF-8 bytes
9165//           tag 5 (Bool)     → u8 0/1
9166//           tag 6 (Vector)   → u32 LE dim + dim×f32 LE
9167//           tag 7 (SmallInt) → i16 LE
9168//           tag 8 (Numeric)  → i128 LE (16 bytes) + u8 scale
9169//           tag 9 (Date)     → i32 LE (days since Unix epoch)
9170//           tag 10 (Timestamp) → i64 LE (microseconds since Unix epoch)
9171//
9172// Bumped to version 3 when NUMERIC was added; to version 4 when
9173// AUTO_INCREMENT (per-column flag) + NSW index `kind` byte landed;
9174// to version 5 when DATE / TIMESTAMP were added; to version 6 when
9175// NSW graph topology started travelling on disk (v2.7); to version 7
9176// when the NSW topology became multi-layer HNSW (v2.13); to version 8
9177// when row encoding switched to schema-driven dense layout (v3.0.2 —
9178// per-row NULL bitmap + per-column fixed-width body, no per-cell type
9179// tag).
9180// =========================================================================
9181
9182const FILE_MAGIC: &[u8; 8] = b"SPGDB001";
9183/// Current catalog snapshot format version emitted by [`Catalog::serialize`].
9184///
9185/// v9 (v5.2) extends v8 by serialising `BTree` index entries directly — every
9186/// `(IndexKey, Vec<RowLocator>)` pair travels on disk with the v5.1
9187/// `RowLocator::write_le` tag-prefixed codec. v8 `BTree` indices stored no
9188/// entries at all (the map was rebuilt from `Table::rows` on load); v9
9189/// preserves on-disk Cold locators so freezer-produced cold-tier index
9190/// entries survive a catalog snapshot round-trip. v8 readers are accepted
9191/// by version dispatch in [`Catalog::deserialize`] — every entry decodes
9192/// as `RowLocator::Hot(_)` via `add_index` rebuild, identical to v5.1
9193/// behaviour.
9194/// v6.7.2 — bumped from 10 to 11 to append per-table
9195/// `hot_tier_bytes: Option<u64>` after the per-table indices
9196/// section. v10 catalogs (v6.7.1) load with `hot_tier_bytes =
9197/// None` for every table (the deserialiser short-circuits when
9198/// version < 11). v11 snapshots written by a pre-v6.7.2 binary
9199/// fail loudly at the version check, matching the v6.1.2 /
9200/// v6.1.4 / v6.2.0 / v6.7.1 envelope-bump upgrade fences.
9201///
9202/// v6.8.0 — bumped from 11 to 12: per-index
9203/// `included_columns: Vec<u16>` appended at the tail of each
9204/// index payload. v11 (= v6.7.2) catalogs load with
9205/// `included_columns = Vec::new()` for every index — same
9206/// "older readers, append-only extension" pattern as the v6.7.2
9207/// hot_tier_bytes byte.
9208/// v7.13.0 — bumped from 22 to 23. mailrs round-5 G3 / G10.
9209/// Per-table appendix gains two new sections:
9210///   * `checks: Vec<String>` — CHECK predicate sources (Display
9211///     form of the AST Expr); re-parsed on INSERT/UPDATE to
9212///     enforce against candidate rows. Same persistence pattern
9213///     as `Index::partial_predicate`.
9214///   * Per `UniquenessConstraint`: trailing `nulls_not_distinct:
9215///     u8` flag for PG 15+ `UNIQUE NULLS NOT DISTINCT (cols)`
9216///     semantics.
9217/// v22 catalogs deserialise with empty `checks` and every UC
9218/// at `nulls_not_distinct = false`.
9219/// v24 introduces:
9220///   * Index kind tag 4 = trigram-GIN (`gin_trgm_ops`-flavoured
9221///     `USING gin` over a TEXT/VARCHAR column). Payload shape is
9222///     identical to tag-3 GIN (String → Vec<RowLocator>); the
9223///     keys are PG-compatible 3-byte trigram shingles instead of
9224///     tsvector lexemes. v23 catalogs deserialise unchanged — no
9225///     v23 writer ever emitted tag 4.
9226/// v25 introduces:
9227///   * Per `TriggerDef`: trailing `enabled: u8` flag (mailrs
9228///     round-9 A.2.b — `ALTER TABLE … { ENABLE | DISABLE }
9229///     TRIGGER …`). v24 catalogs deserialise with every trigger
9230///     `enabled = true`, matching pre-v7.16.1 behaviour.
9231/// v26 introduces (v7.17.0 Phase 1.1):
9232///   * Trailing SEQUENCE catalog block after triggers. Encoded
9233///     as `u32 count` followed by per-sequence:
9234///     `name`, `data_type: u8` (0=SmallInt,1=Int,2=BigInt),
9235///     `start i64`, `increment i64`, `min_value i64`,
9236///     `max_value i64`, `cache i64`, `cycle u8`,
9237///     `owned_by_tag u8` (0=NONE, 1=Column → `table`,`column`),
9238///     `last_value i64`, `is_called u8`. v25-and-below catalogs
9239///     deserialise with an empty sequences map.
9240/// v27 introduces (v7.17.0 Phase 1.2):
9241///   * Trailing VIEW catalog block after sequences. Encoded as
9242///     `u32 count` followed by per-view:
9243///     `name`, `column_count u16`, then column names, then
9244///     `body` long-string. v26-and-below catalogs deserialise
9245///     with an empty views map.
9246/// v28 introduces (v7.17.0 Phase 1.3):
9247///   * Trailing MATERIALIZED VIEW source registry block after
9248///     views. Encoded as `u32 count` followed by per-entry:
9249///     `name`, `body` long-string. The materialised rows live
9250///     as a regular Table of the same name (already covered by
9251///     the pre-existing tables block). v27-and-below catalogs
9252///     deserialise with an empty map.
9253/// v29 introduces (v7.17.0 Phase 1.4):
9254///   * Per-table user_enum_type appendix (after the CHECK
9255///     appendix). Layout: `u16 count` followed by per-binding
9256///     `[u16 col_pos][str enum_name]`. Only columns whose
9257///     `user_enum_type` is Some land here; the catalog stays
9258///     compact for the common no-enum case.
9259///   * Trailing ENUM types catalog block after materialized
9260///     views. Encoded as `u32 count` followed by per-entry:
9261///     `name`, `u16 label_count`, then `label_count` short
9262///     strings. v28-and-below catalogs deserialise with an
9263///     empty enum_types map and every column's
9264///     `user_enum_type = None`.
9265/// v30 introduces (v7.17.0 Phase 1.5):
9266///   * Per-table user_domain_type appendix (after the
9267///     user_enum_type appendix). Same shape as the enum one.
9268///   * Trailing DOMAIN types catalog block after the enum
9269///     block. Encoded as `u32 count` followed by per-entry:
9270///     `name`, `data_type` byte, `nullable u8`,
9271///     `default_present u8` + optional default string,
9272///     `u16 check_count` then `check_count` Display-form
9273///     CHECK strings. v29-and-below catalogs deserialise with
9274///     an empty domain_types map and `user_domain_type = None`.
9275/// v31 introduces (v7.17.0 Phase 1.6):
9276///   * Trailing user-schemas block after the DOMAIN block.
9277///     Encoded as `u32 count` followed by `count` schema-name
9278///     short strings. Built-in schemas (`public`, `pg_catalog`,
9279///     `information_schema`) are NOT serialised — they're
9280///     hardcoded in `is_builtin_schema`. v30-and-below catalogs
9281///     deserialise with an empty user-schemas set.
9282/// v32 introduces (v7.17.0 Phase 2.1):
9283///   * Per-table on_update_runtime appendix (after the
9284///     user_domain_type appendix). Layout: `u16 count` followed
9285///     by per-binding `[u16 col_pos][str expr_src]`. Only
9286///     columns whose `on_update_runtime` is Some land here;
9287///     the catalog stays compact when no MySQL-shaped table
9288///     uses the attribute. v31-and-below catalogs deserialise
9289///     with every column's `on_update_runtime = None`.
9290/// v33 introduces (v7.17.0 Phase 2.2):
9291///   * Index kind tag 5 = fulltext-GIN (MySQL `FULLTEXT KEY`
9292///     surface over a TEXT / VARCHAR column). Payload shape is
9293///     identical to tag-3 / tag-4 GIN (`String → Vec<RowLocator>`);
9294///     the keys are lower-cased word lexemes (same rule as
9295///     `to_tsvector('simple', text)`). v32 catalogs deserialise
9296///     unchanged — no v32 writer ever emitted tag 5, and FULLTEXT
9297///     KEY was silently dropped pre-v7.17 so no rebuild shim is
9298///     needed for round-tripped catalogs.
9299/// v34 introduces (v7.17.0 Phase 2.5):
9300///   * Per-table collation appendix (after the on_update_runtime
9301///     appendix). Sparse layout: only columns whose `collation`
9302///     is non-Binary land here. `u16 count` then per-binding
9303///     `[u16 col_pos][u8 collation_tag]` where the tag matches
9304///     `Collation::TAG_*`. Snapshots written by v33-and-below
9305///     readers deserialise every column with `collation =
9306///     Binary`, preserving the prior byte-wise compare
9307///     semantics. Unknown tags read back as Binary too — keeps
9308///     a forward-compat path if a future v35 adds variants
9309///     and someone rolls back to a v34 reader.
9310/// v35 introduces (v7.17.0 Phase 4.4):
9311///   * Per-table is_unsigned appendix (after the collation
9312///     appendix). Sparse layout: only `is_unsigned = true`
9313///     columns land. `u16 count` then per-binding `[u16 col_pos]`.
9314///     v34-and-below catalogs deserialise every column as
9315///     `is_unsigned = false`, preserving the prior silent-
9316///     accept behaviour for negative inserts on UNSIGNED columns.
9317/// v46 introduces (v7.23, mailrs round-14):
9318///   * Escaped short-string codec — `write_str` lengths >= 0xFFFF
9319///     emit `[u16 0xFFFF][u32 real_len]` so TEXT cells (mail bodies,
9320///     document text) above 64 KiB encode instead of panicking.
9321///     One-way upgrade: v45-and-below readers reject v46 catalogs
9322///     loudly via the version gate; v46 readers decode v45 catalogs
9323///     with the plain-u16 rules (0xFFFF is a legitimate length
9324///     there).
9325/// v47 introduces (v7.27, mailrs round-21):
9326///   * Escaped lengths for the REMAINING u16-length cell payloads —
9327///     BYTEA cells, TEXT[] elements, tsvector lexemes and tsquery
9328///     terms — the same `[u16 0xFFFF][u32 real_len]` escape v46
9329///     gave short strings. Round-14 fixed TEXT and missed these;
9330///     round-21 fired the BYTEA twin during a production migration.
9331///     One-way upgrade, same posture as v46.
9332/// v48 introduces (v7.37.5 β-P2, sentori cutover window):
9333///   * `INTERVAL` becomes a real column type. Catalog tag 34 in
9334///     `write_data_type`; per-row body is a fixed 16 bytes
9335///     (i64 micros + i32 days + i32 months, LE, PG-byte-equal
9336///     field order). The runtime-only days collapse is gone —
9337///     `'1 day'` and `'24 hours'` are stored distinctly. One-way
9338///     upgrade: v47 catalogs without INTERVAL columns deserialise
9339///     identically; v47 readers fed a v48 catalog that contains
9340///     INTERVAL hit the explicit "unknown data type tag: 34"
9341///     fence in `read_data_type`.
9342/// v49 introduces (v7.37.6-B, sentori Epic 2 P0):
9343///   * Per-table partition role appendix(declarative
9344///     `PARTITION BY RANGE` parent / range child / DEFAULT
9345///     child)。Layout, written **after** the inline_set_variants
9346///     appendix and **before** the per-table block close:
9347///       `[u8 role_tag]`
9348///         0 = `None`(普通表,后向兼容默认)
9349///         1 = `Parent`:  `[u8 kind_tag (0=Range)]`
9350///                        `[u16 key_col_count]` `(× u16 col_pos)`
9351///                        `[u16 tmpl_count]` `(× str source)`
9352///         2 = `Range`:   `[str parent_name]` `[Bound]` `[Bound]`
9353///         3 = `Default`: `[str parent_name]`
9354///     `PartitionBound` codec:
9355///       `[u8 bound_tag]` 0=MinValue 1=MaxValue 2=TimestampTz(`[i64 LE micros]`)
9356///     v48-and-below readers stop after the inline_set_variants
9357///     block — they don't see this appendix and deserialise every
9358///     table with `partition_role = None`. v49 writers always emit
9359///     `[0]` for plain tables, so the encoding stays one-byte-cheap.
9360/// v50 introduces (v7.37.7, sentori Epic 3 P1):
9361///   * Per-table `generated_stored_expr` appendix(stored generated
9362///     columns — `GENERATED ALWAYS AS (<expr>) STORED`)。Layout,
9363///     written **after** the partition_role appendix and before
9364///     the per-table block close:
9365///       `[u16 binding_count]`
9366///       `binding_count × { [u16 col_pos][str expr_source] }`
9367///     Sparse — only generated columns land here, so plain-shape
9368///     catalogs stay byte-for-byte identical save for the new
9369///     u16 zero count. v49-and-below readers stop after the
9370///     partition_role appendix; v50 readers default every column
9371///     to `generated_stored_expr = None` when this block is absent.
9372/// v51 introduces (v7.37.8, sentori Epic 5 P2):
9373///   * Per-index tag byte 6 = `GinJsonb`(real posting-list GIN
9374///     over a JSONB column). Payload shape mirrors tag-3 / 4 / 5:
9375///     `[u32 posting_list_count]` then `(str token, u32 locator_count,
9376///     locators …)` per posting list. Same `write_str` /
9377///     `RowLocator::write_le` codec as the rest of the GIN family.
9378///     v50 catalogs never wrote tag 6(the same DDL loaded as a
9379///     BTree fallback); v51 readers see tag 6 explicitly and dispatch
9380///     into `IndexKind::GinJsonb`.
9381/// v52 introduces (v7.37.42-T2 ζ-B composite + domain metasystem):
9382///   * Trailing COMPOSITE-types catalog block after the
9383///     user-schemas block. Encoded as `u32 count` followed by
9384///     per-entry: `name`, `u16 field_count`, then `field_count`
9385///     `[str field_name][data_type]` pairs (`write_data_type` is
9386///     reused). v51-and-below catalogs deserialise with an empty
9387///     composite_types map; v52 readers tolerate v51 catalogs by
9388///     stopping at the schema block (no composite block present
9389///     ⇒ empty map). Composite types are referenced by columns
9390///     via `ColumnSchema.user_composite_type`, mirroring the
9391///     `user_enum_type` / `user_domain_type` pattern. The block
9392///     lands here (not as a per-table appendix) so dropping the
9393///     composite type registers globally and DROP TYPE can find it
9394///     without a table scan.
9395/// v53 introduces (v7.37.16 Epic W — cross-checkpoint tombstone
9396///   durability):
9397///   * Trailing per-table MVCC appendix carrying, for every row,
9398///     its `RowHeader` (`xmin:u64`, `xmax:u64`, `flags:u8`) and its
9399///     stable `RowId` (`u64`), followed by the relation's
9400///     `next_rowid:u64`. Layout per table (after the v50
9401///     generated_stored_expr block, before the table loop closes):
9402///       `[u32 row_count]` (== `Table::rows().len()`, cross-check)
9403///       per row in physical order:
9404///         `[u64 xmin][u64 xmax][u8 flags][u64 rowid]`
9405///       `[u64 next_rowid]`
9406///     v52-and-below catalogs never wrote this block; their reader
9407///     stops after the last per-table appendix and
9408///     `deserialize_rows` leaves every row `RowHeader::frozen()`
9409///     with dense 1..=N ids — the exact pre-v53 contract. A v53
9410///     reader instead reconstructs headers + ids VERBATIM, so a
9411///     tombstone-redo naming a row inserted before the last
9412///     checkpoint resolves by `RowId` across the base-snapshot
9413///     boundary (closing the coupling the Epic W WAL slices deferred
9414///     to this format bump). Because the reader routes on `version`,
9415///     the block is strictly backward-compatible: old images load
9416///     byte-for-byte as before. `SPG_MVCC_INPLACE` is unaffected —
9417///     a gate-off database's rows are all frozen/alive, so
9418///     persisting + restoring their headers is observationally a
9419///     no-op.
9420/// v7.38 (read01 P5.05) — v54 appends a CRC32C over the whole preceding
9421/// image so a corrupted `base.spg` is caught on load instead of silently
9422/// deserialising garbage. Older images (v8..=53) carry no trailer and load
9423/// unchanged.
9424/// v7.39 (round 210) — v72 appends a per-table EXCLUDE-constraint appendix
9425/// (sparse: only tables carrying an EXCLUDE write it) at the very end of the
9426/// per-table block, after the column-ACL appendix. A v71 reader stops before
9427/// it and its tables read back with no exclusion constraints, which is what
9428/// they were.
9429/// v7.39 (round 220) — v73 appends a per-table identity-RESTART appendix
9430/// (sparse: [u16 count] then per entry [u16 col_pos][i64 LE floor]) after
9431/// the EXCLUDE appendix. A v72 reader stops before it; its columns read
9432/// back with no RESTART floor, losing only an un-consumed
9433/// `ALTER … RESTART WITH` across a restart.
9434/// r1039 — v90 adds index-key tags 4 (bytea) and 5 (the canonical
9435/// numeric key), so BYTEA and NUMERIC columns carry a real B-tree
9436/// instead of falling back to a scan. A v89 reader meeting either tag
9437/// reports a corrupt catalog rather than mis-reading it, which is the
9438/// same forward-compatibility story tag 3 (uuid) had at v36.
9439const FILE_VERSION: u8 = 94;
9440
9441/// v7.37 (round 833) — the codec version to decode a row that
9442/// [`encode_row_body_dense`] has just produced.
9443///
9444/// That encoder always writes the newest form, and every decoder gate is
9445/// a `codec_version >= N` feature test, so a freshly encoded row must be
9446/// read at the current version. Cold segments carry their own version in
9447/// their header and keep passing that; this is for in-process round
9448/// trips — sort runs on temp storage — where the bytes never outlive the
9449/// build that wrote them.
9450pub const CURRENT_ROW_CODEC_VERSION: u8 = FILE_VERSION;
9451/// First version that appends the trailing CRC32C integrity trailer.
9452const FILE_VERSION_CRC_TRAILER: u8 = 54;
9453/// Oldest format version [`Catalog::deserialize`] still accepts. v8 is the
9454/// v3.0.2 dense-row layout; pre-v8 catalogs require an offline migration.
9455const MIN_SUPPORTED_FILE_VERSION: u8 = 8;
9456
9457// IndexKey wire format (v9):
9458//   tag 0 = Int  → [i64 LE]
9459//   tag 1 = Text → [u16 LE len + UTF-8 bytes] (via write_str / read_str)
9460//   tag 2 = Bool → [u8 0/1]
9461const INDEX_KEY_TAG_INT: u8 = 0;
9462const INDEX_KEY_TAG_TEXT: u8 = 1;
9463const INDEX_KEY_TAG_BOOL: u8 = 2;
9464/// v7.17.0 — `IndexKey::Uuid([u8; 16])`. Body = raw 16 bytes
9465/// (RFC 4122 byte order). Persisted only in FILE_VERSION 36+
9466/// catalogs.
9467const INDEX_KEY_TAG_UUID: u8 = 3;
9468/// r1039 — `IndexKey::Bytes`. Body = [u32 LE len][raw bytes].
9469/// Persisted only in FILE_VERSION 90+ catalogs.
9470const INDEX_KEY_TAG_BYTES: u8 = 4;
9471/// r1039 — `IndexKey::Numeric`. Body = [u8 class][u8 neg][i32 LE exp]
9472/// [u32 LE digit count][one byte per decimal digit, 0..=9, MSD first].
9473/// Persisted only in FILE_VERSION 90+ catalogs.
9474const INDEX_KEY_TAG_NUMERIC: u8 = 5;
9475/// v7.38.1 (L12) — `IndexKey::Null`, a NULL component inside a
9476/// composite key. No body. Persisted only inside tag-7 multi-index
9477/// payloads, FILE_VERSION 91+.
9478const INDEX_KEY_TAG_NULL: u8 = 6;
9479
9480impl Catalog {
9481    /// Serialize the whole catalog (schema + every row) into a self-contained
9482    /// byte buffer. Format is documented above the impl block.
9483    pub fn serialize(&self) -> Vec<u8> {
9484        let mut out = Vec::with_capacity(64);
9485        out.extend_from_slice(FILE_MAGIC);
9486        out.push(FILE_VERSION);
9487        write_u32(
9488            &mut out,
9489            u32::try_from(self.tables.len()).expect("≤ 4G tables"),
9490        );
9491        for t in &self.tables {
9492            write_str(&mut out, &t.schema.name);
9493            write_u16(
9494                &mut out,
9495                u16::try_from(t.schema.columns.len()).expect("≤ 65k columns/table"),
9496            );
9497            for c in &t.schema.columns {
9498                write_str(&mut out, &c.name);
9499                write_data_type(&mut out, c.ty);
9500                out.push(u8::from(c.nullable));
9501                match &c.default {
9502                    None => out.push(0),
9503                    Some(v) => {
9504                        out.push(1);
9505                        write_value(&mut out, v);
9506                    }
9507                }
9508                out.push(u8::from(c.auto_increment));
9509            }
9510            write_u32(
9511                &mut out,
9512                u32::try_from(t.rows.len()).expect("≤ 4G rows/table"),
9513            );
9514            // v3.0.2 dense row encoding (FILE_VERSION 8): per-row NULL
9515            // bitmap, then tightly-packed bodies. Identical wire format
9516            // as before — extracted into `encode_row_body_dense` so cold-
9517            // tier segments (v5.1+) can share the encoding.
9518            for row in &t.rows {
9519                out.extend_from_slice(&encode_row_body_dense(row, &t.schema));
9520            }
9521            // Index definitions. Per-index payload:
9522            //   [name][col_pos u16][kind u8]
9523            //     kind 0 = B-tree           (no params — rebuilt on load)
9524            //     kind 1 = NSW graph        (u16 M + serialized graph)
9525            // For NSW the graph topology travels on disk so startup
9526            // doesn't re-run the O(n²M) rebuild — see v2.7 notes.
9527            write_u16(
9528                &mut out,
9529                u16::try_from(t.indices.len()).expect("≤ 65k indices/table"),
9530            );
9531            for idx in &t.indices {
9532                write_str(&mut out, &idx.name);
9533                write_u16(
9534                    &mut out,
9535                    u16::try_from(idx.column_position).expect("≤ 65k columns/table"),
9536                );
9537                match &idx.kind {
9538                    IndexKind::BTree(map) => {
9539                        out.push(0);
9540                        // v9: serialise the full PB map. Each entry's
9541                        // RowLocator list travels with the tag-prefixed
9542                        // codec from `row_locator::write_le`, so freezer-
9543                        // produced Cold locators survive a snapshot
9544                        // round-trip. v8 BTree wrote nothing here and
9545                        // rebuilt from rows — v9 readers tolerate v8 by
9546                        // version dispatch in `Catalog::deserialize`.
9547                        write_u32(
9548                            &mut out,
9549                            u32::try_from(map.len()).expect("≤ 4G index entries/index"),
9550                        );
9551                        for (key, locators) in map {
9552                            write_index_key(&mut out, key);
9553                            write_u32(
9554                                &mut out,
9555                                u32::try_from(locators.len()).expect("≤ 4G locators/key"),
9556                            );
9557                            for loc in locators {
9558                                loc.write_le(&mut out);
9559                            }
9560                        }
9561                    }
9562                    // v7.38.1 (L12) — tag byte 7 = BTreeMulti. Payload
9563                    // mirrors the tag-0 BTree encoding, with each key
9564                    // written as `[u16 arity]` followed by that many
9565                    // `write_index_key` components. FILE_VERSION 91+;
9566                    // older catalogs never carried a multi index, so no
9567                    // migration shim is needed.
9568                    IndexKind::BTreeMulti(map) => {
9569                        out.push(7);
9570                        write_u32(
9571                            &mut out,
9572                            u32::try_from(map.len()).expect("≤ 4G index entries/index"),
9573                        );
9574                        for (key, locators) in map {
9575                            write_u16(
9576                                &mut out,
9577                                u16::try_from(key.len()).expect("≤ 65k key components"),
9578                            );
9579                            for component in key.iter() {
9580                                write_index_key(&mut out, component);
9581                            }
9582                            write_u32(
9583                                &mut out,
9584                                u32::try_from(locators.len()).expect("≤ 4G locators/key"),
9585                            );
9586                            for loc in locators {
9587                                loc.write_le(&mut out);
9588                            }
9589                        }
9590                    }
9591                    IndexKind::Nsw(g) => {
9592                        out.push(1);
9593                        write_u16(&mut out, u16::try_from(g.m).expect("≤ 65k NSW neighbours"));
9594                        write_nsw_graph(&mut out, g);
9595                    }
9596                    IndexKind::Brin { column_type, .. } => {
9597                        // v6.7.1 — tag byte 2 = BRIN. Payload is the
9598                        // column type code (1 byte mapping to the
9599                        // shared DataType numeric encoding); no
9600                        // further data — BRIN summaries live in
9601                        // cold segments, not the catalog.
9602                        out.push(2);
9603                        write_data_type(&mut out, *column_type);
9604                    }
9605                    IndexKind::Gin(map) => {
9606                        // v7.12.3 — tag byte 3 = GIN. Payload mirrors
9607                        // the BTree encoding but with String (lexeme
9608                        // word) keys instead of IndexKey. Tag-prefixed
9609                        // RowLocator codec so freezer-produced Cold
9610                        // locators survive snapshot round-trip.
9611                        // FILE_VERSION 21+; v20 catalogs never wrote a
9612                        // GIN index (the AM degraded to BTree fallback
9613                        // pre-v7.12.3), so no migration shim is needed.
9614                        out.push(3);
9615                        write_u32(
9616                            &mut out,
9617                            u32::try_from(map.len()).expect("≤ 4G GIN posting lists"),
9618                        );
9619                        for (word, locators) in map {
9620                            write_str(&mut out, word);
9621                            write_u32(
9622                                &mut out,
9623                                u32::try_from(locators.len()).expect("≤ 4G locators/posting list"),
9624                            );
9625                            for loc in locators {
9626                                loc.write_le(&mut out);
9627                            }
9628                        }
9629                    }
9630                    IndexKind::GinTrgm(map) => {
9631                        // v7.15.0 — tag byte 4 = GinTrgm
9632                        // (`gin_trgm_ops` GIN over a TEXT column).
9633                        // Payload shape is identical to tag-3 GIN —
9634                        // `String → Vec<RowLocator>` posting lists.
9635                        // The String keys are 3-byte trigrams instead
9636                        // of tsvector lexemes; the deserializer
9637                        // dispatches on the tag, not the key shape.
9638                        // FILE_VERSION 24+; v23 catalogs never wrote
9639                        // a trigram-GIN.
9640                        out.push(4);
9641                        write_u32(
9642                            &mut out,
9643                            u32::try_from(map.len()).expect("≤ 4G trigram-GIN posting lists"),
9644                        );
9645                        for (tri, locators) in map {
9646                            write_str(&mut out, tri);
9647                            write_u32(
9648                                &mut out,
9649                                u32::try_from(locators.len()).expect("≤ 4G locators/posting list"),
9650                            );
9651                            for loc in locators {
9652                                loc.write_le(&mut out);
9653                            }
9654                        }
9655                    }
9656                    IndexKind::GinFulltext(map) => {
9657                        // v7.17.0 Phase 2.2 — tag byte 5 =
9658                        // GinFulltext (MySQL `FULLTEXT KEY` GIN
9659                        // over a TEXT/VARCHAR column). Payload
9660                        // shape mirrors tag-3 / tag-4 GIN —
9661                        // `String → Vec<RowLocator>` posting
9662                        // lists keyed by lower-cased word
9663                        // lexemes. FILE_VERSION 33+; v32 catalogs
9664                        // never wrote a fulltext-GIN (FULLTEXT
9665                        // KEY was silently dropped pre-v7.17).
9666                        out.push(5);
9667                        write_u32(
9668                            &mut out,
9669                            u32::try_from(map.len()).expect("≤ 4G fulltext-GIN posting lists"),
9670                        );
9671                        for (lex, locators) in map {
9672                            write_str(&mut out, lex);
9673                            write_u32(
9674                                &mut out,
9675                                u32::try_from(locators.len()).expect("≤ 4G locators/posting list"),
9676                            );
9677                            for loc in locators {
9678                                loc.write_le(&mut out);
9679                            }
9680                        }
9681                    }
9682                    IndexKind::GinJsonb(map) => {
9683                        // v7.37.8 — tag byte 6 = GinJsonb
9684                        // (real posting-list GIN over a JSONB
9685                        // column; sentori Epic 5 P2). Payload
9686                        // shape mirrors tag-3 / 4 / 5 — keys are
9687                        // the canonical `(path, leaf)` tokens
9688                        // from `jsonb_gin::extract_tokens`.
9689                        // FILE_VERSION 51+; v50 catalogs never
9690                        // wrote a JSONB-GIN (the same DDL loaded
9691                        // as a BTree fallback).
9692                        out.push(6);
9693                        write_u32(
9694                            &mut out,
9695                            u32::try_from(map.len()).expect("≤ 4G JSONB-GIN posting lists"),
9696                        );
9697                        for (token, locators) in map {
9698                            write_str(&mut out, token);
9699                            write_u32(
9700                                &mut out,
9701                                u32::try_from(locators.len()).expect("≤ 4G locators/posting list"),
9702                            );
9703                            for loc in locators {
9704                                loc.write_le(&mut out);
9705                            }
9706                        }
9707                    }
9708                }
9709                // v6.8.0 — included_columns appendix per index.
9710                // Layout: [u16 num_included][num × u16 column_position].
9711                // v11 readers stop before this u16 (deserialise loop
9712                // gated on version >= 12); v12+ readers always
9713                // consume it. Empty Vec serialises as a bare 0u16.
9714                write_u16(
9715                    &mut out,
9716                    u16::try_from(idx.included_columns.len()).expect("≤ 65k INCLUDE columns/index"),
9717                );
9718                for col_pos in &idx.included_columns {
9719                    write_u16(
9720                        &mut out,
9721                        u16::try_from(*col_pos).expect("≤ 65k columns/table"),
9722                    );
9723                }
9724                // v6.8.1 — partial_predicate appendix per index.
9725                // Layout: [u8 has_pred][u16 LE len][bytes (if has_pred)].
9726                // Same v12 gate as included_columns.
9727                match &idx.partial_predicate {
9728                    None => out.push(0),
9729                    Some(pred) => {
9730                        out.push(1);
9731                        write_str(&mut out, pred);
9732                    }
9733                }
9734                // v6.8.2 — expression appendix. Same shape as
9735                // partial_predicate.
9736                match &idx.expression {
9737                    None => out.push(0),
9738                    Some(expr) => {
9739                        out.push(1);
9740                        write_str(&mut out, expr);
9741                    }
9742                }
9743                // v7.9.29 — is_unique appendix (FILE_VERSION 16+).
9744                // Single byte 0/1. v15-and-below readers stop before
9745                // this byte; v16 readers always consume it. mailrs K1.
9746                out.push(u8::from(idx.is_unique));
9747                // v7.9.29 — extra_column_positions appendix.
9748                // Layout: [u16 count][count × u16 column_position].
9749                write_u16(
9750                    &mut out,
9751                    u16::try_from(idx.extra_column_positions.len())
9752                        .expect("≤ 65k extra cols / index"),
9753                );
9754                for cp in &idx.extra_column_positions {
9755                    write_u16(&mut out, u16::try_from(*cp).expect("≤ 65k columns/table"));
9756                }
9757                // v7.39 (read01 round 52) — nulls_not_distinct (FILE_VERSION
9758                // 62+). Appended at the end of the per-index block so the v16
9759                // layout above is untouched; v61-and-below readers stop before
9760                // this byte and default the flag to false (NULLS DISTINCT).
9761                out.push(u8::from(idx.nulls_not_distinct));
9762                // v7.39 (round 537) — the key column's ordering clause
9763                // (FILE_VERSION 83+).
9764                out.push(u8::from(idx.descending));
9765                out.push(match idx.nulls_first {
9766                    None => 0,
9767                    Some(true) => 1,
9768                    Some(false) => 2,
9769                });
9770                // v7.39 (round 538) — the key's explicit collation
9771                // (FILE_VERSION 84+).
9772                match &idx.collation {
9773                    Some(c) => {
9774                        out.push(1);
9775                        write_str(&mut out, c);
9776                    }
9777                    None => out.push(0),
9778                }
9779            }
9780            // v6.7.2 — per-table hot_tier_bytes Option<u64>.
9781            // Layout: [u8 has_value][u64 LE value (if has_value)].
9782            // v10 readers stop before this byte (deserialise loop
9783            // gated on version >= 11); v11+ readers always
9784            // consume it.
9785            match t.schema.hot_tier_bytes {
9786                None => out.push(0),
9787                Some(n) => {
9788                    out.push(1);
9789                    out.extend_from_slice(&n.to_le_bytes());
9790                }
9791            }
9792            // v7.6.1 — FOREIGN KEY appendix (catalog FILE_VERSION 13+).
9793            // Layout: [u16 LE fk_count]
9794            //   per fk:
9795            //     [u8 has_name] [str name (if has_name)]
9796            //     [u16 LE local_arity] [u16 LE local_pos]*arity
9797            //     [str parent_table]
9798            //     [u16 LE parent_arity] [u16 LE parent_pos]*arity
9799            //     [u8 on_delete_tag] [u8 on_update_tag]
9800            // Older catalogs (v12 and below) skip this block entirely;
9801            // their reader stops before this byte.
9802            write_u16(
9803                &mut out,
9804                u16::try_from(t.schema.foreign_keys.len()).expect("≤ 65k FKs/table"),
9805            );
9806            for fk in &t.schema.foreign_keys {
9807                match &fk.name {
9808                    None => out.push(0),
9809                    Some(n) => {
9810                        out.push(1);
9811                        write_str(&mut out, n);
9812                    }
9813                }
9814                write_u16(
9815                    &mut out,
9816                    u16::try_from(fk.local_columns.len()).expect("≤ 65k FK columns"),
9817                );
9818                for &p in &fk.local_columns {
9819                    write_u16(&mut out, u16::try_from(p).expect("≤ 65k columns/table"));
9820                }
9821                write_str(&mut out, &fk.parent_table);
9822                write_u16(
9823                    &mut out,
9824                    u16::try_from(fk.parent_columns.len()).expect("≤ 65k FK parent columns"),
9825                );
9826                for &p in &fk.parent_columns {
9827                    write_u16(&mut out, u16::try_from(p).expect("≤ 65k columns/table"));
9828                }
9829                out.push(fk.on_delete.tag());
9830                out.push(fk.on_update.tag());
9831                // v7.38 (read01, T29) — MATCH type tag (FILE_VERSION 55+).
9832                out.push(fk.match_type.tag());
9833                // v7.39 (round 288) — constraint timing (FILE_VERSION 79+).
9834                // One byte, bit 0 = DEFERRABLE, bit 1 = INITIALLY DEFERRED.
9835                out.push(u8::from(fk.deferrable) | (u8::from(fk.initially_deferred) << 1));
9836            }
9837            // v7.9.19 — UniquenessConstraint appendix (catalog
9838            // FILE_VERSION 15+). Layout per table after the FK
9839            // block:
9840            //   [u16 count]
9841            //     per constraint:
9842            //       [u8 is_primary_key]
9843            //       [u16 arity][u16 col_pos]*arity
9844            // Older catalogs (v14 and below) skip this block.
9845            write_u16(
9846                &mut out,
9847                u16::try_from(t.schema.uniqueness_constraints.len())
9848                    .expect("≤ 65k uniqueness constraints/table"),
9849            );
9850            for uc in &t.schema.uniqueness_constraints {
9851                out.push(u8::from(uc.is_primary_key));
9852                write_u16(
9853                    &mut out,
9854                    u16::try_from(uc.columns.len()).expect("≤ 65k cols in uniqueness constraint"),
9855                );
9856                for &p in &uc.columns {
9857                    write_u16(&mut out, u16::try_from(p).expect("≤ 65k columns/table"));
9858                }
9859                // v7.13.0 — `nulls_not_distinct` flag
9860                // (FILE_VERSION 23+). Always written by writers at
9861                // version 23+; deserialise gates on `version >= 23`
9862                // so v22-and-below catalogs round-trip cleanly.
9863                out.push(u8::from(uc.nulls_not_distinct));
9864            }
9865            // v7.9.21 — runtime_default appendix per table.
9866            // Layout: [u16 count] then for each:
9867            //   [u16 col_pos][str expr]
9868            // Only columns whose runtime_default is Some land here;
9869            // catalog stays compact for the common literal-default
9870            // case.
9871            let mut rt_defaults: Vec<(usize, &str)> = Vec::new();
9872            for (i, c) in t.schema.columns.iter().enumerate() {
9873                if let Some(e) = &c.runtime_default {
9874                    rt_defaults.push((i, e.as_str()));
9875                }
9876            }
9877            write_u16(
9878                &mut out,
9879                u16::try_from(rt_defaults.len()).expect("≤ 65k runtime defaults/table"),
9880            );
9881            for (pos, expr) in rt_defaults {
9882                write_u16(&mut out, u16::try_from(pos).expect("≤ 65k columns/table"));
9883                write_str(&mut out, expr);
9884            }
9885            // v7.13.0 — CHECK constraint appendix per table.
9886            // Layout: [u16 count] then `count` Display-form
9887            // expression strings. Re-parsed on every INSERT/UPDATE
9888            // by the engine. FILE_VERSION 23+ only; v22 readers
9889            // never reach this block because the writer also moves
9890            // to v23 in lock-step.
9891            write_u16(
9892                &mut out,
9893                u16::try_from(t.schema.checks.len()).expect("≤ 65k CHECK constraints/table"),
9894            );
9895            for c in &t.schema.checks {
9896                // v7.39 (read01 round 48) — the expr stays in this v23
9897                // appendix (byte layout unchanged for old readers); the
9898                // name rides the v60 constraint-name appendix at the tail.
9899                write_str(&mut out, c.expr.as_str());
9900            }
9901            // v7.17.0 Phase 1.4 — per-table user_enum_type
9902            // appendix. Layout: [u16 count] then
9903            // [u16 col_pos][str enum_name] per binding. Only
9904            // columns whose user_enum_type is Some land here.
9905            let mut enum_bindings: Vec<(usize, &str)> = Vec::new();
9906            for (i, c) in t.schema.columns.iter().enumerate() {
9907                if let Some(e) = &c.user_enum_type {
9908                    enum_bindings.push((i, e.as_str()));
9909                }
9910            }
9911            write_u16(
9912                &mut out,
9913                u16::try_from(enum_bindings.len()).expect("≤ 65k enum-typed columns/table"),
9914            );
9915            for (pos, ename) in enum_bindings {
9916                write_u16(&mut out, u16::try_from(pos).expect("≤ 65k columns/table"));
9917                write_str(&mut out, ename);
9918            }
9919            // v7.17.0 Phase 1.5 — per-table user_domain_type
9920            // appendix. Same layout as the enum one. v29-and-
9921            // below readers stop after the enum appendix.
9922            let mut domain_bindings: Vec<(usize, &str)> = Vec::new();
9923            for (i, c) in t.schema.columns.iter().enumerate() {
9924                if let Some(d) = &c.user_domain_type {
9925                    domain_bindings.push((i, d.as_str()));
9926                }
9927            }
9928            write_u16(
9929                &mut out,
9930                u16::try_from(domain_bindings.len()).expect("≤ 65k domain-typed columns/table"),
9931            );
9932            for (pos, dname) in domain_bindings {
9933                write_u16(&mut out, u16::try_from(pos).expect("≤ 65k columns/table"));
9934                write_str(&mut out, dname);
9935            }
9936            // v7.17.0 Phase 2.1 — per-table on_update_runtime
9937            // appendix. Sparse: only ON UPDATE-bound columns.
9938            let mut on_update_bindings: Vec<(usize, &str)> = Vec::new();
9939            for (i, c) in t.schema.columns.iter().enumerate() {
9940                if let Some(e) = &c.on_update_runtime {
9941                    on_update_bindings.push((i, e.as_str()));
9942                }
9943            }
9944            write_u16(
9945                &mut out,
9946                u16::try_from(on_update_bindings.len()).expect("≤ 65k ON UPDATE columns/table"),
9947            );
9948            for (pos, expr_src) in on_update_bindings {
9949                write_u16(&mut out, u16::try_from(pos).expect("≤ 65k columns/table"));
9950                write_str(&mut out, expr_src);
9951            }
9952            // v7.17.0 Phase 2.5 — per-table collation appendix.
9953            // Sparse: only non-Binary columns land. Layout:
9954            // `[u16 count][u16 col_pos][u8 tag] × count`.
9955            let mut coll_bindings: Vec<(usize, u8)> = Vec::new();
9956            for (i, c) in t.schema.columns.iter().enumerate() {
9957                let tag = match c.collation {
9958                    Collation::Binary => continue,
9959                    Collation::CaseInsensitive => Collation::TAG_CASE_INSENSITIVE,
9960                };
9961                coll_bindings.push((i, tag));
9962            }
9963            write_u16(
9964                &mut out,
9965                u16::try_from(coll_bindings.len()).expect("≤ 65k collation bindings/table"),
9966            );
9967            for (pos, tag) in coll_bindings {
9968                write_u16(&mut out, u16::try_from(pos).expect("≤ 65k columns/table"));
9969                out.push(tag);
9970            }
9971            // v7.17.0 Phase 4.4 — per-table is_unsigned appendix.
9972            // Sparse: only UNSIGNED columns land. Layout:
9973            // `[u16 count][u16 col_pos] × count`.
9974            let mut unsigned_bindings: Vec<usize> = Vec::new();
9975            for (i, c) in t.schema.columns.iter().enumerate() {
9976                if c.is_unsigned {
9977                    unsigned_bindings.push(i);
9978                }
9979            }
9980            write_u16(
9981                &mut out,
9982                u16::try_from(unsigned_bindings.len()).expect("≤ 65k UNSIGNED columns/table"),
9983            );
9984            for pos in unsigned_bindings {
9985                write_u16(&mut out, u16::try_from(pos).expect("≤ 65k columns/table"));
9986            }
9987            // v7.17.0 Phase 3.P0-36 — per-table inline_enum_variants
9988            // appendix. Sparse: only ENUM columns land. Layout:
9989            // `[u16 count] then per binding [u16 col_pos]
9990            // [u16 variant_count] then variant strings`.
9991            // FILE_VERSION 41+; v40 readers never reach this block.
9992            let mut enum_inline_bindings: Vec<(usize, &[String])> = Vec::new();
9993            for (i, c) in t.schema.columns.iter().enumerate() {
9994                if let Some(vs) = &c.inline_enum_variants {
9995                    enum_inline_bindings.push((i, vs.as_slice()));
9996                }
9997            }
9998            write_u16(
9999                &mut out,
10000                u16::try_from(enum_inline_bindings.len()).expect("≤ 65k inline-ENUM columns/table"),
10001            );
10002            for (pos, variants) in enum_inline_bindings {
10003                write_u16(&mut out, u16::try_from(pos).expect("≤ 65k columns/table"));
10004                write_u16(
10005                    &mut out,
10006                    u16::try_from(variants.len()).expect("≤ 65k variants/ENUM"),
10007                );
10008                for v in variants {
10009                    write_str(&mut out, v.as_str());
10010                }
10011            }
10012            // v7.17.0 Phase 3.P0-37 — per-table inline_set_variants
10013            // appendix. Same layout as the inline ENUM block.
10014            // FILE_VERSION 42+; v41 readers never reach this block.
10015            let mut set_inline_bindings: Vec<(usize, &[String])> = Vec::new();
10016            for (i, c) in t.schema.columns.iter().enumerate() {
10017                if let Some(vs) = &c.inline_set_variants {
10018                    set_inline_bindings.push((i, vs.as_slice()));
10019                }
10020            }
10021            write_u16(
10022                &mut out,
10023                u16::try_from(set_inline_bindings.len()).expect("≤ 65k inline-SET columns/table"),
10024            );
10025            for (pos, variants) in set_inline_bindings {
10026                write_u16(&mut out, u16::try_from(pos).expect("≤ 65k columns/table"));
10027                write_u16(
10028                    &mut out,
10029                    u16::try_from(variants.len()).expect("≤ 65k variants/SET"),
10030                );
10031                for v in variants {
10032                    write_str(&mut out, v.as_str());
10033                }
10034            }
10035            // v7.37.6-B — partition role appendix(FILE_VERSION 49+)。
10036            // Layout 详见 FILE_VERSION 49 docstring。普通表 = 单字节 0。
10037            write_partition_role(&mut out, t.schema.partition_role.as_ref());
10038            // v7.37.7 — per-table generated_stored_expr appendix
10039            // (FILE_VERSION 50+). Sparse: only columns whose
10040            // generated_stored_expr is Some land here.
10041            let mut gen_bindings: Vec<(usize, &str)> = Vec::new();
10042            for (i, c) in t.schema.columns.iter().enumerate() {
10043                if let Some(src) = &c.generated_stored_expr {
10044                    gen_bindings.push((i, src.as_str()));
10045                }
10046            }
10047            write_u16(
10048                &mut out,
10049                u16::try_from(gen_bindings.len()).expect("≤ 65k GENERATED STORED columns/table"),
10050            );
10051            for (pos, src) in gen_bindings {
10052                write_u16(&mut out, u16::try_from(pos).expect("≤ 65k columns/table"));
10053                write_str(&mut out, src);
10054            }
10055            // v7.38 (read01) — per-table default_text appendix
10056            // (FILE_VERSION 58+). Sparse: only columns whose default_text
10057            // is Some land here. Mirrors the generated_stored_expr shape.
10058            let mut default_texts: Vec<(usize, &str)> = Vec::new();
10059            for (i, c) in t.schema.columns.iter().enumerate() {
10060                if let Some(src) = &c.default_text {
10061                    default_texts.push((i, src.as_str()));
10062                }
10063            }
10064            write_u16(
10065                &mut out,
10066                u16::try_from(default_texts.len()).expect("≤ 65k defaulted columns/table"),
10067            );
10068            for (pos, src) in default_texts {
10069                write_u16(&mut out, u16::try_from(pos).expect("≤ 65k columns/table"));
10070                write_str(&mut out, src);
10071            }
10072            // v7.39 (RLS) — per-table policy appendix + the two RLS flags
10073            // (FILE_VERSION 59+). Written after the default_text block and
10074            // before the MVCC row appendix, so a v58 reader stops before it.
10075            // Layout: [u8 row_security][u8 force] [u16 policy_count] then per
10076            // policy: [str name][u8 cmd][u8 permissive][u16 role_count]
10077            // (role_count × str) [u8 has_using](+str)[u8 has_check](+str).
10078            out.push(u8::from(t.schema.row_security));
10079            out.push(u8::from(t.schema.force_row_security));
10080            write_u16(
10081                &mut out,
10082                u16::try_from(t.schema.policies.len()).expect("≤ 65k policies/table"),
10083            );
10084            for p in &t.schema.policies {
10085                write_str(&mut out, &p.name);
10086                out.push(p.cmd.to_wire_byte());
10087                out.push(u8::from(p.permissive));
10088                write_u16(
10089                    &mut out,
10090                    u16::try_from(p.roles.len()).expect("≤ 65k roles/policy"),
10091                );
10092                for r in &p.roles {
10093                    write_str(&mut out, r);
10094                }
10095                match &p.using_expr {
10096                    Some(s) => {
10097                        out.push(1);
10098                        write_str(&mut out, s);
10099                    }
10100                    None => out.push(0),
10101                }
10102                match &p.with_check_expr {
10103                    Some(s) => {
10104                        out.push(1);
10105                        write_str(&mut out, s);
10106                    }
10107                    None => out.push(0),
10108                }
10109            }
10110            // v7.37.16 (Epic W) — per-row MVCC header + stable RowId
10111            // appendix (FILE_VERSION 53+). Persists xmin/xmax/flags +
10112            // RowId for every row so a tombstone naming a pre-checkpoint
10113            // row survives a serialize→deserialize base restore
10114            // (cross-checkpoint tombstone durability). `headers` /
10115            // `rowids` are lock-step parallel to `rows` (invariant held
10116            // at every mutation boundary), so the count is `rows.len()`
10117            // and the zipped walk visits them in physical row order —
10118            // the same order the rows block above was written in. v52
10119            // readers never reach this block (the writer also moves to
10120            // v53 in lock-step); a v53 reader restores headers + ids
10121            // verbatim instead of freezing + dense-assigning.
10122            debug_assert_eq!(
10123                t.rows.len(),
10124                t.headers.len(),
10125                "headers must be lock-step with rows at serialize"
10126            );
10127            debug_assert_eq!(
10128                t.rows.len(),
10129                t.rowids.len(),
10130                "rowids must be lock-step with rows at serialize"
10131            );
10132            write_u32(
10133                &mut out,
10134                u32::try_from(t.rows.len()).expect("≤ 4G rows/table"),
10135            );
10136            for (h, rid) in t.headers.iter().zip(t.rowids.iter()) {
10137                out.extend_from_slice(&h.xmin.to_le_bytes());
10138                out.extend_from_slice(&h.xmax.to_le_bytes());
10139                out.push(h.flags);
10140                out.extend_from_slice(&rid.0.to_le_bytes());
10141            }
10142            out.extend_from_slice(
10143                &t.next_rowid
10144                    .load(core::sync::atomic::Ordering::Relaxed)
10145                    .to_le_bytes(),
10146            );
10147            // v7.39 (read01 round 48) — constraint-name appendix
10148            // (FILE_VERSION 60+). Index-aligned to the CHECK and
10149            // uniqueness-constraint appendices written above, so the
10150            // existing byte layouts stay untouched and a v59 catalog still
10151            // decodes (its constraints just come back unnamed).
10152            // Layout: [u16 check_count] then per check
10153            //         [u8 has_name] ([str name] when has_name)
10154            //         [u16 uc_count] then per uc the same pair.
10155            write_u16(
10156                &mut out,
10157                u16::try_from(t.schema.checks.len()).expect("≤ 65k CHECK constraints/table"),
10158            );
10159            for c in &t.schema.checks {
10160                match &c.name {
10161                    Some(n) => {
10162                        out.push(1);
10163                        write_str(&mut out, n);
10164                    }
10165                    None => out.push(0),
10166                }
10167            }
10168            write_u16(
10169                &mut out,
10170                u16::try_from(t.schema.uniqueness_constraints.len())
10171                    .expect("≤ 65k uniqueness constraints/table"),
10172            );
10173            for uc in &t.schema.uniqueness_constraints {
10174                match &uc.name {
10175                    Some(n) => {
10176                        out.push(1);
10177                        write_str(&mut out, n);
10178                    }
10179                    None => out.push(0),
10180                }
10181            }
10182            // v7.39 (read01 round 56) — user_composite_type appendix
10183            // (FILE_VERSION 63+). Sparse, at the very end of the per-table
10184            // block: only composite-typed columns land here, so a v62 reader
10185            // stops before it and its composite columns stay plain JSON.
10186            let mut comp_bindings: Vec<(usize, &str)> = Vec::new();
10187            for (i, c) in t.schema.columns.iter().enumerate() {
10188                if let Some(n) = &c.user_composite_type {
10189                    comp_bindings.push((i, n.as_str()));
10190                }
10191            }
10192            write_u16(
10193                &mut out,
10194                u16::try_from(comp_bindings.len()).expect("≤ 65k composite-typed columns/table"),
10195            );
10196            for (pos, n) in comp_bindings {
10197                write_u16(&mut out, u16::try_from(pos).expect("≤ 65k columns/table"));
10198                write_str(&mut out, n);
10199            }
10200            // v7.39 (read01 round 57) — owner + ACL appendix (FILE_VERSION
10201            // 64+), at the very end of the per-table block so a v63 reader
10202            // stops before it (its tables then read back owner-less, i.e.
10203            // owned by the login role, with no grants — which is exactly what
10204            // they were).
10205            match &t.schema.owner {
10206                Some(o) => {
10207                    out.push(1);
10208                    write_str(&mut out, o);
10209                }
10210                None => out.push(0),
10211            }
10212            write_u16(
10213                &mut out,
10214                u16::try_from(t.schema.acl.len()).expect("≤ 65k aclitems/table"),
10215            );
10216            for a in &t.schema.acl {
10217                write_str(&mut out, &a.grantee);
10218                write_u16(&mut out, a.privs);
10219                write_u16(&mut out, a.grantable);
10220                write_str(&mut out, &a.grantor);
10221            }
10222            // v7.39 (read01 round 59) — COLUMN acl appendix (FILE_VERSION 65+),
10223            // sparse: only columns that carry a grant land here, so a v64 reader
10224            // stops before it and its columns read back un-granted, which is
10225            // what they were.
10226            let granted: Vec<(usize, &ColumnSchema)> = t
10227                .schema
10228                .columns
10229                .iter()
10230                .enumerate()
10231                .filter(|(_, c)| !c.acl.is_empty())
10232                .collect();
10233            write_u16(
10234                &mut out,
10235                u16::try_from(granted.len()).expect("≤ 65k granted columns/table"),
10236            );
10237            for (pos, c) in granted {
10238                write_u16(&mut out, u16::try_from(pos).expect("≤ 65k columns/table"));
10239                write_u16(
10240                    &mut out,
10241                    u16::try_from(c.acl.len()).expect("≤ 65k aclitems/column"),
10242                );
10243                for a in &c.acl {
10244                    write_str(&mut out, &a.grantee);
10245                    write_u16(&mut out, a.privs);
10246                    write_u16(&mut out, a.grantable);
10247                    write_str(&mut out, &a.grantor);
10248                }
10249            }
10250            // v7.39 (round 210) — EXCLUDE-constraint appendix (FILE_VERSION
10251            // 72+), at the very end of the per-table block so a v71 reader
10252            // stops before it and its tables read back with no exclusion
10253            // constraints. Layout: [u16 excl_count] then per constraint
10254            // [str name] [u8 has_method](+str) [u16 elem_count] then per
10255            // element [u16 col_pos][str op].
10256            write_u16(
10257                &mut out,
10258                u16::try_from(t.schema.exclusion_constraints.len())
10259                    .expect("≤ 65k exclusion constraints/table"),
10260            );
10261            for ex in &t.schema.exclusion_constraints {
10262                write_str(&mut out, &ex.name);
10263                match &ex.method {
10264                    Some(m) => {
10265                        out.push(1);
10266                        write_str(&mut out, m);
10267                    }
10268                    None => out.push(0),
10269                }
10270                write_u16(
10271                    &mut out,
10272                    u16::try_from(ex.elements.len()).expect("≤ 65k elements/exclusion"),
10273                );
10274                for (pos, op) in &ex.elements {
10275                    write_u16(&mut out, u16::try_from(*pos).expect("≤ 65k columns/table"));
10276                    write_str(&mut out, op);
10277                }
10278            }
10279            // v7.39 (round 220) — identity-RESTART appendix (FILE_VERSION
10280            // 73+), sparse: only columns carrying a RESTART floor land here.
10281            let restarts: Vec<(usize, i64)> = t
10282                .schema
10283                .columns
10284                .iter()
10285                .enumerate()
10286                .filter_map(|(i, c)| c.auto_restart.map(|n| (i, n)))
10287                .collect();
10288            write_u16(
10289                &mut out,
10290                u16::try_from(restarts.len()).expect("≤ 65k restart columns/table"),
10291            );
10292            for (pos, n) in restarts {
10293                write_u16(&mut out, u16::try_from(pos).expect("≤ 65k columns/table"));
10294                out.extend_from_slice(&n.to_le_bytes());
10295            }
10296            // v7.39 (round 386, type-fidelity epic P1) — per-table
10297            // mysql_int_width appendix (FILE_VERSION 81+). Sparse: only
10298            // TINYINT / MEDIUMINT columns land. Layout:
10299            // `[u16 count]([u16 col_pos][u8 width_tag]) × count`
10300            // (tag 0 = Tiny, 1 = Medium). v80-and-below readers stop after
10301            // the identity-RESTART appendix, leaving every column at None.
10302            let int_widths: Vec<(usize, u8)> = t
10303                .schema
10304                .columns
10305                .iter()
10306                .enumerate()
10307                .filter_map(|(i, c)| {
10308                    c.mysql_int_width.map(|w| {
10309                        let tag = match w {
10310                            MysqlIntWidth::Tiny => 0u8,
10311                            MysqlIntWidth::Medium => 1u8,
10312                            MysqlIntWidth::Small => 2u8,
10313                            MysqlIntWidth::Int => 3u8,
10314                            MysqlIntWidth::Big => 4u8,
10315                        };
10316                        (i, tag)
10317                    })
10318                })
10319                .collect();
10320            write_u16(
10321                &mut out,
10322                u16::try_from(int_widths.len()).expect("≤ 65k narrow-int columns/table"),
10323            );
10324            for (pos, tag) in int_widths {
10325                write_u16(&mut out, u16::try_from(pos).expect("≤ 65k columns/table"));
10326                out.push(tag);
10327            }
10328            // v7.39 (round 424, type-fidelity epic) — per-table mysql_fsp
10329            // appendix (FILE_VERSION 82+). Sparse: only MySQL-declared
10330            // temporal columns land. Layout:
10331            // `[u16 count]([u16 col_pos][u8 fsp]) × count`, fsp in 0..=6.
10332            // v81-and-below readers stop after the int-width appendix,
10333            // leaving every column at None (PG microsecond behaviour).
10334            let fsps: Vec<(usize, u8)> = t
10335                .schema
10336                .columns
10337                .iter()
10338                .enumerate()
10339                .filter_map(|(i, c)| c.mysql_fsp.map(|p| (i, p)))
10340                .collect();
10341            write_u16(
10342                &mut out,
10343                u16::try_from(fsps.len()).expect("≤ 65k temporal columns/table"),
10344            );
10345            for (pos, fsp) in fsps {
10346                write_u16(&mut out, u16::try_from(pos).expect("≤ 65k columns/table"));
10347                out.push(fsp);
10348            }
10349            // v7.39.2 — the declared-TIMESTAMP appendix (FILE_VERSION
10350            // 93+). Sparse: only the columns written as `TIMESTAMP` in a
10351            // MySQL session. Layout: `[u16 count]([u16 col_pos]) × count`.
10352            // v92-and-below readers stop after the CHECK appendix below,
10353            // leaving every column at `false` — which is what they meant.
10354            let declared_ts: Vec<usize> = t
10355                .schema
10356                .columns
10357                .iter()
10358                .enumerate()
10359                .filter_map(|(i, c)| c.mysql_declared_timestamp.then_some(i))
10360                .collect();
10361            write_u16(
10362                &mut out,
10363                u16::try_from(declared_ts.len()).expect("≤ 65k timestamp columns/table"),
10364            );
10365            for pos in declared_ts {
10366                write_u16(&mut out, u16::try_from(pos).expect("≤ 65k columns/table"));
10367            }
10368            // v7.39.3 — the FLOAT/DOUBLE (m,d) appendix (FILE_VERSION
10369            // 94+). Sparse: only columns declared with the pair.
10370            // Layout: `[u16 count]([u16 col_pos][u8 m][u8 d]) × count`.
10371            let float_mds: Vec<(usize, u8, u8)> = t
10372                .schema
10373                .columns
10374                .iter()
10375                .enumerate()
10376                .filter_map(|(i, c)| c.mysql_float_md.map(|(m, d)| (i, m, d)))
10377                .collect();
10378            write_u16(
10379                &mut out,
10380                u16::try_from(float_mds.len()).expect("≤ 65k (m,d) columns/table"),
10381            );
10382            for (pos, m, d) in float_mds {
10383                write_u16(&mut out, u16::try_from(pos).expect("≤ 65k columns/table"));
10384                out.push(m);
10385                out.push(d);
10386            }
10387            // v7.39 (round 652) — CHECK-validated appendix (FILE_VERSION
10388            // 87+). Sparse the other way round from the ones above: the
10389            // common case is every constraint validated, so only the
10390            // NOT VALID ones are written, by their index into the CHECK
10391            // appendix. Layout: `[u16 count]([u16 check_idx]) × count`.
10392            let unvalidated: Vec<usize> = t
10393                .schema
10394                .checks
10395                .iter()
10396                .enumerate()
10397                .filter_map(|(i, c)| (!c.validated).then_some(i))
10398                .collect();
10399            write_u16(
10400                &mut out,
10401                u16::try_from(unvalidated.len()).expect("≤ 65k CHECK constraints/table"),
10402            );
10403            for idx in unvalidated {
10404                write_u16(&mut out, u16::try_from(idx).expect("≤ 65k CHECK/table"));
10405            }
10406            // v7.39 (round 677) — per-column collation names (FILE_VERSION
10407            // 88+). Sparse: only the columns that were written with an
10408            // explicit `COLLATE` appear, so a table that declares none pays
10409            // two bytes. Layout: `[u16 count]([u16 col_idx][str]) × count`.
10410            //
10411            // Without this the declaration survives CREATE TABLE and dies
10412            // at the next restart — measured: a column declared
10413            // `COLLATE "C"` reported attcollation 950 in the session that
10414            // created it and 100 after a reload.
10415            let collated: Vec<(usize, &str)> = t
10416                .schema
10417                .columns
10418                .iter()
10419                .enumerate()
10420                .filter_map(|(i, c)| c.collation_name.as_deref().map(|n| (i, n)))
10421                .collect();
10422            write_u16(
10423                &mut out,
10424                u16::try_from(collated.len()).expect("≤ 65k columns/table"),
10425            );
10426            for (idx, name) in collated {
10427                write_u16(&mut out, u16::try_from(idx).expect("≤ 65k columns/table"));
10428                write_str(&mut out, name);
10429            }
10430            // v7.39 (round 711) — PK/UNIQUE constraint timing (FILE_VERSION
10431            // 89+). Dense, one byte per uniqueness constraint in
10432            // declaration order, the same bit layout the FK block has
10433            // carried since round 288: bit 0 = DEFERRABLE, bit 1 =
10434            // INITIALLY DEFERRED. A v88 reader stops before it.
10435            write_u16(
10436                &mut out,
10437                u16::try_from(t.schema.uniqueness_constraints.len())
10438                    .expect("≤ 65k uniqueness constraints/table"),
10439            );
10440            for uc in &t.schema.uniqueness_constraints {
10441                out.push(u8::from(uc.deferrable) | (u8::from(uc.initially_deferred) << 1));
10442            }
10443        }
10444        // v7.12.4 — catalog-wide appendix: user-defined functions
10445        // then triggers. FILE_VERSION 22+ only. v21 and earlier
10446        // readers stop after the last table; v22 readers always
10447        // consume two `u32` counts (possibly zero).
10448        //
10449        // Function entry layout:
10450        //   [str name] [str args_repr] [str returns]
10451        //   [str language] [str body]
10452        // Trigger entry layout:
10453        //   [str name] [str table] [str timing]
10454        //   [u16 event_count] (event_count × str)
10455        //   [str for_each] [str function]
10456        write_u32(
10457            &mut out,
10458            u32::try_from(self.functions.len()).expect("≤ 4G functions"),
10459        );
10460        for fd in self.functions.values() {
10461            write_str(&mut out, &fd.name);
10462            write_str(&mut out, &fd.args_repr);
10463            write_str(&mut out, &fd.returns);
10464            write_str(&mut out, &fd.language);
10465            write_str_long(&mut out, &fd.body);
10466        }
10467        write_u32(
10468            &mut out,
10469            u32::try_from(self.triggers.len()).expect("≤ 4G triggers"),
10470        );
10471        for td in &self.triggers {
10472            write_str(&mut out, &td.name);
10473            write_str(&mut out, &td.table);
10474            write_str(&mut out, &td.timing);
10475            write_u16(
10476                &mut out,
10477                u16::try_from(td.events.len()).expect("≤ 65k events / trigger"),
10478            );
10479            for ev in &td.events {
10480                write_str(&mut out, ev);
10481            }
10482            write_str(&mut out, &td.for_each);
10483            write_str(&mut out, &td.function);
10484            // v7.13.0 — `UPDATE OF cols` filter
10485            // (FILE_VERSION 23+). v22 readers omit; v23 writers
10486            // always emit (possibly zero).
10487            write_u16(
10488                &mut out,
10489                u16::try_from(td.update_columns.len()).expect("≤ 65k cols / trigger"),
10490            );
10491            for c in &td.update_columns {
10492                write_str(&mut out, c);
10493            }
10494            // v7.16.1 — TriggerDef.enabled (FILE_VERSION 25+).
10495            out.push(u8::from(td.enabled));
10496            // v7.39 (round 138) — WHEN condition text (FILE_VERSION 70+).
10497            write_str(&mut out, &td.when_condition);
10498        }
10499        // v7.17.0 Phase 1.1 — SEQUENCE catalog block (FILE_VERSION 26+).
10500        write_u32(
10501            &mut out,
10502            u32::try_from(self.sequences.len()).expect("≤ 4G sequences"),
10503        );
10504        for seq in self.sequences.values() {
10505            write_str(&mut out, &seq.name);
10506            out.push(match seq.data_type {
10507                SequenceDataType::SmallInt => 0,
10508                SequenceDataType::Int => 1,
10509                SequenceDataType::BigInt => 2,
10510            });
10511            out.extend_from_slice(&seq.start.to_le_bytes());
10512            out.extend_from_slice(&seq.increment.to_le_bytes());
10513            out.extend_from_slice(&seq.min_value.to_le_bytes());
10514            out.extend_from_slice(&seq.max_value.to_le_bytes());
10515            out.extend_from_slice(&seq.cache.to_le_bytes());
10516            out.push(u8::from(seq.cycle));
10517            match &seq.owned_by {
10518                None => out.push(0),
10519                Some((table, column)) => {
10520                    out.push(1);
10521                    write_str(&mut out, table);
10522                    write_str(&mut out, column);
10523                }
10524            }
10525            out.extend_from_slice(&seq.last_value.to_le_bytes());
10526            out.push(u8::from(seq.is_called));
10527        }
10528        // v7.17.0 Phase 1.2 — VIEW catalog block (FILE_VERSION 27+).
10529        write_u32(
10530            &mut out,
10531            u32::try_from(self.views.len()).expect("≤ 4G views"),
10532        );
10533        for view in self.views.values() {
10534            write_str(&mut out, &view.name);
10535            write_u16(
10536                &mut out,
10537                u16::try_from(view.columns.len()).expect("≤ 65k cols / view"),
10538            );
10539            for c in &view.columns {
10540                write_str(&mut out, c);
10541            }
10542            write_str_long(&mut out, &view.body);
10543            // v7.39 (round 132, FILE_VERSION 69+) — WITH CHECK OPTION marker.
10544            out.push(view.check_option);
10545        }
10546        // v7.17.0 Phase 1.3 — MATERIALIZED VIEW source registry
10547        // (FILE_VERSION 28+). The backing rows live as a regular
10548        // table of the same name already in the tables block.
10549        write_u32(
10550            &mut out,
10551            u32::try_from(self.materialized_views.len()).expect("≤ 4G materialized views"),
10552        );
10553        for (name, body) in &self.materialized_views {
10554            write_str(&mut out, name);
10555            write_str_long(&mut out, body);
10556        }
10557        // v7.17.0 Phase 1.4 — ENUM types catalog block
10558        // (FILE_VERSION 29+).
10559        write_u32(
10560            &mut out,
10561            u32::try_from(self.enum_types.len()).expect("≤ 4G enum types"),
10562        );
10563        for e in self.enum_types.values() {
10564            write_str(&mut out, &e.name);
10565            write_u16(
10566                &mut out,
10567                u16::try_from(e.labels.len()).expect("≤ 65k labels / enum"),
10568            );
10569            for l in &e.labels {
10570                write_str(&mut out, l);
10571            }
10572        }
10573        // v7.17.0 Phase 1.5 — DOMAIN types catalog block
10574        // (FILE_VERSION 30+).
10575        write_u32(
10576            &mut out,
10577            u32::try_from(self.domain_types.len()).expect("≤ 4G domain types"),
10578        );
10579        for d in self.domain_types.values() {
10580            write_str(&mut out, &d.name);
10581            write_data_type(&mut out, d.base_type);
10582            out.push(u8::from(d.nullable));
10583            match &d.default {
10584                None => out.push(0),
10585                Some(s) => {
10586                    out.push(1);
10587                    write_str(&mut out, s);
10588                }
10589            }
10590            write_u16(
10591                &mut out,
10592                u16::try_from(d.checks.len()).expect("≤ 65k CHECKs / domain"),
10593            );
10594            for c in &d.checks {
10595                write_str(&mut out, &c.expr);
10596                // v7.39 (round 260) — the constraint name (FILE_VERSION 75+).
10597                write_str(&mut out, &c.name);
10598            }
10599            // v7.39 (round 259) — the parent domain (FILE_VERSION 74+).
10600            match &d.base_domain {
10601                None => out.push(0),
10602                Some(s) => {
10603                    out.push(1);
10604                    write_str(&mut out, s);
10605                }
10606            }
10607        }
10608        // v7.17.0 Phase 1.6 — user-schemas registry
10609        // (FILE_VERSION 31+). Built-ins are hardcoded in
10610        // `is_builtin_schema` and not persisted.
10611        write_u32(
10612            &mut out,
10613            u32::try_from(self.schemas.len()).expect("≤ 4G schemas"),
10614        );
10615        for name in &self.schemas {
10616            write_str(&mut out, name);
10617        }
10618        // v7.37.42-T2 ζ-B — COMPOSITE types catalog block
10619        // (FILE_VERSION 52+). Each entry: name, u16 field_count,
10620        // then field_count `[str field_name][data_type]` pairs.
10621        write_u32(
10622            &mut out,
10623            u32::try_from(self.composite_types.len()).expect("≤ 4G composite types"),
10624        );
10625        for c in self.composite_types.values() {
10626            write_str(&mut out, &c.name);
10627            write_u16(
10628                &mut out,
10629                u16::try_from(c.fields.len()).expect("≤ 65k fields / composite"),
10630            );
10631            for (i, (fname, fty)) in c.fields.iter().enumerate() {
10632                write_str(&mut out, fname);
10633                write_data_type(&mut out, *fty);
10634                // v7.39 (round 264) — the field's user type (v76+).
10635                match c.field_user_types.get(i).and_then(Option::as_ref) {
10636                    None => out.push(0),
10637                    Some(n) => {
10638                        out.push(1);
10639                        write_str(&mut out, n);
10640                    }
10641                }
10642            }
10643        }
10644        // v7.39 (read01 round 50) — COMMENT store (FILE_VERSION 61+).
10645        // Catalog-wide, written last (before the CRC trailer) so every older
10646        // reader stops before it. Layout: [u32 count] then [str key][str text].
10647        write_u32(
10648            &mut out,
10649            u32::try_from(self.comments.len()).expect("≤ 4G comments"),
10650        );
10651        for (k, v) in &self.comments {
10652            write_str(&mut out, k);
10653            write_str_long(&mut out, v);
10654        }
10655        // v7.39 (read01 round 60) — non-table ACLs (FILE_VERSION 66+), catalog-
10656        // wide and written last so a v65 reader stops before them. The sequence
10657        // block itself sits mid-image and cannot grow without breaking older
10658        // readers, so a sequence's owner + ACL rides here, keyed by name.
10659        let acl_out = |out: &mut Vec<u8>, acl: &[AclItem]| {
10660            write_u16(out, u16::try_from(acl.len()).expect("≤ 65k aclitems"));
10661            for a in acl {
10662                write_str(out, &a.grantee);
10663                write_u16(out, a.privs);
10664                write_u16(out, a.grantable);
10665                write_str(out, &a.grantor);
10666            }
10667        };
10668        let owned: Vec<&SequenceDef> = self
10669            .sequences
10670            .values()
10671            .filter(|s| s.owner.is_some() || !s.acl.is_empty())
10672            .collect();
10673        write_u32(
10674            &mut out,
10675            u32::try_from(owned.len()).expect("≤ 4G sequences"),
10676        );
10677        for seq in owned {
10678            write_str(&mut out, &seq.name);
10679            match &seq.owner {
10680                Some(o) => {
10681                    out.push(1);
10682                    write_str(&mut out, o);
10683                }
10684                None => out.push(0),
10685            }
10686            acl_out(&mut out, &seq.acl);
10687        }
10688        acl_out(&mut out, &self.schema_acl);
10689        acl_out(&mut out, &self.database_acl);
10690        // v7.39 (read01 round 61) — FUNCTION owner + ACL (FILE_VERSION 67+).
10691        // The function block sits mid-image like the sequence one, so this
10692        // rides the catalog-wide tail too, keyed by name.
10693        let fns: Vec<&FunctionDef> = self
10694            .functions
10695            .values()
10696            .filter(|f| f.owner.is_some() || !f.acl.is_empty())
10697            .collect();
10698        write_u32(&mut out, u32::try_from(fns.len()).expect("≤ 4G functions"));
10699        for f in fns {
10700            // v7.39 (read01 round 62) — keyed by SIGNATURE now: two overloads
10701            // have two ACLs.
10702            write_str(&mut out, &function_signature_key(&f.name, &f.args_repr));
10703            match &f.owner {
10704                Some(o) => {
10705                    out.push(1);
10706                    write_str(&mut out, o);
10707                }
10708                None => out.push(0),
10709            }
10710            acl_out(&mut out, &f.acl);
10711        }
10712        // v7.39 (round 139) — RULE catalog block (FILE_VERSION 71+), catalog-
10713        // wide and written last (right before the CRC trailer) so every older
10714        // reader stops cleanly before it. Layout: [u32 count] then per rule
10715        // [str name][str table][str event][u8 instead][str when]
10716        // [u16 cmd_count]([str cmd] × cmd_count).
10717        write_u32(
10718            &mut out,
10719            u32::try_from(self.rules.len()).expect("≤ 4G rules"),
10720        );
10721        for r in &self.rules {
10722            write_str(&mut out, &r.name);
10723            write_str(&mut out, &r.table);
10724            write_str(&mut out, &r.event);
10725            out.push(u8::from(r.instead));
10726            write_str(&mut out, &r.when_condition);
10727            write_u16(
10728                &mut out,
10729                u16::try_from(r.commands.len()).expect("≤ 65k commands / rule"),
10730            );
10731            for c in &r.commands {
10732                write_str(&mut out, c);
10733            }
10734        }
10735        // v7.39 (round 280) — extended-statistics block (FILE_VERSION
10736        // 77+), appended after the RULE block for the same reason: an
10737        // older reader stops cleanly before it. Layout: [u32 count]
10738        // then per object [str name][str table][u16 n]([str kind] × n)
10739        // [u16 m]([str column] × m).
10740        write_u32(
10741            &mut out,
10742            u32::try_from(self.statistics_ext.len()).expect("≤ 4G statistics objects"),
10743        );
10744        for st in &self.statistics_ext {
10745            write_str(&mut out, &st.name);
10746            write_str(&mut out, &st.table);
10747            write_u16(
10748                &mut out,
10749                u16::try_from(st.kinds.len()).expect("≤ 65k kinds"),
10750            );
10751            for k in &st.kinds {
10752                write_str(&mut out, k);
10753            }
10754            write_u16(
10755                &mut out,
10756                u16::try_from(st.columns.len()).expect("≤ 65k columns"),
10757            );
10758            for c in &st.columns {
10759                write_str(&mut out, c);
10760            }
10761        }
10762        // v7.39 (round 287) — large-object block (FILE_VERSION 78+),
10763        // appended after the statistics block for the same reason: an
10764        // older reader stops cleanly before it. Layout: [u32 count]
10765        // then per object [u32 oid][u32 len][len bytes].
10766        write_u32(
10767            &mut out,
10768            u32::try_from(self.large_objects.len()).expect("≤ 4G large objects"),
10769        );
10770        for (oid, bytes) in &self.large_objects {
10771            write_u32(&mut out, *oid);
10772            write_u32(
10773                &mut out,
10774                u32::try_from(bytes.len()).expect("≤ 4G per object"),
10775            );
10776            out.extend_from_slice(bytes);
10777        }
10778        // v7.39 (round 322, V46) — function-attribute block (FILE_VERSION
10779        // 80+), appended last for the same reason as every block before
10780        // it: an older reader stops cleanly ahead of it and simply sees
10781        // functions with PG's default attributes. Only functions that
10782        // declared something non-default are written. Layout: [u32 count]
10783        // then per function [str signature_key][u8 volatility][u8 flags]
10784        // [u8 parallel][f64 cost or NaN][f64 rows or NaN], where flags bit
10785        // 0 = strict, 1 = security definer, 2 = leakproof.
10786        let attr_fns: Vec<(&String, &FunctionDef)> = self
10787            .functions
10788            .iter()
10789            .filter(|(_, f)| {
10790                f.volatility != FN_VOLATILE
10791                    || f.strict
10792                    || f.security_definer
10793                    || f.leakproof
10794                    || f.parallel != FN_PARALLEL_UNSAFE
10795                    || f.cost.is_some()
10796                    || f.rows.is_some()
10797            })
10798            .collect();
10799        write_u32(
10800            &mut out,
10801            u32::try_from(attr_fns.len()).expect("≤ 4G functions"),
10802        );
10803        for (key, f) in attr_fns {
10804            write_str(&mut out, key);
10805            out.push(f.volatility);
10806            let flags = u8::from(f.strict)
10807                | (u8::from(f.security_definer) << 1)
10808                | (u8::from(f.leakproof) << 2);
10809            out.push(flags);
10810            out.push(f.parallel);
10811            out.extend_from_slice(&f.cost.unwrap_or(f64::NAN).to_le_bytes());
10812            out.extend_from_slice(&f.rows.unwrap_or(f64::NAN).to_le_bytes());
10813        }
10814        // v7.38 (read01 P5.05) — CRC32C trailer over the whole image so a
10815        // corrupted snapshot is rejected on load. FILE_VERSION is >= the
10816        // trailer version, so this always runs for freshly-written images.
10817        // v7.39 (round 547) — pg_db_role_setting (FILE_VERSION 85+),
10818        // catalog-wide and written LAST so a v84 reader stops before it.
10819        // Layout: [u32 scopes] then [str database][str role][u32 params]
10820        // then [str name][str value] per param.
10821        write_u32(
10822            &mut out,
10823            u32::try_from(self.db_role_settings.len()).expect("≤ 4G scopes"),
10824        );
10825        for ((db, role), params) in &self.db_role_settings {
10826            write_str(&mut out, db);
10827            write_str(&mut out, role);
10828            write_u32(&mut out, u32::try_from(params.len()).expect("≤ 4G params"));
10829            for (name, value) in params {
10830                write_str(&mut out, name);
10831                write_str(&mut out, value);
10832            }
10833        }
10834        // v7.39 (round 550) — replication slots (FILE_VERSION 86+),
10835        // written LAST so a v85 reader stops before them.
10836        write_u32(
10837            &mut out,
10838            u32::try_from(self.replication_slots.len()).expect("≤ 4G slots"),
10839        );
10840        for (name, (plugin, slot_type)) in &self.replication_slots {
10841            write_str(&mut out, name);
10842            write_str(&mut out, plugin);
10843            write_str(&mut out, slot_type);
10844        }
10845        // v7.38.18 (S1) — the database collation (FILE_VERSION 92+).
10846        // Absent on an older image, which reads back as `C`.
10847        match &self.db_collation {
10848            None => out.push(0),
10849            Some(c) => {
10850                out.push(1);
10851                write_str(&mut out, c);
10852            }
10853        }
10854        let crc = spg_crypto::crc32c::crc32c(&out);
10855        write_u32(&mut out, crc);
10856        out
10857    }
10858
10859    /// Deserialize a previously-serialized catalog. Rejects bad magic, version
10860    /// mismatch, unknown tags, truncation, and trailing bytes.
10861    pub fn deserialize(buf: &[u8]) -> Result<Self, StorageError> {
10862        let mut cur = Cursor::new(buf);
10863        let magic = cur.take(8)?;
10864        if magic != FILE_MAGIC {
10865            return Err(StorageError::Corrupt(format!(
10866                "bad magic: expected SPGDB001, got {magic:?}"
10867            )));
10868        }
10869        let version = cur.read_u8()?;
10870        if !(MIN_SUPPORTED_FILE_VERSION..=FILE_VERSION).contains(&version) {
10871            return Err(StorageError::Corrupt(format!(
10872                "unsupported file version: {version} (supported: {MIN_SUPPORTED_FILE_VERSION}..={FILE_VERSION})"
10873            )));
10874        }
10875        // v7.23/v7.27 — escape decoding is version-gated (see
10876        // STR_LEN_ESCAPE / Cursor::codec_version).
10877        cur.codec_version = version;
10878        let table_count = cur.read_u32()? as usize;
10879        let mut cat = Self::new();
10880        for _ in 0..table_count {
10881            deserialize_table(&mut cur, &mut cat, version)?;
10882        }
10883        // v7.37.15 (Phase C.1) — stamp dense stable RelIds on load.
10884        // Pre-V6 envelopes carry no ids; a dense 1..=N assignment is
10885        // sufficient while RelId is process-local bookkeeping (the V6
10886        // envelope, Phase C.6, will round-trip real ids). Sets the
10887        // allocator above the loaded ids so a post-load CREATE TABLE
10888        // never collides.
10889        for (i, t) in cat.tables.iter_mut().enumerate() {
10890            t.set_rel_id(row_header::RelId((i as u64) + 1));
10891        }
10892        cat.next_rel_id = cat.tables.len() as u64;
10893        // v7.12.4 — catalog-wide function + trigger appendix.
10894        // FILE_VERSION 22+ only; v21 and earlier catalogs stop
10895        // after the last table.
10896        if version >= 22 {
10897            let fn_count = cur.read_u32()? as usize;
10898            for _ in 0..fn_count {
10899                let name = cur.read_str()?;
10900                let args_repr = cur.read_str()?;
10901                let returns = cur.read_str()?;
10902                let language = cur.read_str()?;
10903                let body = cur.read_str_long()?;
10904                let key = function_signature_key(&name, &args_repr);
10905                cat.functions.insert(
10906                    key,
10907                    FunctionDef {
10908                        name,
10909                        args_repr,
10910                        returns,
10911                        language,
10912                        body,
10913                        owner: None,
10914                        acl: Vec::new(),
10915                        volatility: FN_VOLATILE,
10916                        strict: false,
10917                        security_definer: false,
10918                        leakproof: false,
10919                        parallel: FN_PARALLEL_UNSAFE,
10920                        cost: None,
10921                        rows: None,
10922                    },
10923                );
10924            }
10925            let trg_count = cur.read_u32()? as usize;
10926            for _ in 0..trg_count {
10927                let name = cur.read_str()?;
10928                let table = cur.read_str()?;
10929                let timing = cur.read_str()?;
10930                let ev_count = cur.read_u16()? as usize;
10931                let mut events = Vec::with_capacity(ev_count);
10932                for _ in 0..ev_count {
10933                    events.push(cur.read_str()?);
10934                }
10935                let for_each = cur.read_str()?;
10936                let function = cur.read_str()?;
10937                // v7.13.0 — trailing `UPDATE OF cols` filter
10938                // (FILE_VERSION 23+ only; v22 catalogs omit and
10939                // deserialise with an empty vec).
10940                let update_columns = if version >= 23 {
10941                    let n = cur.read_u16()? as usize;
10942                    let mut cols = Vec::with_capacity(n);
10943                    for _ in 0..n {
10944                        cols.push(cur.read_str()?);
10945                    }
10946                    cols
10947                } else {
10948                    Vec::new()
10949                };
10950                // v7.16.1 — TriggerDef.enabled (FILE_VERSION 25+).
10951                // v24-and-below catalogs deserialise with `true`
10952                // — pre-v7.16.1 every trigger always fired.
10953                let enabled = if version >= 25 {
10954                    cur.read_u8()? != 0
10955                } else {
10956                    true
10957                };
10958                // v7.39 (round 138) — WHEN condition text added at FILE_VERSION
10959                // 70; older catalogs read back empty (no WHEN filter).
10960                let when_condition = if version >= 70 {
10961                    cur.read_str()?
10962                } else {
10963                    String::new()
10964                };
10965                cat.triggers.push(TriggerDef {
10966                    name,
10967                    table,
10968                    timing,
10969                    events,
10970                    for_each,
10971                    function,
10972                    update_columns,
10973                    enabled,
10974                    when_condition,
10975                });
10976            }
10977        }
10978        // v7.17.0 Phase 1.1 — SEQUENCE block (FILE_VERSION 26+).
10979        // v25-and-below catalogs omit; we leave the map empty.
10980        if version >= 26 {
10981            let seq_count = cur.read_u32()? as usize;
10982            for _ in 0..seq_count {
10983                let name = cur.read_str()?;
10984                let data_type = match cur.read_u8()? {
10985                    0 => SequenceDataType::SmallInt,
10986                    1 => SequenceDataType::Int,
10987                    2 => SequenceDataType::BigInt,
10988                    other => {
10989                        return Err(StorageError::Corrupt(format!(
10990                            "unknown SEQUENCE data-type tag {other}"
10991                        )));
10992                    }
10993                };
10994                let start = cur.read_i64()?;
10995                let increment = cur.read_i64()?;
10996                let min_value = cur.read_i64()?;
10997                let max_value = cur.read_i64()?;
10998                let cache = cur.read_i64()?;
10999                let cycle = cur.read_u8()? != 0;
11000                let owned_by = match cur.read_u8()? {
11001                    0 => None,
11002                    1 => {
11003                        let t = cur.read_str()?;
11004                        let c = cur.read_str()?;
11005                        Some((t, c))
11006                    }
11007                    other => {
11008                        return Err(StorageError::Corrupt(format!(
11009                            "unknown SEQUENCE owned-by tag {other}"
11010                        )));
11011                    }
11012                };
11013                let last_value = cur.read_i64()?;
11014                let is_called = cur.read_u8()? != 0;
11015                cat.sequences.insert(
11016                    name.clone(),
11017                    SequenceDef {
11018                        name,
11019                        data_type,
11020                        start,
11021                        increment,
11022                        min_value,
11023                        max_value,
11024                        cache,
11025                        cycle,
11026                        owned_by,
11027                        last_value,
11028                        is_called,
11029                        owner: None,
11030                        acl: Vec::new(),
11031                    },
11032                );
11033            }
11034        }
11035        // v7.17.0 Phase 1.2 — VIEW block (FILE_VERSION 27+).
11036        // v26-and-below catalogs omit; we leave the map empty.
11037        if version >= 27 {
11038            let view_count = cur.read_u32()? as usize;
11039            for _ in 0..view_count {
11040                let name = cur.read_str()?;
11041                let col_count = cur.read_u16()? as usize;
11042                let mut columns = Vec::with_capacity(col_count);
11043                for _ in 0..col_count {
11044                    columns.push(cur.read_str()?);
11045                }
11046                let body = cur.read_str_long()?;
11047                // v7.39 (round 132) — check-option marker added at FILE_VERSION
11048                // 69; older catalogs default to 0 (no check option).
11049                let check_option = if version >= 69 { cur.read_u8()? } else { 0 };
11050                cat.views.insert(
11051                    name.clone(),
11052                    ViewDef {
11053                        name,
11054                        columns,
11055                        body,
11056                        check_option,
11057                    },
11058                );
11059            }
11060        }
11061        // v7.17.0 Phase 1.3 — MATERIALIZED VIEW source registry
11062        // (FILE_VERSION 28+). v27-and-below catalogs omit.
11063        if version >= 28 {
11064            let mv_count = cur.read_u32()? as usize;
11065            for _ in 0..mv_count {
11066                let name = cur.read_str()?;
11067                let body = cur.read_str_long()?;
11068                cat.materialized_views.insert(name, body);
11069            }
11070        }
11071        // v7.17.0 Phase 1.4 — ENUM types catalog block
11072        // (FILE_VERSION 29+).
11073        if version >= 29 {
11074            let etype_count = cur.read_u32()? as usize;
11075            for _ in 0..etype_count {
11076                let name = cur.read_str()?;
11077                let label_count = cur.read_u16()? as usize;
11078                let mut labels = Vec::with_capacity(label_count);
11079                for _ in 0..label_count {
11080                    labels.push(cur.read_str()?);
11081                }
11082                cat.enum_types
11083                    .insert(name.clone(), EnumDef { name, labels });
11084            }
11085        }
11086        // v7.17.0 Phase 1.5 — DOMAIN types catalog block
11087        // (FILE_VERSION 30+).
11088        if version >= 30 {
11089            let dtype_count = cur.read_u32()? as usize;
11090            for _ in 0..dtype_count {
11091                let name = cur.read_str()?;
11092                let base_type = cur.read_data_type()?;
11093                let nullable = cur.read_u8()? != 0;
11094                let default = match cur.read_u8()? {
11095                    0 => None,
11096                    1 => Some(cur.read_str()?),
11097                    other => {
11098                        return Err(StorageError::Corrupt(format!(
11099                            "unknown DOMAIN default tag {other}"
11100                        )));
11101                    }
11102                };
11103                let check_count = cur.read_u16()? as usize;
11104                let mut checks: Vec<DomainCheck> = Vec::with_capacity(check_count);
11105                for i in 0..check_count {
11106                    let expr = cur.read_str()?;
11107                    // v7.39 (round 260) — names arrived in FILE_VERSION 75.
11108                    // An older catalog gets PG's auto-naming applied to the
11109                    // checks it stored, which is what they would have been.
11110                    let cname = if version >= 75 {
11111                        cur.read_str()?
11112                    } else if i == 0 {
11113                        alloc::format!("{name}_check")
11114                    } else {
11115                        alloc::format!("{name}_check{i}")
11116                    };
11117                    checks.push(DomainCheck { name: cname, expr });
11118                }
11119                // v7.39 (round 259) — the parent domain. Absent before
11120                // FILE_VERSION 74; an older catalog reads as a domain over
11121                // a scalar, which is what it was.
11122                let base_domain = if version >= 74 {
11123                    match cur.read_u8()? {
11124                        0 => None,
11125                        1 => Some(cur.read_str()?),
11126                        other => {
11127                            return Err(StorageError::Corrupt(alloc::format!(
11128                                "domain base_domain tag {other}"
11129                            )));
11130                        }
11131                    }
11132                } else {
11133                    None
11134                };
11135                cat.domain_types.insert(
11136                    name.clone(),
11137                    DomainDef {
11138                        name,
11139                        base_type,
11140                        nullable,
11141                        default,
11142                        checks,
11143                        base_domain,
11144                    },
11145                );
11146            }
11147        }
11148        // v7.17.0 Phase 1.6 — user-schemas registry
11149        // (FILE_VERSION 31+).
11150        if version >= 31 {
11151            let sch_count = cur.read_u32()? as usize;
11152            for _ in 0..sch_count {
11153                let name = cur.read_str()?;
11154                cat.schemas.insert(name);
11155            }
11156        }
11157        // v7.37.42-T2 ζ-B — COMPOSITE types catalog block
11158        // (FILE_VERSION 52+). v51-and-below readers stop at the
11159        // user-schemas block; v52 readers fed a v51 catalog see no
11160        // composite block and default to an empty map.
11161        if version >= 52 {
11162            let ctype_count = cur.read_u32()? as usize;
11163            for _ in 0..ctype_count {
11164                let name = cur.read_str()?;
11165                let field_count = cur.read_u16()? as usize;
11166                let mut fields = Vec::with_capacity(field_count);
11167                let mut field_user_types: Vec<Option<String>> = Vec::with_capacity(field_count);
11168                for _ in 0..field_count {
11169                    let fname = cur.read_str()?;
11170                    let fty = cur.read_data_type()?;
11171                    // v7.39 (round 264) — present from FILE_VERSION 76.
11172                    let ut = if version >= 76 {
11173                        match cur.read_u8()? {
11174                            0 => None,
11175                            1 => Some(cur.read_str()?),
11176                            other => {
11177                                return Err(StorageError::Corrupt(alloc::format!(
11178                                    "composite field user-type tag {other}"
11179                                )));
11180                            }
11181                        }
11182                    } else {
11183                        None
11184                    };
11185                    fields.push((fname, fty));
11186                    field_user_types.push(ut);
11187                }
11188                cat.composite_types.insert(
11189                    name.clone(),
11190                    CompositeDef {
11191                        name,
11192                        fields,
11193                        field_user_types,
11194                    },
11195                );
11196            }
11197        }
11198        // v7.39 (read01 round 50) — COMMENT store (FILE_VERSION 61+).
11199        if version >= 61 {
11200            let comment_count = cur.read_u32()? as usize;
11201            for _ in 0..comment_count {
11202                let key = cur.read_str()?;
11203                let text = cur.read_str_long()?;
11204                cat.comments.insert(key, text);
11205            }
11206        }
11207        // v7.39 (read01 round 60) — non-table ACLs (FILE_VERSION 66+).
11208        if version >= 66 {
11209            let read_acl = |cur: &mut Cursor| -> Result<Vec<AclItem>, StorageError> {
11210                let n = cur.read_u16()? as usize;
11211                let mut acl = Vec::with_capacity(n);
11212                for _ in 0..n {
11213                    let grantee = cur.read_str()?;
11214                    let privs = cur.read_u16()?;
11215                    let grantable = cur.read_u16()?;
11216                    let grantor = cur.read_str()?;
11217                    acl.push(AclItem {
11218                        grantee,
11219                        privs,
11220                        grantable,
11221                        grantor,
11222                    });
11223                }
11224                Ok(acl)
11225            };
11226            let seq_count = cur.read_u32()? as usize;
11227            for _ in 0..seq_count {
11228                let name = cur.read_str()?;
11229                let owner = if cur.read_u8()? == 1 {
11230                    Some(cur.read_str()?)
11231                } else {
11232                    None
11233                };
11234                let acl = read_acl(&mut cur)?;
11235                if let Some(seq) = cat.sequences.get_mut(&name) {
11236                    seq.owner = owner;
11237                    seq.acl = acl;
11238                }
11239            }
11240            cat.schema_acl = read_acl(&mut cur)?;
11241            cat.database_acl = read_acl(&mut cur)?;
11242            // v7.39 (read01 round 61) — FUNCTION owner + ACL (v67+; keyed by
11243            // signature from v68, when overloads became possible).
11244            if version >= 67 {
11245                let fn_count = cur.read_u32()? as usize;
11246                for _ in 0..fn_count {
11247                    let name = cur.read_str()?;
11248                    let owner = if cur.read_u8()? == 1 {
11249                        Some(cur.read_str()?)
11250                    } else {
11251                        None
11252                    };
11253                    let acl = read_acl(&mut cur)?;
11254                    // v7.39 (round 315, V19) — the stored key was computed
11255                    // by whichever formula was current when the image was
11256                    // written. A miss is not "no such function": before the
11257                    // multi-word fix, `f(double precision)` keyed as
11258                    // `f(precision)`, so an older image's grants would land
11259                    // nowhere and vanish silently. Fall back to matching by
11260                    // the old formula, which re-attaches them.
11261                    let target = resolve_stored_function_key(&cat.functions, &name);
11262                    if let Some(k) = target
11263                        && let Some(f) = cat.functions.get_mut(&k)
11264                    {
11265                        f.owner = owner;
11266                        f.acl = acl;
11267                    }
11268                }
11269            }
11270        }
11271        // v7.39 (round 139) — RULE catalog block (FILE_VERSION 71+), read from
11272        // the tail right before the CRC trailer. Pre-71 images stop before it.
11273        if version >= 71 {
11274            let rule_count = cur.read_u32()? as usize;
11275            for _ in 0..rule_count {
11276                let name = cur.read_str()?;
11277                let table = cur.read_str()?;
11278                let event = cur.read_str()?;
11279                let instead = cur.read_u8()? != 0;
11280                let when_condition = cur.read_str()?;
11281                let cmd_count = cur.read_u16()? as usize;
11282                let mut commands = Vec::with_capacity(cmd_count);
11283                for _ in 0..cmd_count {
11284                    commands.push(cur.read_str()?);
11285                }
11286                cat.rules.push(RuleDef {
11287                    name,
11288                    table,
11289                    event,
11290                    instead,
11291                    when_condition,
11292                    commands,
11293                });
11294            }
11295        }
11296        // v7.39 (round 280) — extended-statistics block (FILE_VERSION
11297        // 77+). Pre-77 images stop before it.
11298        if version >= 77 {
11299            let count = cur.read_u32()? as usize;
11300            for _ in 0..count {
11301                let name = cur.read_str()?;
11302                let table = cur.read_str()?;
11303                let nk = cur.read_u16()? as usize;
11304                let mut kinds = Vec::with_capacity(nk);
11305                for _ in 0..nk {
11306                    kinds.push(cur.read_str()?);
11307                }
11308                let nc = cur.read_u16()? as usize;
11309                let mut columns = Vec::with_capacity(nc);
11310                for _ in 0..nc {
11311                    columns.push(cur.read_str()?);
11312                }
11313                cat.statistics_ext.push(StatisticsExtDef {
11314                    name,
11315                    table,
11316                    kinds,
11317                    columns,
11318                });
11319            }
11320        }
11321        // v7.39 (round 287) — large-object block (FILE_VERSION 78+).
11322        // Pre-78 images stop before it.
11323        if version >= 78 {
11324            let count = cur.read_u32()? as usize;
11325            for _ in 0..count {
11326                let oid = cur.read_u32()?;
11327                let len = cur.read_u32()? as usize;
11328                let bytes = cur.read_bytes(len)?;
11329                cat.large_objects.insert(oid, bytes);
11330            }
11331        }
11332        // v7.39 (round 322, V46) — function-attribute block (FILE_VERSION
11333        // 80+). Pre-80 images stop before it and keep PG's defaults.
11334        if version >= 80 {
11335            let count = cur.read_u32()? as usize;
11336            for _ in 0..count {
11337                let key = cur.read_str()?;
11338                let volatility = cur.read_u8()?;
11339                let flags = cur.read_u8()?;
11340                let parallel = cur.read_u8()?;
11341                let cost = f64::from_le_bytes(cur.read_bytes(8)?.try_into().unwrap_or([0; 8]));
11342                let rows = f64::from_le_bytes(cur.read_bytes(8)?.try_into().unwrap_or([0; 8]));
11343                if let Some(f) = cat.functions.get_mut(&key) {
11344                    f.volatility = volatility;
11345                    f.strict = flags & 1 != 0;
11346                    f.security_definer = flags & 2 != 0;
11347                    f.leakproof = flags & 4 != 0;
11348                    f.parallel = parallel;
11349                    f.cost = (!cost.is_nan()).then_some(cost);
11350                    f.rows = (!rows.is_nan()).then_some(rows);
11351                }
11352            }
11353        }
11354        // v7.39 (round 547) — pg_db_role_setting (FILE_VERSION 85+).
11355        // Pre-85 images stop before it and carry no GUC defaults.
11356        if version >= 85 {
11357            let scopes = cur.read_u32()? as usize;
11358            for _ in 0..scopes {
11359                let db = cur.read_str()?;
11360                let role = cur.read_str()?;
11361                let params = cur.read_u32()? as usize;
11362                let mut m: BTreeMap<String, String> = BTreeMap::new();
11363                for _ in 0..params {
11364                    let name = cur.read_str()?;
11365                    let value = cur.read_str()?;
11366                    m.insert(name, value);
11367                }
11368                if !m.is_empty() {
11369                    cat.db_role_settings.insert((db, role), m);
11370                }
11371            }
11372        }
11373        // v7.39 (round 550) — replication slots (FILE_VERSION 86+).
11374        if version >= 86 {
11375            let count = cur.read_u32()? as usize;
11376            for _ in 0..count {
11377                let name = cur.read_str()?;
11378                let plugin = cur.read_str()?;
11379                let slot_type = cur.read_str()?;
11380                cat.replication_slots.insert(name, (plugin, slot_type));
11381            }
11382        }
11383        // v7.38.18 (S1) — the database collation (FILE_VERSION 92+).
11384        if version >= 92 {
11385            match cur.read_u8()? {
11386                0 => {}
11387                1 => cat.db_collation = Some(cur.read_str()?),
11388                other => {
11389                    return Err(StorageError::Corrupt(format!(
11390                        "db_collation tag: unknown byte {other}"
11391                    )));
11392                }
11393            }
11394        }
11395        // v7.38.18 (S3) — a database created under a collation this
11396        // build cannot perform does not open.
11397        //
11398        // Falling back to bytes would answer with a different comparator
11399        // than every index key in it was built under, which is the one
11400        // failure this whole layer exists to prevent — and it would do
11401        // it silently, since a byte-ordered answer looks exactly like a
11402        // correct one. The check is a NAME classification here; the
11403        // engine, which owns the collator, verifies it can actually
11404        // perform the name before recording it.
11405        if let Some(c) = &cat.db_collation
11406            && c.trim().is_empty()
11407        {
11408            return Err(StorageError::Corrupt(format!(
11409                "database collation is recorded as {c:?}, which names nothing"
11410            )));
11411        }
11412        // v7.38.18 (S2) — and every table read back learns it, because a
11413        // table decides for itself which of its indexes key under a
11414        // collation. Done here rather than per-table in the loop above
11415        // because the byte that says so is written after the tables.
11416        let db_coll = cat.db_collation().to_string();
11417        for t in &mut cat.tables {
11418            t.set_db_collation(&db_coll);
11419        }
11420        // v7.38 (read01 P5.05) — v54+ images end with a CRC32C over every
11421        // preceding byte; verify it before accepting the snapshot. Older
11422        // images have no trailer and fall through to the trailing-byte check.
11423        if version >= FILE_VERSION_CRC_TRAILER {
11424            let crc_start = cur.pos;
11425            let stored = cur.read_u32()?;
11426            let computed = spg_crypto::crc32c::crc32c(&buf[..crc_start]);
11427            if computed != stored {
11428                return Err(StorageError::Corrupt(format!(
11429                    "base snapshot CRC mismatch: computed {computed:#010x}, stored {stored:#010x}"
11430                )));
11431            }
11432        }
11433        if cur.pos < buf.len() {
11434            return Err(StorageError::Corrupt(format!(
11435                "trailing bytes: {} unread",
11436                buf.len() - cur.pos
11437            )));
11438        }
11439        Ok(cat)
11440    }
11441}
11442
11443#[cfg(test)]
11444mod tests;