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/// A row-cell value, including SQL `NULL`. `Float` uses `f64`; NaN compares
640/// non-equal to itself (PG behaviour) — `PartialEq` is derived so callers
641/// must opt into NaN-aware comparison if they need stronger guarantees.
642///
643/// v7.37.42-arena Phase 1: parameterised on `'arena` so heap-bearing
644/// variants (Text/Json/Xml/Bytes/Vector/BitString.bytes) can borrow from
645/// a per-query bump arena (`Cow::Borrowed(&'arena ...)`). Persistent /
646/// catalog Values use `Value<'static>` (alias `ValueOwned`) with
647/// `Cow::Owned(...)`. Phase 1 keeps Range/Multirange recursive `Box<Value>`
648/// at `'static` (owned) — arena migration deferred to a later phase.
649/// Array-of-Option<String> variants (TextArray etc.) also stay owned in
650/// Phase 1; their nested shape is awkward for the simple Cow lift and the
651/// SCALARSQ hot path doesn't touch them.
652/// v7.38 (read01, T6) — the IEEE-style class of a NUMERIC value. `Finite` is the
653/// ordinary fixed-point case; the specials mirror PG's `'NaN'` / `'Infinity'` /
654/// `'-Infinity'`. Derived `PartialEq` gives `NaN == NaN` — correct for NUMERIC
655/// (unlike float's NaN ≠ NaN); the total order (`-Inf < finite < +Inf < NaN`)
656/// lives in the comparison paths, not in `Ord`.
657#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Hash)]
658pub enum NumericKind {
659    #[default]
660    Finite,
661    NaN,
662    PosInf,
663    NegInf,
664}
665
666#[derive(Debug, Clone, PartialEq)]
667#[non_exhaustive]
668pub enum Value<'arena> {
669    SmallInt(i16),
670    Int(i32),
671    BigInt(i64),
672    Float(f64),
673    /// v7.38 (read01, T-float4) — PG `real` (32-bit IEEE float).
674    Real(f32),
675    Text(Cow<'arena, str>),
676    Bool(bool),
677    Vector(Cow<'arena, [f32]>),
678    /// v6.0.1: 8-bit scalar-quantised vector cell. Lives in
679    /// columns declared `VECTOR(N) USING SQ8`. Layout per cell:
680    /// `Sq8Vector { min: f32, max: f32, bytes: Vec<u8> }` —
681    /// 4× compression vs `Vector(Vec<f32>)`. The wire layer
682    /// dequantises to `f32` on SELECT; INSERT path quantises
683    /// incoming `Vector(Vec<f32>)` cells into this variant.
684    Sq8Vector(crate::quantize::Sq8Vector),
685    /// v6.0.3: IEEE-754 binary16 vector cell. Lives in columns
686    /// declared `VECTOR(N) USING HALF`. Stores raw u16 LE bits
687    /// (2× compression vs `Vector(Vec<f32>)`). Wire / display
688    /// paths dequantise to f32 bit-exactly; INSERT path converts
689    /// incoming f32 vectors at the engine boundary.
690    HalfVector(crate::halfvec::HalfVector),
691    /// Exact fixed-point decimal. `scaled` holds the value as
692    /// `actual * 10^scale` so the storage type is always integral —
693    /// arithmetic never falls back to floating-point. v7.38 (read01, T6) —
694    /// `kind` classifies the value as finite (the common case, using
695    /// `scaled`/`scale`) or one of PG's NUMERIC specials (NaN / ±Infinity),
696    /// which ignore `scaled`/`scale` (canonicalized to 0).
697    Numeric {
698        scaled: i128,
699        /// v7.39 (round 271) — widened from u8. PG's numeric carries a
700        /// display scale up to 16383; at u8 a literal with 256 decimal
701        /// places could not be represented at all, and the conversion
702        /// aborted the query with an internal error.
703        scale: u16,
704        kind: NumericKind,
705    },
706    /// v7.38 (read01, T3) — an exact NUMERIC whose mantissa overflows `i128`
707    /// (PG's NUMERIC is unbounded). Boxed so the common finite case keeps its
708    /// small footprint; specials never take this form (they stay `Numeric`).
709    NumericBig(alloc::boxed::Box<crate::bignum::BigNumeric>),
710    /// Days since the Unix epoch (1970-01-01). Negative for earlier dates.
711    Date(i32),
712    /// Microseconds since the Unix epoch (1970-01-01T00:00:00Z).
713    Timestamp(i64),
714    /// Calendar span: `months` + `days` + `micros`. Three fields are
715    /// required for PG byte-equal: `'1 day'` ≠ `'24 hours'` (DST,
716    /// month-boundary, and the on-wire `pg_type` `interval` are all
717    /// `i64 micros + i32 days + i32 months`). v7.37.5 β widened from
718    /// `{months, micros}`; column storage lands in the same window.
719    Interval {
720        months: i32,
721        days: i32,
722        micros: i64,
723    },
724    /// v4.9 `JSON` — raw JSON text. No structural validation
725    /// happens at the storage layer; whatever the parser hands us
726    /// round-trips verbatim. Equality is byte-wise.
727    Json(Cow<'arena, str>),
728    /// v7.10.4 `BYTEA` — raw binary blob. Equality is byte-wise.
729    /// Layout matches `Text`'s length-prefixed shape (`[u32 LE
730    /// len][bytes]`) under tag 18; the engine accepts PG hex
731    /// literals (`'\xDEADBEEF'`) and escape literals at the
732    /// coercion boundary.
733    Bytes(Cow<'arena, [u8]>),
734    /// v7.10.9 `TEXT[]` — single-dimension TEXT array with
735    /// optional NULL elements. Equality is element-wise. PG's
736    /// NULL-element comparison semantics: NULL ≠ NULL inside
737    /// arrays under `=`, so `[NULL] != [NULL]` (the engine
738    /// honours this).
739    TextArray(Vec<Option<String>>),
740    /// v7.11.12 `INT[]` — single-dimension i32 array with optional
741    /// NULL elements. Codec mirrors TextArray with i32 LE per
742    /// element instead of length-prefixed UTF-8.
743    IntArray(Vec<Option<i32>>),
744    /// v7.11.12 `BIGINT[]` — single-dimension i64 array with optional
745    /// NULL elements.
746    BigIntArray(Vec<Option<i64>>),
747    /// v7.37.5 β-P4 `INTERVAL[]` — single-dimension array of
748    /// `IntervalSpan { months, days, micros }` with optional NULL
749    /// elements. PG external form quotes each non-NULL element
750    /// (`{"1 day","24:00:00",NULL}`) because interval text contains
751    /// spaces and colons. Storage codec follows the BigIntArray
752    /// shape with a 16-byte per-element body.
753    IntervalArray(Vec<Option<IntervalSpan>>),
754    /// v7.37.5 γ — single-dimension arrays of the remaining PG
755    /// scalar types. Each carries `Vec<Option<T>>` with the
756    /// scalar's natural Rust shape; element NULLs are first-class
757    /// (per PG: `{1,NULL,3}` is a 3-element array, not a 2-element
758    /// one). Codec follows the IntervalArray shape — `[u16 count]
759    /// [per elem: u8 null + (non-null) scalar body]`.
760    BoolArray(Vec<Option<bool>>),
761    SmallIntArray(Vec<Option<i16>>),
762    FloatArray(Vec<Option<f64>>),
763    /// PG `NUMERIC[]` — `(scaled: i128, scale: u16)` per element.
764    NumericArray(Vec<Option<(i128, u16)>>),
765    DateArray(Vec<Option<i32>>),
766    TimestampArray(Vec<Option<i64>>),
767    TimestamptzArray(Vec<Option<i64>>),
768    UuidArray(Vec<Option<[u8; 16]>>),
769    JsonArray(Vec<Option<String>>),
770    JsonbArray(Vec<Option<String>>),
771    BytesArray(Vec<Option<Vec<u8>>>),
772    VarcharArray(Vec<Option<String>>),
773    CharArray(Vec<Option<String>>),
774    /// v7.37.5 δ — PG 14+ multirange. `ranges` is a Vec of
775    /// non-overlapping bounds spans of the shared `kind`. PG's
776    /// canonical text form is `{[a,b),[c,d),...}` (comma-separated
777    /// ranges in braces; `{}` for the empty multirange). SPG's
778    /// constructor enforces no overlap/coalescing — for now the
779    /// engine trusts the caller (mirrors PG's `_construct_array`
780    /// pattern). Catalog tag 49 + 1-byte RangeKind on the dense
781    /// type-tag side; schema-less path is unreachable (multirange
782    /// is column-typed only).
783    Multirange {
784        kind: RangeKind,
785        ranges: Vec<RangeSpan>,
786    },
787    /// v7.37.5 ε — PG geometry scalars. Per-type Vec/struct shape;
788    /// codec body shape is described on the matching DataType
789    /// variant. PG canonical text forms:
790    ///   Point   `(x,y)`
791    ///   Lseg    `[(x1,y1),(x2,y2)]`
792    ///   Path    open `[(x,y),(x,y),...]` / closed `((x,y),(x,y),...)`
793    ///   Box     `(ux,uy),(lx,ly)` (PG normalises to upper-right + lower-left)
794    ///   Polygon `((x,y),(x,y),...)` (implicit closed)
795    ///   Line    `{a,b,c}` (Ax + By + C = 0)
796    ///   Circle  `<(x,y),r>`
797    Point(Point2D),
798    Lseg(Point2D, Point2D),
799    /// `closed = true` is `((p,p,...))`; `false` is `[(p,p,...)]`.
800    Path {
801        points: Vec<Point2D>,
802        closed: bool,
803    },
804    /// PG `box` — stored as `(upper_right, lower_left)` (PG's
805    /// normalised order). The engine accepts both endpoint
806    /// orderings at parse time and normalises here.
807    PgBox(Point2D, Point2D),
808    Polygon(Vec<Point2D>),
809    Line {
810        a: f64,
811        b: f64,
812        c: f64,
813    },
814    Circle {
815        center: Point2D,
816        radius: f64,
817    },
818    /// v7.37.5 ζ-A — PG `inet`. `family = 4` (IPv4) or `6` (IPv6).
819    /// `bits` is the netmask bit count (0..=32 for IPv4, 0..=128
820    /// for IPv6). `addr` is right-padded with zeros when family=4
821    /// (first 4 bytes are the address).
822    Inet {
823        family: u8,
824        bits: u8,
825        addr: [u8; 16],
826    },
827    /// v7.37.5 ζ-A — PG `cidr`. Same shape as Inet; CIDR's
828    /// invariant (host bits zero) is enforced at parse / coerce.
829    Cidr {
830        family: u8,
831        bits: u8,
832        addr: [u8; 16],
833    },
834    /// v7.37.5 ζ-A — PG `macaddr`. 6 bytes (XX:XX:XX:XX:XX:XX).
835    Macaddr([u8; 6]),
836    /// v7.37.5 ζ-A — PG `macaddr8`. 8 bytes (EUI-64).
837    Macaddr8([u8; 8]),
838    /// v7.39 (read01 pg_lsn.c) — PG `pg_lsn`, a 64-bit WAL location.
839    PgLsn(u64),
840    /// v7.39 (read01 ruleutils.c) — PG `regclass`: an OID-typed relation
841    /// reference that renders as the relation name. SPG carries BOTH
842    /// (the synthetic oid for catalog joins, the name for display) so
843    /// `conrelid = 't'::regclass` and `'t'::regclass::text` agree.
844    /// Eval-only (no column storage).
845    RegClass(i64, alloc::boxed::Box<str>),
846    /// v7.39 (round 342, V65) — PG `regproc`: an OID-typed FUNCTION
847    /// reference that renders as the function name. Same dual shape
848    /// [`Value::RegClass`] carries, and for the same reason: without the
849    /// oid half, `pg_proc.oid = 'f'::regproc` cannot join, and a callee
850    /// cannot tell `pg_get_functiondef('f'::regproc)` — which PG answers
851    /// — from `pg_get_functiondef('f')` — which PG rejects.
852    /// Eval-only (no column storage).
853    RegProc(i64, alloc::boxed::Box<str>),
854    /// v7.39 (round 648) — PG `regtype`: an OID-typed TYPE reference
855    /// that renders as the type name. The third of the shape
856    /// [`Value::RegClass`] and [`Value::RegProc`] carry, and the one
857    /// that was missing it: `::regtype` produced a plain `Value::Text`
858    /// holding the canonical name, so `'text'::regtype::oid` tried to
859    /// parse the NAME as a number and answered `invalid input syntax
860    /// for type oid: "text"` where PG answers 25. `pg_typeof` on one
861    /// said `text` rather than `regtype` for the same reason.
862    ///
863    /// Eval-only (no column storage).
864    RegType(i64, alloc::boxed::Box<str>),
865    /// v7.39 (round 512) — PG `xid` and `cid`, the transaction and command
866    /// ids the `xmin` / `xmax` / `cmin` / `cmax` system columns carry.
867    ///
868    /// Their own types rather than integers, because PG deliberately gives
869    /// them almost no operators: measured on PG18, `xmin + 1` is "operator
870    /// does not exist: xid + integer", `xmin > 0` likewise, `xmin::bigint`
871    /// is "cannot cast type xid to bigint", and there is no `max(xid)`.
872    /// Carrying them as BigInt would quietly allow all four.
873    ///
874    /// Eval-only (no column storage).
875    Xid(u32),
876    Cid(u32),
877    /// v7.39 (round 511) — PG `tid`, the physical row identity `ctid`
878    /// carries: a block number and a one-based offset inside it, rendered
879    /// `(block,offset)`.
880    ///
881    /// It is a real type rather than a two-field record because the idiom
882    /// that makes `ctid` worth having — `DELETE … WHERE ctid NOT IN (SELECT
883    /// min(ctid) … GROUP BY key)` — needs `min()` over it, and PG has no
884    /// `min(record)`. Ordering is by block then offset, so `(0,2) < (0,9) <
885    /// (0,10)`; a text form would order those `(0,10) < (0,2) < (0,9)` and
886    /// the dedup would keep the wrong row.
887    ///
888    /// Eval-only (no column storage).
889    Tid(u32, u32),
890    /// v7.37.5 ζ-A — PG `bit` / `bit varying`. `nbits` is the
891    /// actual bit count; `bytes` is the packed representation
892    /// (big-endian within each byte; final byte right-padded
893    /// with 0s if `nbits % 8 != 0`).
894    BitString {
895        nbits: u32,
896        bytes: Cow<'arena, [u8]>,
897    },
898    /// v7.37.5 ζ-A — PG `xml`. Stored verbatim as a string; no
899    /// parse-time validation (matches the SPG JSON convention).
900    Xml(Cow<'arena, str>),
901    /// v7.37.5 ζ-A — PG `"char"` (internal single-byte type,
902    /// distinct from CHAR(n)).
903    Char1(u8),
904    /// v7.38 (read01, T11) — PG `bpchar` / CHAR(n): blank-padded fixed-length
905    /// string. Stored space-padded to the declared width (as PG does + for wire
906    /// display); length / comparison / ::text / concat all ignore the trailing
907    /// blanks (handled at those sites).
908    BpChar(Cow<'arena, str>),
909    /// v7.37.5 ζ-A — PG `money[]`.
910    MoneyArray(Vec<Option<i64>>),
911    /// v7.12.0 `tsvector` — sorted-by-word, deduped lexeme set with
912    /// positions + weights. The engine enforces sort/dedup on
913    /// construction; consumers can rely on `lexemes.windows(2)`
914    /// being strictly ascending by `word`.
915    TsVector(Vec<TsLexeme>),
916    /// v7.12.0 `tsquery` — boolean / phrase parse tree over
917    /// lexemes. Engine builds via `to_tsquery` family.
918    TsQuery(TsQueryAst),
919    /// v7.17.0 `uuid` — 128-bit identifier. Stored as 16 bytes
920    /// (big-endian / network-byte order, same as RFC 4122).
921    /// Display normalises to canonical lowercase 8-4-4-4-12
922    /// hyphenated form. Equality is byte-wise.
923    Uuid([u8; 16]),
924    /// v7.17.0 Phase 3.P0-32 — PG `time` (without time zone) —
925    /// i64 microseconds since 00:00:00. Range 0..86_400_000_000.
926    /// Display: `HH:MM:SS` zero-padded, with optional `.ffffff`
927    /// suffix when fractional is non-zero.
928    Time(i64),
929    /// v7.17.0 Phase 3.P0-33 — MySQL `YEAR` — u16 in range
930    /// 1901..=2155 plus the special zero-year sentinel 0.
931    /// Display always 4 digits zero-padded (`0000` for the
932    /// sentinel; `1985`/`2007` otherwise).
933    Year(u16),
934    /// v7.17.0 Phase 3.P0-34 — PG `time with time zone` — i64
935    /// microseconds since 00:00:00 in the LOCAL wall clock PLUS
936    /// an i32 offset-from-UTC in seconds. PG preserves the
937    /// offset on output, so the wall-clock value is NOT shifted
938    /// to UTC at storage time. Offset range: ±50400 seconds
939    /// (±14 hours).
940    TimeTz {
941        us: i64,
942        offset_secs: i32,
943    },
944    /// v7.17.0 Phase 3.P0-35 — PG `money` — i64 cents
945    /// (locale-independent storage; the en_US locale renders on
946    /// display via `$N,NNN.CC`).
947    Money(i64),
948    /// v7.17.0 Phase 3.P0-39 — PG `hstore` value: flat
949    /// `text => text` map with NULL value support. Insertion
950    /// order preserved on input; duplicate keys take last-write-
951    /// wins at parse time.
952    Hstore(Vec<(String, Option<String>)>),
953    /// v7.17.0 Phase 3.P0-40 — 2D INT matrix (row-major).
954    IntArray2D(Vec<Vec<Option<i32>>>),
955    /// v7.17.0 Phase 3.P0-40 — 2D BIGINT matrix (row-major).
956    BigIntArray2D(Vec<Vec<Option<i64>>>),
957    /// v7.17.0 Phase 3.P0-40 — 2D TEXT matrix (row-major).
958    TextArray2D(Vec<Vec<Option<String>>>),
959    /// v7.39 (read01 round 75) — see `DataType::BoolArray2D`.
960    BoolArray2D(Vec<Vec<Option<bool>>>),
961    /// v7.17.0 Phase 3.P0-38 — PG range value. One shape covers
962    /// all six builtin range types; `kind` pins the element type
963    /// (must match the column's `DataType::Range(kind)`).
964    /// `lower` / `upper` are `None` for the unbounded sides;
965    /// `lower_inc` / `upper_inc` mirror the canonical PG
966    /// `[` / `(` / `]` / `)` bracket inclusivity. `empty=true`
967    /// supersedes all other fields (the empty range has no
968    /// bounds).
969    Range {
970        kind: RangeKind,
971        // v7.37.42-arena Phase 1: Range bounds stay owned ('static).
972        // Recursive arena lifetimes are awkward to migrate at this
973        // phase and the SCALARSQ hot path doesn't construct ranges.
974        lower: Option<alloc::boxed::Box<Value<'static>>>,
975        upper: Option<alloc::boxed::Box<Value<'static>>>,
976        lower_inc: bool,
977        upper_inc: bool,
978        empty: bool,
979    },
980    /// v7.38 (read01, T9) — a composite / record value (a `row(...)`
981    /// constructor or a whole-row reference). Fields are `(name, value)`; the
982    /// names are `f1..fN` for an anonymous `row(...)` or the source column
983    /// names for a table row. Transient — flows through row_to_json / to_json
984    /// and the composite text form `(a,b)`; not a storable column type here.
985    Composite(alloc::vec::Vec<(alloc::string::String, Value<'static>)>),
986    Null,
987}
988
989/// Owned `Value` — heap-bearing variants are `Cow::Owned`. Used everywhere
990/// a Value must outlive a query-scoped arena (catalog defaults, persistent
991/// storage, public APIs).
992pub type ValueOwned = Value<'static>;
993
994/// v7.37.5 ε — PG `point` building block. Shared by every other
995/// geometric type (lseg / path / box / polygon / circle all
996/// reduce to compositions of `Point2D`). Packed `{x: f64, y: f64}`,
997/// 16 B, on-disk LE field order matches the PG binary point
998/// format byte-for-byte (so a future binary BIND path lands
999/// without rearrangement).
1000#[derive(Debug, Clone, Copy, PartialEq)]
1001pub struct Point2D {
1002    pub x: f64,
1003    pub y: f64,
1004}
1005
1006/// v7.37.5 δ — single-range bounds without the kind tag. Used as
1007/// the element type of `Value::Multirange { kind, ranges }` so a
1008/// multirange carries one shared `RangeKind` plus N bounds-only
1009/// spans (saves 1 byte/elem vs duplicating the kind). The five
1010/// other fields mirror `Value::Range` exactly.
1011#[derive(Debug, Clone, PartialEq)]
1012pub struct RangeSpan {
1013    // v7.37.42-arena Phase 1: stays owned ('static) — same rationale as
1014    // Range bounds above.
1015    pub lower: Option<alloc::boxed::Box<Value<'static>>>,
1016    pub upper: Option<alloc::boxed::Box<Value<'static>>>,
1017    pub lower_inc: bool,
1018    pub upper_inc: bool,
1019    pub empty: bool,
1020}
1021
1022/// v7.37.5 β-P4 — element type for `Value::IntervalArray`. Mirrors
1023/// the `{months, days, micros}` shape of scalar `Value::Interval`,
1024/// broken out as a named struct so `IntervalArray`'s element type
1025/// is concrete (24 bytes, packed) instead of an enum-boxed Value.
1026/// All three dimensions are independent — `IntervalSpan { days: 1,
1027/// .. }` is distinct from `IntervalSpan { micros: 86_400_000_000,
1028/// .. }` per PG byte-equal.
1029#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1030pub struct IntervalSpan {
1031    pub months: i32,
1032    pub days: i32,
1033    pub micros: i64,
1034}
1035
1036impl<'arena> Value<'arena> {
1037    /// Type tag, or `None` for `NULL` (unknown at value level).
1038    pub fn data_type(&self) -> Option<DataType> {
1039        match self {
1040            Self::SmallInt(_) => Some(DataType::SmallInt),
1041            Self::Int(_) => Some(DataType::Int),
1042            Self::BigInt(_) => Some(DataType::BigInt),
1043            Self::Float(_) => Some(DataType::Float),
1044            Self::Real(_) => Some(DataType::Real),
1045            // `Text` covers both unbounded TEXT and bounded VARCHAR/CHAR
1046            // — the constraint lives on the column schema, not the value.
1047            Self::Text(_) => Some(DataType::Text),
1048            Self::Bool(_) => Some(DataType::Bool),
1049            Self::Vector(v) => Some(DataType::Vector {
1050                dim: u32::try_from(v.len()).expect("vector dim ≤ u32"),
1051                encoding: VecEncoding::F32,
1052            }),
1053            Self::Sq8Vector(q) => Some(DataType::Vector {
1054                dim: u32::try_from(q.bytes.len()).expect("vector dim ≤ u32"),
1055                encoding: VecEncoding::Sq8,
1056            }),
1057            Self::HalfVector(h) => Some(DataType::Vector {
1058                dim: u32::try_from(h.dim()).expect("vector dim ≤ u32"),
1059                encoding: VecEncoding::F16,
1060            }),
1061            // `Value::Numeric` doesn't carry its precision (the column
1062            // schema does); we surface precision=0 as "unknown" and let
1063            // the engine reconcile against the column type at coercion
1064            // time.
1065            // v7.39 (round 273) — a VALUE's display scale is unsigned and
1066            // never exceeds PG's 16383 ceiling, so it always fits the
1067            // signed declared-scale field this describes itself with.
1068            Self::Numeric { scale, .. } => Some(DataType::Numeric {
1069                precision: 0,
1070                scale: i16::try_from(*scale).unwrap_or(i16::MAX),
1071            }),
1072            Self::NumericBig(b) => Some(DataType::Numeric {
1073                precision: 0,
1074                scale: i16::try_from(b.scale()).unwrap_or(i16::MAX),
1075            }),
1076            Self::Date(_) => Some(DataType::Date),
1077            Self::Timestamp(_) => Some(DataType::Timestamp),
1078            Self::Interval { .. } => Some(DataType::Interval),
1079            Self::Json(_) => Some(DataType::Json),
1080            Self::Bytes(_) => Some(DataType::Bytes),
1081            Self::TextArray(_) => Some(DataType::TextArray),
1082            Self::IntArray(_) => Some(DataType::IntArray),
1083            Self::BigIntArray(_) => Some(DataType::BigIntArray),
1084            Self::IntervalArray(_) => Some(DataType::IntervalArray),
1085            Self::BoolArray(_) => Some(DataType::BoolArray),
1086            Self::SmallIntArray(_) => Some(DataType::SmallIntArray),
1087            Self::FloatArray(_) => Some(DataType::FloatArray),
1088            Self::NumericArray(_) => Some(DataType::NumericArray),
1089            Self::DateArray(_) => Some(DataType::DateArray),
1090            Self::TimestampArray(_) => Some(DataType::TimestampArray),
1091            Self::TimestamptzArray(_) => Some(DataType::TimestamptzArray),
1092            Self::UuidArray(_) => Some(DataType::UuidArray),
1093            Self::JsonArray(_) => Some(DataType::JsonArray),
1094            Self::JsonbArray(_) => Some(DataType::JsonbArray),
1095            Self::BytesArray(_) => Some(DataType::BytesArray),
1096            Self::VarcharArray(_) => Some(DataType::VarcharArray),
1097            Self::CharArray(_) => Some(DataType::CharArray),
1098            Self::Multirange { kind, .. } => Some(DataType::Multirange(*kind)),
1099            Self::Point(_) => Some(DataType::Point),
1100            Self::Lseg(_, _) => Some(DataType::Lseg),
1101            Self::Path { .. } => Some(DataType::Path),
1102            Self::PgBox(_, _) => Some(DataType::PgBox),
1103            Self::Polygon(_) => Some(DataType::Polygon),
1104            Self::Line { .. } => Some(DataType::Line),
1105            Self::Circle { .. } => Some(DataType::Circle),
1106            Self::Inet { .. } => Some(DataType::Inet),
1107            Self::Cidr { .. } => Some(DataType::Cidr),
1108            Self::Macaddr(_) => Some(DataType::Macaddr),
1109            Self::Macaddr8(_) => Some(DataType::Macaddr8),
1110            Self::PgLsn(_) => Some(DataType::PgLsn),
1111            // BitString could be either Bit or BitVarying; column
1112            // schema decides. Default to BitVarying when called
1113            // schema-less (rare; storage path is always
1114            // schema-aware so this only matters for diagnostics).
1115            Self::BitString { .. } => Some(DataType::BitVarying(0)),
1116            Self::Xml(_) => Some(DataType::Xml),
1117            Self::Char1(_) => Some(DataType::Char1),
1118            // BpChar reports its declared width from the padded length.
1119            Self::BpChar(s) => Some(DataType::Char(
1120                u32::try_from(s.chars().count()).unwrap_or(0),
1121            )),
1122            Self::MoneyArray(_) => Some(DataType::MoneyArray),
1123            Self::TsVector(_) => Some(DataType::TsVector),
1124            Self::TsQuery(_) => Some(DataType::TsQuery),
1125            Self::Uuid(_) => Some(DataType::Uuid),
1126            Self::Time(_) => Some(DataType::Time),
1127            Self::Year(_) => Some(DataType::Year),
1128            Self::TimeTz { .. } => Some(DataType::TimeTz),
1129            Self::Money(_) => Some(DataType::Money),
1130            Self::Range { kind, .. } => Some(DataType::Range(*kind)),
1131            Self::Hstore(_) => Some(DataType::Hstore),
1132            Self::IntArray2D(_) => Some(DataType::IntArray2D),
1133            Self::BigIntArray2D(_) => Some(DataType::BigIntArray2D),
1134            Self::TextArray2D(_) => Some(DataType::TextArray2D),
1135            Self::BoolArray2D(_) => Some(DataType::BoolArray2D),
1136            // v7.38 (read01, T9) — a transient composite/record has no storable
1137            // column DataType (it flows through row_to_json / to_json).
1138            Self::Composite(_) => None,
1139            // v7.39 (read01 ruleutils.c) — regclass is eval-only (dual
1140            // oid+name shape); no column storage type.
1141            // v7.39 (round 640) — `xid` became a column type, so its value
1142            // has a DataType to answer with. `cid` and `tid` are equally
1143            // legal column types on PG (measured: `CREATE TABLE t (a cid,
1144            // b tid)` is accepted), but SPG's grammar has no keyword for
1145            // them yet; they stay eval-only rather than half-declared.
1146            Self::Xid(_) => Some(DataType::Xid),
1147            Self::RegClass(..)
1148            | Self::RegProc(..)
1149            | Self::RegType(..)
1150            | Self::Tid(..)
1151            | Self::Cid(_) => None,
1152            Self::Null => None,
1153        }
1154    }
1155
1156    pub const fn is_null(&self) -> bool {
1157        matches!(self, Self::Null)
1158    }
1159
1160    /// v7.37.42-arena Phase 1: lift any `Value<'arena>` (possibly
1161    /// borrowing from a bump arena) into a fully-owned `Value<'static>`.
1162    /// Used at boundaries that must outlive the per-query arena
1163    /// (catalog write, public QueryResult emit, sqlx materialise).
1164    ///
1165    /// For the recursive Range/Multirange variants — bounds are already
1166    /// `Box<Value<'static>>` per Phase 1 design, so we just rebuild the
1167    /// outer enum at `'static`.
1168    pub fn into_owned(self) -> Value<'static> {
1169        match self {
1170            Value::SmallInt(n) => Value::SmallInt(n),
1171            Value::Int(n) => Value::Int(n),
1172            Value::BigInt(n) => Value::BigInt(n),
1173            Value::Float(f) => Value::Float(f),
1174            Value::Real(f) => Value::Real(f),
1175            Value::Text(s) => Value::Text(Cow::Owned(s.into_owned())),
1176            Value::Bool(b) => Value::Bool(b),
1177            Value::Vector(v) => Value::Vector(Cow::Owned(v.into_owned())),
1178            Value::Sq8Vector(q) => Value::Sq8Vector(q),
1179            Value::HalfVector(h) => Value::HalfVector(h),
1180            Value::Numeric {
1181                scaled,
1182                scale,
1183                kind,
1184            } => Value::Numeric {
1185                scaled,
1186                scale,
1187                kind,
1188            },
1189            Value::NumericBig(b) => Value::NumericBig(b),
1190            Value::Date(d) => Value::Date(d),
1191            Value::Timestamp(t) => Value::Timestamp(t),
1192            Value::Interval {
1193                months,
1194                days,
1195                micros,
1196            } => Value::Interval {
1197                months,
1198                days,
1199                micros,
1200            },
1201            Value::Json(s) => Value::Json(Cow::Owned(s.into_owned())),
1202            Value::Bytes(b) => Value::Bytes(Cow::Owned(b.into_owned())),
1203            Value::TextArray(v) => Value::TextArray(v),
1204            Value::IntArray(v) => Value::IntArray(v),
1205            Value::BigIntArray(v) => Value::BigIntArray(v),
1206            Value::IntervalArray(v) => Value::IntervalArray(v),
1207            Value::BoolArray(v) => Value::BoolArray(v),
1208            Value::SmallIntArray(v) => Value::SmallIntArray(v),
1209            Value::FloatArray(v) => Value::FloatArray(v),
1210            Value::NumericArray(v) => Value::NumericArray(v),
1211            Value::DateArray(v) => Value::DateArray(v),
1212            Value::TimestampArray(v) => Value::TimestampArray(v),
1213            Value::TimestamptzArray(v) => Value::TimestamptzArray(v),
1214            Value::UuidArray(v) => Value::UuidArray(v),
1215            Value::JsonArray(v) => Value::JsonArray(v),
1216            Value::JsonbArray(v) => Value::JsonbArray(v),
1217            Value::BytesArray(v) => Value::BytesArray(v),
1218            Value::VarcharArray(v) => Value::VarcharArray(v),
1219            Value::CharArray(v) => Value::CharArray(v),
1220            Value::Multirange { kind, ranges } => Value::Multirange { kind, ranges },
1221            // v7.38 (read01, T9) — Composite fields are already `Value<'static>`.
1222            Value::Composite(fields) => Value::Composite(fields),
1223            Value::RegClass(oid, name) => Value::RegClass(oid, name),
1224            Value::Tid(b, o) => Value::Tid(b, o),
1225            Value::Xid(x) => Value::Xid(x),
1226            Value::Cid(c) => Value::Cid(c),
1227            Value::RegProc(oid, name) => Value::RegProc(oid, name),
1228            Value::RegType(oid, name) => Value::RegType(oid, name),
1229            Value::Point(p) => Value::Point(p),
1230            Value::Lseg(a, b) => Value::Lseg(a, b),
1231            Value::Path { points, closed } => Value::Path { points, closed },
1232            Value::PgBox(a, b) => Value::PgBox(a, b),
1233            Value::Polygon(p) => Value::Polygon(p),
1234            Value::Line { a, b, c } => Value::Line { a, b, c },
1235            Value::Circle { center, radius } => Value::Circle { center, radius },
1236            Value::Inet { family, bits, addr } => Value::Inet { family, bits, addr },
1237            Value::Cidr { family, bits, addr } => Value::Cidr { family, bits, addr },
1238            Value::Macaddr(m) => Value::Macaddr(m),
1239            Value::Macaddr8(m) => Value::Macaddr8(m),
1240            Value::PgLsn(l) => Value::PgLsn(l),
1241            Value::BitString { nbits, bytes } => Value::BitString {
1242                nbits,
1243                bytes: Cow::Owned(bytes.into_owned()),
1244            },
1245            Value::Xml(s) => Value::Xml(Cow::Owned(s.into_owned())),
1246            Value::Char1(c) => Value::Char1(c),
1247            Value::BpChar(s) => Value::BpChar(Cow::Owned(s.into_owned())),
1248            Value::MoneyArray(v) => Value::MoneyArray(v),
1249            Value::TsVector(v) => Value::TsVector(v),
1250            Value::TsQuery(q) => Value::TsQuery(q),
1251            Value::Uuid(u) => Value::Uuid(u),
1252            Value::Time(t) => Value::Time(t),
1253            Value::Year(y) => Value::Year(y),
1254            Value::TimeTz { us, offset_secs } => Value::TimeTz { us, offset_secs },
1255            Value::Money(m) => Value::Money(m),
1256            Value::Range {
1257                kind,
1258                lower,
1259                upper,
1260                lower_inc,
1261                upper_inc,
1262                empty,
1263            } => Value::Range {
1264                kind,
1265                lower,
1266                upper,
1267                lower_inc,
1268                upper_inc,
1269                empty,
1270            },
1271            Value::Hstore(h) => Value::Hstore(h),
1272            Value::IntArray2D(a) => Value::IntArray2D(a),
1273            Value::BigIntArray2D(a) => Value::BigIntArray2D(a),
1274            Value::TextArray2D(a) => Value::TextArray2D(a),
1275            Value::BoolArray2D(a) => Value::BoolArray2D(a),
1276            Value::Null => Value::Null,
1277        }
1278    }
1279
1280    /// v7.37.42-arena Phase 4 — copy heap payloads into the supplied
1281    /// bump arena, yielding a `Value<'a>` whose Cow-variant payloads
1282    /// are arena-borrowed (or stay as small owned scalars for the
1283    /// `Copy`-able variants).
1284    ///
1285    /// Used at the catalog ↔ ephemeral boundary: a `ColumnSchema.default`
1286    /// is `Value<'static>` but INSERT-time eval may want it stamped into
1287    /// the per-statement arena alongside other arena-built scalars.
1288    ///
1289    /// Allocates only into the supplied arena; the input `&self` keeps
1290    /// its own storage. For `Copy`-able / nested-owned variants the
1291    /// implementation falls back to `clone()` (the nested heap blocks
1292    /// stay on the global allocator, which is fine — the boundary
1293    /// requirement is just "no aliasing of caller-owned strings").
1294    pub fn clone_into<'a>(&self, arena: &'a bumpalo::Bump) -> Value<'a> {
1295        match self {
1296            Value::Text(s) => Value::Text(Cow::Borrowed(arena.alloc_str(s))),
1297            Value::Json(s) => Value::Json(Cow::Borrowed(arena.alloc_str(s))),
1298            Value::Xml(s) => Value::Xml(Cow::Borrowed(arena.alloc_str(s))),
1299            Value::BpChar(s) => Value::BpChar(Cow::Borrowed(arena.alloc_str(s))),
1300            Value::Bytes(b) => {
1301                let slot = arena.alloc_slice_copy::<u8>(b);
1302                Value::Bytes(Cow::Borrowed(slot))
1303            }
1304            Value::Vector(v) => {
1305                let slot = arena.alloc_slice_copy::<f32>(v);
1306                Value::Vector(Cow::Borrowed(slot))
1307            }
1308            Value::BitString { nbits, bytes } => {
1309                let slot = arena.alloc_slice_copy::<u8>(bytes);
1310                Value::BitString {
1311                    nbits: *nbits,
1312                    bytes: Cow::Borrowed(slot),
1313                }
1314            }
1315            // Copy-able scalars + variants whose nested heap blocks are
1316            // `'static` regardless of `'arena` (TextArray, JsonArray,
1317            // Hstore, TsVector, Range bounds, …). Clone the heap block
1318            // via the standard `into_owned()` path then lift the
1319            // resulting `Value<'static>` to `Value<'a>` via the Cow
1320            // variance — `'static` covers any lifetime.
1321            other => other.clone().into_owned(),
1322        }
1323    }
1324}
1325
1326impl Value<'static> {
1327    /// v7.37.42-arena Phase 1 — owned-Text constructor. The variant now
1328    /// holds `Cow<'arena, str>`, so the previous `Value::Text(String)`
1329    /// shape no longer compiles directly. This helper preserves the
1330    /// historical ergonomics: `Value::text("foo")` or
1331    /// `Value::text(String::from("foo"))`.
1332    pub fn text<S: Into<String>>(s: S) -> Self {
1333        Value::Text(Cow::Owned(s.into()))
1334    }
1335
1336    /// v7.38 (read01, T6) — a finite NUMERIC from its fixed-point parts.
1337    pub const fn numeric(scaled: i128, scale: u16) -> Self {
1338        Value::Numeric {
1339            scaled,
1340            scale,
1341            kind: NumericKind::Finite,
1342        }
1343    }
1344
1345    /// v7.38 (read01, T6) — a special NUMERIC (NaN / ±Infinity). The fixed-point
1346    /// fields are canonicalized to 0 so equal specials compare byte-identical.
1347    pub const fn numeric_special(kind: NumericKind) -> Self {
1348        Value::Numeric {
1349            scaled: 0,
1350            scale: 0,
1351            kind,
1352        }
1353    }
1354
1355    /// v7.37.42-arena Phase 1 — owned-Json constructor (mirrors `text`).
1356    pub fn json<S: Into<String>>(s: S) -> Self {
1357        Value::Json(Cow::Owned(s.into()))
1358    }
1359
1360    /// v7.37.42-arena Phase 1 — owned-Xml constructor.
1361    pub fn xml<S: Into<String>>(s: S) -> Self {
1362        Value::Xml(Cow::Owned(s.into()))
1363    }
1364
1365    /// v7.37.42-arena Phase 1 — owned-Bytes constructor.
1366    pub fn bytes<B: Into<Vec<u8>>>(b: B) -> Self {
1367        Value::Bytes(Cow::Owned(b.into()))
1368    }
1369
1370    /// v7.37.42-arena Phase 1 — owned-Vector constructor.
1371    pub fn vector<V: Into<Vec<f32>>>(v: V) -> Self {
1372        Value::Vector(Cow::Owned(v.into()))
1373    }
1374
1375    /// v7.37.42-arena Phase 1 — owned-BitString constructor.
1376    pub fn bit_string<B: Into<Vec<u8>>>(nbits: u32, bytes: B) -> Self {
1377        Value::BitString {
1378            nbits,
1379            bytes: Cow::Owned(bytes.into()),
1380        }
1381    }
1382}
1383
1384/// One table row — values are positional and must match
1385/// `TableSchema.columns` in length and (modulo NULL) in `DataType`.
1386///
1387/// v7.37.42-arena Phase 1: parameterised on `'arena` so per-query rows
1388/// can borrow from a bump arena. The owned shape (`Row<'static>`, alias
1389/// `RowOwned`) is what catalog storage, public APIs, and tests use.
1390#[derive(Debug, Clone, PartialEq)]
1391pub struct Row<'arena> {
1392    pub values: Vec<Value<'arena>>,
1393}
1394
1395/// Owned `Row` — values are `Value<'static>`. Used everywhere a row must
1396/// outlive a query-scoped arena.
1397pub type RowOwned = Row<'static>;
1398
1399impl<'arena> Row<'arena> {
1400    pub const fn new(values: Vec<Value<'arena>>) -> Self {
1401        Self { values }
1402    }
1403
1404    pub fn len(&self) -> usize {
1405        self.values.len()
1406    }
1407
1408    pub fn is_empty(&self) -> bool {
1409        self.values.is_empty()
1410    }
1411}
1412
1413impl<'arena> Row<'arena> {
1414    /// v7.37.42-arena Phase 4 — copy every cell into the supplied bump
1415    /// arena, yielding a `Row<'a>` whose Cow-payloads are arena-borrowed.
1416    /// Boundary helper for catalog defaults → DML eval handoff and
1417    /// arena-local row scratch.
1418    pub fn clone_into<'a>(&self, arena: &'a bumpalo::Bump) -> Row<'a> {
1419        Row {
1420            values: self.values.iter().map(|v| v.clone_into(arena)).collect(),
1421        }
1422    }
1423
1424    /// v7.37.42-arena Phase 4 — lift this `Row<'arena>` to a fully-owned
1425    /// `Row<'static>` for catalog write / WAL serialisation. Equivalent
1426    /// to `Row::from_arena(self)` but consumes by value at any lifetime
1427    /// (callers can write `row.into_owned()` mirroring `Value::into_owned`).
1428    pub fn into_owned(self) -> Row<'static> {
1429        Row {
1430            values: self.values.into_iter().map(Value::into_owned).collect(),
1431        }
1432    }
1433}
1434
1435impl Row<'static> {
1436    /// v7.37.42-arena Phase 1 — lift any `Row<'arena>` (possibly arena-
1437    /// borrowed) into a fully-owned `Row<'static>`. Mirrors
1438    /// `Value::into_owned`.
1439    pub fn from_arena(row: Row<'_>) -> Self {
1440        Self {
1441            values: row.values.into_iter().map(Value::into_owned).collect(),
1442        }
1443    }
1444}
1445
1446/// Each bool is an independent, separately-persisted column attribute
1447/// (`nullable`, `auto_increment`, `is_unsigned`, `identity_always`) that the
1448/// catalog appendix reads and writes by name. Packing them into a bitflags
1449/// word would buy nothing and would put a decoding step between the on-disk
1450/// format and every reader of the schema.
1451#[allow(clippy::struct_excessive_bools)]
1452#[derive(Debug, Clone, PartialEq)]
1453pub struct ColumnSchema {
1454    pub name: String,
1455    pub ty: DataType,
1456    pub nullable: bool,
1457    /// Optional `DEFAULT` value, frozen at CREATE TABLE time. `None`
1458    /// means "no default" (so omitted columns become NULL, or error
1459    /// out when the column is NOT NULL). Literal defaults take this
1460    /// path.
1461    ///
1462    /// v7.37.42-arena Phase 1: explicitly `Value<'static>` — catalog
1463    /// defaults must outlive any per-query arena.
1464    pub default: Option<Value<'static>>,
1465    /// v7.9.21 — for DEFAULT expressions that need INSERT-time
1466    /// evaluation (e.g. `DEFAULT now()`, `DEFAULT CURRENT_TIMESTAMP`),
1467    /// the Display form of the expression. The engine re-parses
1468    /// it on each INSERT default-fill, evaluates against an empty
1469    /// row context, and coerces to the column type. mailrs G4.
1470    /// Persisted in catalog FILE_VERSION 15+; older catalogs
1471    /// deserialise with None.
1472    pub runtime_default: Option<String>,
1473    /// MySQL-style `AUTO_INCREMENT`. When set, an INSERT that leaves
1474    /// this column unbound (or sets it to NULL) gets the next integer
1475    /// computed from the column's current max + 1.
1476    /// v7.39 (round 676) — the collation NAME as written, when the column
1477    /// carried an explicit `COLLATE`.
1478    ///
1479    /// `spg_sql::Collation` cannot carry it: it is a two-variant MySQL enum
1480    /// and `from_collation_name` folds `C`, `POSIX`, `en_US` and `default`
1481    /// all into `Binary`. Without the name `pg_attribute.attcollation` can
1482    /// only ever report the type's default, which is what F36 records as
1483    /// "the declaration is taken and ignored".
1484    ///
1485    /// None means the column was written without a `COLLATE` clause and
1486    /// takes its type's collation. Persisted through the v88 appendix,
1487    /// which costs two bytes for a table that declares none.
1488    pub collation_name: Option<String>,
1489    pub auto_increment: bool,
1490    /// v7.17.0 Phase 1.4 — when the column is bound to a user-
1491    /// defined ENUM type (the parser saw an unknown type ident
1492    /// and the engine resolved it against `catalog.enum_types`),
1493    /// this carries the enum name so INSERT/UPDATE can validate
1494    /// the cell value against the enum's labels. `ty` is
1495    /// `DataType::Text` in that case. Persisted in catalog
1496    /// FILE_VERSION 29+; older catalogs deserialise with None.
1497    pub user_enum_type: Option<String>,
1498    /// v7.17.0 Phase 1.5 — when the column is bound to a user-
1499    /// defined DOMAIN (the parser saw an unknown type ident and
1500    /// the engine resolved it against `catalog.domain_types`),
1501    /// this carries the domain name. `ty` is the domain's base
1502    /// type; INSERT/UPDATE re-evaluates the domain's CHECK list
1503    /// + NOT NULL against the cell value. Persisted in catalog
1504    /// FILE_VERSION 30+; older catalogs deserialise with None.
1505    pub user_domain_type: Option<String>,
1506    /// v7.39 (read01 round 56) — when the column is bound to a user-defined
1507    /// COMPOSITE type. `ty` stays `DataType::Jsonb` (the on-disk form), but the
1508    /// engine REHYDRATES the stored JSON into a `Value::Composite` on read, so
1509    /// field access `(p).x`, `= ROW(…)`, ordering and the canonical `(2,b)`
1510    /// text form all work — they were already implemented on Value::Composite;
1511    /// what was missing was that the column never recorded WHICH composite type
1512    /// it holds (this field's doc comment existed for two releases, the field
1513    /// itself did not). Persisted in the composite-column appendix
1514    /// (FILE_VERSION 63+); older catalogs deserialise with None.
1515    pub user_composite_type: Option<String>,
1516    /// v7.39 (read01 round 59) — column-level privileges (PG
1517    /// `pg_attribute.attacl`). `GRANT SELECT (pub) ON t TO dan` lands here and
1518    /// does NOT touch the table's `relacl`. Empty = no column grant, which is
1519    /// every column until one is made.
1520    pub acl: Vec<AclItem>,
1521    /// v7.17.0 Phase 2.1 — MySQL `ON UPDATE CURRENT_TIMESTAMP`
1522    /// column attribute. When `Some(expr_src)`, an UPDATE that
1523    /// does NOT bind this column overrides the new value with
1524    /// the engine-evaluated expression (always `now()` in
1525    /// v7.17.0). Stored as Display-form source so storage
1526    /// stays free of spg-sql; the engine re-parses at UPDATE
1527    /// time. Persisted in catalog FILE_VERSION 32+; older
1528    /// catalogs deserialise with None — preserves the existing
1529    /// "silent ignore" behaviour for snapshots written before
1530    /// the upgrade.
1531    pub on_update_runtime: Option<String>,
1532    /// v7.17.0 Phase 2.5 — text collation. Pre-2.5 SPG accepted
1533    /// `COLLATE <name>` clauses but discarded the name, so a
1534    /// column declared `COLLATE "case_insensitive"` (or any
1535    /// MySQL `_ci` collation) still compared byte-wise — a
1536    /// Tier-S silent failure where `WHERE name = 'foo'` never
1537    /// matched stored `'Foo'`. This carries the parser-derived
1538    /// classification so the engine's WHERE evaluator can route
1539    /// text equality through a case-aware compare. `Binary` (the
1540    /// default) preserves the prior byte-wise behaviour. Only
1541    /// CaseInsensitive lands in the catalog appendix — Binary
1542    /// columns stay implicit, keeping snapshots compact.
1543    /// Persisted in catalog FILE_VERSION 34+; older catalogs
1544    /// deserialise every column as `Binary`.
1545    pub collation: Collation,
1546    /// v7.17.0 Phase 4.4 — MySQL `UNSIGNED` modifier flag. Drives
1547    /// engine-side INSERT / UPDATE range enforcement (rejects
1548    /// negative values on UNSIGNED int columns). Pre-4.4 the
1549    /// parser consumed and discarded the keyword silently, so
1550    /// every UNSIGNED column quietly accepted negatives — a
1551    /// Tier-A correctness drift. Sparse: only UNSIGNED columns
1552    /// land in the catalog appendix; the default `false` keeps
1553    /// snapshots compact for the common signed-int path.
1554    /// Persisted in catalog FILE_VERSION 35+; older catalogs
1555    /// deserialise every column as `is_unsigned = false`.
1556    pub is_unsigned: bool,
1557    /// v7.17.0 Phase 3.P0-36 — MySQL inline `ENUM('a','b','c')`
1558    /// value list. Distinct from `user_enum_type` (which points
1559    /// to a separately CREATE TYPE'd PG enum); this carries the
1560    /// column-local list MySQL DDL declares inline. When `Some`,
1561    /// `ty` is `DataType::Text` and INSERT/UPDATE validates the
1562    /// cell value against this list. Variant ORDER is preserved
1563    /// (MySQL uses it for `ORDER BY col`). Sparse: only ENUM
1564    /// columns land in the catalog appendix.
1565    /// Persisted in catalog FILE_VERSION 41+; older catalogs
1566    /// deserialise with None — preserves silent-drop behaviour
1567    /// for snapshots written before P0-36.
1568    pub inline_enum_variants: Option<Vec<String>>,
1569    /// v7.17.0 Phase 3.P0-37 — MySQL inline `SET('a','b','c')`
1570    /// variant list. Storage is TEXT (canonical comma-joined in
1571    /// definition order, de-duplicated). INSERT/UPDATE validates
1572    /// every comma-separated token against this list. Sparse:
1573    /// only SET columns land in the catalog appendix.
1574    /// Persisted in catalog FILE_VERSION 42+; older catalogs
1575    /// deserialise with None.
1576    pub inline_set_variants: Option<Vec<String>>,
1577    /// v7.37.7(sentori Epic 3 P1)— `GENERATED ALWAYS AS (<expr>)
1578    /// STORED` computed-column source. When `Some`, INSERT / UPDATE
1579    /// recompute the cell against the candidate row(re-parse the
1580    /// stored Display form and evaluate)and overwrite any
1581    /// user-supplied value, matching PG's stored-generated-column
1582    /// semantics. `None` (the default) preserves the regular
1583    /// "column value is whatever the caller passed" path.
1584    /// Persisted in catalog FILE_VERSION 50+; older catalogs
1585    /// deserialise with None.
1586    pub generated_stored_expr: Option<String>,
1587    /// v7.38 (read01) — `GENERATED ALWAYS AS IDENTITY`. Both identity
1588    /// flavours set `auto_increment`; this additionally marks the ALWAYS
1589    /// flavour, whose explicit INSERT value PG rejects ("cannot insert a
1590    /// non-DEFAULT value into column …") unless `OVERRIDING SYSTEM VALUE`.
1591    /// `false` (serial / `BY DEFAULT`) keeps the permissive path. In-memory
1592    /// only for now — not yet in the catalog appendix, so a reloaded table
1593    /// deserialises as `false` (the pre-existing permissive behaviour).
1594    pub identity_always: bool,
1595    /// v7.38 (read01) — the DEFAULT expression's source text, deparsed to
1596    /// PG-compatible form at CREATE TABLE time (e.g. `0`, `(3 + 4)`,
1597    /// `'hi'::text`, `now()`, `CURRENT_DATE`). Distinct from `default`
1598    /// (the coerced value the INSERT path fills) and `runtime_default`
1599    /// (the recompute-per-row Display form): those lose the source
1600    /// spelling, so `information_schema.columns.column_default` /
1601    /// `pg_attrdef` / `pg_get_expr` reported the coerced render
1602    /// (`0.00` for `numeric(10,2) DEFAULT 0`) instead of PG's `0`.
1603    /// `None` for a column with no explicit default. Persisted in catalog
1604    /// FILE_VERSION 58+; older catalogs deserialise with None.
1605    pub default_text: Option<String>,
1606    /// v7.39 (round 220) — `ALTER TABLE … ALTER COLUMN … RESTART [WITH n]`
1607    /// on an identity column. SPG's identity allocation is a max+1 scan;
1608    /// this floor lifts the next allocated value to at least `n`
1609    /// (`max(max+1, n)`) — exactly what a dump-restore RESTART needs, and
1610    /// safer than PG for a backward RESTART (no duplicate-key landmine).
1611    /// Persisted in the FILE_VERSION 73+ sparse appendix; older catalogs
1612    /// deserialise with None.
1613    pub auto_restart: Option<i64>,
1614    /// v7.39 (read01 round 78) — this column is the ONLY column of a FROM item
1615    /// that calls a function returning a BASE type, so the item's row type IS
1616    /// this column: a whole-row reference collapses to the value
1617    /// (`SELECT j FROM jsonb_array_elements('[1]') AS j` → `1`, PG). Runtime
1618    /// only — a catalogued table column is never one, and it is not persisted.
1619    pub scalar_row_source: bool,
1620    /// v7.39 (round 386, type-fidelity epic P1) — the declared MySQL narrow
1621    /// integer width (TINYINT / MEDIUMINT) whose range the storage `ty`
1622    /// (SmallInt / Int) is too wide to enforce. `None` for every other
1623    /// column. Drives the epic-P2 write-path range check. Persisted in the
1624    /// FILE_VERSION 81+ sparse appendix; older catalogs deserialise as None.
1625    pub mysql_int_width: Option<MysqlIntWidth>,
1626    /// v7.39 (round 424, type-fidelity epic) — the declared MySQL
1627    /// fractional-seconds precision of a temporal column: `DATETIME(3)` is
1628    /// `Some(3)`, a BARE `DATETIME` / `TIME` / `TIMESTAMP` is `Some(0)`
1629    /// (MySQL's default is zero — the fraction is dropped on write), and
1630    /// `None` means "not a MySQL-declared temporal column", which is every
1631    /// PG column and leaves microsecond behaviour untouched.
1632    ///
1633    /// Drives write-path truncation (toward zero) and render padding
1634    /// (exactly this many digits, `.000` when the fraction is zero).
1635    /// Persisted in the FILE_VERSION 82+ sparse appendix; older catalogs
1636    /// deserialise as None.
1637    pub mysql_fsp: Option<u8>,
1638}
1639
1640/// v7.17.0 Phase 2.5 — column-level text collation. Drives the
1641/// engine's WHERE / GROUP BY equality routing for `Value::Text`.
1642/// Only two variants are modelled in v7.17:
1643///   * `Binary`  — byte-wise comparison (the SPG default;
1644///                 matches PG `COLLATE "C"` / `pg_catalog.default`
1645///                 and MySQL `*_bin`).
1646///   * `CaseInsensitive` — ASCII case-folded comparison (like
1647///                 MySQL `*_ci` collations; PG has NO built-in
1648///                 collation of this name — round-761 audit: a
1649///                 nondeterministic ICU collation must be CREATEd
1650///                 there first). Non-ASCII bytes
1651///                 still compare byte-wise; full ICU folding is
1652///                 out of v7.17 scope.
1653/// New variants append at the end — older catalogs read missing
1654/// columns as `Binary`.
1655#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1656pub enum Collation {
1657    Binary,
1658    CaseInsensitive,
1659}
1660
1661/// v7.39 (round 386, type-fidelity epic P1) — the declared MySQL narrow
1662/// integer type for a column whose storage `DataType` cannot express it.
1663/// MySQL `TINYINT` (i8, -128..127) collapses to `DataType::SmallInt` (i16)
1664/// and `MEDIUMINT` (24-bit) to `DataType::Int` (i32) — both wider than the
1665/// declared type, so a range check against `ty` alone accepts out-of-range
1666/// values (`INSERT 128 INTO TINYINT` is stored silently where MariaDB
1667/// strict raises ERROR 1264). This annotation records the lost width so the
1668/// write path (epic P2) can enforce the real bounds. `SMALLINT` / `INT` /
1669/// `BIGINT` need no marker — their storage `DataType` is already faithful.
1670/// Sparse: only TINYINT / MEDIUMINT columns carry it; persisted in the
1671/// FILE_VERSION 81+ appendix, older catalogs deserialise as None.
1672#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1673pub enum MysqlIntWidth {
1674    /// MySQL `TINYINT` — signed -128..127, unsigned 0..255. Storage i16.
1675    Tiny,
1676    /// MySQL `SMALLINT UNSIGNED` — 0..65535. Storage widened to i32 (a
1677    /// signed SMALLINT keeps `DataType::SmallInt` and carries no marker).
1678    Small,
1679    /// MySQL `MEDIUMINT` — signed -8388608..8388607, unsigned 0..16777215.
1680    /// Storage i32.
1681    Medium,
1682    /// MySQL `INT UNSIGNED` — 0..4294967295. Storage widened to i64 (a
1683    /// signed INT keeps `DataType::Int` and carries no marker).
1684    Int,
1685    /// v7.39 (round 471, epic P4b) — MySQL `BIGINT UNSIGNED` —
1686    /// 0..18446744073709551615. i64 stops at 2^63-1, so the storage tag is
1687    /// widened to `Numeric` (i128-backed, scale 0), which already compares,
1688    /// orders, indexes and renders as an exact integer. A signed BIGINT
1689    /// keeps `DataType::BigInt` and carries no marker.
1690    Big,
1691}
1692
1693/// v7.39 (round 363, M4 P1) — MySQL's default accent- and
1694/// case-insensitive fold (`utf8mb4_uca1400_ai_ci`).
1695///
1696/// This is the primitive M4 rests on: a session on the MySQL dialect
1697/// compares, groups, sorts and de-duplicates text by its FOLDED form, so
1698/// `Foo` = `foo` = `FOO` and, because the default collation is accent-
1699/// insensitive too, `Bär` = `bar`. The later stages (read path, then the
1700/// UNIQUE / index write path) all route through here so they cannot fold
1701/// differently from one another.
1702///
1703/// The fold is more than case + strip-combining: MariaDB EXPANDS some
1704/// letters — `ß` → `ss`, `æ` → `ae`, `œ` → `oe` — which is why the result
1705/// is built as a `String` rather than mapped char-for-char. Every mapping
1706/// below was measured on MariaDB 11 (`'Bär'='bar'` is 1, `'straße'=
1707/// 'strasse'` is 1, `'a'='æ'` is 0, `'s'='ß'` is 0). Characters with no
1708/// entry keep their lower-cased self, so ASCII and unknown scripts pass
1709/// through unchanged.
1710#[must_use]
1711pub fn mysql_ci_fold(s: &str) -> String {
1712    let mut out = String::with_capacity(s.len());
1713    for ch in s.chars() {
1714        // Lower-case first (`À` → `à`, `Æ` → `æ`), then fold the base.
1715        for lc in ch.to_lowercase() {
1716            match fold_latin_base(lc) {
1717                Some(base) => out.push_str(base),
1718                None => out.push(lc),
1719            }
1720        }
1721    }
1722    out
1723}
1724
1725/// v7.39 (round 375) — the fold used to COMPARE / GROUP / de-dup text on
1726/// the MySQL dialect. Its default collation is PAD SPACE: trailing spaces
1727/// do not affect a comparison (`'a' = 'a '`, `'' = ' '`, measured on
1728/// MariaDB 11), so they are stripped before the case/accent fold. Only
1729/// literal spaces pad — a tab or other whitespace is significant — and
1730/// this is NOT used by `LIKE`, whose pattern treats a trailing space
1731/// literally.
1732pub fn mysql_compare_fold(s: &str) -> String {
1733    mysql_ci_fold(s.trim_end_matches(' '))
1734}
1735
1736/// The base letter(s) a lower-cased Latin character folds to, or `None`
1737/// when it is already a base / has no fold. Expansions (`ß` → `ss`) are
1738/// why this returns a string.
1739fn fold_latin_base(c: char) -> Option<&'static str> {
1740    Some(match c {
1741        'à' | 'á' | 'â' | 'ã' | 'ä' | 'å' | 'ā' | 'ă' | 'ą' => "a",
1742        'æ' => "ae",
1743        'ç' | 'ć' | 'č' | 'ĉ' | 'ċ' => "c",
1744        'ð' | 'ď' | 'đ' => "d",
1745        'è' | 'é' | 'ê' | 'ë' | 'ē' | 'ĕ' | 'ė' | 'ę' | 'ě' => "e",
1746        'ĝ' | 'ğ' | 'ġ' | 'ģ' => "g",
1747        'ì' | 'í' | 'î' | 'ï' | 'ĩ' | 'ī' | 'ĭ' | 'į' => "i",
1748        'ĵ' => "j",
1749        'ķ' => "k",
1750        'ł' | 'ĺ' | 'ļ' | 'ľ' => "l",
1751        'ñ' | 'ń' | 'ņ' | 'ň' => "n",
1752        'ò' | 'ó' | 'ô' | 'õ' | 'ö' | 'ø' | 'ō' | 'ŏ' | 'ő' => "o",
1753        'œ' => "oe",
1754        'ŕ' | 'ŗ' | 'ř' => "r",
1755        'ś' | 'š' | 'ŝ' | 'ş' => "s",
1756        'ß' => "ss",
1757        'ţ' | 'ť' | 'ŧ' => "t",
1758        'ù' | 'ú' | 'û' | 'ü' | 'ũ' | 'ū' | 'ŭ' | 'ů' | 'ű' | 'ų' => "u",
1759        'ý' | 'ÿ' => "y",
1760        'ź' | 'ž' | 'ż' => "z",
1761        _ => return None,
1762    })
1763}
1764
1765#[allow(clippy::derivable_impls)]
1766impl Default for Collation {
1767    fn default() -> Self {
1768        Self::Binary
1769    }
1770}
1771
1772impl Collation {
1773    /// Wire tag persisted in the FILE_VERSION 34+ catalog appendix.
1774    /// Stable: future variants append above the recognised range
1775    /// and unknown tags read back as `Binary` for forward-compat
1776    /// on rollback.
1777    pub const TAG_BINARY: u8 = 0;
1778    pub const TAG_CASE_INSENSITIVE: u8 = 1;
1779}
1780
1781/// v7.39 (RLS) — the command a policy applies to. `ALL` is the default and
1782/// covers every command; the others scope the policy to one statement kind.
1783/// Persisted as a single byte in the policy appendix (FILE_VERSION 59+).
1784#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1785pub enum PolicyCmd {
1786    All,
1787    Select,
1788    Insert,
1789    Update,
1790    Delete,
1791}
1792
1793impl PolicyCmd {
1794    /// PG `pg_policy.polcmd` single-char encoding.
1795    #[must_use]
1796    pub const fn as_pg_char(self) -> char {
1797        match self {
1798            Self::All => '*',
1799            Self::Select => 'r',
1800            Self::Insert => 'a',
1801            Self::Update => 'w',
1802            Self::Delete => 'd',
1803        }
1804    }
1805
1806    /// PG `pg_policies.cmd` word form.
1807    #[must_use]
1808    pub const fn as_pg_word(self) -> &'static str {
1809        match self {
1810            Self::All => "ALL",
1811            Self::Select => "SELECT",
1812            Self::Insert => "INSERT",
1813            Self::Update => "UPDATE",
1814            Self::Delete => "DELETE",
1815        }
1816    }
1817
1818    #[must_use]
1819    pub const fn to_wire_byte(self) -> u8 {
1820        match self {
1821            Self::All => 0,
1822            Self::Select => 1,
1823            Self::Insert => 2,
1824            Self::Update => 3,
1825            Self::Delete => 4,
1826        }
1827    }
1828
1829    #[must_use]
1830    pub const fn from_wire_byte(b: u8) -> Option<Self> {
1831        match b {
1832            0 => Some(Self::All),
1833            1 => Some(Self::Select),
1834            2 => Some(Self::Insert),
1835            3 => Some(Self::Update),
1836            4 => Some(Self::Delete),
1837            _ => None,
1838        }
1839    }
1840}
1841
1842/// v7.39 (RLS) — one `CREATE POLICY` object, stored per table. The `using_expr`
1843/// / `with_check_expr` hold the qualifying expression's `Display` form
1844/// (re-parsed and evaluated per row at enforcement time, exactly like
1845/// `TableSchema.checks`); `None` means the clause was absent. `roles` empty =
1846/// PUBLIC. Persisted in the policy appendix (FILE_VERSION 59+).
1847#[derive(Debug, Clone, PartialEq)]
1848pub struct PolicyDef {
1849    pub name: String,
1850    pub cmd: PolicyCmd,
1851    /// `true` = PERMISSIVE (default, OR-combined), `false` = RESTRICTIVE
1852    /// (AND-combined).
1853    pub permissive: bool,
1854    pub roles: Vec<String>,
1855    pub using_expr: Option<String>,
1856    pub with_check_expr: Option<String>,
1857}
1858
1859#[derive(Debug, Clone, PartialEq)]
1860pub struct TableSchema {
1861    pub name: String,
1862    pub columns: Vec<ColumnSchema>,
1863    /// v6.7.2 — per-table hot-tier byte budget override. `None`
1864    /// falls through to the global `SPG_HOT_TIER_BYTES` setting;
1865    /// `Some(n)` overrides it for this specific table. Set via
1866    /// `ALTER TABLE t SET hot_tier_bytes = X`. Persisted in
1867    /// catalog FILE_VERSION 11+.
1868    pub hot_tier_bytes: Option<u64>,
1869    /// v7.6.1 — FOREIGN KEY constraints declared on this table.
1870    /// Engine maintains this in lock-step with `spg-sql`'s parser
1871    /// AST; the storage layer carries the on-disk shape so a
1872    /// catalog snapshot round-trips without external mapping.
1873    /// Persisted in catalog FILE_VERSION 13+. Older catalogs
1874    /// deserialise with an empty vec.
1875    pub foreign_keys: Vec<ForeignKeyConstraint>,
1876    /// v7.9.19 — composite UNIQUE / PRIMARY KEY constraints
1877    /// declared at the table level. Each entry's leading column
1878    /// has a BTree index (created via the constraint), and INSERT
1879    /// path enforces the full-tuple uniqueness via a scan keyed
1880    /// by the leading column. Persisted in catalog FILE_VERSION
1881    /// 15+. Older catalogs (≤ 14) deserialise with an empty vec.
1882    pub uniqueness_constraints: Vec<UniquenessConstraint>,
1883    /// v7.39 (round 210) — `EXCLUDE` constraints declared at the table level.
1884    /// Enforced on INSERT/UPDATE by a full live-row scan re-checking each
1885    /// element's operator (no equality index can answer overlap). Persisted
1886    /// in catalog FILE_VERSION 72+; older catalogs deserialise with an empty
1887    /// vec.
1888    pub exclusion_constraints: Vec<ExclusionConstraint>,
1889    /// v7.13.0 — `CHECK (<expr>)` predicates declared on this
1890    /// table. Both column-level inline `CHECK (…)` and
1891    /// table-level `CHECK (…)` fold into this list. Each entry
1892    /// is the AST Expr's `Display` form, re-parsed on every
1893    /// INSERT/UPDATE and evaluated against the candidate row.
1894    /// A false / NULL result rejects the mutation (PG semantics).
1895    /// Persisted in catalog FILE_VERSION 23+. Older catalogs
1896    /// deserialise with an empty vec. v7.39 (read01 round 48) — each entry
1897    /// now carries the user's constraint name too (FILE_VERSION 60+).
1898    pub checks: Vec<CheckConstraint>,
1899    /// v7.37.6-B — declarative partition role(sentori Epic 2 P0).
1900    /// `None` = 普通表(后向兼容,< v49 catalog 默认 None)。
1901    /// `Some(Parent { … })` = `CREATE TABLE p (...) PARTITION BY RANGE (key_col)` 父表 —
1902    /// 父表自己 `rows` 永远空,INSERT 在引擎层路由到命中的 child。
1903    /// `Some(Range { … })` = `CREATE TABLE c PARTITION OF p FOR VALUES FROM (a) TO (b)` 范围子表。
1904    /// `Some(Default { … })` = `CREATE TABLE c PARTITION OF p DEFAULT` 兜底子表。
1905    /// 持久化于 FILE_VERSION 49+。
1906    pub partition_role: Option<PartitionRole>,
1907    /// v7.39 (RLS) — `CREATE POLICY` objects on this table, independent of the
1908    /// `row_security` flag (PG stores policies even on non-RLS tables; they
1909    /// only take effect once RLS is enabled). Persisted in the policy appendix
1910    /// (FILE_VERSION 59+). Older catalogs deserialise with an empty vec.
1911    pub policies: Vec<PolicyDef>,
1912    /// v7.39 (RLS) — `ALTER TABLE … ENABLE ROW LEVEL SECURITY`
1913    /// (PG `pg_class.relrowsecurity`). Fresh table = `false`.
1914    pub row_security: bool,
1915    /// v7.39 (RLS) — `ALTER TABLE … FORCE ROW LEVEL SECURITY`
1916    /// (PG `pg_class.relforcerowsecurity`); subjects the table owner to RLS
1917    /// too. Fresh table = `false`.
1918    pub force_row_security: bool,
1919    /// v7.39 (read01 round 57, ACL) — the role that owns this table: whoever
1920    /// ran CREATE TABLE (PG `pg_class.relowner`). The owner holds every
1921    /// privilege implicitly and is the only role that may ALTER / DROP it.
1922    /// `None` = an image written before FILE_VERSION 64, which predates roles
1923    /// entirely; those tables read back as owned by the login role.
1924    pub owner: Option<String>,
1925    /// v7.39 (read01 round 57, ACL) — explicit GRANTs on this table
1926    /// (PG `pg_class.relacl`). EMPTY means "never granted": PG leaves relacl
1927    /// NULL while only the owner's implicit privileges apply, and materialises
1928    /// the whole list — owner's default entry included — on the first GRANT.
1929    /// Once materialised it stays, even after every grant is revoked.
1930    pub acl: Vec<AclItem>,
1931}
1932
1933/// v7.39 (read01 round 57) — one PG `aclitem`: what `grantee` may do to a
1934/// table, and who granted it. Renders as `grantee=privs/grantor`, with an
1935/// EMPTY grantee meaning PUBLIC (`=r/owner`).
1936#[derive(Debug, Clone, PartialEq, Eq)]
1937pub struct AclItem {
1938    /// The role the privileges are held by. Empty string = PUBLIC.
1939    pub grantee: String,
1940    /// Bitmask over `priv_bits`: which privileges are held.
1941    pub privs: u16,
1942    /// Bitmask over `priv_bits`: which of them carry WITH GRANT OPTION
1943    /// (PG renders those with a trailing `*` — `r*`).
1944    pub grantable: u16,
1945    /// The role that ran the GRANT.
1946    pub grantor: String,
1947}
1948
1949/// v7.39 (read01 round 57) — the table-privilege bits, in PG's `aclitem`
1950/// rendering order (`arwdDxtm`). The order matters: `relacl` output is
1951/// byte-compared against PG.
1952pub mod priv_bits {
1953    pub const INSERT: u16 = 1 << 0; // a
1954    pub const SELECT: u16 = 1 << 1; // r
1955    pub const UPDATE: u16 = 1 << 2; // w
1956    pub const DELETE: u16 = 1 << 3; // d
1957    pub const TRUNCATE: u16 = 1 << 4; // D
1958    pub const REFERENCES: u16 = 1 << 5; // x
1959    pub const TRIGGER: u16 = 1 << 6; // t
1960    pub const MAINTAIN: u16 = 1 << 7; // m
1961    /// v7.39 (read01 round 60) — the non-table privileges. They share the
1962    /// bitmask because an aclitem is an aclitem whatever it hangs off; which
1963    /// bits are MEANINGFUL depends on the object (a sequence has r / w / U, a
1964    /// schema has U / C, a database has C / c / T).
1965    pub const USAGE: u16 = 1 << 8; // U
1966    pub const CREATE: u16 = 1 << 9; // C
1967    pub const CONNECT: u16 = 1 << 10; // c
1968    pub const TEMPORARY: u16 = 1 << 11; // T
1969    pub const EXECUTE: u16 = 1 << 12; // X
1970    /// Every TABLE privilege — what `GRANT ALL ON <table>` grants and what a
1971    /// table's owner holds.
1972    pub const ALL: u16 =
1973        INSERT | SELECT | UPDATE | DELETE | TRUNCATE | REFERENCES | TRIGGER | MAINTAIN;
1974    /// `GRANT ALL ON SEQUENCE` — PG renders a sequence owner's default as `rwU`.
1975    pub const ALL_SEQUENCE: u16 = SELECT | UPDATE | USAGE;
1976    /// `GRANT ALL ON SCHEMA` — `UC`.
1977    pub const ALL_SCHEMA: u16 = USAGE | CREATE;
1978    /// `GRANT ALL ON DATABASE` — `CTc`.
1979    pub const ALL_DATABASE: u16 = CREATE | CONNECT | TEMPORARY;
1980    /// `GRANT ALL ON FUNCTION` — just `X`.
1981    pub const ALL_FUNCTION: u16 = EXECUTE;
1982}
1983
1984/// v7.37.6-B — partition 三态(parent / range child / default child)。
1985#[derive(Debug, Clone, PartialEq, Eq)]
1986pub enum PartitionRole {
1987    Parent {
1988        kind: PartitionKind,
1989        /// 父表 columns 中 key 列的下标(单列 v7.37.6-B,
1990        /// `Vec` 为将来扩多列预留)。
1991        key_column_positions: Vec<usize>,
1992        /// `CREATE INDEX ON parent (…)` 的 Display-form 源串。
1993        /// child 创建时再 parse + 在 child 上 execute,这样 future
1994        /// child 也自动继承父表索引。fan-out 实施在引擎层。
1995        index_template_sources: Vec<String>,
1996    },
1997    Range {
1998        parent_name: String,
1999        /// 半开区间下界(`>=`,SQL `FROM (lower)`).
2000        lower: PartitionBound,
2001        /// 半开区间上界(`<`,SQL `TO (upper)`).
2002        upper: PartitionBound,
2003    },
2004    /// v7.37.16 (16.1) — LIST child:行属于本 child iff key ∈ values。
2005    /// `values` 在 child 创建时从 SQL `FOR VALUES IN (lit, …)` 求值;
2006    /// 跟 PG 一样,显式 NULL ∈ values 由 caller 单独处理(不在
2007    /// PartitionBound 内表达 NULL)。
2008    List {
2009        parent_name: String,
2010        values: Vec<PartitionBound>,
2011    },
2012    /// v7.39 (round 645) — PG 表继承的 CHILD:`CREATE TABLE c (…)
2013    /// INHERITS (p1, p2)`。跟分区 child 的三个本质区别(实测 PG18):
2014    ///   * 父表**自己有行**(分区父表永远空),所以父表的联合体要含自身;
2015    ///   * `INSERT INTO 父表` **不路由**到 child(分区会路由);
2016    ///   * `DROP TABLE 父表` 不带 CASCADE **报错**(分区父表连子表一起删)。
2017    /// 多父继承合法,故 `parent_names` 是 Vec;`pg_inherits.inhseqno`
2018    /// 正是父表在这个列表里的位置(1-based)。
2019    Inherits {
2020        parent_names: Vec<String>,
2021    },
2022    /// v7.37.16 (16.2) — HASH child:行属于本 child iff
2023    /// `pg_compatible_hash(key) mod modulus == remainder`。
2024    /// PG 强制 `0 ≤ remainder < modulus`;parser/DDL 层先 gate。
2025    Hash {
2026        parent_name: String,
2027        modulus: u32,
2028        remainder: u32,
2029    },
2030    Default {
2031        parent_name: String,
2032    },
2033}
2034
2035/// v7.37.6-B — 分区策略。
2036///
2037/// - `Range`:半开区间 `[lower, upper)`(v7.37.6-B 初始)
2038/// - `List` (v7.37.16):枚举集合 — 行属于 partition iff key ∈ children list
2039/// - `Hash` (v7.37.16):`hash(key) mod modulus == remainder`
2040#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2041pub enum PartitionKind {
2042    Range,
2043    List,
2044    Hash,
2045}
2046
2047/// v7.37.6-B — partition 边界 literal。
2048///
2049/// v7.37.6-B 仅 `TimestampTz`(i64 microseconds since epoch);
2050/// v7.37.16 (16.6) 加全 PG 内建可比类型,匹配 `Value` 的对应 variant
2051/// 以避免 LIST membership 比较时的类型转换。
2052///
2053/// `MinValue` / `MaxValue` 对应 SQL `MINVALUE` / `MAXVALUE`,仅
2054/// Range 策略有意义(LIST 无 minvalue/maxvalue 概念,HASH 不
2055/// 使用 PartitionBound)。
2056#[derive(Debug, Clone, PartialEq, Eq)]
2057pub enum PartitionBound {
2058    MinValue,
2059    MaxValue,
2060    TimestampTz(i64),
2061    /// v7.37.16 (16.6) — BIGINT partition key.
2062    BigInt(i64),
2063    /// v7.37.16 (16.6) — INTEGER partition key (also covers
2064    /// `SERIAL` since SPG decomposes it to INTEGER + sequence).
2065    Int(i32),
2066    /// v7.37.16 (16.6) — SMALLINT partition key.
2067    SmallInt(i16),
2068    /// v7.37.16 (16.6) — DATE partition key. Stored as days
2069    /// since the Unix epoch (matches `Value::Date`).
2070    Date(i32),
2071    /// v7.37.16 (16.6) — TEXT / VARCHAR partition key.
2072    Text(alloc::string::String),
2073}
2074
2075impl PartitionBound {
2076    /// v7.37.16 (16.6) — true iff this bound's underlying value
2077    /// equals `other`'s. Used for LIST partition membership
2078    /// checks. Returns false for `MinValue` / `MaxValue`
2079    /// (sentinels — never literal equality).
2080    #[must_use]
2081    pub fn equals_value(&self, other: &Value<'_>) -> bool {
2082        match (self, other) {
2083            (PartitionBound::TimestampTz(a), Value::Timestamp(b)) => a == b,
2084            (PartitionBound::BigInt(a), Value::BigInt(b)) => a == b,
2085            (PartitionBound::Int(a), Value::Int(b)) => a == b,
2086            (PartitionBound::SmallInt(a), Value::SmallInt(b)) => a == b,
2087            (PartitionBound::Date(a), Value::Date(b)) => a == b,
2088            (PartitionBound::Text(a), Value::Text(b)) => a.as_str() == b.as_ref(),
2089            _ => false,
2090        }
2091    }
2092}
2093
2094/// v7.9.19 — composite UNIQUE / PRIMARY KEY constraint persisted
2095/// on the table schema. The leading column always has a BTree
2096/// index (created at CREATE TABLE time); INSERT enforcement
2097/// scans that index for collisions on the full column tuple.
2098/// v7.39 (read01 round 48) — a `CHECK` constraint: the SQL name the user
2099/// gave it (via `ADD CONSTRAINT <name> CHECK (...)` or the inline
2100/// `CONSTRAINT <name> CHECK (...)` form) plus the predicate source. `None`
2101/// name = unnamed, in which case `pg_constraint` synthesises PG's
2102/// `<table>_<col>_check` form. Names are persisted in the constraint-name
2103/// appendix (FILE_VERSION 60+); older catalogs deserialise with `None`.
2104#[derive(Debug, Clone, PartialEq, Eq)]
2105pub struct CheckConstraint {
2106    pub name: Option<String>,
2107    /// The AST Expr's `Display` form, re-parsed on every INSERT/UPDATE.
2108    pub expr: String,
2109    /// v7.39 (round 652) — `false` for a constraint added `NOT VALID`: the
2110    /// rows already in the table were never scanned against it, and
2111    /// `pg_constraint.convalidated` says so. It does NOT weaken the check on
2112    /// new rows — INSERT and UPDATE enforce it either way, as in PG.
2113    /// `VALIDATE CONSTRAINT` does the deferred scan and flips it. Persisted
2114    /// by the FILE_VERSION 87 appendix; older catalogs deserialise as `true`,
2115    /// which is what every constraint they could hold actually was.
2116    pub validated: bool,
2117}
2118
2119#[derive(Debug, Clone, PartialEq, Eq)]
2120pub struct UniquenessConstraint {
2121    /// `true` when this constraint was declared as `PRIMARY KEY`
2122    /// (vs `UNIQUE`). Semantically PK implies NOT NULL on all
2123    /// referenced columns; the engine enforces that at CREATE
2124    /// TABLE time.
2125    pub is_primary_key: bool,
2126    /// Column positions on the parent table. ≥ 1 element. For
2127    /// single-column UNIQUE this is exactly one position; the
2128    /// BTree index alone enforces it.
2129    pub columns: Vec<usize>,
2130    /// v7.13.0 — `UNIQUE NULLS NOT DISTINCT` modifier
2131    /// (mailrs round-5 G10; PG 15+ surface). When `true`, two
2132    /// rows whose constrained columns are all NULL collide on
2133    /// the constraint. Default (`false`) is the SQL-standard
2134    /// `NULLS DISTINCT` behaviour where any NULL passes.
2135    /// Persisted in catalog FILE_VERSION 23+.
2136    pub nulls_not_distinct: bool,
2137    /// v7.39 (read01 round 48) — the constraint's SQL name when the user
2138    /// supplied one (`ADD CONSTRAINT <name> PRIMARY KEY/UNIQUE (...)`, or
2139    /// the inline `CONSTRAINT <name>` form). `None` = unnamed, in which
2140    /// case `pg_constraint` synthesises PG's `<table>_pkey` /
2141    /// `<table>_<col>_key` form. DROP CONSTRAINT resolves the stored name
2142    /// first and falls back to the synthesised one, so catalogs written
2143    /// before this field (< FILE_VERSION 60) keep working unchanged.
2144    pub name: Option<String>,
2145    /// v7.39 (round 711) — `[NOT] DEFERRABLE`. Round 621 taught the parser
2146    /// to CONSUME the clause on PK/UNIQUE (the FK path had stored it since
2147    /// round 288); this is the storing half. Persisted in the v89 timing
2148    /// appendix.
2149    pub deferrable: bool,
2150    /// `INITIALLY DEFERRED`: the check belongs to COMMIT, not the
2151    /// statement, unless `SET CONSTRAINTS … IMMEDIATE` pulls it in.
2152    pub initially_deferred: bool,
2153}
2154
2155/// v7.39 (round 210) — an `EXCLUDE` constraint. Forbids two distinct live
2156/// rows from satisfying, for EVERY element, `new.col <op> existing.col`
2157/// (e.g. `EXCLUDE USING gist (during WITH &&)` = no two `during` ranges
2158/// overlap). Unlike a uniqueness constraint the operator is not equality,
2159/// so enforcement is a full live-row scan re-checking the operator (a real
2160/// GiST index that answers overlap in O(log n) is a later perf phase). A
2161/// NULL in any element column exempts the row (matching PG / UNIQUE NULL
2162/// semantics). Persisted in catalog FILE_VERSION 72+.
2163#[derive(Debug, Clone, PartialEq, Eq)]
2164pub struct ExclusionConstraint {
2165    /// The constraint's SQL name. PG auto-names an unnamed EXCLUDE
2166    /// `<table>_<leading-col>_excl`; the engine synthesises that at CREATE
2167    /// TABLE time so this is always populated.
2168    pub name: String,
2169    /// Access method spelled after `USING` (`gist`, `spgist`, …), lower-cased.
2170    /// `None` = no `USING` clause. Purely cosmetic for enforcement; it round-
2171    /// trips into `pg_get_constraintdef`.
2172    pub method: Option<String>,
2173    /// One `(column-position, operator-spelling)` pair per element, in
2174    /// declaration order. The operator spelling is the wire token (`&&`,
2175    /// `=`, `@>`, `<@`, `&<`, `&>`) evaluated against each existing row.
2176    pub elements: Vec<(usize, String)>,
2177}
2178
2179/// v7.6.1 — Storage-layer mirror of `spg_sql::ast::ForeignKeyConstraint`.
2180/// The engine's CREATE TABLE path translates between the two; keeping
2181/// them separate preserves the no-deps boundary between
2182/// `spg-storage` and `spg-sql`.
2183#[derive(Debug, Clone, PartialEq, Eq)]
2184pub struct ForeignKeyConstraint {
2185    /// Optional user-supplied constraint name (`CONSTRAINT <name>`
2186    /// prefix). Used by `ALTER TABLE DROP CONSTRAINT <name>` in
2187    /// v7.6.8; ignored by enforcement.
2188    pub name: Option<String>,
2189    /// Positions of local columns in this table's column list.
2190    /// Same arity as `parent_columns`.
2191    pub local_columns: Vec<usize>,
2192    /// Referenced parent table name.
2193    pub parent_table: String,
2194    /// Positions of parent columns in the parent's column list.
2195    /// Engine resolves these at CREATE TABLE time (after the parent
2196    /// schema is known) so enforcement paths can skip the name
2197    /// lookup on every row.
2198    pub parent_columns: Vec<usize>,
2199    /// Referential action when a parent row is deleted.
2200    pub on_delete: FkAction,
2201    /// Referential action when a parent row's referenced columns
2202    /// are updated.
2203    pub on_update: FkAction,
2204    /// v7.38 (read01, T29) — `MATCH SIMPLE | FULL`. Defaults to `Simple`.
2205    pub match_type: MatchType,
2206    /// v7.39 (round 288) — `[NOT] DEFERRABLE`.
2207    pub deferrable: bool,
2208    /// `INITIALLY DEFERRED`: the check runs at COMMIT rather than at
2209    /// the statement, unless `SET CONSTRAINTS … IMMEDIATE` pulls it in.
2210    pub initially_deferred: bool,
2211}
2212
2213/// v7.38 (read01, T29) — FK MATCH type. Mirrors `spg_sql::ast::MatchType`.
2214#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
2215pub enum MatchType {
2216    #[default]
2217    Simple,
2218    Full,
2219}
2220
2221impl MatchType {
2222    /// On-disk tag byte (catalog appendix, `FILE_VERSION` 55+).
2223    pub const fn tag(self) -> u8 {
2224        match self {
2225            Self::Simple => 0,
2226            Self::Full => 1,
2227        }
2228    }
2229    pub const fn from_tag(b: u8) -> Option<Self> {
2230        Some(match b {
2231            0 => Self::Simple,
2232            1 => Self::Full,
2233            _ => return None,
2234        })
2235    }
2236}
2237
2238/// v7.6.1 — referential action tag. Mirrors `spg_sql::ast::FkAction`.
2239#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2240pub enum FkAction {
2241    Restrict,
2242    Cascade,
2243    SetNull,
2244    SetDefault,
2245    NoAction,
2246}
2247
2248impl FkAction {
2249    /// On-disk tag byte (v13 catalog appendix).
2250    pub const fn tag(self) -> u8 {
2251        match self {
2252            Self::Restrict => 0,
2253            Self::Cascade => 1,
2254            Self::SetNull => 2,
2255            Self::SetDefault => 3,
2256            Self::NoAction => 4,
2257        }
2258    }
2259    pub const fn from_tag(b: u8) -> Option<Self> {
2260        Some(match b {
2261            0 => Self::Restrict,
2262            1 => Self::Cascade,
2263            2 => Self::SetNull,
2264            3 => Self::SetDefault,
2265            4 => Self::NoAction,
2266            _ => return None,
2267        })
2268    }
2269}
2270
2271impl TableSchema {
2272    pub fn column_position(&self, name: &str) -> Option<usize> {
2273        self.columns.iter().position(|c| c.name == name)
2274    }
2275}
2276
2277/// Key type accepted by secondary indices. Float / NULL / Vector values
2278/// can't participate in a B-tree index — `f64` is only `PartialOrd`, NULL
2279/// has SQL-three-valued semantics, and Vector belongs to the (future) HNSW
2280/// path. Index lookups on those columns fall back to full scan.
2281#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
2282pub enum IndexKey {
2283    Int(i64),
2284    Text(String),
2285    Bool(bool),
2286    /// v7.17.0 — `Value::Uuid` index key. Comparison is byte-wise
2287    /// (RFC 4122 byte order) so PRIMARY KEY UUID lookups land on
2288    /// the same fast-path as Int / Text.
2289    Uuid([u8; 16]),
2290    /// r1039 — `Value::Bytes` (bytea). PG orders bytea by plain byte
2291    /// comparison, shorter-prefix first (`'' < \x00 < \x0000 < \x01ff <
2292    /// \xff`, measured on 18.4), which is exactly `Vec<u8>`'s `Ord`.
2293    Bytes(Vec<u8>),
2294    /// r1039 — exact decimal, in the canonical form described on
2295    /// [`NumericKey`].
2296    ///
2297    /// r1040 — BOXED, and the box is load-bearing for every OTHER index.
2298    /// A `NumericKey` is 48 bytes against `Text(String)`'s 24, so inline
2299    /// it set the size of the whole enum and every B-tree node in every
2300    /// index grew with it: 32 bytes per key to 48, align 8 to 16.
2301    /// Measured through the release sweep, `SELECT pad FROM t ORDER BY
2302    /// id` over 400,000 rows — a walk of the primary key's index — went
2303    /// 39.4-40.6 ms to 42.3-44.1, in both leg orders. The indirection is
2304    /// charged to numeric keys, which are new, instead of to every index
2305    /// that existed already.
2306    Numeric(alloc::boxed::Box<NumericKey>),
2307    /// v7.38.1 (L12) — a NULL component INSIDE a composite key, and
2308    /// nothing else. `IndexKey::from_value(Value::Null)` still returns
2309    /// `None`, so single-column B-trees never hold one, and no probe
2310    /// path ever BUILDS one (`col = NULL` is not a match in SQL) — the
2311    /// variant is only reachable through a composite key's component
2312    /// list, where it exists so that a row like `(2, 3, NULL)` stays
2313    /// findable by a PREFIX probe on `(w, d)`. Declared last: slice
2314    /// `Ord` then sorts NULL components after every value, PG's
2315    /// NULLS LAST.
2316    Null,
2317}
2318
2319/// r1039 — an exact-decimal index key, canonical so that representation
2320/// equality IS value equality.
2321///
2322/// That property is the whole reason this is a struct rather than the
2323/// `(scaled, scale)` pair the value carries. `1.5` and `1.50` are the
2324/// same NUMERIC (PG18.4: `1.5::numeric = 1.50::numeric` is true) and
2325/// arrive here as `(15, 1)` and `(150, 2)`. A B-tree keyed on the raw
2326/// pair would file them apart, so `WHERE n = 1.5` would miss a row stored
2327/// as `1.50` — an index changing the answer, which is the one thing an
2328/// index may never do. `BigNumeric::cmp` carries the same warning and
2329/// declines to implement `Ord` for exactly this reason; a KEY cannot
2330/// decline, so it normalizes instead.
2331///
2332/// Canonical form: significant decimal digits with no leading and no
2333/// trailing zeros, most significant first, plus the decimal exponent of
2334/// the leading digit. Zero is the empty digit vector with `neg == false`
2335/// and `exp == 0`, so there is no `-0`.
2336///
2337/// Ordering is PG's, measured: `-Infinity < -1 < 0 < 1 < Infinity < NaN`,
2338/// and `NaN = NaN`.
2339#[derive(Debug, Clone, PartialEq, Eq)]
2340pub struct NumericKey {
2341    /// 0 = -Infinity, 1 = finite, 2 = +Infinity, 3 = NaN. Ordering the
2342    /// classes by this byte is what puts NaN on top, where PG keeps it.
2343    class: u8,
2344    /// Finite only, and never set for zero.
2345    neg: bool,
2346    /// Decimal exponent of the leading significant digit; 0 for zero.
2347    exp: i32,
2348    /// r1040 — the first [`HEAD_DIGITS`] significant digits, LEFT-ALIGNED
2349    /// (multiplied up so the leading digit always sits at 10^36). That
2350    /// alignment is what makes an integer comparison of two heads the same
2351    /// answer as a digit-by-digit one: `12` and `1` become 1.2e36 and
2352    /// 1.0e36, which order the way the digit strings do, where the bare
2353    /// integers 12 and 1 would not.
2354    ///
2355    /// Zero for the value zero and for every special.
2356    ///
2357    /// This started as a `Vec<u8>` of digits, which is correct and cost
2358    /// an allocation per key and a slice comparison per sort comparison.
2359    /// `ORDER BY <numeric>` builds one key per row and compares n log n
2360    /// times: 200,000 rows measured 65.4 ms against 39.6 for the f64
2361    /// projection that had been returning rows in the wrong order.
2362    head: u128,
2363    /// Significant digits past the 37th, one per byte, no trailing zeros.
2364    /// Empty for everything an `i128` mantissa can hold with room to
2365    /// spare — and an empty `Vec` does not allocate, which is the point.
2366    tail: Vec<u8>,
2367}
2368
2369/// Significant digits carried in [`NumericKey::head`]. 37 is the most
2370/// that can be left-aligned inside a `u128`: the largest such value is
2371/// 9.99…e36, and `u128::MAX` is 3.4e38.
2372const HEAD_DIGITS: u32 = 37;
2373/// `10^36` — where a left-aligned leading digit sits.
2374const HEAD_SCALE: u128 = 1_000_000_000_000_000_000_000_000_000_000_000_000;
2375
2376/// The `class` byte of [`NumericKey`], in PG's order.
2377const NUM_CLASS_NEG_INF: u8 = 0;
2378const NUM_CLASS_FINITE: u8 = 1;
2379const NUM_CLASS_POS_INF: u8 = 2;
2380const NUM_CLASS_NAN: u8 = 3;
2381
2382impl NumericKey {
2383    /// The key for a `Value::Numeric`'s three fields.
2384    ///
2385    /// Public because the ORDER BY key wants the same canonical form the
2386    /// index key uses: two sort keys that disagree about which of two
2387    /// NUMERICs is larger is the same class of defect as an index that
2388    /// disagrees with a scan, and one definition is how they stay honest.
2389    #[must_use]
2390    pub fn from_numeric(scaled: i128, scale: u16, kind: NumericKind) -> Self {
2391        match kind {
2392            NumericKind::Finite => {
2393                let mut buf = [0u8; 40];
2394                let n = digits_of_u128(scaled.unsigned_abs(), &mut buf);
2395                Self::finite(scaled < 0, &buf[..n], i32::from(scale))
2396            }
2397            NumericKind::NaN => Self::special(NUM_CLASS_NAN),
2398            NumericKind::PosInf => Self::special(NUM_CLASS_POS_INF),
2399            NumericKind::NegInf => Self::special(NUM_CLASS_NEG_INF),
2400        }
2401    }
2402
2403    /// The key for an exact integer — no scale, so no rounding.
2404    #[must_use]
2405    pub fn from_i128(n: i128) -> Self {
2406        let mut buf = [0u8; 40];
2407        let len = digits_of_u128(n.unsigned_abs(), &mut buf);
2408        Self::finite(n < 0, &buf[..len], 0)
2409    }
2410
2411    /// The key for a mantissa that overflowed `i128`. The two
2412    /// representations of one value land on one key.
2413    #[must_use]
2414    pub fn from_big(b: &crate::bignum::BigNumeric) -> Self {
2415        let (neg, limbs, scale) = b.parts();
2416        Self::finite(neg, &digits_of_limbs(limbs), i32::from(scale))
2417    }
2418
2419    /// The `f64` this key means, for the one comparison PG defines that
2420    /// way: `numeric` against `float8` demotes the numeric.
2421    ///
2422    /// Lossy by construction — that is the point, and it is why nothing
2423    /// else uses it.
2424    #[must_use]
2425    #[allow(clippy::cast_precision_loss)]
2426    pub fn to_f64(&self) -> f64 {
2427        match self.class {
2428            NUM_CLASS_NAN => return f64::NAN,
2429            NUM_CLASS_POS_INF => return f64::INFINITY,
2430            NUM_CLASS_NEG_INF => return f64::NEG_INFINITY,
2431            _ => {}
2432        }
2433        if self.head == 0 {
2434            return 0.0;
2435        }
2436        // `head` is `d.ddd… × 10^36`; the value is that leading digit and
2437        // its followers at `exp`. The tail is below f64's resolution by
2438        // construction (it starts at the 38th significant digit).
2439        let mantissa = self.head as f64 / HEAD_SCALE as f64;
2440        let out = mantissa * pow10_f64(self.exp);
2441        if self.neg { -out } else { out }
2442    }
2443
2444    /// The significant decimal digits, most significant first — the form
2445    /// the catalog codec writes, and the one `from_parts` reads back.
2446    #[must_use]
2447    pub fn digits(&self) -> Vec<u8> {
2448        let mut out = Vec::new();
2449        if self.head != 0 {
2450            let mut h = self.head;
2451            for _ in 0..HEAD_DIGITS {
2452                let d = u8::try_from(h / HEAD_SCALE).unwrap_or(0);
2453                out.push(d);
2454                h = (h % HEAD_SCALE) * 10;
2455            }
2456            while out.last() == Some(&0) {
2457                out.pop();
2458            }
2459        }
2460        out.extend_from_slice(&self.tail);
2461        out
2462    }
2463
2464    /// The wire parts, for the catalog codec.
2465    #[must_use]
2466    pub fn parts(&self) -> (u8, bool, i32) {
2467        (self.class, self.neg, self.exp)
2468    }
2469
2470    /// Rebuild from the wire parts. Returns `None` on parts that are not
2471    /// canonical, so a corrupt catalog cannot smuggle in a key whose `Eq`
2472    /// and `Ord` disagree.
2473    #[must_use]
2474    pub fn from_parts(class: u8, neg: bool, exp: i32, digits: &[u8]) -> Option<Self> {
2475        if class > NUM_CLASS_NAN || digits.iter().any(|d| *d > 9) {
2476            return None;
2477        }
2478        if class != NUM_CLASS_FINITE && (neg || exp != 0 || !digits.is_empty()) {
2479            return None;
2480        }
2481        if digits.is_empty() {
2482            if neg || exp != 0 {
2483                return None;
2484            }
2485            return Some(Self::special(class));
2486        }
2487        if digits[0] == 0 || digits[digits.len() - 1] == 0 {
2488            return None;
2489        }
2490        Some(Self {
2491            class,
2492            neg,
2493            exp,
2494            head: head_of(digits),
2495            tail: digits.iter().skip(HEAD_DIGITS as usize).copied().collect(),
2496        })
2497    }
2498
2499    /// Canonicalize `(-1)^neg · <digits as an integer> · 10^-scale`.
2500    ///
2501    /// `digits` is most-significant-first and may carry leading and
2502    /// trailing zeros; both are stripped, which is what makes `1.5` and
2503    /// `1.50` land on the same key.
2504    fn finite(neg: bool, digits: &[u8], scale: i32) -> Self {
2505        let lead = digits.iter().position(|d| *d != 0).unwrap_or(digits.len());
2506        let digits = &digits[lead..];
2507        if digits.is_empty() {
2508            return Self::special(NUM_CLASS_FINITE);
2509        }
2510        // The leading digit's exponent, taken BEFORE trailing zeros go:
2511        // dropping low-order digits does not move the leading one.
2512        let exp = i32::try_from(digits.len()).unwrap_or(i32::MAX) - 1 - scale;
2513        let mut end = digits.len();
2514        while end > 0 && digits[end - 1] == 0 {
2515            end -= 1;
2516        }
2517        let digits = &digits[..end];
2518        Self {
2519            class: NUM_CLASS_FINITE,
2520            neg,
2521            exp,
2522            head: head_of(digits),
2523            tail: digits.iter().skip(HEAD_DIGITS as usize).copied().collect(),
2524        }
2525    }
2526
2527    fn special(class: u8) -> Self {
2528        Self {
2529            class,
2530            neg: false,
2531            exp: 0,
2532            head: 0,
2533            tail: Vec::new(),
2534        }
2535    }
2536}
2537
2538/// The first [`HEAD_DIGITS`] of `digits`, left-aligned so the leading one
2539/// sits at `10^36`.
2540fn head_of(digits: &[u8]) -> u128 {
2541    let mut head: u128 = 0;
2542    let take = (HEAD_DIGITS as usize).min(digits.len());
2543    for d in &digits[..take] {
2544        head = head * 10 + u128::from(*d);
2545    }
2546    for _ in take..HEAD_DIGITS as usize {
2547        head *= 10;
2548    }
2549    head
2550}
2551
2552/// Decimal digits of `mag` into `buf`, most significant first; returns how
2553/// many were written. Zero writes none.
2554///
2555/// r1040 — split at `u64` on purpose. A `u128` divide is a called routine,
2556/// not an instruction, and this loop runs once per digit per key.
2557fn digits_of_u128(mag: u128, buf: &mut [u8; 40]) -> usize {
2558    if mag == 0 {
2559        return 0;
2560    }
2561    let mut rev = [0u8; 40];
2562    let mut n = 0usize;
2563    let mut big = mag;
2564    // Peel nineteen digits at a time — the most a `u64` holds — so the
2565    // wide divide runs at most twice.
2566    while big > u128::from(u64::MAX) {
2567        let mut chunk = u64::try_from(big % 10_000_000_000_000_000_000_u128).unwrap_or(0);
2568        big /= 10_000_000_000_000_000_000_u128;
2569        for _ in 0..19 {
2570            rev[n] = u8::try_from(chunk % 10).unwrap_or(0);
2571            chunk /= 10;
2572            n += 1;
2573        }
2574    }
2575    let mut small = u64::try_from(big).unwrap_or(0);
2576    while small > 0 {
2577        rev[n] = u8::try_from(small % 10).unwrap_or(0);
2578        small /= 10;
2579        n += 1;
2580    }
2581    for i in 0..n {
2582        buf[i] = rev[n - 1 - i];
2583    }
2584    n
2585}
2586
2587/// Decimal digits of a base-10^9 little-endian limb vector, most
2588/// significant first. Every limb but the leading one is padded to its
2589/// full nine digits — that padding is the whole point, since a limb of 5
2590/// in the middle of a number means `000000005`.
2591fn digits_of_limbs(limbs: &[u32]) -> Vec<u8> {
2592    let mut out = Vec::new();
2593    let mut buf = [0u8; 40];
2594    for (i, limb) in limbs.iter().enumerate().rev() {
2595        let n = digits_of_u128(u128::from(*limb), &mut buf);
2596        if i + 1 == limbs.len() {
2597            out.extend_from_slice(&buf[..n]);
2598        } else {
2599            out.extend(core::iter::repeat_n(0u8, 9 - n));
2600            out.extend_from_slice(&buf[..n]);
2601        }
2602    }
2603    out
2604}
2605
2606/// `10^e` as an `f64`, for any `e` a canonical key can carry.
2607#[allow(clippy::cast_precision_loss)]
2608fn pow10_f64(e: i32) -> f64 {
2609    let mut out = 1.0_f64;
2610    let mag = e.unsigned_abs();
2611    for _ in 0..mag {
2612        out *= 10.0;
2613    }
2614    if e < 0 { 1.0 / out } else { out }
2615}
2616
2617impl Ord for NumericKey {
2618    fn cmp(&self, other: &Self) -> core::cmp::Ordering {
2619        use core::cmp::Ordering;
2620        if self.class != other.class {
2621            return self.class.cmp(&other.class);
2622        }
2623        if self.class != NUM_CLASS_FINITE {
2624            // Each of the three specials is a single value, and PG holds
2625            // `'NaN'::numeric = 'NaN'::numeric` true.
2626            return Ordering::Equal;
2627        }
2628        // Zero first: it is stored with `neg == false` and `exp == 0`, so
2629        // the magnitude comparison below would put it above every value
2630        // smaller than 1 rather than between the negatives and positives.
2631        match (self.head == 0, other.head == 0) {
2632            (true, true) => return Ordering::Equal,
2633            (true, false) => {
2634                return if other.neg {
2635                    Ordering::Greater
2636                } else {
2637                    Ordering::Less
2638                };
2639            }
2640            (false, true) => {
2641                return if self.neg {
2642                    Ordering::Less
2643                } else {
2644                    Ordering::Greater
2645                };
2646            }
2647            (false, false) => {}
2648        }
2649        match (self.neg, other.neg) {
2650            (false, true) => return Ordering::Greater,
2651            (true, false) => return Ordering::Less,
2652            _ => {}
2653        }
2654        // Same sign, both non-zero: more integer digits is bigger, and at
2655        // equal exponent the left-aligned heads compare as one integer —
2656        // the alignment is what makes that the same answer as comparing
2657        // the digit strings. The tail only speaks when the first 37
2658        // significant digits are identical.
2659        let mag = self
2660            .exp
2661            .cmp(&other.exp)
2662            .then_with(|| self.head.cmp(&other.head))
2663            .then_with(|| self.tail.cmp(&other.tail));
2664        if self.neg { mag.reverse() } else { mag }
2665    }
2666}
2667
2668impl PartialOrd for NumericKey {
2669    fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
2670        Some(self.cmp(other))
2671    }
2672}
2673
2674impl IndexKey {
2675    /// v7.37.43 (INSUBQ B-4) — inline-friendly BigInt fast path.
2676    /// `try_count_star_pk_in_subquery_fast` (and any other hot loop
2677    /// probing an integer PK) already holds an `i64`; this builds the
2678    /// `IndexKey` without going through the generic `from_value`
2679    /// dispatch tree.
2680    #[inline]
2681    pub fn from_i64(n: i64) -> Self {
2682        Self::Int(n)
2683    }
2684
2685    /// r1039 — the key a value takes when the INDEXED COLUMN is `ty`, or
2686    /// `None` when it takes none (→ the caller falls back to a scan).
2687    ///
2688    /// Every key under one index comes from one column, so they all live
2689    /// in one key SPACE. A probe built in a different space finds nothing
2690    /// — and "nothing" is indistinguishable from "no matching rows",
2691    /// which is how round 564 and r1037 both turned an index into a wrong
2692    /// answer (a TEXT key sought against a DATE-keyed and a UUID-keyed
2693    /// index).
2694    ///
2695    /// The two spaces this round adds make that trap reachable again from
2696    /// a new direction: `WHERE n = 2` on a NUMERIC column produces
2697    /// `Value::Int`, and an integer key would look in a space nothing
2698    /// lives in. So NUMERIC columns take integers by converting them
2699    /// exactly, and refuse anything they cannot convert; BYTEA columns
2700    /// take only `Value::Bytes`; and no other column may be keyed in
2701    /// either of the two new spaces.
2702    ///
2703    /// Use this wherever the key comes from a LITERAL or from another
2704    /// table's value. [`IndexKey::from_value`] stays right for building
2705    /// the index itself, where the value is the column's own.
2706    pub fn from_value_for_column(v: &Value<'_>, ty: DataType) -> Option<Self> {
2707        match ty {
2708            DataType::Numeric { .. } => match v {
2709                Value::SmallInt(n) => Some(Self::exact_int_key(i128::from(*n))),
2710                Value::Int(n) => Some(Self::exact_int_key(i128::from(*n))),
2711                Value::BigInt(n) => Some(Self::exact_int_key(i128::from(*n))),
2712                Value::Numeric { .. } | Value::NumericBig(_) => Self::from_value(v),
2713                // Float included: `2.0::float8` and `2.0::numeric` are not
2714                // the same value to a B-tree, and rounding one into the
2715                // other's space is how a seek reaches the wrong row.
2716                _ => None,
2717            },
2718            DataType::Bytes => match v {
2719                Value::Bytes(b) => Some(Self::Bytes(b.to_vec())),
2720                _ => None,
2721            },
2722            _ => match Self::from_value(v) {
2723                Some(Self::Numeric(_) | Self::Bytes(_)) => None,
2724                other => other,
2725            },
2726        }
2727    }
2728
2729    /// An integer as a NUMERIC key. Exact by construction — no scale, no
2730    /// rounding — which is why the conversion is allowed at all.
2731    fn exact_int_key(n: i128) -> Self {
2732        Self::Numeric(alloc::boxed::Box::new(NumericKey::from_i128(n)))
2733    }
2734
2735    pub fn from_value(v: &Value<'_>) -> Option<Self> {
2736        match v {
2737            // v7.37.43 (INSUBQ B-4) — BigInt hits first (the dominant
2738            // INSUBQ shape probes PK as BigInt). Tiny micro-win.
2739            Value::BigInt(n) => Some(Self::Int(*n)),
2740            Value::SmallInt(n) => Some(Self::Int(i64::from(*n))),
2741            Value::Int(n) => Some(Self::Int(i64::from(*n))),
2742            Value::Text(s) => Some(Self::Text(s.clone().into_owned())),
2743            // v7.38 (read01, T11) — bpchar keys compare blank-insensitively.
2744            Value::BpChar(s) => Some(Self::Text(s.trim_end_matches(' ').to_string())),
2745            Value::Bool(b) => Some(Self::Bool(*b)),
2746            // Date/Timestamp use their integer storage repr as the
2747            // index key — same order semantics, same comparison.
2748            Value::Date(d) => Some(Self::Int(i64::from(*d))),
2749            Value::Timestamp(t) => Some(Self::Int(*t)),
2750            // v7.17.0: UUID indexable via byte-wise ordering. Lookup
2751            // on `id = '...'::uuid` resolves through the secondary
2752            // index rather than full-scan.
2753            Value::Uuid(b) => Some(Self::Uuid(*b)),
2754            // v7.17.0 Phase 3.P0-32: TIME indexable via i64 — same
2755            // order semantics as Date/Timestamp.
2756            Value::Time(us) => Some(Self::Int(*us)),
2757            // v7.17.0 Phase 3.P0-33: YEAR indexable as i64 — u16
2758            // widens losslessly and gives the natural calendar
2759            // ordering.
2760            Value::Year(y) => Some(Self::Int(i64::from(*y))),
2761            // v7.17.0 Phase 3.P0-34: TIMETZ indexable by its
2762            // UTC-equivalent microseconds (local wall - offset).
2763            // Without normalising, two values for the same
2764            // physical instant in different zones would sort
2765            // wrong. Matches PG's TIMETZ index behaviour.
2766            Value::TimeTz { us, offset_secs } => {
2767                Some(Self::Int(us - i64::from(*offset_secs) * 1_000_000))
2768            }
2769            // v7.17.0 Phase 3.P0-35: MONEY indexable as i64 cents
2770            // (no scaling needed — natural numeric ordering).
2771            Value::Money(c) => Some(Self::Int(*c)),
2772            // v7.17.0 Phase 3.P0-38: ranges are NOT indexable in
2773            // v7.17.0 — they'd need a custom comparator (PG uses
2774            // SP-GiST for this). Skip.
2775            Value::Range { .. } => None,
2776            // v7.17.0 Phase 3.P0-39: hstore is NOT indexable in
2777            // v7.17.0 — map columns need GIN with bespoke ops.
2778            Value::Hstore(_) => None,
2779            // r1039 — exact decimals index through the canonical
2780            // [`NumericKey`], which is what makes `1.5` and `1.50` one key.
2781            Value::NumericBig(b) => Some(Self::Numeric(alloc::boxed::Box::new(NumericKey::from_big(b)))),
2782            Value::Numeric {
2783                scaled,
2784                scale,
2785                kind,
2786            } => Some(Self::Numeric(alloc::boxed::Box::new(
2787                NumericKey::from_numeric(*scaled, *scale, *kind),
2788            ))),
2789            // r1039 — bytea orders by plain byte comparison, which is
2790            // `Vec<u8>`'s own.
2791            Value::Bytes(b) => Some(Self::Bytes(b.to_vec())),
2792            // v7.17.0 Phase 3.P0-40: 2D arrays aren't indexable.
2793            Value::IntArray2D(_)
2794            | Value::BigIntArray2D(_)
2795            | Value::TextArray2D(_)
2796            | Value::BoolArray2D(_) => None,
2797            // v7.37.5 β-P4: INTERVAL[] isn't indexable (PG uses
2798            // GIN/intarray for array-contains queries; SPG plans
2799            // that as a separate axis under v7.37.8 GIN-on-jsonb).
2800            Value::IntervalArray(_) => None,
2801            // v7.37.5 γ — none of the array-of-scalar family is
2802            // B-tree indexable. Same reason as IntervalArray: PG
2803            // serves array-contains / array-overlap queries via
2804            // GIN, and SPG's GIN axis lands in v7.37.8.
2805            Value::BoolArray(_)
2806            | Value::SmallIntArray(_)
2807            | Value::FloatArray(_)
2808            | Value::NumericArray(_)
2809            | Value::DateArray(_)
2810            | Value::TimestampArray(_)
2811            | Value::TimestamptzArray(_)
2812            | Value::UuidArray(_)
2813            | Value::JsonArray(_)
2814            | Value::JsonbArray(_)
2815            | Value::BytesArray(_)
2816            | Value::VarcharArray(_)
2817            | Value::CharArray(_)
2818            // v7.37.5 δ — multirange not indexable (PG uses GiST/
2819            // SP-GiST + a custom operator class; SPG plans the same
2820            // axis under v7.37.8 with ranges).
2821            | Value::Multirange { .. }
2822            // v7.37.5 ε — geometric scalars not B-tree indexable
2823            // (PG uses GiST/SP-GiST for these too; SPG plans the
2824            // same axis under v7.37.8).
2825            | Value::Point(_)
2826            | Value::Lseg(_, _)
2827            | Value::Path { .. }
2828            | Value::PgBox(_, _)
2829            | Value::Polygon(_)
2830            | Value::Line { .. }
2831            | Value::Circle { .. }
2832            // v7.37.5 ζ-A — network / bit / xml / "char" / money[].
2833            // INET / CIDR / MACADDR / MACADDR8 could be B-tree
2834            // indexable (PG does this), but the byte-wise compare
2835            // family-blind would mis-order IPv4 vs IPv6; left as
2836            // a follow-up under v7.37.8 GIN window.
2837            | Value::Inet { .. }
2838            | Value::Cidr { .. }
2839            | Value::Macaddr(_)
2840            | Value::Macaddr8(_)
2841            | Value::PgLsn(_)
2842            | Value::BitString { .. }
2843            | Value::Xml(_)
2844            | Value::Char1(_)
2845            | Value::MoneyArray(_)
2846            | Value::Composite(_)
2847            | Value::Tid(..)
2848            | Value::Xid(_)
2849            | Value::Cid(_)
2850            | Value::RegClass(..)
2851            | Value::RegProc(..)
2852            | Value::RegType(..) => None,
2853            // Interval isn't index-eligible (and can't reach this path
2854            // through column storage anyway). Float / Real stay out
2855            // because `f64` is only `PartialOrd`.
2856            Value::Null
2857            | Value::Float(_)
2858            | Value::Vector(_)
2859            | Value::Sq8Vector(_)
2860            | Value::HalfVector(_)
2861            | Value::Interval { .. }
2862            | Value::Json(_)
2863            | Value::TextArray(_)
2864            | Value::IntArray(_)
2865            | Value::BigIntArray(_)
2866            | Value::TsVector(_)
2867            | Value::TsQuery(_)
2868            | Value::Real(_) => None,
2869        }
2870    }
2871}
2872
2873/// A single-column secondary index. v2.0 carries either a B-tree map
2874/// (the default — used for equality / range lookups on scalar columns)
2875/// or a navigable-small-world graph (used for kNN over vector
2876/// columns).
2877#[derive(Debug, Clone)]
2878pub struct Index {
2879    pub name: String,
2880    pub column_position: usize,
2881    pub kind: IndexKind,
2882    /// v6.8.0 — column positions of `INCLUDE (col1, col2, …)`
2883    /// non-key columns. Carries the planner's "this query is
2884    /// covered by the index" signal; lookup paths still resolve
2885    /// via the `RowLocator` to fetch the row body, but EXPLAIN
2886    /// surfaces the covered-scan annotation so operators can
2887    /// confirm the planner sees the coverage.
2888    ///
2889    /// Empty `Vec` = no `INCLUDE` clause (the legacy shape). v12
2890    /// catalog snapshots deserialise with an empty vec.
2891    pub included_columns: Vec<usize>,
2892    /// v6.8.1 — partial-index predicate stored as its canonical
2893    /// Display form (the engine re-parses it on the maintenance
2894    /// path). `None` = unconditional index (the legacy shape).
2895    /// Persisted as `[u8 has_pred][u16 LE len][bytes]` on the
2896    /// catalog snapshot (FILE_VERSION 12, appended after
2897    /// `included_columns`).
2898    pub partial_predicate: Option<String>,
2899    /// v6.8.2 — expression-index key, stored as the expression's
2900    /// canonical Display form. `None` = bare column-reference
2901    /// index (the legacy shape). Persisted alongside
2902    /// `partial_predicate` on the v12 catalog snapshot.
2903    pub expression: Option<String>,
2904    /// v7.39 (read01 round 52) — `CREATE UNIQUE INDEX … NULLS NOT DISTINCT`
2905    /// (PG 15+): a NULL in the key no longer exempts the row, so two
2906    /// all-NULL keys collide. Default `false` = SQL-standard NULLS DISTINCT.
2907    /// Persisted in the index appendix (FILE_VERSION 62+); older catalogs
2908    /// deserialise with `false`.
2909    pub nulls_not_distinct: bool,
2910    /// v7.39 (round 537) — the key column's ordering clause, as written.
2911    ///
2912    /// SPG's index does not scan in a direction, so this changes no
2913    /// lookup; `pg_indexes.indexdef` is a reproduction of the DDL and
2914    /// dropping the clause made `CREATE INDEX i ON t (a DESC NULLS
2915    /// LAST)` read back as `(a)` — a dump lost it and a schema diff saw
2916    /// drift every run. `nulls_first` is `None` when the statement did
2917    /// not say, in which case PG's default applies and neither word is
2918    /// rendered.
2919    pub descending: bool,
2920    pub nulls_first: Option<bool>,
2921    /// v7.39 (round 538) — an explicit `COLLATE` on the key, as written.
2922    /// SPG orders text by bytes, so it changes no comparison; PG prints
2923    /// it because a named collation and an inherited one are different
2924    /// objects even where they sort identically.
2925    pub collation: Option<String>,
2926    /// v7.9.29 — `CREATE UNIQUE INDEX …`. When true the engine
2927    /// rejects INSERTs whose key already appears in this index
2928    /// (combined with `partial_predicate` when present — only
2929    /// rows matching the predicate enter the uniqueness check).
2930    /// Catalog FILE_VERSION 16+; older snapshots deserialise
2931    /// with `false`. mailrs K1.
2932    pub is_unique: bool,
2933    /// v7.9.29 — extra (non-leading) column positions for
2934    /// multi-column indexes (`CREATE INDEX … (a, b, c)`). The
2935    /// planner today still only uses the leading
2936    /// `column_position` for index seeks, but UNIQUE INDEX
2937    /// enforcement walks the full tuple so partial-unique
2938    /// invariants like CalDAV `(calendar_id, uid,
2939    /// recurrence_id)` are enforced correctly. Catalog
2940    /// FILE_VERSION 16+; older snapshots deserialise empty.
2941    pub extra_column_positions: Vec<usize>,
2942}
2943
2944/// Default neighbor degree (M) for the NSW graph. Picked at construction
2945/// time and persisted with the index.
2946pub const NSW_DEFAULT_M: usize = 16;
2947
2948/// v5.2.2: outcome of a successful [`Catalog::freeze_oldest_to_cold`]
2949/// call. The catalog state has already been mutated by the time this
2950/// is returned (hot rows dropped + segment registered + Cold locators
2951/// flipped). The caller's only remaining concern is `segment_bytes` —
2952/// persist them to disk under `<db>.spg/segments/seg_<id>.spg` so a
2953/// future restart can reload via the v5.1 `SPG_PRELOAD_COLD_SEGMENT`
2954/// path. (v5.3's manifest will subsume this manual step.)
2955#[derive(Debug, Clone)]
2956pub struct FreezeReport {
2957    /// Id allocated by [`Catalog::load_segment_bytes`] for the new
2958    /// cold-tier segment. Stable across the call's success path.
2959    pub segment_id: u32,
2960    /// Number of rows that moved hot → cold. Equals the `max_rows`
2961    /// the caller asked for (the API is strict on the count).
2962    pub frozen_rows: usize,
2963    /// Hot-tier bytes reclaimed by the freeze — the
2964    /// [`Table::hot_bytes`] delta before vs after. Useful to feed
2965    /// back into the freezer's budget check on the next tick.
2966    pub bytes_freed: u64,
2967    /// Encoded segment bytes, byte-identical to what
2968    /// [`encode_segment`] produced. The catalog already owns a
2969    /// copy inside `cold_segments`; this hand-off lets the caller
2970    /// persist them without re-encoding.
2971    pub segment_bytes: Vec<u8>,
2972}
2973
2974/// v6.7.4 — read-only output of [`Catalog::prepare_freeze_slice`].
2975/// Carries every row body + key in a contiguous hot-row range,
2976/// already encoded and sorted by PK so the coordinator's merge
2977/// step is a k-way merge over already-sorted streams.
2978///
2979/// `Vec<FreezeSlice>` from N independent workers feeds
2980/// [`Catalog::commit_freeze_slices`], which concats + encodes the
2981/// merged segment + atomically swaps the catalog state.
2982#[derive(Debug, Clone)]
2983pub struct FreezeSlice {
2984    /// Hot-row index range this slice covered (half-open, in the
2985    /// table's `rows: PersistentVec` ordering at call time). The
2986    /// commit step uses this to compute the union range that
2987    /// gets passed to [`Table::delete_rows`].
2988    pub row_range: core::ops::Range<usize>,
2989    /// `(pk_u64, encoded_row_body, IndexKey)` triples, sorted
2990    /// ascending by `pk_u64`. Per-slice sort happens inside
2991    /// `prepare_freeze_slice`; the coordinator does only a
2992    /// k-way merge to reach the global PK ordering
2993    /// [`encode_segment`] requires.
2994    pub rows: Vec<(u64, Vec<u8>, IndexKey)>,
2995}
2996
2997/// v6.7.3 — outcome of a [`Catalog::compact_cold_segments`] call.
2998/// The catalog state has already been mutated when this is returned:
2999/// the merged segment is loaded into `cold_segments`, the source
3000/// segment slots are tombstoned (`None`), and every BTree-index
3001/// `RowLocator::Cold` that previously pointed at a source now
3002/// points at the merged segment. The caller's remaining job is to
3003/// persist `merged_segment_bytes` under
3004/// `<db>.spg/segments/seg_<merged_segment_id>.spg` and update the
3005/// in-memory `segment_id → path` map (remove the source ids, add
3006/// the merged id) so the next CHECKPOINT writes a manifest that
3007/// no longer lists the retired sources.
3008///
3009/// On a no-op (fewer than 2 candidate segments under the threshold),
3010/// `merged_segment_id` is `None` and `sources` is empty; the
3011/// catalog was not mutated.
3012#[derive(Debug, Clone)]
3013pub struct CompactReport {
3014    /// Source segment ids that were merged + tombstoned.
3015    pub sources: Vec<u32>,
3016    /// Id allocated for the merged segment. `None` on no-op.
3017    pub merged_segment_id: Option<u32>,
3018    /// Encoded merged-segment bytes (empty on no-op).
3019    pub merged_segment_bytes: Vec<u8>,
3020    /// Number of rows that landed in the merged segment.
3021    pub merged_rows: usize,
3022    /// `Σ source.num_rows − merged_rows`. Rows present in source
3023    /// segment payloads but unreferenced by any live BTree
3024    /// `Cold` locator — DELETE'd-but-still-frozen rows that
3025    /// compaction GC'd during the merge.
3026    pub deleted_rows_pruned: usize,
3027    /// `Σ source.bytes() − merged.bytes()`. Estimate of on-disk
3028    /// space the merge will reclaim once the source segment files
3029    /// are GC'd. Saturating subtract — never negative.
3030    pub bytes_reclaimed_estimate: u64,
3031}
3032
3033#[derive(Debug, Clone)]
3034pub enum IndexKind {
3035    /// v4.40: structural-sharing B-tree over `IndexKey`. Replaces the v0.8
3036    /// `BTreeMap<IndexKey, Vec<usize>>` — `Index::clone` is now an `Arc`
3037    /// bump regardless of index size, so `Catalog::clone` inside the
3038    /// v4.34 auto-commit wrap stays O(1) even for tables with secondary
3039    /// indices (the case that bottlenecked v4.39 at 1M rows in the
3040    /// sweep).
3041    ///
3042    /// v5.1: value type widened from `Vec<usize>` to `Vec<RowLocator>` so
3043    /// a single key can point to a mix of hot-tier rows (`RowLocator::Hot`,
3044    /// equivalent to the pre-v5 `usize` row index) and cold-tier rows
3045    /// (`RowLocator::Cold { segment_id, page_offset }`) once the v5.2
3046    /// freezer starts producing them. Pre-v5.2 only `Hot` entries appear
3047    /// — the on-disk encoding stays at `FILE_VERSION` 8 (raw u64 row index)
3048    /// because every locator round-trips through `RowLocator::from_legacy_v8_u64`
3049    /// without information loss. `FILE_VERSION` 9 with tagged encoding lands
3050    /// alongside the first freezer commit (v5.1 step 2b / v5.2).
3051    BTree(PersistentBTreeMap<IndexKey, crate::posting::PostingList>),
3052    /// Navigable-small-world graph for vector kNN search.
3053    Nsw(NswGraph),
3054    /// v6.7.1 — BRIN (Block Range INdex). Pure metadata: BRIN
3055    /// indexes carry NO in-memory key→locator map. The (min,
3056    /// max) summaries live in each cold-tier segment's v2
3057    /// envelope sidecar; the BRIN entry in `Table.indices` only
3058    /// records THAT a BRIN index exists on this column so the
3059    /// segment encoder + planner can opt into the summary path.
3060    Brin {
3061        /// The cell type at `column_position` at CREATE INDEX time.
3062        /// Used by the planner to type-check WHERE-clause range
3063        /// predicates against the BRIN-indexed column.
3064        column_type: DataType,
3065        /// v7.38.11 — one `(min, max)` per [`BRIN_RANGE_ROWS`] slots of
3066        /// the hot tier, so a range predicate can skip the ranges that
3067        /// cannot contain a match.
3068        ///
3069        /// Maintenance is WIDEN-ONLY and that is the whole safety
3070        /// argument: an insert widens its range, an update widens, and
3071        /// a delete leaves the range alone. A range left wider than the
3072        /// rows it now covers is correct and merely less selective —
3073        /// which is exactly PG's contract for a lossy index, since the
3074        /// predicate is re-checked on every row the summary lets
3075        /// through. A summary may over-report; it can never
3076        /// under-report, so no matching row can be skipped.
3077        ///
3078        /// `None` for a range whose rows carry no comparable key (all
3079        /// NULL, say), and such a range is never skipped.
3080        summaries: alloc::vec::Vec<Option<(i64, i64)>>,
3081    },
3082    /// v7.12.3 — GIN inverted index over a `tsvector` column.
3083    ///
3084    /// Storage shape: `lexeme word → Vec<RowLocator>`. The posting
3085    /// list per word is appended in row-order, so range scans are
3086    /// O(matching rows) once the per-word lookup is done. Multi-
3087    /// term queries intersect / union posting lists.
3088    ///
3089    /// `IndexKey::from_value(TsVector)` returns `None` — GIN doesn't
3090    /// participate in `try_index_seek` (which is BTree-equality-keyed).
3091    /// The engine consults this index through `try_gin_lookup` on
3092    /// `WHERE col @@ tsquery` predicates instead.
3093    ///
3094    /// Backed by a `PersistentBTreeMap` so `Catalog::clone` (the
3095    /// per-write snapshot) stays O(1) — same structural-sharing
3096    /// invariant as BTree.
3097    Gin(PersistentBTreeMap<alloc::string::String, crate::posting::PostingList>),
3098    /// v7.15.0 — `USING gin (col gin_trgm_ops)` over a `TEXT`
3099    /// column. Posting lists map `trigram` (PG-compatible 3-byte
3100    /// shingle on the lower-cased + space-padded input) to row
3101    /// locators. The planner uses this index to accelerate
3102    /// `WHERE col LIKE '…'` / `ILIKE '…'` / `similarity(col, q) >
3103    /// t` — every literal run of length ≥ 1 in the pattern
3104    /// produces a trigram set, the engine intersects the posting
3105    /// lists, and the LIKE / similarity predicate is re-evaluated
3106    /// per candidate row to filter the over-approximation.
3107    /// Persisted via tag-4 index payload in `FILE_VERSION` 24+.
3108    GinTrgm(PersistentBTreeMap<alloc::string::String, crate::posting::PostingList>),
3109    /// v7.17.0 Phase 2.2 — MySQL `FULLTEXT KEY (col)` over a
3110    /// `TEXT` / `VARCHAR` column. Posting lists map
3111    /// `tsvector('simple') lexeme` to row locators. At insert /
3112    /// build time the engine derives the lexemes from the cell
3113    /// via the same lower-case tokenisation rule as
3114    /// `to_tsvector('simple', ...)` — the column itself stays a
3115    /// plain text type on disk (mysqldump round-trips would be
3116    /// broken otherwise). The planner uses this index to
3117    /// accelerate MySQL-shape `MATCH(col) AGAINST('term')`
3118    /// queries by mapping them onto the existing tsquery `@@`
3119    /// walker. Persisted via tag-5 index payload in
3120    /// `FILE_VERSION` 33+.
3121    GinFulltext(PersistentBTreeMap<alloc::string::String, crate::posting::PostingList>),
3122    /// v7.37.8(sentori Epic 5 P2)— `USING gin (col)` over a
3123    /// `JSON` / `JSONB` column. Posting lists map a canonical
3124    /// `(path, leaf)` token(see [`crate::jsonb_gin::extract_tokens`])
3125    /// to row locators so the planner can resolve
3126    /// `<col> @> <jsonb_literal>` to a candidate row set via
3127    /// posting-list intersection + per-row `json::contains`
3128    /// re-verification. Pre-7.37.8 the same DDL loaded as a
3129    /// BTree fallback so `pg_dump` JSONB-GIN scripts kept loading
3130    /// without query-time acceleration. Persisted via tag-6 index
3131    /// payload in `FILE_VERSION` 51+.
3132    GinJsonb(PersistentBTreeMap<alloc::string::String, crate::posting::PostingList>),
3133    /// v7.38.1 (L12) — a REAL multi-column B-tree: the key is the whole
3134    /// column tuple, `[leading, extras…]`, ordered lexicographically by
3135    /// slice `Ord`. That ordering is the entire design: every key
3136    /// sharing a prefix is contiguous, so an equality on a PREFIX of
3137    /// the columns is one `O(log N)` descent plus a bounded walk, and a
3138    /// full-tuple equality is a point `get`. The single-column `BTree`
3139    /// kind used to stand in for multi-column DDL by keying on the
3140    /// leading column only and carrying the rest as metadata — TPC-C's
3141    /// `customer (c_w_id, c_d_id, c_last, c_first)` then answered a
3142    /// three-column equality with every row of one warehouse and a
3143    /// per-row filter over 30 000 candidates.
3144    ///
3145    /// Rows where any component column is NULL (or of an unkeyable
3146    /// type) are NOT entered: this index serves `=` probes, and in SQL
3147    /// `col = v` never selects a NULL. Uniqueness keeps its own
3148    /// full-tuple walk with NULLS-DISTINCT semantics on the
3149    /// enforcement path, exactly as before.
3150    ///
3151    /// Persisted via tag-7 index payload in `FILE_VERSION` 91+.
3152    BTreeMulti(PersistentBTreeMap<alloc::boxed::Box<[IndexKey]>, crate::posting::PostingList>),
3153}
3154
3155impl IndexKind {
3156    /// v7.31 (memory campaign, C2) — bytes this index variant holds
3157    /// resident in RAM, computed by walking its OWN structure rather
3158    /// than a parametric guess made by the engine. Replaces the old
3159    /// `spg_admin::memory_stats` inline match, which charged NSW with
3160    /// a stale `m_max_0 * 8` per node (neighbour slots are `u32` = 4 B
3161    /// since v6.1.x, and most nodes never fill `m_max_0`) and lumped
3162    /// every GIN family index into a flat 1 KiB token — a gross
3163    /// undercount for the text-heavy posting lists that dominate
3164    /// mailrs' footprint. Per-entry container overhead uses the
3165    /// 3-word (24 B on 64-bit) `Vec`/`String` header as the charge.
3166    ///
3167    /// O(index entries): operator/monitoring surface (`memory_stats` /
3168    /// `spg_memory_stats`), not a query path.
3169    #[must_use]
3170    pub fn approx_resident_bytes(&self) -> u64 {
3171        const HEADER: usize = 24; // Vec/String 3-word header on 64-bit.
3172        let loc = core::mem::size_of::<RowLocator>();
3173        match self {
3174            IndexKind::BTree(map) => {
3175                let key = core::mem::size_of::<IndexKey>();
3176                map.iter()
3177                    .map(|(_, locs)| (key + HEADER + locs.len() * loc) as u64)
3178                    .sum()
3179            }
3180            // v7.38.1 (L12) — multi keys own a boxed slice of components.
3181            IndexKind::BTreeMulti(map) => {
3182                let key = core::mem::size_of::<IndexKey>();
3183                map.iter()
3184                    .map(|(k, locs)| (HEADER + k.len() * key + HEADER + locs.len() * loc) as u64)
3185                    .sum()
3186            }
3187            IndexKind::Nsw(g) => {
3188                // `levels` is one byte per node; each layer's adjacency
3189                // is a `Vec<u32>` per node whose actual length we walk
3190                // (the dense layer-0 list dominates, but upper layers
3191                // are sparse — the old estimate ignored that).
3192                let mut b = g.levels.len() as u64;
3193                for layer in &g.layers {
3194                    for nbrs in layer.iter() {
3195                        b += (HEADER + nbrs.len() * core::mem::size_of::<u32>()) as u64;
3196                    }
3197                }
3198                b
3199            }
3200            // BRIN carries NO in-memory key→locator map (the (min,max)
3201            // summaries live in cold-segment sidecars on disk); the
3202            // resident footprint is just the column-type token.
3203            IndexKind::Brin { .. } => core::mem::size_of::<DataType>() as u64,
3204            IndexKind::Gin(map)
3205            | IndexKind::GinTrgm(map)
3206            | IndexKind::GinFulltext(map)
3207            | IndexKind::GinJsonb(map) => map
3208                .iter()
3209                .map(|(word, postings)| {
3210                    (word.len() + HEADER + HEADER + postings.len() * loc) as u64
3211                })
3212                .sum(),
3213        }
3214    }
3215}
3216
3217/// Multi-layer HNSW graph (v2.13). Each node is assigned a `top_level`;
3218/// it appears in layers `0..=top_level`. Higher layers are sparser, so
3219/// search starts from the entry at the top layer, greedy-descends to
3220/// layer 0, and beam-searches there. Layer 0 keeps a larger neighbour
3221/// budget (`m_max_0 = 2 * m` per the HNSW paper); upper layers cap at
3222/// `m`. The struct name stays `NswGraph` so external users / on-disk
3223/// callers don't have to track a rename — the algorithm changed, the
3224/// data slot didn't.
3225#[derive(Debug, Clone)]
3226pub struct NswGraph {
3227    /// Max neighbours per node on layers ≥ 1.
3228    pub m: usize,
3229    /// Max neighbours on layer 0 (the dense bottom layer). HNSW
3230    /// convention: `m_max_0 = 2 * m`.
3231    pub m_max_0: usize,
3232    /// Entry point — the node that sits on the topmost layer. Search
3233    /// always starts here.
3234    pub entry: Option<usize>,
3235    /// Top layer of the entry node (== `layers.len() - 1` when populated).
3236    pub entry_level: u8,
3237    /// `levels[i]` = top layer of node `i`. Nodes whose vector cell is
3238    /// NULL / non-Vector have `levels[i] = 0` and no neighbour entries.
3239    ///
3240    /// v5.5.0: backed by `PersistentVec` so `NswGraph::clone` (and the
3241    /// `Catalog::clone` on every group-commit write that contains it) is O(1)
3242    /// structural-sharing instead of an O(N) element copy.
3243    pub levels: PersistentVec<u8>,
3244    /// `layers[l][i]` = neighbours of node `i` at layer `l`. Inner vec
3245    /// is empty when node `i` doesn't reach layer `l`.
3246    ///
3247    /// v5.5.0: the per-node middle dimension (the O(N) one) is a
3248    /// `PersistentVec`; the outer layer dimension stays a plain `Vec`
3249    /// (layer count ≤ 8, so its clone is O(1) in practice) and the inner
3250    /// neighbour list stays a `Vec` (bounded by `m_max_0`).
3251    ///
3252    /// v6.1.x: neighbour slot widened from `usize` (8 B on 64-bit) to
3253    /// `u32` (4 B). Row indices are catalog-bounded by `u32::MAX` (4G
3254    /// rows per table); the cast at the NSW boundary asserts this. At
3255    /// 1M dim-128 SQ8, layer 0 adjacency alone shrinks by ~128 MiB
3256    /// — the largest single contribution to the v6.0.5-measured
3257    /// 624 MiB ambition gap. On-disk format already used u32 LE, so
3258    /// this is a pure in-memory layout change; no `FILE_VERSION` bump.
3259    pub layers: Vec<PersistentVec<Vec<u32>>>,
3260}
3261
3262impl NswGraph {
3263    fn new(m: usize) -> Self {
3264        Self {
3265            m,
3266            m_max_0: m.saturating_mul(2),
3267            entry: None,
3268            entry_level: 0,
3269            levels: PersistentVec::new(),
3270            layers: alloc::vec![PersistentVec::new()],
3271        }
3272    }
3273
3274    /// Max-neighbour budget for layer `l`.
3275    pub const fn cap_for_layer(&self, layer: u8) -> usize {
3276        if layer == 0 { self.m_max_0 } else { self.m }
3277    }
3278}
3279
3280/// Deterministic level assignment, seeded on the row index so the same
3281/// insert order reproduces the same topology. Distribution is roughly
3282/// HNSW-flavoured with `mL ≈ 1/ln(M) ≈ 0.36` for M=16: each 4-bit
3283/// chunk that comes up zero promotes the node one layer (so P(level ≥
3284/// L) ≈ (1/16)^L).
3285#[allow(clippy::verbose_bit_mask)] // clippy suggests trailing_zeros(); we need an explicit MAX cap and a stable distribution shape.
3286pub fn nsw_assign_level(row_idx: usize) -> u8 {
3287    const MAX_LEVEL: u8 = 7; // 7 ⇒ ~16^7 ≈ 2.7e8 expected nodes between promotions; ample.
3288    // SplitMix-style mixer — cheap and seedable.
3289    let mut x = (row_idx as u64).wrapping_mul(0x9E37_79B9_7F4A_7C15);
3290    x ^= x >> 30;
3291    x = x.wrapping_mul(0xBF58_476D_1CE4_E5B9);
3292    x ^= x >> 27;
3293    x = x.wrapping_mul(0x94D0_49BB_1331_11EB);
3294    x ^= x >> 31;
3295    // Count contiguous low-end zero nibbles (4-bit chunks). Each zero
3296    // nibble has probability 1/16, mirroring HNSW's `mL ≈ 1/ln(M)` for
3297    // M=16. `trailing_zeros / 4` would lose the ordering when x = 0, so
3298    // a plain loop with a cap is clearer.
3299    let mut level: u8 = 0;
3300    while x & 0xF == 0 && level < MAX_LEVEL {
3301        level += 1;
3302        x >>= 4;
3303    }
3304    level
3305}
3306
3307/// v7.38.1 (L12) — the composite key `values` takes in a multi-column
3308/// B-tree over `[lead, extras…]`. A NULL component keys as
3309/// [`IndexKey::Null`] (declared to sort last, PG's NULLS LAST) so the
3310/// row stays findable by prefix probes on the columns before it. `None`
3311/// = some non-null component has no key form; the row is then not
3312/// entered, which is why creation gates every component column's type
3313/// through [`multi_component_type_ok`].
3314pub(crate) fn compose_multi_key(
3315    values: &[Value<'_>],
3316    lead: usize,
3317    extras: &[usize],
3318) -> Option<alloc::boxed::Box<[IndexKey]>> {
3319    let mut comps: Vec<IndexKey> = Vec::with_capacity(1 + extras.len());
3320    for pos in core::iter::once(lead).chain(extras.iter().copied()) {
3321        let v = values.get(pos)?;
3322        if matches!(v, Value::Null) {
3323            comps.push(IndexKey::Null);
3324        } else {
3325            comps.push(IndexKey::from_value(v)?);
3326        }
3327    }
3328    Some(comps.into_boxed_slice())
3329}
3330
3331/// v7.38.1 (L12) — component-type gate for multi-column B-trees: every
3332/// NON-NULL value of these types keys through `IndexKey::from_value`,
3333/// so a row can only be absent from the index when creation raced a
3334/// type this list does not name. Deliberately conservative — a type
3335/// outside the list simply keeps its index on the leading-column path.
3336pub(crate) fn multi_component_type_ok(ty: DataType) -> bool {
3337    matches!(
3338        ty,
3339        DataType::SmallInt
3340            | DataType::Int
3341            | DataType::BigInt
3342            | DataType::Text
3343            | DataType::Varchar(_)
3344            | DataType::Char(_)
3345            | DataType::Bool
3346            | DataType::Uuid
3347            | DataType::Date
3348            | DataType::Timestamp
3349    )
3350}
3351
3352impl Index {
3353    fn new_btree(name: String, column_position: usize) -> Self {
3354        Self {
3355            name,
3356            column_position,
3357            kind: IndexKind::BTree(PersistentBTreeMap::new()),
3358            included_columns: Vec::new(),
3359            partial_predicate: None,
3360            expression: None,
3361            is_unique: false,
3362            nulls_not_distinct: false,
3363            descending: false,
3364            nulls_first: None,
3365            collation: None,
3366            extra_column_positions: Vec::new(),
3367        }
3368    }
3369
3370    /// v7.38.1 (L12) — a real multi-column B-tree shell. The caller
3371    /// sets `extra_column_positions` before the first row enters; the
3372    /// key arity is `1 + extras` from then on.
3373    fn new_btree_multi(name: String, column_position: usize) -> Self {
3374        Self {
3375            kind: IndexKind::BTreeMulti(PersistentBTreeMap::new()),
3376            ..Self::new_btree(name, column_position)
3377        }
3378    }
3379
3380    /// v7.38.1 (L12) — the composite key this row takes in a
3381    /// [`IndexKind::BTreeMulti`] index. NULL components key as
3382    /// [`IndexKey::Null`] so prefix probes still find the row; `None`
3383    /// only when a non-null component produces no key, which creation's
3384    /// component-type gate makes unreachable for well-formed indexes.
3385    pub fn multi_key_for_row(&self, values: &[Value<'_>]) -> Option<alloc::boxed::Box<[IndexKey]>> {
3386        compose_multi_key(values, self.column_position, &self.extra_column_positions)
3387    }
3388
3389    fn new_nsw(name: String, column_position: usize, m: usize) -> Self {
3390        Self {
3391            name,
3392            column_position,
3393            kind: IndexKind::Nsw(NswGraph::new(m)),
3394            included_columns: Vec::new(),
3395            partial_predicate: None,
3396            expression: None,
3397            is_unique: false,
3398            nulls_not_distinct: false,
3399            descending: false,
3400            nulls_first: None,
3401            collation: None,
3402            extra_column_positions: Vec::new(),
3403        }
3404    }
3405
3406    /// v6.7.1 — BRIN index constructor. BRIN carries no in-memory
3407    /// data; the `column_type` snapshot is used by the segment
3408    /// encoder + planner for type-checking range predicates.
3409    fn new_brin(name: String, column_position: usize, column_type: DataType) -> Self {
3410        Self {
3411            name,
3412            column_position,
3413            kind: IndexKind::Brin {
3414                column_type,
3415                summaries: alloc::vec::Vec::new(),
3416            },
3417            included_columns: Vec::new(),
3418            partial_predicate: None,
3419            expression: None,
3420            is_unique: false,
3421            nulls_not_distinct: false,
3422            descending: false,
3423            nulls_first: None,
3424            collation: None,
3425            extra_column_positions: Vec::new(),
3426        }
3427    }
3428
3429    /// v7.12.3 — GIN inverted-index constructor. Empty posting-list
3430    /// map; caller (typically [`Table::add_gin_index`] or
3431    /// [`Table::restore_gin_index`]) populates it from existing rows
3432    /// or from a deserialised snapshot.
3433    fn new_gin(name: String, column_position: usize) -> Self {
3434        Self {
3435            name,
3436            column_position,
3437            kind: IndexKind::Gin(PersistentBTreeMap::new()),
3438            included_columns: Vec::new(),
3439            partial_predicate: None,
3440            expression: None,
3441            is_unique: false,
3442            nulls_not_distinct: false,
3443            descending: false,
3444            nulls_first: None,
3445            collation: None,
3446            extra_column_positions: Vec::new(),
3447        }
3448    }
3449
3450    /// v7.15.0 — `gin_trgm_ops`-flavoured GIN constructor. Same
3451    /// shape as `new_gin` but the posting-list keys are 3-byte
3452    /// trigram shingles (`pg_trgm`-compatible) and the column
3453    /// type is `TEXT` / `VARCHAR` (not `TSVECTOR`).
3454    fn new_gin_trgm(name: String, column_position: usize) -> Self {
3455        Self {
3456            name,
3457            column_position,
3458            kind: IndexKind::GinTrgm(PersistentBTreeMap::new()),
3459            included_columns: Vec::new(),
3460            partial_predicate: None,
3461            expression: None,
3462            is_unique: false,
3463            nulls_not_distinct: false,
3464            descending: false,
3465            nulls_first: None,
3466            collation: None,
3467            extra_column_positions: Vec::new(),
3468        }
3469    }
3470
3471    /// v7.17.0 Phase 2.2 — MySQL `FULLTEXT KEY` GIN constructor.
3472    /// Same shape as `new_gin_trgm` but the posting-list keys
3473    /// are lower-cased word lexemes (`to_tsvector('simple', col)`
3474    /// equivalent) instead of trigrams, and the column type is
3475    /// `TEXT` / `VARCHAR` (not `TSVECTOR`).
3476    fn new_gin_fulltext(name: String, column_position: usize) -> Self {
3477        Self {
3478            name,
3479            column_position,
3480            kind: IndexKind::GinFulltext(PersistentBTreeMap::new()),
3481            included_columns: Vec::new(),
3482            partial_predicate: None,
3483            expression: None,
3484            is_unique: false,
3485            nulls_not_distinct: false,
3486            descending: false,
3487            nulls_first: None,
3488            collation: None,
3489            extra_column_positions: Vec::new(),
3490        }
3491    }
3492
3493    /// v7.37.8(sentori Epic 5 P2)— JSONB-GIN constructor. Same
3494    /// shape as the other GIN-family indexes; posting-list keys
3495    /// are the canonical `(path, leaf)` tokens emitted by
3496    /// `crate::jsonb_gin::extract_tokens`. Maintains posting
3497    /// lists from `Value::Json` cells(JSONB is a synonym for the
3498    /// same in-memory string-backed Value).
3499    fn new_gin_jsonb(name: String, column_position: usize) -> Self {
3500        Self {
3501            name,
3502            column_position,
3503            kind: IndexKind::GinJsonb(PersistentBTreeMap::new()),
3504            included_columns: Vec::new(),
3505            partial_predicate: None,
3506            expression: None,
3507            is_unique: false,
3508            nulls_not_distinct: false,
3509            descending: false,
3510            nulls_first: None,
3511            collation: None,
3512            extra_column_positions: Vec::new(),
3513        }
3514    }
3515
3516    /// v7.34.4 — descending-order iterator over `(IndexKey, locators)`
3517    /// pairs for a BTree index, with O(log N) descent to the rightmost
3518    /// leaf and lazy emission thereafter. Returns an empty iterator
3519    /// for non-BTree index kinds — callers handle both uniformly.
3520    /// Used by the ORDER BY `<indexed col>` DESC + LIMIT N executor
3521    /// path: walking only the first N matches off the rightmost leaf
3522    /// avoids the per-row materialisation + partial-sort cost on
3523    /// large tables (mailrs `content_worker` at 250 k rows).
3524    pub fn iter_desc(
3525        &self,
3526    ) -> alloc::boxed::Box<dyn Iterator<Item = (&IndexKey, &crate::posting::PostingList)> + '_>
3527    {
3528        match &self.kind {
3529            IndexKind::BTree(m) => alloc::boxed::Box::new(m.iter_rev()),
3530            // v7.38.1 (L12) — projecting the leading component of a
3531            // composite key preserves order: keys sort by the whole
3532            // tuple, so the leading component is non-increasing here
3533            // (non-decreasing in iter_asc), exactly what an ORDER BY
3534            // on the leading column needs.
3535            IndexKind::BTreeMulti(m) => {
3536                alloc::boxed::Box::new(m.iter_rev().map(|(k, l)| (&k[0], l)))
3537            }
3538            IndexKind::Nsw(_)
3539            | IndexKind::Brin { .. }
3540            | IndexKind::Gin(_)
3541            | IndexKind::GinTrgm(_)
3542            | IndexKind::GinFulltext(_)
3543            | IndexKind::GinJsonb(_) => alloc::boxed::Box::new(core::iter::empty()),
3544        }
3545    }
3546
3547    /// v7.34.4 — ascending-order iterator over `(IndexKey, locators)`
3548    /// pairs. Mirror of `iter_desc` for ORDER BY ... ASC + LIMIT N.
3549    pub fn iter_asc(
3550        &self,
3551    ) -> alloc::boxed::Box<dyn Iterator<Item = (&IndexKey, &crate::posting::PostingList)> + '_>
3552    {
3553        match &self.kind {
3554            IndexKind::BTree(m) => alloc::boxed::Box::new(m.iter()),
3555            // v7.38.1 (L12) — see iter_desc: the leading component of
3556            // a tuple-sorted walk is itself in order.
3557            IndexKind::BTreeMulti(m) => alloc::boxed::Box::new(m.iter().map(|(k, l)| (&k[0], l))),
3558            IndexKind::Nsw(_)
3559            | IndexKind::Brin { .. }
3560            | IndexKind::Gin(_)
3561            | IndexKind::GinTrgm(_)
3562            | IndexKind::GinFulltext(_)
3563            | IndexKind::GinJsonb(_) => alloc::boxed::Box::new(core::iter::empty()),
3564        }
3565    }
3566
3567    /// Look up the locators stored under `key` (B-tree only). Returns
3568    /// an empty slice when the key is absent or the index isn't a
3569    /// BTree — callers can treat both cases uniformly.
3570    ///
3571    /// v5.1: return type widened from `&[usize]` to `&[RowLocator]`.
3572    /// Pre-v5.2 callers can read the slice and `.as_hot().unwrap()`
3573    /// each entry (no `Cold` variants exist until the freezer lands);
3574    /// post-v5.2 callers dispatch hot vs. cold per locator.
3575    pub fn lookup_eq(&self, key: &IndexKey) -> &crate::posting::PostingList {
3576        match &self.kind {
3577            IndexKind::BTree(m) => m.get(key).map_or(&EMPTY_POSTINGS, |l| l),
3578            // BRIN / NSW / GIN / trigram-GIN / fulltext-GIN have
3579            // no IndexKey-keyed map; lookup is a no-op. GIN uses
3580            // [`Index::gin_lookup_word`] instead.
3581            IndexKind::Nsw(_)
3582            | IndexKind::Brin { .. }
3583            | IndexKind::Gin(_)
3584            | IndexKind::GinTrgm(_)
3585            | IndexKind::GinFulltext(_)
3586            | IndexKind::GinJsonb(_)
3587            | IndexKind::BTreeMulti(_) => &EMPTY_POSTINGS,
3588        }
3589    }
3590
3591    /// v7.37.43 (INSUBQ B-2) — specialised lookup for integer-PK probes.
3592    /// `try_count_star_pk_in_subquery_fast` already holds an `i64` (the
3593    /// inner survivor key); skip the `IndexKey::from_value` enum-dispatch
3594    /// trip and build the key inline. ~20 ns × N_survivors saved on
3595    /// the INSUBQ hot loop.
3596    #[inline]
3597    pub fn lookup_eq_i64(&self, n: i64) -> &crate::posting::PostingList {
3598        match &self.kind {
3599            IndexKind::BTree(m) => m.get(&IndexKey::Int(n)).map_or(&EMPTY_POSTINGS, |l| l),
3600            IndexKind::Nsw(_)
3601            | IndexKind::Brin { .. }
3602            | IndexKind::Gin(_)
3603            | IndexKind::GinTrgm(_)
3604            | IndexKind::GinFulltext(_)
3605            | IndexKind::GinJsonb(_)
3606            | IndexKind::BTreeMulti(_) => &EMPTY_POSTINGS,
3607        }
3608    }
3609
3610    /// v7.38 (perf, index range scan) — flatten the row locators for every key
3611    /// in `[lo, hi]` (bounds per `core::ops::Bound`) via the BTree's `O(log N +
3612    /// k)` range walk. Returns `None` once more than `cap` locators accumulate
3613    /// — a "this range isn't selective enough, seq-scan instead" signal that
3614    /// stops a wide range from materialising a near-full table's worth of rows
3615    /// through the index. BTree only (other kinds → None).
3616    pub fn lookup_range_capped(
3617        &self,
3618        lo: core::ops::Bound<&IndexKey>,
3619        hi: core::ops::Bound<&IndexKey>,
3620        cap: usize,
3621    ) -> Option<Vec<RowLocator>> {
3622        self.lookup_range_capped_by(lo, hi, cap, |_| true)
3623    }
3624
3625    /// v7.39 (round 490) — the same range walk, but the caller decides
3626    /// which locators are worth carrying, and the cap counts only those.
3627    ///
3628    /// A BTree index holds one locator per row VERSION. On a churned table
3629    /// the dead versions are still in there: round 490 measured a
3630    /// 1000-row range handing back 61 000 locators after 60
3631    /// delete-and-reinsert cycles with the background vacuum switched off.
3632    /// Every caller then dropped the dead ones — the mutation paths and the
3633    /// SELECT range path all test `is_row_visible` and `continue` — but only
3634    /// after they had been collected into a `Vec`, sorted, and walked.
3635    ///
3636    /// Handing the predicate down means the walk keeps ~1000, and the cap
3637    /// (which exists so an index walk never costs more than the scan it
3638    /// replaces) is once again measured in rows a caller will actually look
3639    /// at. Round 461 had to add the dead count to the budget to stop the
3640    /// seek being refused outright; with the filter here that compensation
3641    /// is no longer needed.
3642    pub fn lookup_range_capped_by(
3643        &self,
3644        lo: core::ops::Bound<&IndexKey>,
3645        hi: core::ops::Bound<&IndexKey>,
3646        cap: usize,
3647        keep: impl Fn(RowLocator) -> bool,
3648    ) -> Option<Vec<RowLocator>> {
3649        match &self.kind {
3650            IndexKind::BTree(m) => {
3651                let mut out: Vec<RowLocator> = Vec::new();
3652                for (_, locs) in m.range(lo, hi) {
3653                    out.extend(locs.iter().copied().filter(|l| keep(*l)));
3654                    if out.len() > cap {
3655                        return None;
3656                    }
3657                }
3658                Some(out)
3659            }
3660            IndexKind::Nsw(_)
3661            | IndexKind::Brin { .. }
3662            | IndexKind::Gin(_)
3663            | IndexKind::GinTrgm(_)
3664            | IndexKind::GinFulltext(_)
3665            | IndexKind::GinJsonb(_)
3666            | IndexKind::BTreeMulti(_) => None,
3667        }
3668    }
3669
3670    /// v7.38.1 (L12) — full-tuple point lookup on a [`IndexKind::BTreeMulti`]
3671    /// index. `key` must carry exactly as many components as the index
3672    /// has columns; anything else (including a probe against a
3673    /// non-multi index) finds nothing, and "nothing" here is safe
3674    /// because the caller falls back to a scan, never to an answer.
3675    pub fn lookup_eq_multi(&self, key: &[IndexKey]) -> &crate::posting::PostingList {
3676        match &self.kind {
3677            IndexKind::BTreeMulti(m) if key.len() == 1 + self.extra_column_positions.len() => {
3678                m.get_by(key).map_or(&EMPTY_POSTINGS, |l| l)
3679            }
3680            _ => &EMPTY_POSTINGS,
3681        }
3682    }
3683
3684    /// v7.38.1 (L12) — locators for every key whose leading components
3685    /// equal `prefix`, on a [`IndexKind::BTreeMulti`] index. Slice
3686    /// ordering keeps a prefix's keys contiguous, so this is one
3687    /// descent to `[prefix]` and a walk that stops at the first key
3688    /// leaving the prefix. Same cap/keep contract as
3689    /// [`Index::lookup_range_capped_by`]: `None` = not selective
3690    /// enough (or not a multi index), fall back.
3691    pub fn lookup_prefix_capped_by(
3692        &self,
3693        prefix: &[IndexKey],
3694        cap: usize,
3695        keep: impl Fn(RowLocator) -> bool,
3696    ) -> Option<Vec<RowLocator>> {
3697        let IndexKind::BTreeMulti(m) = &self.kind else {
3698            return None;
3699        };
3700        if prefix.is_empty() || prefix.len() > 1 + self.extra_column_positions.len() {
3701            return None;
3702        }
3703        let lo: alloc::boxed::Box<[IndexKey]> = prefix.to_vec().into_boxed_slice();
3704        let mut out: Vec<RowLocator> = Vec::new();
3705        for (k, locs) in m.range(core::ops::Bound::Included(&lo), core::ops::Bound::Unbounded) {
3706            if k.len() < prefix.len() || k[..prefix.len()] != *prefix {
3707                break;
3708            }
3709            out.extend(locs.iter().copied().filter(|l| keep(*l)));
3710            if out.len() > cap {
3711                return None;
3712            }
3713        }
3714        Some(out)
3715    }
3716
3717    /// v7.39 (round 560) — the index range as (key, locator) pairs.
3718    ///
3719    /// `lookup_range_capped_by` throws the KEY away and returns only
3720    /// locators, so a query whose projection is exactly the indexed
3721    /// column still goes to the row store for a value the walk already
3722    /// had in hand — paying per row for something the index knows.
3723    ///
3724    /// Uncapped on purpose: an index-only walk touches no row, so the
3725    /// selectivity ceiling that keeps a seek from being worse than the
3726    /// scan it replaces does not apply to it.
3727    ///
3728    /// v7.39 (round 562) — and it does not collect, either. This
3729    /// returned a `Vec<(IndexKey, RowLocator)>`: for a 100k-row range,
3730    /// 100k key clones into a `Vec::new()` that doubles its way up to
3731    /// several MB, all to be walked once and dropped. A profile of the
3732    /// server serving that query put 20% of the connection thread's CPU
3733    /// on the collect alone, with another 18% in the allocator beside
3734    /// it. The caller consumes the pairs in order and needs the key
3735    /// only by reference, so it can have the walk itself.
3736    pub fn range_keyed(
3737        &self,
3738        lo: core::ops::Bound<&IndexKey>,
3739        hi: core::ops::Bound<&IndexKey>,
3740    ) -> Option<impl Iterator<Item = (&IndexKey, RowLocator)> + '_> {
3741        match &self.kind {
3742            IndexKind::BTree(m) => Some(
3743                m.range(lo, hi)
3744                    .flat_map(|(k, locs)| locs.iter().map(move |l| (k, *l))),
3745            ),
3746            IndexKind::Nsw(_)
3747            | IndexKind::Brin { .. }
3748            | IndexKind::Gin(_)
3749            | IndexKind::GinTrgm(_)
3750            | IndexKind::GinFulltext(_)
3751            | IndexKind::GinJsonb(_)
3752            | IndexKind::BTreeMulti(_) => None,
3753        }
3754    }
3755
3756    /// v7.12.3 — GIN posting-list lookup. Returns the row locators
3757    /// whose `tsvector` cell contains `word`. Empty when the word is
3758    /// absent from the index or this isn't a GIN index.
3759    pub fn gin_lookup_word(&self, word: &str) -> &crate::posting::PostingList {
3760        match &self.kind {
3761            // v7.17.0 Phase 2.2 — fulltext-GIN shares the same
3762            // lexeme-keyed posting list shape as the
3763            // tsvector-typed GIN, so the same lookup applies.
3764            IndexKind::Gin(m) | IndexKind::GinFulltext(m) => {
3765                m.get(&String::from(word)).map_or(&EMPTY_POSTINGS, |l| l)
3766            }
3767            IndexKind::BTree(_)
3768            | IndexKind::Nsw(_)
3769            | IndexKind::Brin { .. }
3770            | IndexKind::GinTrgm(_)
3771            | IndexKind::GinJsonb(_)
3772            | IndexKind::BTreeMulti(_) => &EMPTY_POSTINGS,
3773        }
3774    }
3775
3776    /// v7.15.0 — trigram-GIN posting-list lookup. Returns the row
3777    /// locators whose indexed `TEXT` cell contains the trigram
3778    /// `tri`. Empty when the trigram is absent or this isn't a
3779    /// trigram-GIN index.
3780    pub fn gin_trgm_lookup(&self, tri: &str) -> &crate::posting::PostingList {
3781        match &self.kind {
3782            IndexKind::GinTrgm(m) => m.get(&String::from(tri)).map_or(&EMPTY_POSTINGS, |l| l),
3783            IndexKind::BTree(_)
3784            | IndexKind::Nsw(_)
3785            | IndexKind::Brin { .. }
3786            | IndexKind::Gin(_)
3787            | IndexKind::GinFulltext(_)
3788            | IndexKind::GinJsonb(_)
3789            | IndexKind::BTreeMulti(_) => &EMPTY_POSTINGS,
3790        }
3791    }
3792
3793    /// v7.37.8(sentori Epic 5 P2)— JSONB-GIN posting-list lookup.
3794    /// Returns the row locators whose indexed JSONB cell carries
3795    /// the canonical `token`(see [`crate::jsonb_gin::extract_tokens`]).
3796    /// Empty when the token is absent or this isn't a JSONB-GIN
3797    /// index. Planners drive `<col> @> <jsonb_literal>` through here.
3798    pub fn gin_jsonb_lookup(&self, token: &str) -> &crate::posting::PostingList {
3799        match &self.kind {
3800            IndexKind::GinJsonb(m) => m.get(&String::from(token)).map_or(&EMPTY_POSTINGS, |l| l),
3801            IndexKind::BTree(_)
3802            | IndexKind::Nsw(_)
3803            | IndexKind::Brin { .. }
3804            | IndexKind::Gin(_)
3805            | IndexKind::GinTrgm(_)
3806            | IndexKind::GinFulltext(_)
3807            | IndexKind::BTreeMulti(_) => &EMPTY_POSTINGS,
3808        }
3809    }
3810
3811    /// Borrow the NSW graph (if this is an NSW index). Callers that need
3812    /// the graph for a kNN search go through here.
3813    pub const fn nsw(&self) -> Option<&NswGraph> {
3814        match &self.kind {
3815            IndexKind::Nsw(g) => Some(g),
3816            IndexKind::BTree(_)
3817            | IndexKind::Brin { .. }
3818            | IndexKind::Gin(_)
3819            | IndexKind::GinTrgm(_)
3820            | IndexKind::GinFulltext(_)
3821            | IndexKind::GinJsonb(_)
3822            | IndexKind::BTreeMulti(_) => None,
3823        }
3824    }
3825
3826    /// v6.7.1 — true when this index is a BRIN (block range) index.
3827    /// Used by the segment encoder to opt into BRIN sidecar emission
3828    /// at freeze time, and by the planner to opt into page-skipping
3829    /// on range predicates.
3830    pub const fn is_brin(&self) -> bool {
3831        matches!(self.kind, IndexKind::Brin { .. })
3832    }
3833
3834    /// v7.15.0 — true when this index is a trigram GIN
3835    /// (`gin_trgm_ops`-flavoured). Used by the LIKE planner to
3836    /// opt into trigram acceleration.
3837    pub const fn is_gin_trgm(&self) -> bool {
3838        matches!(self.kind, IndexKind::GinTrgm(_))
3839    }
3840
3841    /// v7.12.3 — true when this index is a GIN inverted index.
3842    /// Used by the planner to opt into posting-list acceleration on
3843    /// `WHERE col @@ tsquery` predicates.
3844    pub const fn is_gin(&self) -> bool {
3845        matches!(self.kind, IndexKind::Gin(_))
3846    }
3847
3848    /// v7.17.0 Phase 2.2 — true when this index is a fulltext
3849    /// GIN over a TEXT / VARCHAR column (MySQL `FULLTEXT KEY`
3850    /// surface). Used by the planner to opt the FULLTEXT-indexed
3851    /// column into MATCH AGAINST acceleration.
3852    pub const fn is_gin_fulltext(&self) -> bool {
3853        matches!(self.kind, IndexKind::GinFulltext(_))
3854    }
3855
3856    /// v7.37.8(sentori Epic 5 P2)— true when this index is a
3857    /// real JSONB-GIN(posting-list backed). Used by the planner
3858    /// to opt `<col> @> <jsonb_literal>` into posting-list seek.
3859    pub const fn is_gin_jsonb(&self) -> bool {
3860        matches!(self.kind, IndexKind::GinJsonb(_))
3861    }
3862}
3863
3864/// In-memory table: schema + a persistent row vector + secondary indices.
3865///
3866/// v4.39: `rows` is a [`PersistentVec`] (Bitmapped Vector Trie, 32-way) so
3867/// `Table::clone()` is `O(1)` — the whole reason for v4.39's existence is
3868/// to make `Catalog::clone()` cheap inside the v4.34 auto-commit wrap.
3869///
3870/// v5.2.1: `hot_bytes` tracks the encoded byte size of every row currently
3871/// in [`Self::rows`], summed over rows. Updated incrementally by `insert`
3872/// (+= encoded row size), `delete_rows` (-= removed rows' encoded sizes),
3873/// and `update_row` (-= old size, += new size). The value is what the
3874/// v5.2 freezer reads to decide when to demote cold rows — when the
3875/// catalog-wide sum crosses `SPG_HOT_TIER_BYTES` (default 4 GiB) the
3876/// freezer thread wakes. v5.2.1 ships measurement only; the freezer
3877/// itself lands in v5.2.2. Stored as `u64` so a single field clone in
3878/// `Catalog::clone` stays at the O(1) invariant v4.39 built.
3879/// v7.34 (crash-recovery P0 #2) — one row-level physical redo record.
3880/// Row-level redo replaces statement-based WAL replay (which re-executes
3881/// each SQL through the full engine — O(records × catalog_rows), the
3882/// superlinear recovery hang root-caused on the mailrs crash-recovery
3883/// P0). A `RowChange` is the exact storage mutation the engine applied
3884/// (`Table::insert` / `update_row` / `delete_rows`); replaying it on a
3885/// catalog restored from the matching checkpoint reproduces the state
3886/// WITHOUT re-validating uniqueness/FK/parse/plan — O(changed rows).
3887///
3888/// Positions are physical, not key-based: `serialize`/`deserialize`
3889/// preserve row order exactly (rows written + read back in `self.rows`
3890/// order) and the mutation ops are deterministic, so the same op sequence
3891/// replayed from the same checkpoint reproduces the same positions. This
3892/// matches PostgreSQL's physical redo and supports tables with no primary
3893/// key. (Caveat handled at replay integration: a post-checkpoint cold-tier
3894/// freeze shifts hot positions and must itself be logged or fenced by a
3895/// checkpoint — see `row-level-redo-design`.)
3896/// ## v7.37.15 (Epic W slice 1) — additive MVCC identity metadata
3897///
3898/// Each variant now also carries, additively, the stable
3899/// [`RowId`](row_header::RowId) of the affected row(s) and the
3900/// **writer version** (`xmin` for an insert, `xmax` for a
3901/// delete/update). This is the codec foundation for making
3902/// in-place MVCC tombstones durable across crash/upgrade recovery.
3903///
3904/// Two important properties for the durability path:
3905///
3906/// 1. **Replay resolution is UNCHANGED.** `apply_redo_run_on_table`
3907///    still resolves every change by physical `pos`/`positions`
3908///    exactly as before. The new metadata is *carried but unused*
3909///    by replay in this slice; resolving-by-`RowId` and
3910///    header-preserving replay are later slices.
3911/// 2. **Backward compatibility.** A redo payload written by
3912///    pre-Epic-W code carries no metadata; [`decode_redo_log`]
3913///    fills `rowid`/`rowids` with [`RowId::UNASSIGNED`](row_header::RowId::UNASSIGNED)
3914///    (empty for `Delete`) and `writer_version` with `0`. See the
3915///    codec version gate in [`encode_redo_log`]/[`decode_redo_log`].
3916///
3917/// The `writer_version` is captured as `0` at the storage layer
3918/// (`Table::insert`/`delete_rows`/`update_row` don't have the
3919/// committing `TxId`), then **stamped with the real committing
3920/// version by the engine** after it drains the statement's changes
3921/// (Epic W slice 2 — [`RowChange::set_writer_version`], driven from
3922/// `Engine::writer_version_for_current_stmt`). All changes from one
3923/// statement share the one version. Replay still resolves by
3924/// physical position and does not read `writer_version` — that is a
3925/// later slice (header-preserving replay).
3926#[derive(Debug, Clone, PartialEq)]
3927pub enum RowChange {
3928    /// Append `row` to `table`.
3929    Insert {
3930        table: String,
3931        row: Row<'static>,
3932        /// Epic W: stable id the appended row will receive.
3933        /// [`RowId::UNASSIGNED`](row_header::RowId::UNASSIGNED) when
3934        /// decoded from a pre-Epic-W redo payload.
3935        rowid: row_header::RowId,
3936        /// Epic W: writer version (`xmin`). `0` until the writing
3937        /// `TxId` is threaded to the storage layer (later slice).
3938        writer_version: u64,
3939    },
3940    /// Replace the row at physical `pos` in `table` with `new_row`.
3941    Update {
3942        table: String,
3943        pos: usize,
3944        new_row: Vec<Value<'static>>,
3945        /// Epic W: stable id of the row at `pos`.
3946        /// [`RowId::UNASSIGNED`](row_header::RowId::UNASSIGNED) when
3947        /// decoded from a pre-Epic-W redo payload.
3948        rowid: row_header::RowId,
3949        /// Epic W: writer version (`xmax` of the superseded tuple).
3950        /// `0` until the writing `TxId` is threaded (later slice).
3951        writer_version: u64,
3952    },
3953    /// Remove the rows at the given physical `positions` from `table`.
3954    Delete {
3955        table: String,
3956        positions: Vec<usize>,
3957        /// Epic W: stable ids parallel to `positions` (same length,
3958        /// [`RowId::UNASSIGNED`](row_header::RowId::UNASSIGNED) for an
3959        /// out-of-bounds input position). **Empty** when decoded from
3960        /// a pre-Epic-W redo payload (no metadata was recorded).
3961        rowids: Vec<row_header::RowId>,
3962        /// Epic W: writer version (`xmax`). `0` until the writing
3963        /// `TxId` is threaded to the storage layer (later slice).
3964        writer_version: u64,
3965    },
3966    /// v7.37.15 (Epic W durable-tombstone slice) — an **in-place MVCC
3967    /// delete**: the row(s) named by `rowids` are NOT physically
3968    /// removed; their header `xmax` is stamped so newer snapshots stop
3969    /// seeing them (vacuum reclaims later). This is the redo shape of
3970    /// the gate-on (`SPG_MVCC_INPLACE`) DELETE / UPDATE-old-version /
3971    /// ON-CONFLICT paths, which call [`Table::mark_row_deleted`]
3972    /// instead of `delete_rows`.
3973    ///
3974    /// Unlike `Delete`, the target is named by **stable `RowId`**, not
3975    /// physical position: a tombstone keeps the slot, so position would
3976    /// be ambiguous after later compaction, and the header-preserving
3977    /// replay must re-find the exact row the writer tombstoned. On
3978    /// replay the id is matched against the ids the same redo run
3979    /// produced (an `Insert`'s `rowid`, or the table's ids snapshotted
3980    /// at run start); an id that cannot be resolved is skipped and
3981    /// counted (see `apply_redo_run_on_table`) — this is the documented
3982    /// cross-checkpoint limitation until the V6 envelope persists ids.
3983    Tombstone {
3984        table: String,
3985        /// Stable ids of the tombstoned rows (from `self.rowids()[pos]`
3986        /// at capture). Never empty for a recorded tombstone.
3987        rowids: Vec<row_header::RowId>,
3988        /// The version stamped into each target row's header `xmax`
3989        /// (the deleting statement's writer version).
3990        xmax: u64,
3991    },
3992}
3993
3994impl RowChange {
3995    /// v7.39 (round 736) — which table this change applies to.
3996    #[must_use]
3997    pub fn table_name(&self) -> &str {
3998        match self {
3999            Self::Insert { table, .. }
4000            | Self::Update { table, .. }
4001            | Self::Delete { table, .. }
4002            | Self::Tombstone { table, .. } => table,
4003        }
4004    }
4005
4006    /// v7.37.15 (Epic W slice 2) — stamp the committing writer
4007    /// version onto this change. Every change drained from a single
4008    /// statement shares one version (the statement's `xmin`/`xmax`),
4009    /// so the engine calls this on each drained change with the value
4010    /// from [`Engine::writer_version_for_current_stmt`]. Additive
4011    /// metadata only: replay still resolves by physical position and
4012    /// does not read `writer_version` (that is a later slice).
4013    pub fn set_writer_version(&mut self, v: u64) {
4014        match self {
4015            RowChange::Insert { writer_version, .. }
4016            | RowChange::Update { writer_version, .. }
4017            | RowChange::Delete { writer_version, .. } => *writer_version = v,
4018            // A tombstone captures `xmax` directly from the deleting
4019            // statement's version at record time (via
4020            // `mark_row_deleted`), so it already equals `v`. Keep the
4021            // "one statement, one version" invariant mechanical by
4022            // asserting agreement in debug builds rather than silently
4023            // overwriting a possibly-different value.
4024            RowChange::Tombstone { xmax, .. } => {
4025                debug_assert_eq!(
4026                    *xmax, v,
4027                    "tombstone xmax must match the statement writer version"
4028                );
4029                *xmax = v;
4030            }
4031        }
4032    }
4033}
4034
4035/// v7.37.15 (Epic W slice 1) — leading marker byte of the
4036/// metadata-carrying redo layout. A **pre-Epic-W** redo payload leads
4037/// with `FILE_VERSION` (8..=52 today, rising ~1 per release); this
4038/// marker is `0xFF` and can therefore never collide with a real
4039/// `FILE_VERSION`, so [`decode_redo_log`] tells the two layouts apart
4040/// by inspecting the first byte alone. The compile-time assertion
4041/// below makes the "never collide" invariant a hard build gate: if
4042/// `FILE_VERSION` ever climbs toward `0xFF` the build breaks and forces
4043/// a redesign long before an ambiguity could ship.
4044const REDO_META_MARKER: u8 = 0xFF;
4045/// v7.37.15 (Epic W slice 1) — version of the metadata-carrying redo
4046/// layout that follows [`REDO_META_MARKER`]. Bumped when the per-change
4047/// metadata shape changes; an unknown value is a hard decode error.
4048const REDO_META_VERSION: u8 = 1;
4049
4050/// v7.37.15 (Epic W durable-tombstone slice) — process-wide count of
4051/// [`RowChange::Tombstone`] targets that `apply_redo` could NOT resolve
4052/// to a row by `RowId`. A non-zero value is expected only across a
4053/// checkpoint boundary (the table's ids are reassigned on deserialize
4054/// and the V6 envelope does not yet persist them), where a tombstone
4055/// naming a pre-checkpoint row is left visible rather than mis-applied.
4056/// Surfaced for observability; never affects correctness of the resolved
4057/// tombstones. Read via [`unresolved_tombstone_count`].
4058static UNRESOLVED_TOMBSTONES: core::sync::atomic::AtomicU64 = core::sync::atomic::AtomicU64::new(0);
4059
4060/// v7.39 (flip crash-replay P0) — observability read for the replay
4061/// tombstones that could not be resolved to a row (each one is a
4062/// resurrected delete).
4063#[must_use]
4064pub fn unresolved_tombstones() -> u64 {
4065    UNRESOLVED_TOMBSTONES.load(core::sync::atomic::Ordering::Relaxed)
4066}
4067
4068/// v7.37.15 (Epic W durable-tombstone slice) — read the process-wide
4069/// count of redo tombstones that could not be resolved to a row by
4070/// `RowId` during `apply_redo`. See [`UNRESOLVED_TOMBSTONES`].
4071#[must_use]
4072pub fn unresolved_tombstone_count() -> u64 {
4073    UNRESOLVED_TOMBSTONES.load(core::sync::atomic::Ordering::Relaxed)
4074}
4075// Provably-unambiguous old/new distinction: the pre-Epic-W layout's
4076// first byte is `FILE_VERSION`, which must stay strictly below the
4077// marker forever.
4078const _: () = assert!(FILE_VERSION < REDO_META_MARKER);
4079
4080/// v7.34 (crash-recovery P0 #2), extended v7.37.15 (Epic W slice 1) —
4081/// encode a row-level redo log to bytes for a WAL record.
4082///
4083/// ## Layout (Epic W metadata-carrying form, always emitted now)
4084///
4085/// `[u8 REDO_META_MARKER=0xFF][u8 REDO_META_VERSION][u8 FILE_VERSION]
4086/// [u32 count]` then per change `[u8 op][str table]` and, per op:
4087/// - `Insert [u32 n][value×n][u64 rowid][u64 writer_version]`
4088/// - `Update [u32 pos][u32 n][value×n][u64 rowid][u64 writer_version]`
4089/// - `Delete [u32 n][u32 pos×n][u64 rowid×n][u64 writer_version]`
4090/// - `Tombstone [u32 n][u64 rowid×n][u64 xmax]` (op byte 3; only ever
4091///   emitted under the metadata-carrying layout — the pre-Epic-W layout
4092///   had no in-place tombstone, so a legacy stream can never carry it)
4093///
4094/// Positions are physical (u32 ≤ 4 G rows). The `FILE_VERSION` byte
4095/// still rides along (now the 3rd byte) so the value codec decodes
4096/// string / BYTEA escapes exactly as before.
4097///
4098/// ## Backward compatibility
4099///
4100/// The **pre-Epic-W** layout was `[u8 FILE_VERSION][u32 count]…` with
4101/// no per-change metadata. [`decode_redo_log`] still decodes that form
4102/// (first byte < `0xFF`) byte-for-byte identically — every WAL file
4103/// written by released code replays unchanged.
4104#[must_use]
4105pub fn encode_redo_log(changes: &[RowChange]) -> Vec<u8> {
4106    let mut out = Vec::new();
4107    out.push(REDO_META_MARKER);
4108    out.push(REDO_META_VERSION);
4109    out.push(FILE_VERSION);
4110    codec::write_u32(&mut out, changes.len() as u32);
4111    let write_values = |out: &mut Vec<u8>, vals: &[Value<'static>]| {
4112        codec::write_u32(out, vals.len() as u32);
4113        for v in vals {
4114            codec::write_value(out, v);
4115        }
4116    };
4117    for change in changes {
4118        match change {
4119            RowChange::Insert {
4120                table,
4121                row,
4122                rowid,
4123                writer_version,
4124            } => {
4125                out.push(0);
4126                codec::write_str(&mut out, table);
4127                write_values(&mut out, &row.values);
4128                codec::write_u64(&mut out, rowid.0);
4129                codec::write_u64(&mut out, *writer_version);
4130            }
4131            RowChange::Update {
4132                table,
4133                pos,
4134                new_row,
4135                rowid,
4136                writer_version,
4137            } => {
4138                out.push(1);
4139                codec::write_str(&mut out, table);
4140                codec::write_u32(&mut out, *pos as u32);
4141                write_values(&mut out, new_row);
4142                codec::write_u64(&mut out, rowid.0);
4143                codec::write_u64(&mut out, *writer_version);
4144            }
4145            RowChange::Delete {
4146                table,
4147                positions,
4148                rowids,
4149                writer_version,
4150            } => {
4151                out.push(2);
4152                codec::write_str(&mut out, table);
4153                codec::write_u32(&mut out, positions.len() as u32);
4154                for p in positions {
4155                    codec::write_u32(&mut out, *p as u32);
4156                }
4157                // Epic W: one RowId per position (parallel). Capture
4158                // sites always produce `rowids.len() == positions.len()`;
4159                // this assertion pins that invariant at encode time so a
4160                // mismatch is a loud bug, not a silently short payload.
4161                debug_assert_eq!(
4162                    rowids.len(),
4163                    positions.len(),
4164                    "redo Delete: rowids must be parallel to positions"
4165                );
4166                for rid in rowids {
4167                    codec::write_u64(&mut out, rid.0);
4168                }
4169                codec::write_u64(&mut out, *writer_version);
4170            }
4171            RowChange::Tombstone {
4172                table,
4173                rowids,
4174                xmax,
4175            } => {
4176                out.push(3);
4177                codec::write_str(&mut out, table);
4178                codec::write_u32(&mut out, rowids.len() as u32);
4179                for rid in rowids {
4180                    codec::write_u64(&mut out, rid.0);
4181                }
4182                codec::write_u64(&mut out, *xmax);
4183            }
4184        }
4185    }
4186    out
4187}
4188
4189/// v7.34, extended v7.37.15 (Epic W slice 1) — decode a row-level redo
4190/// log written by [`encode_redo_log`].
4191///
4192/// Decodes **both** the Epic W metadata-carrying layout (first byte
4193/// `REDO_META_MARKER = 0xFF`) and the pre-Epic-W layout (first byte is
4194/// `FILE_VERSION`, always `< 0xFF`). For the old layout the per-change
4195/// metadata is absent, so `rowid`/`rowids` come back
4196/// [`RowId::UNASSIGNED`](row_header::RowId::UNASSIGNED) (empty for
4197/// `Delete`) and `writer_version` comes back `0`.
4198///
4199/// A truncated / corrupt buffer is a hard error — never a panic — the
4200/// embedding layer frames each record with its own length + CRC, so a
4201/// frame that decodes short is corruption, not a torn tail.
4202pub fn decode_redo_log(bytes: &[u8]) -> Result<Vec<RowChange>, StorageError> {
4203    let first = *bytes
4204        .first()
4205        .ok_or_else(|| StorageError::Corrupt("redo log: empty".into()))?;
4206    // Epic W: `0xFF` marker ⇒ metadata-carrying layout; anything else
4207    // is a pre-Epic-W `FILE_VERSION` byte (old layout, no metadata).
4208    let has_meta = first == REDO_META_MARKER;
4209    let (codec_version, header_len) = if has_meta {
4210        let meta_version = *bytes
4211            .get(1)
4212            .ok_or_else(|| StorageError::Corrupt("redo log: short header".into()))?;
4213        if meta_version != REDO_META_VERSION {
4214            return Err(StorageError::Corrupt(alloc::format!(
4215                "redo log: unknown metadata version {meta_version}"
4216            )));
4217        }
4218        let file_version = *bytes
4219            .get(2)
4220            .ok_or_else(|| StorageError::Corrupt("redo log: short header".into()))?;
4221        // header = [marker][meta_version][file_version]
4222        (file_version, 3usize)
4223    } else {
4224        // Old layout: the first byte IS the FILE_VERSION.
4225        (first, 1usize)
4226    };
4227    let mut cur = codec::Cursor::new(bytes).with_codec_version(codec_version);
4228    for _ in 0..header_len {
4229        cur.read_u8()?;
4230    }
4231    let count = cur.read_u32()? as usize;
4232    let mut read_values =
4233        |cur: &mut codec::Cursor<'_>| -> Result<Vec<Value<'static>>, StorageError> {
4234            let n = cur.read_u32()? as usize;
4235            let mut vals = Vec::with_capacity(n);
4236            for _ in 0..n {
4237                vals.push(cur.read_value()?);
4238            }
4239            Ok(vals)
4240        };
4241    let mut changes = Vec::with_capacity(count);
4242    for _ in 0..count {
4243        let op = cur.read_u8()?;
4244        let table = cur.read_str()?;
4245        let change = match op {
4246            0 => {
4247                let row = Row::new(read_values(&mut cur)?);
4248                let (rowid, writer_version) = if has_meta {
4249                    (row_header::RowId(cur.read_u64()?), cur.read_u64()?)
4250                } else {
4251                    (row_header::RowId::UNASSIGNED, 0)
4252                };
4253                RowChange::Insert {
4254                    table,
4255                    row,
4256                    rowid,
4257                    writer_version,
4258                }
4259            }
4260            1 => {
4261                let pos = cur.read_u32()? as usize;
4262                let new_row = read_values(&mut cur)?;
4263                let (rowid, writer_version) = if has_meta {
4264                    (row_header::RowId(cur.read_u64()?), cur.read_u64()?)
4265                } else {
4266                    (row_header::RowId::UNASSIGNED, 0)
4267                };
4268                RowChange::Update {
4269                    table,
4270                    pos,
4271                    new_row,
4272                    rowid,
4273                    writer_version,
4274                }
4275            }
4276            2 => {
4277                let n = cur.read_u32()? as usize;
4278                let mut positions = Vec::with_capacity(n);
4279                for _ in 0..n {
4280                    positions.push(cur.read_u32()? as usize);
4281                }
4282                let (rowids, writer_version) = if has_meta {
4283                    let mut rowids = Vec::with_capacity(n);
4284                    for _ in 0..n {
4285                        rowids.push(row_header::RowId(cur.read_u64()?));
4286                    }
4287                    (rowids, cur.read_u64()?)
4288                } else {
4289                    // Old layout carried no RowId metadata.
4290                    (Vec::new(), 0)
4291                };
4292                RowChange::Delete {
4293                    table,
4294                    positions,
4295                    rowids,
4296                    writer_version,
4297                }
4298            }
4299            // Op 3 is the Epic W in-place tombstone — it only exists in
4300            // the metadata-carrying layout. Guarding on `has_meta` means
4301            // a legacy stream that happens to contain a `3` byte here is
4302            // reported as an unknown op (corruption), never mis-decoded.
4303            3 if has_meta => {
4304                let n = cur.read_u32()? as usize;
4305                let mut rowids = Vec::with_capacity(n);
4306                for _ in 0..n {
4307                    rowids.push(row_header::RowId(cur.read_u64()?));
4308                }
4309                let xmax = cur.read_u64()?;
4310                RowChange::Tombstone {
4311                    table,
4312                    rowids,
4313                    xmax,
4314                }
4315            }
4316            other => {
4317                return Err(StorageError::Corrupt(alloc::format!(
4318                    "redo log: unknown op {other}"
4319                )));
4320            }
4321        };
4322        changes.push(change);
4323    }
4324    Ok(changes)
4325}
4326
4327/// v7.39 (pg_stat knife B) — per-table scan counters, bumped from
4328/// `&self` read paths. Clone (tx shadow catalogs clone tables) copies
4329/// the current values; the counters are volatile like PG's cumulative
4330/// stats.
4331#[derive(Debug, Default)]
4332pub struct ScanStats {
4333    pub seq_scan: core::sync::atomic::AtomicU64,
4334    pub seq_tup_read: core::sync::atomic::AtomicU64,
4335    pub idx_scan: core::sync::atomic::AtomicU64,
4336    pub idx_tup_fetch: core::sync::atomic::AtomicU64,
4337}
4338
4339impl Clone for ScanStats {
4340    fn clone(&self) -> Self {
4341        use core::sync::atomic::{AtomicU64, Ordering};
4342        Self {
4343            seq_scan: AtomicU64::new(self.seq_scan.load(Ordering::Relaxed)),
4344            seq_tup_read: AtomicU64::new(self.seq_tup_read.load(Ordering::Relaxed)),
4345            idx_scan: AtomicU64::new(self.idx_scan.load(Ordering::Relaxed)),
4346            idx_tup_fetch: AtomicU64::new(self.idx_tup_fetch.load(Ordering::Relaxed)),
4347        }
4348    }
4349}
4350
4351/// v7.39 (round 215) — the lower-bound sort key for a range value, used by
4352/// the range-exclusion index. The bound as an `i128` (unbounded lower =
4353/// `i128::MIN`, sorting first) plus an inclusivity rank (inclusive lower
4354/// sorts before exclusive at the same value, `[3` before `(3`). Returns
4355/// `None` for range kinds whose bound isn't an integer scalar (numrange's
4356/// numeric/bignum), for empty ranges, and for non-range values — the caller
4357/// then keeps the O(n) scan rather than risk an unsound order. Int4/Int8/
4358/// Date/Ts/TsTz all reduce here (tstzrange bounds are `Value::Timestamp`).
4359/// Maintenance (index build) and query (overlap probe) MUST agree on this
4360/// key, so both sides call exactly this function.
4361#[must_use]
4362pub fn range_excl_index_key(v: &Value<'_>) -> Option<(i128, u8)> {
4363    let Value::Range {
4364        lower,
4365        lower_inc,
4366        empty,
4367        ..
4368    } = v
4369    else {
4370        return None;
4371    };
4372    if *empty {
4373        return None;
4374    }
4375    let key = match lower {
4376        None => i128::MIN,
4377        Some(b) => match b.as_ref() {
4378            Value::SmallInt(n) => i128::from(*n),
4379            Value::Int(n) => i128::from(*n),
4380            Value::BigInt(n) => i128::from(*n),
4381            Value::Date(n) => i128::from(*n),
4382            Value::Timestamp(n) => i128::from(*n),
4383            _ => return None,
4384        },
4385    };
4386    Some((key, u8::from(!*lower_inc)))
4387}
4388
4389/// v7.39 (round 215) — a per-table range-exclusion index: an incrementally
4390/// maintained map from a range column's lower-bound key
4391/// ([`range_excl_index_key`]) to the physical row locators carrying that
4392/// bound. Lets EXCLUDE enforcement find the few candidate rows a new range
4393/// might overlap in O(log n) instead of scanning every row (measured O(N²),
4394/// r213). Because the stored ranges under a valid `EXCLUDE (col WITH &&)`
4395/// are pairwise disjoint, a candidate overlaps only its predecessor or the
4396/// successors whose lower bound precedes its upper — a handful of probes.
4397///
4398/// NOT persisted: rebuilt from the (persisted) exclusion constraints + rows
4399/// on catalog load, exactly like BRIN re-derives. Backed by a
4400/// `PersistentBTreeMap` so `Table::clone` (the per-write snapshot) stays
4401/// O(1). Locators to tombstoned rows are left in place and filtered by the
4402/// consumer via `is_deleted()` at query time — the established index pattern.
4403#[derive(Debug, Clone)]
4404pub struct ExclRangeIndex {
4405    /// The constrained range column's position in the table.
4406    pub column_position: usize,
4407    /// Lower-bound key → row locators. A key maps to a `Vec` because a
4408    /// tombstoned-then-reinserted bound can transiently collide; live rows
4409    /// under the constraint are disjoint so each key has one live locator.
4410    pub map: PersistentBTreeMap<(i128, u8), crate::posting::PostingList>,
4411}
4412
4413/// v7.38.2 (R2) — see [`Table::tx_write_track`]. Positions are the
4414/// insert-time slots (verified against the header's version at
4415/// extraction, so a shifted slot falls back to the scan); tombstones
4416/// carry the stable RowId, which is what the write-set wants anyway.
4417#[derive(Debug, Clone, Default)]
4418struct TxWriteTrack {
4419    version: u64,
4420    inserted: Vec<(usize, row_header::RowId)>,
4421    tombstoned: Vec<row_header::RowId>,
4422}
4423
4424/// v7.38.11 — hot-tier BRIN granularity: slots per summarised range.
4425///
4426/// 1024 keeps the summary vector three orders of magnitude smaller
4427/// than the table while staying fine enough that a one-day window over
4428/// a 90-day table skips ~99 % of it. A tuning constant, not a format:
4429/// summaries are rebuilt from the rows on load, so changing it costs
4430/// nothing on disk.
4431pub const BRIN_RANGE_ROWS: usize = 1024;
4432
4433/// The comparable scalar a BRIN summary tracks, or `None` for a value
4434/// with no ordering this index can use.
4435///
4436/// Deliberately narrow: only types whose ordering IS the i64 ordering
4437/// of this number. A type added here whose comparison is not that —
4438/// text under a collation, say — would make the summary under-report
4439/// and skip matching rows, which is the one failure this design must
4440/// not have.
4441#[must_use]
4442pub fn brin_scalar(v: &Value<'_>) -> Option<i64> {
4443    match v {
4444        Value::SmallInt(n) => Some(i64::from(*n)),
4445        Value::Int(n) => Some(i64::from(*n)),
4446        Value::BigInt(n) | Value::Timestamp(n) => Some(*n),
4447        Value::Date(d) => Some(i64::from(*d)),
4448        Value::Bool(b) => Some(i64::from(*b)),
4449        _ => None,
4450    }
4451}
4452
4453#[derive(Debug, Clone)]
4454pub struct Table {
4455    schema: TableSchema,
4456    /// v7.37.15 (Phase C.1) — stable per-catalog relation identity.
4457    /// [`RelId::UNASSIGNED`](row_header::RelId::UNASSIGNED) until
4458    /// `Catalog::create_table` (or the deserialize dense-assign pass)
4459    /// stamps a real id. Keys the Phase C.4 row-lock table and the
4460    /// Phase C.5 `RelationStore`; survives `DROP TABLE` slot shifts.
4461    rel_id: row_header::RelId,
4462    rows: PersistentVec<Row<'static>>,
4463    /// v7.37.15 (Phase A.2) — per-row MVCC visibility headers
4464    /// parallel to `rows`. `headers.len() == rows.len()` is the
4465    /// load-bearing invariant; debug builds assert it on every
4466    /// scan boundary, release builds rely on it from
4467    /// disciplined insert / delete / update paths.
4468    ///
4469    /// Pre-v7.37.15-loaded tables (every row currently in the
4470    /// fleet) start as `RowHeader::frozen()` — `is_all_visible_fast()`
4471    /// returns `true`, so the per-row visibility gate Phase B
4472    /// adds is a no-op against any snapshot.
4473    ///
4474    /// Headers are NOT yet serialised into the envelope at this
4475    /// commit — on snapshot deserialize every row gets a fresh
4476    /// `RowHeader::frozen()`. Phase D adds the visibility-map
4477    /// + segment-freeze story which makes serialisation
4478    /// meaningful; until then the on-disk story is "the catalog
4479    /// is the set of visible rows."
4480    headers: PersistentVec<row_header::RowHeader>,
4481    /// v7.37.15 (Phase C.1) — stable per-relation row identity
4482    /// parallel to `rows` / `headers`. `rowids[i]` is the never-
4483    /// reused [`RowId`](row_header::RowId) of the row physically at
4484    /// slot `i`; `rowids.len() == rows.len()` joins the same load-
4485    /// bearing lock-step invariant as `headers`. Compaction (delete
4486    /// / vacuum) rebuilds all three vecs together so the id travels
4487    /// with the row while the slot shifts.
4488    ///
4489    /// Introduced additively: allocated + kept lock-step, but index
4490    /// locators still address rows by physical slot at this commit.
4491    /// Later phases migrate the lock table (C.4), HOT chains (D),
4492    /// and the WAL (Epic W) to address by `RowId`.
4493    ///
4494    /// Not yet serialised into the envelope — on load every row is
4495    /// assigned a fresh dense id `1..=len` (see `next_rowid`), which
4496    /// is sufficient while the id is process-local bookkeeping. The
4497    /// V6 envelope (Phase C.6) will persist ids so a WAL redo can
4498    /// name a row across restart.
4499    rowids: PersistentVec<row_header::RowId>,
4500    /// v7.37.15 (Phase C.1) — per-relation monotonic allocator for
4501    /// `rowids`. Starts at 1 (0 is the `RowId::UNASSIGNED` sentinel);
4502    /// every append takes `next_rowid` then increments. Never reused
4503    /// even after the row is deleted / vacuumed, so a stale lock /
4504    /// redo reference can be detected rather than silently aliasing a
4505    /// later row that reused the slot.
4506    ///
4507    /// 7.38.1 (S2.4, MATRIX #20 root cause) — the allocator is SHARED
4508    /// across every `clone()` of the relation (`Arc`), because the
4509    /// monotonic-never-reused promise is a LINEAGE invariant: each
4510    /// open transaction's shadow catalog is a clone, and when clones
4511    /// carried private counters two concurrent shadows minted the
4512    /// same id — duplicate rids in the base after both committed,
4513    /// aliasing every rid-addressed mechanism (locks, tombstones,
4514    /// redo, the rebase unique pre-check).
4515    next_rowid: alloc::sync::Arc<core::sync::atomic::AtomicU64>,
4516    /// v7.37.16 (autovacuum) — live count of tombstoned-but-present hot
4517    /// rows (`headers[i].xmax != XMAX_ALIVE`). Maintained incrementally:
4518    /// `mark_row_deleted` / `mark_rows_deleted` increment (the only
4519    /// tombstone producers), `delete_rows_no_index` recomputes over the
4520    /// survivors (it is the compaction hub every physical removal —
4521    /// including vacuum — flows through), and the v53 snapshot loader
4522    /// recounts verbatim-restored headers. Drives the engine's
4523    /// autovacuum threshold; not persisted (recomputed on load).
4524    dead_rows: u64,
4525    /// v7.39 (pg_stat knife A) — volatile per-table write counters
4526    /// backing `pg_stat_user_tables.n_tup_ins/upd/del`. Not persisted
4527    /// (PG's cumulative stats are shared-memory-volatile too — a
4528    /// restart zeroes them).
4529    stat_tup_ins: u64,
4530    stat_tup_upd: u64,
4531    stat_tup_del: u64,
4532    /// v7.39 (pg_stat knife B) — volatile scan counters
4533    /// (`seq_scan/seq_tup_read/idx_scan/idx_tup_fetch`). Atomics: the
4534    /// read paths that bump them hold only `&Table`.
4535    scan_stats: ScanStats,
4536    /// v7.39 (pg_stat knife C) — wall-clock stamps (unix µs, from the
4537    /// host ClockFn) for pg_stat_user_tables' last_autovacuum /
4538    /// last_analyze. Volatile, like PG's cumulative stats. SPG has no
4539    /// manual-VACUUM statement semantics, so last_vacuum stays NULL.
4540    last_autovacuum_us: Option<i64>,
4541    last_analyze_us: Option<i64>,
4542    indices: Vec<Index>,
4543    hot_bytes: u64,
4544    /// v6.7.0 — cached count of rows currently materialised in the
4545    /// cold tier via `RowLocator::Cold` entries across THIS table's
4546    /// indices. Populated by `ANALYZE` (walks every BTree index and
4547    /// counts Cold locators); the count survives until the next
4548    /// ANALYZE recomputes it. Surfaced via `spg_statistic.cold_row_count`
4549    /// and `spg_stat_segment.table_name`.
4550    ///
4551    /// Honest scope: this is a CACHED count, not a live one.
4552    /// Freezer / promote / DELETE don't currently update the cache
4553    /// incrementally — they invalidate it by setting the
4554    /// `cold_row_count_stale` flag, and the next ANALYZE re-walks.
4555    /// Incremental maintenance is a v6.7.x candidate if observation
4556    /// shows the ANALYZE walk cost dominates.
4557    cold_row_count: u64,
4558    /// v6.7.0 — set when the cached `cold_row_count` may be wrong
4559    /// because rows moved into / out of the cold tier since the last
4560    /// ANALYZE. The virtual-table surface reports the cached value
4561    /// regardless (operators run ANALYZE to refresh).
4562    cold_row_count_stale: bool,
4563    /// v7.34 (crash-recovery P0 #2) — row-level redo capture buffer.
4564    /// `None` (default, in-memory mode) captures nothing — zero overhead.
4565    /// `Some` (set by the engine when persistence is on, before a
4566    /// mutating call) makes `insert` / `update_row` / `delete_rows`
4567    /// record the physical [`RowChange`] they applied, which the engine
4568    /// drains after the statement and writes to the WAL in place of the
4569    /// SQL text. Transient: never serialized; a `Catalog::clone` between
4570    /// enable and drain copies it (cheap — empty in the steady state).
4571    redo_log: Option<Vec<RowChange>>,
4572    /// v7.39 (round 215) — per-`EXCLUDE`-constraint range-overlap indexes,
4573    /// one per single-`&&` constraint on an integer-keyable range column.
4574    /// Maintained incrementally on insert / update / rebuild (mirroring the
4575    /// BTree secondary indexes); NOT serialized — rebuilt from the schema's
4576    /// exclusion constraints on load. Empty for tables with no EXCLUDE
4577    /// constraint (the common case), so `Table::clone` pays nothing.
4578    excl_indexes: Vec<ExclRangeIndex>,
4579    /// v7.38.2 (R2) — incremental write-set track for the RC rebase.
4580    /// `extract_tx_writeset` used to full-scan every header per call —
4581    /// ~200 µs on a 20k-row table, per in-transaction statement, every
4582    /// time a concurrent COMMIT moved the epoch; on tpcb's 100k-row
4583    /// accounts that scan was the c2 concurrency cliff itself. The
4584    /// three version-marking funnels (`insert_with_xmin`,
4585    /// `mark_row_deleted`, `mark_rows_deleted`) record here instead.
4586    ///
4587    /// One track per table, keyed by the LAST writer version: a shadow
4588    /// belongs to one transaction, so a different version claiming the
4589    /// table simply replaces the track (on the committed base that
4590    /// makes memory bounded by the last writer's footprint). Extraction
4591    /// verifies every recorded position still carries the version —
4592    /// any mismatch (compaction, inherited track, pre-track rows)
4593    /// falls back to the full scan, so the fast path can be wrong
4594    /// about NOTHING, only slow.
4595    tx_write_track: Option<TxWriteTrack>,
4596    /// v7.39 (round 493) — the snapshot floor below which a deleted row
4597    /// version is invisible to everyone, as of the statement now running.
4598    ///
4599    /// Runtime only: never serialised, and `0` (the default) prunes
4600    /// nothing, so any path that forgets to set it is merely slower, not
4601    /// wrong. The engine sets it from `vacuum_oldest_active()` — the same
4602    /// floor `vacuum` itself takes — before the statement's inserts.
4603    prune_horizon: u64,
4604}
4605
4606/// Catalog: insertion-ordered `Vec<Table>` for stable iter / serialize,
4607/// plus a `BTreeMap<String, usize>` sidecar index so `get` / `get_mut`
4608/// run in O(log n) instead of the old linear scan with per-element
4609/// string compares.
4610///
4611/// A pure `BTreeMap<String, Table>` was tried in an interim version
4612/// of v3.1.2 and regressed the single-table catalog benches by ~10%
4613/// (the per-element `BTreeMap` overhead outweighs the lookup win
4614/// when n is small). The sidecar shape preserves the insertion-order
4615/// iteration the on-disk encoding relies on and keeps `last_mut`
4616/// (used by the deserialize hot path) cheap.
4617/// v7.39 (pg_stat blks knife) — catalog-wide cold-tier read counter
4618/// backing pg_stat_database.blks_read. Row-granular (SPG has no 8 KB
4619/// page notion): one cold-segment row resolution = one "block read",
4620/// one hot row access = one "block hit" — the hit RATIO monitoring
4621/// dashboards compute keeps its meaning. Volatile like PG's stats.
4622#[derive(Debug, Default)]
4623pub struct ColdReadStats {
4624    pub cold_reads: core::sync::atomic::AtomicU64,
4625}
4626
4627impl Clone for ColdReadStats {
4628    fn clone(&self) -> Self {
4629        Self {
4630            cold_reads: core::sync::atomic::AtomicU64::new(
4631                self.cold_reads.load(core::sync::atomic::Ordering::Relaxed),
4632            ),
4633        }
4634    }
4635}
4636
4637/// 7.38.1 S3.1 (D4) — the non-table catalog families that carry a
4638/// per-transaction dirty window (see `Catalog::dirty_nontable`). One
4639/// entry class per side-map the poisoned-commit merge reconciles.
4640#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
4641pub enum NonTableKind {
4642    Sequence,
4643    View,
4644    MaterializedView,
4645    EnumType,
4646    DomainType,
4647    CompositeType,
4648}
4649
4650#[derive(Debug, Clone, Default)]
4651pub struct Catalog {
4652    /// v7.39 (pg_stat blks knife) — see [`ColdReadStats`].
4653    pub cold_read_stats: ColdReadStats,
4654    tables: Vec<Table>,
4655    /// `name → tables[index]`. Kept in lock-step with `tables`.
4656    /// `create_table` is the only write path.
4657    by_name: BTreeMap<String, usize>,
4658    /// v7.39 (round 436) — the current session's temporary-table namespace.
4659    /// A temp table is stored under `<prefix><name>`, and every lookup tries
4660    /// that first: exactly PG's `pg_temp` search-path rule, and MySQL's
4661    /// "a TEMPORARY table shadows a permanent one of the same name".
4662    ///
4663    /// Process-local, never serialised: the engine sets it per session, and
4664    /// a catalog read back from disk starts with none. Kept here rather than
4665    /// at each of the ~170 engine call sites because `by_name` is private —
4666    /// this is the ONE place a table name becomes an index.
4667    temp_prefix: Option<String>,
4668    /// v7.39 (round 496) — the names of tables this catalog handle has had
4669    /// changed since the set was last cleared.
4670    ///
4671    /// Runtime only, never serialised. A transaction's shadow catalog
4672    /// clears it at BEGIN, so at COMMIT the set is exactly the tables the
4673    /// transaction changed — which is what lets a commit that cannot use
4674    /// the row-level merge install only those tables instead of the whole
4675    /// catalog, leaving another session's concurrent work in place.
4676    ///
4677    /// Recorded where the change actually happens (`get_mut`,
4678    /// `create_table`, `drop_table`) rather than from the statement
4679    /// classifier: round 494 tried classification for a correctness gate
4680    /// and it was wrong, because `SELECT lo_write(…)` reads as read-only.
4681    dirty_tables: alloc::collections::BTreeSet<String>,
4682    /// 7.38.1 S3.1 (D4) — the non-table twin of `dirty_tables`: which
4683    /// sequences / views / matviews / enum / domain / composite types
4684    /// THIS window created, altered, renamed or dropped. Counter
4685    /// advances (`nextval`) deliberately do NOT record — counter
4686    /// values merge via `sequence_counters` / `restore_sequence_
4687    /// counters`, and a tx that only consumed ids must not shadow a
4688    /// neighbour's ALTER SEQUENCE. Cleared by `clear_dirty_tables`
4689    /// (one window, both records).
4690    dirty_nontable: alloc::collections::BTreeSet<(NonTableKind, String)>,
4691    /// v7.37.15 (Phase C.1) — monotonic allocator for stable
4692    /// [`RelId`](row_header::RelId)s. Pre-incremented on each
4693    /// `create_table` so real ids start at 1 (0 is `UNASSIGNED`);
4694    /// never reused even after `DROP TABLE`, so a stale lock / redo
4695    /// reference is detectable. Process-local bookkeeping — not yet
4696    /// serialised; `deserialize` re-assigns dense ids on load (the
4697    /// V6 envelope, Phase C.6, will round-trip real ids).
4698    next_rel_id: u64,
4699    /// v5.1: in-memory cold-tier segments. Side-loaded via
4700    /// [`Catalog::load_segment_bytes`] — they live outside the
4701    /// catalog snapshot (caller persists them as separate files
4702    /// and re-loads on boot, until v5.3's `CatalogManifest` makes
4703    /// that wiring automatic). `RowLocator::Cold { segment_id, .. }`
4704    /// indexes this `Vec`. Cleared on `Catalog::new` / fresh
4705    /// `deserialize`.
4706    ///
4707    /// `Arc` wrap keeps `Catalog::clone` at O(N segments) bumps
4708    /// (rather than O(total segment bytes) memcpy) so the v4.42
4709    /// group-commit pre-image rollback invariant — clone is
4710    /// effectively free — survives the cold-tier addition.
4711    ///
4712    /// v6.7.3 — slots became `Option<…>` so cold-segment compaction
4713    /// can tombstone merged sources without breaking the
4714    /// `segment_id = index_into_vec` contract that on-disk
4715    /// `RowLocator::Cold { segment_id }` already serialized.
4716    /// `None` slot = the segment was retired by compaction; the
4717    /// physical file may still be on disk (next CHECKPOINT writes
4718    /// a manifest that no longer lists it, and the file becomes
4719    /// an orphan eligible for offline cleanup).
4720    cold_segments: Vec<Option<Arc<OwnedSegment>>>,
4721    /// v7.12.4 — user-defined functions (PL/pgSQL + SQL).
4722    /// Keyed by function name (PG overloading is out of scope).
4723    /// Bodies are stored as the raw source text the parser saw
4724    /// between `$$ ... $$`; the engine re-parses on each
4725    /// invocation. This keeps `spg-storage` free of `spg-sql`
4726    /// dependency — same pattern as partial-index predicates.
4727    functions: BTreeMap<String, FunctionDef>,
4728    /// v7.12.4 — triggers in insertion order. PG18-measured (round
4729    /// 753): PG fires same-event triggers in NAME order (a_trig
4730    /// before z_trig regardless of creation order); SPG fires in
4731    /// insertion order — a real divergence, ledgered as F31-B2.
4732    triggers: Vec<TriggerDef>,
4733    /// v7.39 (round 139) — query-rewrite RULEs, flat like triggers.
4734    rules: Vec<RuleDef>,
4735    /// v7.39 (round 280) — extended-statistics objects. Recorded so a
4736    /// pg_dump restores them and reflection reports them; the planner
4737    /// does not consult them yet.
4738    statistics_ext: Vec<StatisticsExtDef>,
4739    /// v7.39 (round 287) — server-side large objects, keyed by OID.
4740    /// PG stores them as 2 KB pages in `pg_largeobject`; the page split
4741    /// is a storage detail of ITS heap, so SPG holds the whole byte
4742    /// string and renders the pages on read. What must match is the
4743    /// observable surface: the OIDs, the bytes, and the page rows.
4744    large_objects: alloc::collections::BTreeMap<u32, Vec<u8>>,
4745    /// v7.17.0 — catalogued SEQUENCE objects (Phase 1.1). Each
4746    /// `nextval(name)` reaches in here, atomically increments
4747    /// `last_value` / flips `is_called`, returns the new value.
4748    /// Persisted in catalog FILE_VERSION 26+; older catalogs
4749    /// deserialise with an empty map.
4750    sequences: BTreeMap<String, SequenceDef>,
4751    /// v7.39 (read01 round 60) — the `public` schema's ACL (PG
4752    /// `pg_namespace.nspacl`). EMPTY = PG's default, which is not "nothing":
4753    /// PUBLIC holds USAGE and the owner holds USAGE + CREATE. Materialised on
4754    /// the first GRANT / REVOKE, exactly like a table's relacl.
4755    schema_acl: Vec<AclItem>,
4756    /// v7.39 (read01 round 60) — the database's ACL. EMPTY = PG's default:
4757    /// PUBLIC holds CONNECT + TEMPORARY, the owner holds all three.
4758    database_acl: Vec<AclItem>,
4759    /// v7.17.0 — catalogued VIEW objects (Phase 1.2). Each
4760    /// `SELECT FROM v` at engine exec-time looks up `v` here and
4761    /// prepends the view body as a synthetic CTE. Persisted in
4762    /// catalog FILE_VERSION 27+; older catalogs deserialise with
4763    /// an empty map.
4764    views: BTreeMap<String, ViewDef>,
4765    /// v7.17.0 — catalogued MATERIALIZED VIEW source registry
4766    /// (Phase 1.3). Maps name → SELECT source. The materialised
4767    /// rows themselves live as a regular `Table` with the same
4768    /// name; REFRESH re-parses + re-executes the source against
4769    /// the table. Persisted in catalog FILE_VERSION 28+;
4770    /// older catalogs deserialise with an empty map.
4771    materialized_views: BTreeMap<String, String>,
4772    /// v7.17.0 — catalogued user-defined ENUM types (Phase 1.4).
4773    /// Maps name → label list. Columns reference these by name
4774    /// via `ColumnSchema.user_enum_type`. Persisted in catalog
4775    /// FILE_VERSION 29+; older catalogs deserialise with an empty
4776    /// map.
4777    enum_types: BTreeMap<String, EnumDef>,
4778    /// v7.17.0 — catalogued user-defined DOMAIN types (Phase 1.5).
4779    /// Maps name → base + CHECK constraints. Columns reference
4780    /// these by name via `ColumnSchema.user_domain_type`.
4781    /// Persisted in catalog FILE_VERSION 30+; older catalogs
4782    /// deserialise with an empty map.
4783    domain_types: BTreeMap<String, DomainDef>,
4784    /// v7.39 (read01 round 50) — `COMMENT ON <kind> <obj> IS '…'` store.
4785    /// Keyed by a canonical `"<kind>:<name>"` string (`"table:t"`,
4786    /// `"column:t.c"`, `"index:i"`, `"view:v"`, …) so a new commentable
4787    /// object kind needs no schema change. `COMMENT … IS NULL` removes the
4788    /// entry. Persisted in catalog FILE_VERSION 61+; older catalogs
4789    /// deserialise with an empty map. Read back by obj_description /
4790    /// col_description and the pg_description view.
4791    comments: BTreeMap<String, String>,
4792    /// v7.39 (round 547) — PG's `pg_db_role_setting`: the GUC defaults
4793    /// `ALTER ROLE … SET` / `ALTER DATABASE … SET` record, applied when
4794    /// a session starts.
4795    ///
4796    /// Keyed exactly as PG keys it — `(database, role)` where an empty
4797    /// name is PG's oid 0, meaning "all". So `ALTER ROLE ALL SET` is
4798    /// `("", "")`, `ALTER DATABASE d SET` is `(d, "")`, `ALTER ROLE r
4799    /// SET` is `("", r)` and `ALTER ROLE r IN DATABASE d SET` is
4800    /// `(d, r)`. The value is that scope's parameter list.
4801    db_role_settings: BTreeMap<(String, String), BTreeMap<String, String>>,
4802    /// v7.39 (round 550) — replication slots, by name.
4803    ///
4804    /// A slot in PG is two things: a named record, and a reservation
4805    /// that holds WAL back. SPG keeps the record — which is what every
4806    /// setup script and monitoring query reads — and reports
4807    /// `wal_status = 'unreserved'`, PG's own word for a slot that no
4808    /// longer holds WAL. The whole family used to answer NULL and
4809    /// report success, so `pg_drop_replication_slot('nosuchslot')` said
4810    /// it worked and a setup script created nothing.
4811    ///
4812    /// Value: (plugin, slot_type). `plugin` is empty for a physical slot.
4813    replication_slots: BTreeMap<String, (String, String)>,
4814    /// v7.37.42-T2 ζ-B — catalogued user-defined COMPOSITE types
4815    /// (`CREATE TYPE name AS (field_name field_type, …)`). Columns
4816    /// reference these by name via
4817    /// `ColumnSchema.user_composite_type` (parallel to
4818    /// `user_enum_type` / `user_domain_type`). Persisted in catalog
4819    /// FILE_VERSION 52+; older catalogs deserialise with an empty
4820    /// map.
4821    composite_types: BTreeMap<String, CompositeDef>,
4822    /// v7.17.0 — schema-namespace registry (Phase 1.6). Tracks
4823    /// which schemas exist. `public`, `pg_catalog`, and
4824    /// `information_schema` are built-in and always present.
4825    /// Schema-qualified table references still strip the prefix
4826    /// at lookup time per v7.16-and-earlier — full
4827    /// schema-as-isolation is v7.18+ scope. Persisted in catalog
4828    /// FILE_VERSION 31+; older catalogs deserialise with just
4829    /// the built-ins.
4830    schemas: alloc::collections::BTreeSet<String>,
4831}
4832
4833/// v7.12.4 — catalogued user-defined function. `body` is the raw
4834/// source text between `$$ ... $$`; the engine re-parses it on
4835/// invocation. This keeps the storage codec stable when the
4836/// PL/pgSQL surface grows (no breaking-change risk on the disk
4837/// format).
4838// v7.39 (round 322, V46) — no longer `Eq`: COST / ROWS are f64, as in PG.
4839#[derive(Debug, Clone, PartialEq)]
4840pub struct FunctionDef {
4841    pub name: String,
4842    /// Display form of the argument list, e.g.
4843    /// `"(name TEXT, ts TIMESTAMP)"`. Empty `"()"` for the trigger
4844    /// function shape. Parser-side canonicalised before storage.
4845    pub args_repr: String,
4846    /// Display form of the return type, e.g. `"TRIGGER"` /
4847    /// `"INT"` / `"SETOF text"`. The engine special-cases
4848    /// `"TRIGGER"` (case-insensitive) to gate trigger-only
4849    /// semantics (NEW/OLD).
4850    pub returns: String,
4851    /// `LANGUAGE` clause, lowercased. `"plpgsql"` / `"sql"`.
4852    pub language: String,
4853    /// Source body of the function. PL/pgSQL: includes the
4854    /// surrounding `BEGIN ... END;`. SQL: includes the
4855    /// statement(s). The engine re-parses on invocation; bad
4856    /// bodies surface as a parse error at CALL time, not CREATE.
4857    pub body: String,
4858    /// v7.39 (read01 round 61) — the role that ran CREATE FUNCTION.
4859    pub owner: Option<String>,
4860    /// v7.39 (read01 round 61) — explicit GRANTs (PG `pg_proc.proacl`). EMPTY
4861    /// is NOT "nobody may call it": PG grants EXECUTE to PUBLIC by default, and
4862    /// leaves proacl NULL to say so. The list materialises on the first
4863    /// GRANT / REVOKE.
4864    pub acl: Vec<AclItem>,
4865    /// v7.39 (round 322, V46) — `IMMUTABLE` / `STRICT` / `PARALLEL SAFE` /
4866    /// `SECURITY DEFINER` / `LEAKPROOF` / `COST` / `ROWS`. `strict` is the
4867    /// only one with execution semantics today (a NULL argument yields a
4868    /// NULL result without running the body); the rest are recorded so
4869    /// `pg_get_functiondef` and `pg_proc` report what was declared.
4870    pub volatility: u8,
4871    pub strict: bool,
4872    pub security_definer: bool,
4873    pub leakproof: bool,
4874    pub parallel: u8,
4875    pub cost: Option<f64>,
4876    pub rows: Option<f64>,
4877}
4878
4879/// v7.39 (round 322, V46) — `FunctionDef.volatility` codes: PG's
4880/// `pg_proc.provolatile` letters.
4881pub const FN_VOLATILE: u8 = b'v';
4882pub const FN_IMMUTABLE: u8 = b'i';
4883pub const FN_STABLE: u8 = b's';
4884
4885/// v7.39 (round 322, V46) — `FunctionDef.parallel` codes: PG's
4886/// `pg_proc.proparallel` letters.
4887pub const FN_PARALLEL_UNSAFE: u8 = b'u';
4888pub const FN_PARALLEL_RESTRICTED: u8 = b'r';
4889pub const FN_PARALLEL_SAFE: u8 = b's';
4890
4891/// v7.39 (round 315, V19) — which catalogued function does a persisted
4892/// ACL key refer to?
4893///
4894/// The key was computed by whichever formula was current when the image
4895/// was written, and the multi-word fix changed that formula for bare
4896/// types like `double precision`. A miss therefore does NOT mean "no
4897/// such function": an older image's key would land nowhere and its owner
4898/// and grants would be dropped in silence. Exact match first, then the
4899/// pre-fix formula.
4900#[must_use]
4901pub fn resolve_stored_function_key(
4902    functions: &BTreeMap<String, FunctionDef>,
4903    stored: &str,
4904) -> Option<String> {
4905    if functions.contains_key(stored) {
4906        return Some(stored.to_string());
4907    }
4908    functions
4909        .values()
4910        .find(|f| function_signature_key_legacy(&f.name, &f.args_repr) == stored)
4911        .map(|f| function_signature_key(&f.name, &f.args_repr))
4912}
4913
4914/// v7.39 (round 344, V49) — re-exported from [`spg_sql`], which owns the
4915/// SQL type spellings. This crate carried a byte-identical copy because
4916/// the two were siblings that did not depend on each other; spg-sql is a
4917/// dependency-free leaf, so the dependency is acyclic and the publish
4918/// order already puts it first. One list, one place to keep it right.
4919pub use spg_sql::parser::is_multiword_type_phrase;
4920
4921/// v7.39 (round 315, V19) — the signature key as computed BEFORE the
4922/// multi-word fix, used only to recognise what an older image wrote.
4923///
4924/// The function catalogue recomputes its keys from the stored name and
4925/// argument text on load, so it needs no migration. The ACL block does
4926/// not: it persists the computed key as a string and matches on it. A
4927/// key that changed shape would simply fail to match, and the owner and
4928/// grants would be dropped without a word — so the loader falls back to
4929/// this when the stored key finds nothing.
4930#[must_use]
4931pub fn function_signature_key_legacy(name: &str, args_repr: &str) -> String {
4932    let inner = args_repr
4933        .trim()
4934        .trim_start_matches('(')
4935        .trim_end_matches(')');
4936    let types: Vec<String> = if inner.trim().is_empty() {
4937        Vec::new()
4938    } else {
4939        inner
4940            .split(',')
4941            .map(|part| {
4942                let mut words: Vec<&str> = part.split_whitespace().collect();
4943                if !words.is_empty()
4944                    && (words[0].eq_ignore_ascii_case("OUT")
4945                        || words[0].eq_ignore_ascii_case("INOUT"))
4946                {
4947                    words.remove(0);
4948                }
4949                let ty = if words.len() >= 2 {
4950                    words[1..].join(" ")
4951                } else {
4952                    words.first().map_or(String::new(), |w| (*w).to_string())
4953                };
4954                normalize_type_name(&ty)
4955            })
4956            .collect()
4957    };
4958    format!("{}({})", name.to_ascii_lowercase(), types.join(","))
4959}
4960
4961pub fn function_signature_key(name: &str, args_repr: &str) -> String {
4962    let types = function_arg_types(args_repr);
4963    format!("{}({})", name.to_ascii_lowercase(), types.join(","))
4964}
4965
4966/// The declared argument TYPES of a function, out of its `args_repr`
4967/// (`"(x INT, y DOUBLE PRECISION)"` → `["int", "float"]`). An entry may be a
4968/// bare type with no name (`"(INT)"`).
4969#[must_use]
4970pub fn function_arg_types(args_repr: &str) -> Vec<String> {
4971    let inner = args_repr
4972        .trim()
4973        .trim_start_matches('(')
4974        .trim_end_matches(')');
4975    if inner.trim().is_empty() {
4976        return Vec::new();
4977    }
4978    inner
4979        .split(',')
4980        .map(|part| {
4981            let mut words: Vec<&str> = part.split_whitespace().collect();
4982            // `OUT x INT` / `INOUT x INT` — the mode is not part of the type.
4983            if !words.is_empty()
4984                && (words[0].eq_ignore_ascii_case("OUT") || words[0].eq_ignore_ascii_case("INOUT"))
4985            {
4986                words.remove(0);
4987            }
4988            // v7.39 (round 315, V19) — two or more words is USUALLY
4989            // `name TYPE`, but not when the type itself is spelled in
4990            // several words. `double precision` was read as a parameter
4991            // named "double" of type "precision", so it keyed differently
4992            // from `x double precision` — the same signature written two
4993            // ways did not resolve to the same function. Decide by asking
4994            // whether the whole phrase names a type first; only then is
4995            // the leading word a parameter name.
4996            let whole = words.join(" ");
4997            let ty = if words.len() >= 2 && !is_multiword_type_phrase(&whole) {
4998                words[1..].join(" ")
4999            } else {
5000                whole
5001            };
5002            normalize_type_name(&ty)
5003        })
5004        .collect()
5005}
5006
5007/// v7.39 (read01 round 65) — the declared argument NAMES of a function (`""` for
5008/// a bare type with no name).
5009#[must_use]
5010pub fn function_arg_names(args_repr: &str) -> Vec<String> {
5011    let inner = args_repr
5012        .trim()
5013        .trim_start_matches('(')
5014        .trim_end_matches(')');
5015    if inner.trim().is_empty() {
5016        return Vec::new();
5017    }
5018    inner
5019        .split(',')
5020        .map(|part| {
5021            let mut words: Vec<&str> = part.split_whitespace().collect();
5022            if !words.is_empty()
5023                && (words[0].eq_ignore_ascii_case("OUT") || words[0].eq_ignore_ascii_case("INOUT"))
5024            {
5025                words.remove(0);
5026            }
5027            if words.len() >= 2 {
5028                words[0].to_string()
5029            } else {
5030                String::new()
5031            }
5032        })
5033        .collect()
5034}
5035
5036/// Fold PG's type aliases so a signature key is stable across spellings.
5037/// Unknown names pass through lower-cased — consistency is what the key needs.
5038#[must_use]
5039pub fn normalize_type_name(ty: &str) -> String {
5040    let t = ty.trim().to_ascii_lowercase();
5041    // Peel a precision/length modifier: `numeric(10,2)`, `varchar(64)`.
5042    let base = t.split_once('(').map_or(t.as_str(), |(h, _)| h).trim();
5043    match base {
5044        "int" | "int4" | "integer" => "int",
5045        "bigint" | "int8" => "bigint",
5046        "smallint" | "int2" => "smallint",
5047        "text" | "varchar" | "character varying" | "char" | "character" | "bpchar" => "text",
5048        "bool" | "boolean" => "bool",
5049        "float" | "float8" | "double precision" => "float",
5050        "real" | "float4" => "real",
5051        "numeric" | "decimal" => "numeric",
5052        "timestamptz" | "timestamp with time zone" => "timestamptz",
5053        "timestamp" | "timestamp without time zone" => "timestamp",
5054        other => other,
5055    }
5056    .to_string()
5057}
5058
5059/// v7.12.4 — catalogued trigger. References its function by
5060/// name; the function must exist at TRIGGER creation time
5061/// (forward references are deferred to v7.12.5+).
5062#[derive(Debug, Clone, PartialEq, Eq)]
5063pub struct TriggerDef {
5064    pub name: String,
5065    /// Watched table. Trigger is dropped when the table drops.
5066    pub table: String,
5067    /// `"BEFORE"` / `"AFTER"` / `"INSTEAD OF"`. Stored as the
5068    /// uppercased keyword so deserialised catalogs round-trip
5069    /// without canonicalisation surprises.
5070    pub timing: String,
5071    /// Each entry is one of `"INSERT"` / `"UPDATE"` / `"DELETE"`
5072    /// / `"TRUNCATE"`. `INSERT OR UPDATE` parses to two entries.
5073    pub events: Vec<String>,
5074    /// `"ROW"` / `"STATEMENT"`. v7.12.4 ships `"ROW"` only;
5075    /// `"STATEMENT"` parses and persists but the executor
5076    /// refuses it at trigger fire time.
5077    pub for_each: String,
5078    /// Name of the PL/pgSQL function to invoke.
5079    pub function: String,
5080    /// v7.13.0 — `UPDATE OF col, col, …` column-list filter
5081    /// (mailrs round-5 G7). Non-empty means the trigger fires
5082    /// only when at least one of these columns appears in the
5083    /// UPDATE's SET list. Empty = no column filter. Stored in
5084    /// catalog FILE_VERSION 23+; older catalogs deserialise with
5085    /// an empty vec.
5086    pub update_columns: Vec<String>,
5087    /// v7.16.1 — whether the trigger fires when its watched
5088    /// event occurs. Toggled by `ALTER TABLE … { ENABLE |
5089    /// DISABLE } TRIGGER …`; pg_dump --disable-triggers wraps
5090    /// every data block with a DISABLE/ENABLE pair so the
5091    /// rows already-computed in prod don't get re-rewritten.
5092    /// Defaults to `true` at CREATE TRIGGER time. Stored in
5093    /// catalog FILE_VERSION 25+; older catalogs deserialise
5094    /// with `enabled = true`.
5095    pub enabled: bool,
5096    /// v7.39 (round 138) — the deparsed `WHEN ( condition )` predicate text
5097    /// (re-parsed at fire time to filter row triggers). Empty = no WHEN.
5098    /// Persisted from FILE_VERSION 70; older catalogs read back empty.
5099    pub when_condition: String,
5100}
5101
5102/// v7.39 (round 280) — one `CREATE STATISTICS` object.
5103#[derive(Debug, Clone, PartialEq, Eq)]
5104pub struct StatisticsExtDef {
5105    pub name: String,
5106    pub table: String,
5107    /// PG's single-letter kinds: `d` ndistinct, `f` dependencies,
5108    /// `m` mcv. PG's default set is all three.
5109    pub kinds: Vec<String>,
5110    pub columns: Vec<String>,
5111}
5112
5113/// v7.39 (round 139) — a catalogued query-rewrite RULE. Stored flat like
5114/// `TriggerDef`, keyed by `(name, table)`. Command / WHEN text is deparsed SQL
5115/// re-parsed at rewrite time (the same round-trip trick as
5116/// `TriggerDef.when_condition`). Persisted from FILE_VERSION 71.
5117#[derive(Debug, Clone, PartialEq, Eq)]
5118pub struct RuleDef {
5119    pub name: String,
5120    pub table: String,
5121    /// Event keyword, uppercased: `INSERT` / `UPDATE` / `DELETE` / `SELECT`.
5122    pub event: String,
5123    /// `true` = `DO INSTEAD`, `false` = `DO ALSO`.
5124    pub instead: bool,
5125    /// Deparsed `WHERE` predicate text; empty = unconditional.
5126    pub when_condition: String,
5127    /// Deparsed DO command statements; empty = `NOTHING`.
5128    pub commands: Vec<String>,
5129}
5130
5131/// v7.17.0 — catalogued SEQUENCE. PG semantics: a counter object
5132/// returning monotonically increasing values via `nextval(name)`.
5133/// `last_value` is the most recent value handed out; `is_called`
5134/// is false until the first `nextval`/`setval`. Stored separately
5135/// from tables in the catalog.
5136#[derive(Debug, Clone, PartialEq, Eq)]
5137pub struct SequenceDef {
5138    pub name: String,
5139    /// Data type — narrows the i64 range. PG default BIGINT.
5140    pub data_type: SequenceDataType,
5141    pub start: i64,
5142    pub increment: i64,
5143    pub min_value: i64,
5144    pub max_value: i64,
5145    pub cache: i64,
5146    pub cycle: bool,
5147    /// `OWNED BY` target — `(table, column)` or NONE.
5148    pub owned_by: Option<(String, String)>,
5149    /// Most recently handed-out value. Meaningless when
5150    /// `is_called == false`; in that case the NEXT `nextval`
5151    /// will return `start`.
5152    pub last_value: i64,
5153    pub is_called: bool,
5154    /// v7.39 (read01 round 60) — the role that ran CREATE SEQUENCE. `None` = an
5155    /// image written before FILE_VERSION 66, which predates sequence owners.
5156    pub owner: Option<String>,
5157    /// v7.39 (read01 round 60) — explicit GRANTs on this sequence. A sequence's
5158    /// meaningful privileges are SELECT (`currval`), UPDATE (`setval`) and
5159    /// USAGE (`nextval`).
5160    pub acl: Vec<AclItem>,
5161}
5162
5163/// v7.17.0 — sequence integer width.
5164#[derive(Debug, Clone, Copy, PartialEq, Eq)]
5165pub enum SequenceDataType {
5166    SmallInt,
5167    Int,
5168    BigInt,
5169}
5170
5171/// v7.17.0 Phase 1.6 — built-in schema names that every Catalog
5172/// understands without an explicit CREATE SCHEMA. Used by
5173/// [`Catalog::schema_exists`] and the engine's schema-qualified
5174/// lookup path.
5175#[must_use]
5176pub fn is_builtin_schema(name: &str) -> bool {
5177    name.eq_ignore_ascii_case("public")
5178        || name.eq_ignore_ascii_case("pg_catalog")
5179        || name.eq_ignore_ascii_case("information_schema")
5180}
5181
5182/// v7.17.0 — parse a PG-canonical UUID text representation into the
5183/// 16-byte network-order layout used by `Value::Uuid`. Accepted input
5184/// shapes (all case-insensitive):
5185///   * Canonical hyphenated 8-4-4-4-12 (`550e8400-e29b-41d4-a716-446655440000`)
5186///   * Unhyphenated 32-char hex (`550e8400e29b41d4a716446655440000`)
5187///   * Either form wrapped in `{ ... }`
5188///
5189/// Returns `None` for any malformed input (wrong length, non-hex
5190/// characters, misplaced hyphens). The caller surfaces a SQL error
5191/// at coercion time — silent acceptance of garbage would mask
5192/// application bugs and is exactly the divergence from PG that
5193/// breaks the 0-change cutover promise.
5194#[must_use]
5195pub fn parse_uuid_str(input: &str) -> Option<[u8; 16]> {
5196    let s = input.trim();
5197    // Strip surrounding braces if present.
5198    let s = if let Some(inner) = s.strip_prefix('{').and_then(|x| x.strip_suffix('}')) {
5199        inner
5200    } else {
5201        s
5202    };
5203    // Two valid shapes after braces are stripped: 32 hex chars or
5204    // the canonical 36-char hyphenated form.
5205    let hex: String = match s.len() {
5206        32 => s.to_ascii_lowercase(),
5207        36 => {
5208            // Hyphens must be exactly at positions 8, 13, 18, 23.
5209            let b = s.as_bytes();
5210            if b[8] != b'-' || b[13] != b'-' || b[18] != b'-' || b[23] != b'-' {
5211                return None;
5212            }
5213            let mut out = String::with_capacity(32);
5214            out.push_str(&s[0..8]);
5215            out.push_str(&s[9..13]);
5216            out.push_str(&s[14..18]);
5217            out.push_str(&s[19..23]);
5218            out.push_str(&s[24..36]);
5219            out.make_ascii_lowercase();
5220            out
5221        }
5222        _ => return None,
5223    };
5224    let bytes = hex.as_bytes();
5225    let mut out = [0u8; 16];
5226    for i in 0..16 {
5227        let hi = hex_nibble(bytes[i * 2])?;
5228        let lo = hex_nibble(bytes[i * 2 + 1])?;
5229        out[i] = (hi << 4) | lo;
5230    }
5231    Some(out)
5232}
5233
5234fn hex_nibble(b: u8) -> Option<u8> {
5235    match b {
5236        b'0'..=b'9' => Some(b - b'0'),
5237        b'a'..=b'f' => Some(10 + b - b'a'),
5238        b'A'..=b'F' => Some(10 + b - b'A'),
5239        _ => None,
5240    }
5241}
5242
5243/// v7.17.0 — render a `Value::Uuid` payload as the canonical
5244/// lowercase 8-4-4-4-12 hyphenated form PG `text` cast surfaces.
5245#[must_use]
5246pub fn format_uuid(b: &[u8; 16]) -> String {
5247    const HEX: &[u8; 16] = b"0123456789abcdef";
5248    let mut out = String::with_capacity(36);
5249    for (i, byte) in b.iter().enumerate() {
5250        if matches!(i, 4 | 6 | 8 | 10) {
5251            out.push('-');
5252        }
5253        out.push(HEX[(byte >> 4) as usize] as char);
5254        out.push(HEX[(byte & 0x0f) as usize] as char);
5255    }
5256    out
5257}
5258
5259/// v7.17.0 Phase 1.5 — catalogued user-defined DOMAIN. A domain
5260/// is a named CHECK-constrained alias over a built-in type;
5261/// columns bound to it inherit the base type plus the CHECK
5262/// predicates + NOT NULL + DEFAULT at INSERT/UPDATE time.
5263/// v7.37.17 (Phase E RC rebase) — the write-set one writer version left
5264/// on a table, addressed by stable [`row_header::RowId`]s so it can be
5265/// replayed onto a fresher clone of the relation whose physical slots
5266/// differ. Produced by [`Table::extract_tx_writeset`], consumed by
5267/// [`Table::replay_tx_writeset`].
5268#[derive(Debug, Clone, Default)]
5269pub struct TxWriteSet {
5270    /// INSERTs and UPDATE-new-versions (`header.xmin == v`).
5271    pub inserted: Vec<(row_header::RowId, Row<'static>)>,
5272    /// DELETE / UPDATE-old-version targets (`header.xmax == v`).
5273    pub tombstoned: Vec<row_header::RowId>,
5274}
5275
5276impl TxWriteSet {
5277    #[must_use]
5278    pub fn is_empty(&self) -> bool {
5279        self.inserted.is_empty() && self.tombstoned.is_empty()
5280    }
5281}
5282
5283/// v7.39 (round 260) — one named CHECK on a domain. PG auto-names an
5284/// unnamed one `<domain>_check`, then `_check1`, `_check2`, … (probed).
5285#[derive(Debug, Clone, PartialEq, Eq)]
5286pub struct DomainCheck {
5287    pub name: String,
5288    /// The predicate source, referencing the pseudo-column `VALUE`.
5289    pub expr: String,
5290}
5291
5292/// `default` / `checks` are stored as Display-form source so
5293/// `spg-storage` stays free of `spg-sql` dependency — same
5294/// pattern as FunctionDef / ViewDef.
5295#[derive(Debug, Clone, PartialEq, Eq)]
5296pub struct DomainDef {
5297    pub name: String,
5298    pub base_type: DataType,
5299    pub nullable: bool,
5300    pub default: Option<String>,
5301    /// v7.39 (round 260) — each CHECK carries its constraint NAME, so
5302    /// `ALTER DOMAIN … DROP CONSTRAINT <name>` can find it and the
5303    /// violation message can report the constraint that actually failed.
5304    /// PG's auto-naming for an unnamed check is `<domain>_check`, then
5305    /// `_check1`, `_check2`, … (probed).
5306    pub checks: Vec<DomainCheck>,
5307    /// v7.39 (round 258/259) — when this domain was declared over ANOTHER
5308    /// domain (`CREATE DOMAIN child AS parent CHECK (…)`), the parent's
5309    /// name. `base_type` is the ultimate scalar type either way, so
5310    /// without this the parent's constraints were invisible and a value
5311    /// violating them was silently accepted. PG checks the whole chain,
5312    /// base-first, and an `ALTER DOMAIN` on the parent takes effect for
5313    /// the child immediately (probed) — so the chain is walked at check
5314    /// time rather than copied at CREATE time. Catalog FILE_VERSION 74+.
5315    pub base_domain: Option<String>,
5316}
5317
5318/// v7.17.0 Phase 1.4 — catalogued user-defined ENUM type. The
5319/// label vector is order-preserving (PG enum ordering follows the
5320/// declared order). At INSERT/UPDATE on a column bound to this
5321/// enum, the engine looks up the value against `labels` and
5322/// rejects non-members.
5323#[derive(Debug, Clone, PartialEq, Eq)]
5324pub struct EnumDef {
5325    pub name: String,
5326    pub labels: Vec<String>,
5327}
5328
5329/// v7.37.42-T2 ζ-B — catalogued user-defined COMPOSITE type
5330/// (`CREATE TYPE name AS (field_name field_type, ...)`). Order
5331/// matters: PG composite literals are positional, and SPG mirrors
5332/// that. Stored as ordered `(name, DataType)` pairs to keep the
5333/// codec straightforward and to allow eventual `Value::Composite`
5334/// bodies to encode positionally. Persisted in catalog FILE_VERSION
5335/// 52+; older catalogs deserialise with an empty composite_types
5336/// map. Composite types can be used as a column type by spelling
5337/// the composite's name; the resolution from
5338/// `ColumnSchema.user_composite_type = Some(name)` happens at the
5339/// engine boundary (parallel to `user_enum_type` /
5340/// `user_domain_type`). The dense storage shape — JSON-text body
5341/// keyed by the composite's field list — keeps the codec free of
5342/// recursive `Value` bodies until the full Value::Composite arena
5343/// migration in a later phase.
5344#[derive(Debug, Clone, PartialEq, Eq)]
5345pub struct CompositeDef {
5346    pub name: String,
5347    /// Ordered `(field_name, field_type)` pairs. PG composite
5348    /// literals are positional, so order is part of the type's
5349    /// identity.
5350    pub fields: Vec<(String, DataType)>,
5351    /// v7.39 (round 264) — parallel to `fields`: the USER type name of
5352    /// each field when it is itself a composite (or another named user
5353    /// type). `DataType` has no room for one, so a nested composite
5354    /// field resolved to the parser's Text placeholder and the inner
5355    /// record stayed TEXT — `(x).inner.street` errored, `pg_typeof`
5356    /// said text, and `row_to_json` nested a string instead of an
5357    /// object. Same shape as `ColumnSchema.user_composite_type` and
5358    /// `DomainDef.base_domain`. Catalog FILE_VERSION 76+; an older
5359    /// catalog reads all-None, which is what it meant.
5360    pub field_user_types: Vec<Option<String>>,
5361}
5362
5363/// v7.17.0 Phase 1.2 — catalogued VIEW. The body is stored as the
5364/// raw source text the parser saw between `AS` and the statement
5365/// terminator; the engine re-parses on each invocation. Same
5366/// pattern as `FunctionDef` — keeps `spg-storage` free of
5367/// `spg-sql` dependency.
5368#[derive(Debug, Clone, PartialEq, Eq)]
5369pub struct ViewDef {
5370    pub name: String,
5371    /// Optional `(col, col, …)` rename list. Empty when the body's
5372    /// projected names are used directly.
5373    pub columns: Vec<String>,
5374    /// Raw SELECT source. Display-rendered at storage time so the
5375    /// catalog round-trips a deterministic form regardless of
5376    /// whitespace / comments in the original input. Re-parsed at
5377    /// SELECT-from-view time to materialise as a synthetic CTE.
5378    pub body: String,
5379    /// v7.39 (round 132) — `WITH CHECK OPTION`: 0 = none, 1 = LOCAL,
5380    /// 2 = CASCADED. A storage-local u8 (no dependency on the SQL AST).
5381    /// Persisted from FILE_VERSION 69; older catalogs read back as 0.
5382    pub check_option: u8,
5383}
5384
5385impl SequenceDataType {
5386    /// PG default min/max per AS clause.
5387    pub fn default_bounds(self, increment_positive: bool) -> (i64, i64) {
5388        match self {
5389            Self::SmallInt => {
5390                if increment_positive {
5391                    (1, i64::from(i16::MAX))
5392                } else {
5393                    (i64::from(i16::MIN), -1)
5394                }
5395            }
5396            Self::Int => {
5397                if increment_positive {
5398                    (1, i64::from(i32::MAX))
5399                } else {
5400                    (i64::from(i32::MIN), -1)
5401                }
5402            }
5403            Self::BigInt => {
5404                if increment_positive {
5405                    (1, i64::MAX)
5406                } else {
5407                    (i64::MIN, -1)
5408                }
5409            }
5410        }
5411    }
5412}
5413
5414impl Catalog {
5415    /// v7.37.15 (Phase D) — fleet-wide vacuum pass. Walks every
5416    /// user table and reclaims rows whose delete-commit version is
5417    /// older than `oldest_active_snapshot`. Returns an aggregated
5418    /// report with per-table breakdown so hosts can emit metrics.
5419    ///
5420    /// `dry_run = true` reports the work without doing it. Use it
5421    /// to estimate the cost before scheduling a real pass.
5422    pub fn vacuum_all(
5423        &mut self,
5424        oldest_active_snapshot: u64,
5425        dry_run: bool,
5426    ) -> vacuum::VacuumReport {
5427        let mut total = vacuum::VacuumReport::default();
5428        // Snapshot the table names so we don't hold an immutable
5429        // borrow during the get_mut loop.
5430        let names: Vec<String> = self
5431            .tables
5432            .iter()
5433            .map(|t| t.schema().name.clone())
5434            .collect();
5435        for name in names {
5436            let Some(t) = self.get_mut(&name) else {
5437                continue;
5438            };
5439            let r = t.vacuum(oldest_active_snapshot, dry_run);
5440            if r.rows_reclaimed > 0 {
5441                total.per_table.push((name, r.rows_reclaimed));
5442            }
5443            total.rows_reclaimed += r.rows_reclaimed;
5444            total.rows_examined += r.rows_examined;
5445        }
5446        total
5447    }
5448
5449    pub const fn new() -> Self {
5450        Self {
5451            cold_read_stats: ColdReadStats {
5452                cold_reads: core::sync::atomic::AtomicU64::new(0),
5453            },
5454            tables: Vec::new(),
5455            by_name: BTreeMap::new(),
5456            temp_prefix: None,
5457            dirty_tables: alloc::collections::BTreeSet::new(),
5458            dirty_nontable: alloc::collections::BTreeSet::new(),
5459            next_rel_id: 0,
5460            cold_segments: Vec::new(),
5461            functions: BTreeMap::new(),
5462            triggers: Vec::new(),
5463            rules: Vec::new(),
5464            statistics_ext: Vec::new(),
5465            large_objects: alloc::collections::BTreeMap::new(),
5466            sequences: BTreeMap::new(),
5467            schema_acl: Vec::new(),
5468            database_acl: Vec::new(),
5469            views: BTreeMap::new(),
5470            materialized_views: BTreeMap::new(),
5471            enum_types: BTreeMap::new(),
5472            domain_types: BTreeMap::new(),
5473            comments: BTreeMap::new(),
5474            db_role_settings: BTreeMap::new(),
5475            replication_slots: BTreeMap::new(),
5476            composite_types: BTreeMap::new(),
5477            schemas: alloc::collections::BTreeSet::new(),
5478        }
5479    }
5480
5481    /// v7.12.4 — read-only view of catalogued user-defined
5482    /// functions. Engine callers go through here to look up the
5483    /// function body before re-parsing it for invocation.
5484    pub const fn functions(&self) -> &BTreeMap<String, FunctionDef> {
5485        &self.functions
5486    }
5487
5488    /// v7.12.4 — register a new user-defined function. With
5489    /// `or_replace = false`, errors if the name is taken. The
5490    /// engine validates the body before passing it here.
5491    pub fn create_function(
5492        &mut self,
5493        def: FunctionDef,
5494        or_replace: bool,
5495    ) -> Result<(), StorageError> {
5496        // v7.39 (read01 round 62) — functions are keyed by SIGNATURE, not by
5497        // name: `f(int)` and `f(text)` are two functions, as in PG. Keying by
5498        // name alone made a second overload an "already exists" error — so a
5499        // pg_dump carrying an overload set could not restore — and, worse, a
5500        // call to one overload silently ran the other.
5501        let key = function_signature_key(&def.name, &def.args_repr);
5502        if !or_replace && self.functions.contains_key(&key) {
5503            return Err(StorageError::Corrupt(format!(
5504                "function {:?} already exists (drop or use CREATE OR REPLACE)",
5505                def.name
5506            )));
5507        }
5508        self.functions.insert(key, def);
5509        Ok(())
5510    }
5511
5512    /// v7.39 (read01 round 62) — every overload of `name`.
5513    #[must_use]
5514    pub fn functions_named(&self, name: &str) -> Vec<&FunctionDef> {
5515        self.functions
5516            .values()
5517            .filter(|f| f.name.eq_ignore_ascii_case(name))
5518            .collect()
5519    }
5520
5521    /// v7.39 (read01 round 62) — one overload, by its signature key.
5522    #[must_use]
5523    pub fn function_by_key(&self, key: &str) -> Option<&FunctionDef> {
5524        self.functions.get(key)
5525    }
5526
5527    /// v7.39 (read01 round 62) — drop ONE overload. `true` if it was there.
5528    pub fn drop_function_by_key(&mut self, key: &str) -> bool {
5529        self.functions.remove(key).is_some()
5530    }
5531
5532    /// v7.12.4 — remove a user-defined function by name. Returns
5533    /// `true` if a function was removed, `false` if none matched.
5534    /// Caller decides whether to surface `if_exists` semantics.
5535    /// v7.39 (read01 round 62) — with no signature, PG drops the function only
5536    /// when the name is unambiguous. SPG mirrors that: this removes EVERY
5537    /// overload of `name`, and the caller (ddl.rs) refuses the ambiguous case
5538    /// before getting here.
5539    pub fn drop_function(&mut self, name: &str) -> bool {
5540        let keys: Vec<String> = self
5541            .functions
5542            .iter()
5543            .filter(|(_, f)| f.name.eq_ignore_ascii_case(name))
5544            .map(|(k, _)| k.clone())
5545            .collect();
5546        let hit = !keys.is_empty();
5547        for k in keys {
5548            self.functions.remove(&k);
5549        }
5550        hit
5551    }
5552
5553    /// v7.17.0 — read-only handle to catalogued sequences.
5554    /// v7.39 (read01 round 60) — the `public` schema's ACL (PG nspacl).
5555    #[must_use]
5556    pub fn schema_acl(&self) -> &[AclItem] {
5557        &self.schema_acl
5558    }
5559
5560    pub fn schema_acl_mut(&mut self) -> &mut Vec<AclItem> {
5561        &mut self.schema_acl
5562    }
5563
5564    /// v7.39 (read01 round 60) — the database's ACL.
5565    #[must_use]
5566    pub fn database_acl(&self) -> &[AclItem] {
5567        &self.database_acl
5568    }
5569
5570    pub fn database_acl_mut(&mut self) -> &mut Vec<AclItem> {
5571        &mut self.database_acl
5572    }
5573
5574    /// v7.39 (read01 round 60) — mutable sequence access, for GRANT.
5575    /// v7.39 (round 469) — resolves the session's temporary sequence
5576    /// first, like its read-only twin. `nextval` and `setval` reach the
5577    /// map through here, so a temporary sequence shadowing a permanent one
5578    /// advances the temporary one — measured against PG18, where the
5579    /// permanent sequence's counter is untouched while the temp exists.
5580    pub fn sequence_mut(&mut self, name: &str) -> Option<&mut SequenceDef> {
5581        let key = self.sequence_key(name);
5582        self.sequences.get_mut(&key)
5583    }
5584
5585    /// v7.39 (read01 round 61) — mutable function access, for GRANT.
5586    pub fn function_mut(&mut self, name: &str) -> Option<&mut FunctionDef> {
5587        self.functions.get_mut(name)
5588    }
5589
5590    /// Every catalogued sequence, temp ones included under their mangled
5591    /// storage names. Listing code filters these through
5592    /// [`Self::listed_name`]; anything resolving ONE name by its logical
5593    /// spelling wants [`Self::sequence`] instead.
5594    pub const fn sequences_all(&self) -> &BTreeMap<String, SequenceDef> {
5595        &self.sequences
5596    }
5597
5598    /// v7.39 (round 469) — resolve one sequence by its logical name, the
5599    /// session's temporary one winning over a permanent one of the same
5600    /// name. The same rule [`Self::resolve_index`] applies to tables.
5601    #[must_use]
5602    pub fn sequence(&self, name: &str) -> Option<&SequenceDef> {
5603        if let Some(mangled) = self.temp_name_for(name)
5604            && let Some(def) = self.sequences.get(&mangled)
5605        {
5606            return Some(def);
5607        }
5608        self.sequences.get(name)
5609    }
5610
5611    /// Does a sequence of this logical name exist for this session?
5612    #[must_use]
5613    pub fn has_sequence(&self, name: &str) -> bool {
5614        self.sequence(name).is_some()
5615    }
5616
5617    /// The storage key a sequence of this logical name resolves to — the
5618    /// session's temp mangling when it has one, else the name itself.
5619    #[must_use]
5620    pub fn sequence_key(&self, name: &str) -> String {
5621        if let Some(mangled) = self.temp_name_for(name)
5622            && self.sequences.contains_key(&mangled)
5623        {
5624            return mangled;
5625        }
5626        name.into()
5627    }
5628
5629    /// v7.17.0 — register a new SEQUENCE. Errors if `name`
5630    /// collides with an existing sequence and `if_not_exists`
5631    /// is false.
5632    pub fn create_sequence(
5633        &mut self,
5634        def: SequenceDef,
5635        if_not_exists: bool,
5636    ) -> Result<(), StorageError> {
5637        if self.sequences.contains_key(&def.name) {
5638            if if_not_exists {
5639                return Ok(());
5640            }
5641            // v7.39 (read01 round 47) — a sequence is a relation to PG (42P07).
5642            return Err(StorageError::Corrupt(format!(
5643                "relation {:?} already exists",
5644                def.name
5645            )));
5646        }
5647        self.mark_nontable_dirty(NonTableKind::Sequence, &def.name);
5648        self.sequences.insert(def.name.clone(), def);
5649        Ok(())
5650    }
5651
5652    /// v7.17.0 — remove a SEQUENCE by name. Returns `true` if a
5653    /// sequence was removed, `false` if none matched. Caller
5654    /// surfaces IF EXISTS semantics.
5655    /// v7.39 (read01 round 49) — `ALTER SEQUENCE old RENAME TO new`.
5656    /// Errors when `old` is missing or `new` is taken; the SequenceDef's own
5657    /// `name` field is rewritten so it stays self-describing.
5658    pub fn rename_sequence(&mut self, old: &str, new: &str) -> Result<(), StorageError> {
5659        if !self.sequences.contains_key(old) {
5660            return Err(StorageError::Corrupt(format!(
5661                "relation {old:?} does not exist"
5662            )));
5663        }
5664        if self.sequences.contains_key(new) {
5665            return Err(StorageError::Corrupt(format!(
5666                "relation {new:?} already exists"
5667            )));
5668        }
5669        self.mark_nontable_dirty(NonTableKind::Sequence, old);
5670        self.mark_nontable_dirty(NonTableKind::Sequence, new);
5671        if let Some(mut def) = self.sequences.remove(old) {
5672            def.name = new.to_string();
5673            self.sequences.insert(new.to_string(), def);
5674        }
5675        Ok(())
5676    }
5677
5678    pub fn drop_sequence(&mut self, name: &str) -> bool {
5679        self.mark_nontable_dirty(NonTableKind::Sequence, name);
5680        self.sequences.remove(name).is_some()
5681    }
5682
5683    /// v7.17.0 — atomic nextval. Increments `last_value` per
5684    /// `increment`, returns the new value, sets `is_called`.
5685    /// Returns an error on CYCLE-less overflow.
5686    /// v7.39 (round 497) — the counter state of every sequence, for
5687    /// carrying across a commit install.
5688    ///
5689    /// A sequence's VALUE is not transactional in PG: `nextval` advances
5690    /// shared state that a rollback does not give back, because two
5691    /// sessions must never receive the same number. SPG keeps sequences in
5692    /// the catalog, and a transaction works on a catalog CLONE, so
5693    /// installing that clone at COMMIT would restore whatever the counter
5694    /// was at BEGIN. These two let the install put the live counters back.
5695    #[must_use]
5696    pub fn sequence_counters(&self) -> Vec<(String, i64, bool)> {
5697        self.sequences
5698            .iter()
5699            .map(|(k, d)| (k.clone(), d.last_value, d.is_called))
5700            .collect()
5701    }
5702
5703    /// Restore counters saved by [`Self::sequence_counters`], for the
5704    /// sequences that still exist. A sequence the transaction CREATED is
5705    /// absent from the saved set and keeps the value it was given.
5706    pub fn restore_sequence_counters(&mut self, saved: &[(String, i64, bool)]) {
5707        for (k, last, called) in saved {
5708            if let Some(d) = self.sequences.get_mut(k) {
5709                d.last_value = *last;
5710                d.is_called = *called;
5711            }
5712        }
5713    }
5714
5715    pub fn sequence_next_value(&mut self, name: &str) -> Result<i64, StorageError> {
5716        let key = self.sequence_key(name);
5717        let Some(seq) = self.sequences.get_mut(&key) else {
5718            return Err(StorageError::TableNotFound { name: name.into() });
5719        };
5720        // PG semantics: when !is_called (fresh sequence or
5721        // setval(_, false)), the next nextval returns the stored
5722        // `last_value`. When is_called, it advances by `increment`
5723        // and CYCLE-wraps on overflow.
5724        let candidate = if seq.is_called {
5725            let next = seq.last_value.checked_add(seq.increment).ok_or_else(|| {
5726                StorageError::Corrupt(format!("sequence {name:?} arithmetic overflow"))
5727            })?;
5728            if seq.increment > 0 {
5729                if next > seq.max_value {
5730                    if seq.cycle {
5731                        seq.min_value
5732                    } else {
5733                        // v7.39 (round 220) — PG's 2200H wording, not a
5734                        // Corrupt-classed error.
5735                        return Err(StorageError::SequenceExhausted {
5736                            name: name.into(),
5737                            limit: seq.max_value,
5738                            is_max: true,
5739                        });
5740                    }
5741                } else {
5742                    next
5743                }
5744            } else if next < seq.min_value {
5745                if seq.cycle {
5746                    seq.max_value
5747                } else {
5748                    return Err(StorageError::SequenceExhausted {
5749                        name: name.into(),
5750                        limit: seq.min_value,
5751                        is_max: false,
5752                    });
5753                }
5754            } else {
5755                next
5756            }
5757        } else {
5758            seq.last_value
5759        };
5760        seq.last_value = candidate;
5761        seq.is_called = true;
5762        Ok(candidate)
5763    }
5764
5765    /// v7.17.0 — currval. Errors if the session has never called
5766    /// nextval on this sequence (PG semantics). At the catalog
5767    /// level we approximate "session" with "is_called persisted";
5768    /// the engine session-tracking layer can wrap this for the
5769    /// strict per-session semantics later.
5770    pub fn sequence_current_value(&self, name: &str) -> Result<i64, StorageError> {
5771        let Some(seq) = self.sequences.get(name) else {
5772            return Err(StorageError::TableNotFound { name: name.into() });
5773        };
5774        if !seq.is_called {
5775            return Err(StorageError::Corrupt(format!(
5776                "currval of sequence {name:?} is not yet defined in this session"
5777            )));
5778        }
5779        Ok(seq.last_value)
5780    }
5781
5782    /// v7.17.0 — setval(name, value [, is_called]). PG returns
5783    /// `value` regardless. `is_called=true` means the NEXT
5784    /// nextval will return `value + increment`; `is_called=false`
5785    /// means the next nextval will return `value`.
5786    pub fn sequence_set_value(
5787        &mut self,
5788        name: &str,
5789        value: i64,
5790        is_called: bool,
5791    ) -> Result<i64, StorageError> {
5792        let key = self.sequence_key(name);
5793        let Some(seq) = self.sequences.get_mut(&key) else {
5794            return Err(StorageError::TableNotFound { name: name.into() });
5795        };
5796        // v7.39 (round 244) — PG refuses a value outside the sequence's
5797        // range (22003); SPG accepted it silently, leaving last_value out
5798        // of bounds.
5799        if value < seq.min_value || value > seq.max_value {
5800            return Err(StorageError::Unsupported(format!(
5801                "setval: value {value} is out of bounds for sequence \"{name}\" ({}..{})",
5802                seq.min_value, seq.max_value
5803            )));
5804        }
5805        seq.last_value = value;
5806        seq.is_called = is_called;
5807        Ok(value)
5808    }
5809
5810    /// v7.17.0 Phase 1.2 — read-only handle to catalogued views. Temp ones
5811    /// are in here under their mangled storage names; listing code filters
5812    /// through [`Self::listed_name`], and anything resolving ONE name by
5813    /// its logical spelling wants [`Self::view`].
5814    pub const fn views_all(&self) -> &BTreeMap<String, ViewDef> {
5815        &self.views
5816    }
5817
5818    /// v7.39 (round 469) — resolve one view by its logical name, the
5819    /// session's temporary one winning over a permanent one of the same
5820    /// name.
5821    #[must_use]
5822    pub fn view(&self, name: &str) -> Option<&ViewDef> {
5823        if let Some(mangled) = self.temp_name_for(name)
5824            && let Some(def) = self.views.get(&mangled)
5825        {
5826            return Some(def);
5827        }
5828        self.views.get(name)
5829    }
5830
5831    /// Does a view of this logical name exist for this session?
5832    #[must_use]
5833    pub fn has_view(&self, name: &str) -> bool {
5834        self.view(name).is_some()
5835    }
5836
5837    /// The storage key a view of this logical name resolves to.
5838    #[must_use]
5839    pub fn view_key(&self, name: &str) -> String {
5840        if let Some(mangled) = self.temp_name_for(name)
5841            && self.views.contains_key(&mangled)
5842        {
5843            return mangled;
5844        }
5845        name.into()
5846    }
5847
5848    /// v7.17.0 Phase 1.2 — install a VIEW. `or_replace=true`
5849    /// overwrites an existing entry; `if_not_exists=true` is a
5850    /// silent no-op when the name is taken. Errors if both flags
5851    /// are off and the name collides.
5852    pub fn create_view(
5853        &mut self,
5854        def: ViewDef,
5855        or_replace: bool,
5856        if_not_exists: bool,
5857    ) -> Result<(), StorageError> {
5858        if self.views.contains_key(&def.name) {
5859            if or_replace {
5860                self.mark_nontable_dirty(NonTableKind::View, &def.name);
5861                self.mark_nontable_dirty(NonTableKind::View, &def.name);
5862                self.views.insert(def.name.clone(), def);
5863                return Ok(());
5864            }
5865            if if_not_exists {
5866                return Ok(());
5867            }
5868            // v7.39 (read01 round 47) — a view is a relation to PG (42P07).
5869            return Err(StorageError::Corrupt(format!(
5870                "relation {:?} already exists",
5871                def.name
5872            )));
5873        }
5874        // Reject name collision with tables / sequences — same
5875        // namespace per PG.
5876        if self.by_name.contains_key(&def.name) {
5877            return Err(StorageError::Corrupt(format!(
5878                "view {:?} would shadow an existing table",
5879                def.name
5880            )));
5881        }
5882        if self.sequences.contains_key(&def.name) {
5883            return Err(StorageError::Corrupt(format!(
5884                "view {:?} would shadow an existing sequence",
5885                def.name
5886            )));
5887        }
5888        self.views.insert(def.name.clone(), def);
5889        Ok(())
5890    }
5891
5892    /// v7.17.0 Phase 1.2 — remove a view by name. Returns true if
5893    /// a view was removed.
5894    pub fn drop_view(&mut self, name: &str) -> bool {
5895        self.mark_nontable_dirty(NonTableKind::View, name);
5896        self.views.remove(name).is_some()
5897    }
5898
5899    /// v7.17.0 Phase 1.3 — read-only handle to the materialised-
5900    /// view source registry. Each entry pairs with a regular
5901    /// table of the same name that holds the cached rows.
5902    pub const fn materialized_views(&self) -> &BTreeMap<String, String> {
5903        &self.materialized_views
5904    }
5905
5906    /// v7.17.0 Phase 1.3 — register a source for a materialised
5907    /// view. Caller has already created the backing table.
5908    pub fn register_materialized_view(&mut self, name: String, body: String) {
5909        self.mark_nontable_dirty(NonTableKind::MaterializedView, &name);
5910        self.materialized_views.insert(name, body);
5911    }
5912
5913    /// v7.17.0 Phase 1.3 — drop the source registry entry. Returns
5914    /// true if a source was unregistered. Caller separately drops
5915    /// the backing table.
5916    pub fn drop_materialized_view_source(&mut self, name: &str) -> bool {
5917        self.mark_nontable_dirty(NonTableKind::MaterializedView, name);
5918        self.materialized_views.remove(name).is_some()
5919    }
5920
5921    /// v7.17.0 Phase 1.4 — read-only handle to user-defined ENUM
5922    /// catalog.
5923    pub const fn enum_types(&self) -> &BTreeMap<String, EnumDef> {
5924        &self.enum_types
5925    }
5926
5927    /// v7.17.0 Phase 1.4 — install a new ENUM type. Errors if
5928    /// `name` collides with an existing enum (no IF NOT EXISTS
5929    /// per PG semantics for CREATE TYPE).
5930    pub fn create_enum_type(&mut self, def: EnumDef) -> Result<(), StorageError> {
5931        if self.enum_types.contains_key(&def.name) {
5932            return Err(StorageError::Corrupt(format!(
5933                "type {:?} already exists",
5934                def.name
5935            )));
5936        }
5937        self.mark_nontable_dirty(NonTableKind::EnumType, &def.name);
5938        self.enum_types.insert(def.name.clone(), def);
5939        Ok(())
5940    }
5941
5942    /// v7.17.0 Phase 1.4 — drop an ENUM type by name. Returns
5943    /// true if a type was removed.
5944    /// v7.37 D.55 — `ALTER TYPE … ADD VALUE`. Appends `label` to an existing
5945    /// enum's ordered label list, or inserts it before/after an existing label.
5946    /// `if_not_exists` makes a duplicate a no-op; otherwise a duplicate errors.
5947    /// Returns `Ok(true)` if a label was added, `Ok(false)` if it already existed
5948    /// (only possible under `if_not_exists`).
5949    /// v7.39 (read01 round 49) — `ALTER TYPE t RENAME VALUE 'old' TO 'new'`.
5950    /// The parser used to swallow this form as a no-op, so the rename was
5951    /// accepted and silently ignored. Renaming in place keeps the label's
5952    /// sort position, which is what PG does (enumsortorder is untouched).
5953    pub fn rename_enum_value(
5954        &mut self,
5955        type_name: &str,
5956        old: &str,
5957        new: &str,
5958    ) -> Result<(), StorageError> {
5959        let def = self
5960            .enum_types
5961            .get_mut(type_name)
5962            .ok_or_else(|| StorageError::Corrupt(format!("type {type_name:?} does not exist")))?;
5963        if def.labels.iter().any(|l| l == new) {
5964            return Err(StorageError::Corrupt(format!(
5965                "enum label {new:?} already exists"
5966            )));
5967        }
5968        let at = def.labels.iter().position(|l| l == old).ok_or_else(|| {
5969            StorageError::Corrupt(format!("{old:?} is not an existing enum label"))
5970        })?;
5971        def.labels[at] = new.to_string();
5972        Ok(())
5973    }
5974
5975    /// v7.39 (read01 round 50) — set (or, with `None`, remove) the comment on
5976    /// an object. `key` is the canonical `"<kind>:<name>"` form.
5977    pub fn set_comment(&mut self, key: &str, text: Option<&str>) {
5978        match text {
5979            Some(t) => {
5980                self.comments.insert(key.to_string(), t.to_string());
5981            }
5982            None => {
5983                self.comments.remove(key);
5984            }
5985        }
5986    }
5987
5988    /// v7.39 (read01 round 50) — the comment on an object, if any.
5989    #[must_use]
5990    pub fn comment(&self, key: &str) -> Option<&str> {
5991        self.comments.get(key).map(String::as_str)
5992    }
5993
5994    /// v7.39 (round 547) — record a GUC default for a scope. An empty
5995    /// database or role name is PG's oid 0 ("all"). `None` value
5996    /// removes just that parameter, as PG's RESET does.
5997    pub fn set_db_role_setting(
5998        &mut self,
5999        database: &str,
6000        role: &str,
6001        param: &str,
6002        value: Option<&str>,
6003    ) {
6004        let key = (database.to_string(), role.to_string());
6005        match value {
6006            Some(v) => {
6007                self.db_role_settings
6008                    .entry(key)
6009                    .or_default()
6010                    .insert(param.to_ascii_lowercase(), v.to_string());
6011            }
6012            None => {
6013                if let Some(m) = self.db_role_settings.get_mut(&key) {
6014                    m.remove(&param.to_ascii_lowercase());
6015                    if m.is_empty() {
6016                        self.db_role_settings.remove(&key);
6017                    }
6018                }
6019            }
6020        }
6021    }
6022
6023    /// v7.39 (round 550) — create a replication slot. `Err` carries
6024    /// PG's own message for a duplicate.
6025    ///
6026    /// # Errors
6027    /// When a slot of that name already exists.
6028    pub fn create_replication_slot(
6029        &mut self,
6030        name: &str,
6031        plugin: &str,
6032        slot_type: &str,
6033    ) -> Result<(), String> {
6034        if self.replication_slots.contains_key(name) {
6035            return Err(alloc::format!("replication slot \"{name}\" already exists"));
6036        }
6037        self.replication_slots.insert(
6038            name.to_string(),
6039            (plugin.to_string(), slot_type.to_string()),
6040        );
6041        Ok(())
6042    }
6043
6044    /// # Errors
6045    /// When no slot of that name exists — PG's message, and the case
6046    /// that used to report success.
6047    pub fn drop_replication_slot(&mut self, name: &str) -> Result<(), String> {
6048        if self.replication_slots.remove(name).is_none() {
6049            return Err(alloc::format!("replication slot \"{name}\" does not exist"));
6050        }
6051        Ok(())
6052    }
6053
6054    #[must_use]
6055    pub const fn replication_slots(&self) -> &BTreeMap<String, (String, String)> {
6056        &self.replication_slots
6057    }
6058
6059    /// PG's RESET ALL: drops this scope's whole entry, leaving the
6060    /// other scopes alone — measured on PG18, where `ALTER ROLE r RESET
6061    /// ALL` left the ALL, the database and the role-in-database rows.
6062    pub fn reset_db_role_settings(&mut self, database: &str, role: &str) {
6063        self.db_role_settings
6064            .remove(&(database.to_string(), role.to_string()));
6065    }
6066
6067    #[must_use]
6068    pub const fn db_role_settings(&self) -> &BTreeMap<(String, String), BTreeMap<String, String>> {
6069        &self.db_role_settings
6070    }
6071
6072    /// v7.39 (read01 round 50) — every `(key, text)` pair, for the
6073    /// pg_description view.
6074    #[must_use]
6075    pub const fn comments(&self) -> &BTreeMap<String, String> {
6076        &self.comments
6077    }
6078
6079    /// v7.39 (read01 round 50) — drop every comment whose key names `obj`
6080    /// (the object itself and, for a table, its columns). Called when the
6081    /// object is dropped so a later object of the same name doesn't inherit
6082    /// a stale comment.
6083    pub fn drop_comments_for(&mut self, kind: &str, name: &str) {
6084        let exact = alloc::format!("{kind}:{name}");
6085        let col_prefix = alloc::format!("column:{name}.");
6086        self.comments
6087            .retain(|k, _| *k != exact && !k.starts_with(&col_prefix));
6088    }
6089
6090    pub fn add_enum_value(
6091        &mut self,
6092        type_name: &str,
6093        label: &str,
6094        if_not_exists: bool,
6095        position: Option<(bool, String)>,
6096    ) -> Result<bool, StorageError> {
6097        self.mark_nontable_dirty(NonTableKind::EnumType, type_name);
6098        let def = self
6099            .enum_types
6100            .get_mut(type_name)
6101            .ok_or_else(|| StorageError::Corrupt(format!("type {type_name:?} does not exist")))?;
6102        if def.labels.iter().any(|l| l == label) {
6103            if if_not_exists {
6104                return Ok(false);
6105            }
6106            // v7.39 (read01 round 49) — PG wording (42710 at the wire).
6107            return Err(StorageError::Corrupt(format!(
6108                "enum label {label:?} already exists"
6109            )));
6110        }
6111        match position {
6112            None => def.labels.push(label.to_string()),
6113            Some((is_before, anchor)) => {
6114                let at = def
6115                    .labels
6116                    .iter()
6117                    .position(|l| l == &anchor)
6118                    .ok_or_else(|| {
6119                        StorageError::Corrupt(format!(
6120                            "enum label {anchor:?} does not exist in type {type_name:?}"
6121                        ))
6122                    })?;
6123                let idx = if is_before { at } else { at + 1 };
6124                def.labels.insert(idx, label.to_string());
6125            }
6126        }
6127        Ok(true)
6128    }
6129
6130    pub fn drop_enum_type(&mut self, name: &str) -> bool {
6131        self.mark_nontable_dirty(NonTableKind::EnumType, name);
6132        self.enum_types.remove(name).is_some()
6133    }
6134
6135    /// v7.17.0 Phase 1.5 — read-only handle to DOMAIN catalog.
6136    pub const fn domain_types(&self) -> &BTreeMap<String, DomainDef> {
6137        &self.domain_types
6138    }
6139
6140    /// v7.17.0 Phase 1.5 — install a DOMAIN. Errors on collision
6141    /// with an existing domain.
6142    pub fn create_domain_type(&mut self, def: DomainDef) -> Result<(), StorageError> {
6143        if self.domain_types.contains_key(&def.name) {
6144            return Err(StorageError::Corrupt(format!(
6145                "domain {:?} already exists",
6146                def.name
6147            )));
6148        }
6149        self.mark_nontable_dirty(NonTableKind::DomainType, &def.name);
6150        self.domain_types.insert(def.name.clone(), def);
6151        Ok(())
6152    }
6153
6154    /// v7.17.0 Phase 1.5 — drop a DOMAIN by name.
6155    pub fn drop_domain_type(&mut self, name: &str) -> bool {
6156        self.mark_nontable_dirty(NonTableKind::DomainType, name);
6157        self.domain_types.remove(name).is_some()
6158    }
6159
6160    /// v7.37.42-T2 ζ-B — read-only handle to user-defined COMPOSITE
6161    /// catalog. Used by the engine to resolve
6162    /// `ColumnSchema.user_composite_type` lookups + by
6163    /// information_schema-style introspection.
6164    pub const fn composite_types(&self) -> &BTreeMap<String, CompositeDef> {
6165        &self.composite_types
6166    }
6167
6168    /// v7.37.42-T2 ζ-B — install a new COMPOSITE type. Errors if
6169    /// `name` already exists in the composite registry (PG forbids
6170    /// IF NOT EXISTS on CREATE TYPE composite; the engine surfaces
6171    /// the collision with the existing name).
6172    pub fn create_composite_type(&mut self, def: CompositeDef) -> Result<(), StorageError> {
6173        if self.composite_types.contains_key(&def.name) {
6174            return Err(StorageError::Corrupt(format!(
6175                "type {:?} already exists",
6176                def.name
6177            )));
6178        }
6179        self.mark_nontable_dirty(NonTableKind::CompositeType, &def.name);
6180        self.composite_types.insert(def.name.clone(), def);
6181        Ok(())
6182    }
6183
6184    /// v7.37.42-T2 ζ-B — drop a COMPOSITE type by name. Returns
6185    /// true if a type was removed.
6186    pub fn drop_composite_type(&mut self, name: &str) -> bool {
6187        self.mark_nontable_dirty(NonTableKind::CompositeType, name);
6188        self.composite_types.remove(name).is_some()
6189    }
6190
6191    /// v7.17.0 Phase 1.6 — read-only handle to the user-created
6192    /// schema registry. Built-in schemas (`public`, `pg_catalog`,
6193    /// `information_schema`) are NOT included here; use
6194    /// [`schema_exists`](Self::schema_exists) for the full
6195    /// check.
6196    pub const fn user_schemas(&self) -> &alloc::collections::BTreeSet<String> {
6197        &self.schemas
6198    }
6199
6200    /// v7.17.0 Phase 1.6 — schema-name resolver. Returns true
6201    /// for built-in schemas + every user-CREATEd one. Used by
6202    /// CREATE SCHEMA collision checks and (future) by
6203    /// information_schema.schemata.
6204    pub fn schema_exists(&self, name: &str) -> bool {
6205        is_builtin_schema(name) || self.schemas.contains(name)
6206    }
6207
6208    /// v7.17.0 Phase 1.6 — register a new schema. Errors if the
6209    /// name already exists and `if_not_exists=false`. Built-in
6210    /// names cannot be redeclared.
6211    pub fn create_schema(&mut self, name: String, if_not_exists: bool) -> Result<(), StorageError> {
6212        if is_builtin_schema(&name) {
6213            if if_not_exists {
6214                return Ok(());
6215            }
6216            return Err(StorageError::Corrupt(format!(
6217                "schema {name:?} is built-in and cannot be redeclared"
6218            )));
6219        }
6220        if self.schemas.contains(&name) {
6221            if if_not_exists {
6222                return Ok(());
6223            }
6224            return Err(StorageError::Corrupt(format!(
6225                "schema {name:?} already exists"
6226            )));
6227        }
6228        self.schemas.insert(name);
6229        Ok(())
6230    }
6231
6232    /// v7.17.0 Phase 1.6 — drop a user-created schema. Returns
6233    /// true if a schema was removed. Built-in names always
6234    /// return false (cannot be dropped). Tables that previously
6235    /// used the schema as a prefix keep their bare name and stay
6236    /// queryable — this is the "prefix routing, not isolation"
6237    /// posture documented in v7.17 Phase 1.6.
6238    pub fn drop_schema(&mut self, name: &str) -> Result<bool, StorageError> {
6239        if is_builtin_schema(name) {
6240            return Err(StorageError::Corrupt(format!(
6241                "schema {name:?} is built-in and cannot be dropped"
6242            )));
6243        }
6244        Ok(self.schemas.remove(name))
6245    }
6246
6247    /// v7.17.0 — ALTER SEQUENCE option merge. Caller-provided
6248    /// updates overwrite the matching fields; unset fields keep
6249    /// their stored values. RESTART variants update last_value
6250    /// directly per PG: `RESTART` resets to current `start`;
6251    /// `RESTART WITH n` resets to `n`.
6252    #[allow(clippy::too_many_arguments)]
6253    pub fn alter_sequence(
6254        &mut self,
6255        name: &str,
6256        increment: Option<i64>,
6257        min_value: Option<i64>,
6258        max_value: Option<i64>,
6259        start: Option<i64>,
6260        restart: Option<Option<i64>>,
6261        cache: Option<i64>,
6262        cycle: Option<bool>,
6263        owned_by: Option<Option<(String, String)>>,
6264    ) -> Result<(), StorageError> {
6265        self.mark_nontable_dirty(NonTableKind::Sequence, name);
6266        let Some(seq) = self.sequences.get_mut(name) else {
6267            return Err(StorageError::TableNotFound { name: name.into() });
6268        };
6269        if let Some(v) = increment {
6270            seq.increment = v;
6271        }
6272        if let Some(v) = min_value {
6273            seq.min_value = v;
6274        }
6275        if let Some(v) = max_value {
6276            seq.max_value = v;
6277        }
6278        if let Some(v) = start {
6279            seq.start = v;
6280        }
6281        if let Some(restart_value) = restart {
6282            seq.last_value = restart_value.unwrap_or(seq.start);
6283            seq.is_called = false;
6284        }
6285        if let Some(v) = cache {
6286            seq.cache = v;
6287        }
6288        if let Some(v) = cycle {
6289            seq.cycle = v;
6290        }
6291        if let Some(v) = owned_by {
6292            seq.owned_by = v;
6293        }
6294        Ok(())
6295    }
6296
6297    /// v7.12.4 — read-only slice of all catalogued triggers.
6298    /// Engine row-write paths filter this by (table, event,
6299    /// timing) and fire matches in slice order.
6300    pub fn triggers(&self) -> &[TriggerDef] {
6301        &self.triggers
6302    }
6303
6304    /// v7.15.0 — mutable handle to the trigger slice for
6305    /// `ALTER TABLE … RENAME COLUMN`, which rewrites every
6306    /// `update_columns` entry that referenced the renamed
6307    /// column.
6308    pub fn triggers_mut(&mut self) -> &mut Vec<TriggerDef> {
6309        &mut self.triggers
6310    }
6311
6312    /// v7.12.4 — register a new trigger. With `or_replace = false`,
6313    /// errors when a trigger with the same name already exists on
6314    /// the same table (PG scoping rule — trigger names are
6315    /// per-table, not global). Trigger function must already
6316    /// exist in the catalog at registration time.
6317    pub fn create_trigger(
6318        &mut self,
6319        def: TriggerDef,
6320        or_replace: bool,
6321    ) -> Result<(), StorageError> {
6322        // v7.39 (round 137) — a trigger may target a base table (BEFORE / AFTER)
6323        // or a view (INSTEAD OF). The engine enforces the timing↔target rule;
6324        // storage only requires the relation to exist as one or the other.
6325        if !self.by_name.contains_key(&def.table) && !self.views.contains_key(&def.table) {
6326            return Err(StorageError::TableNotFound {
6327                name: def.table.clone(),
6328            });
6329        }
6330        // v7.39 (read01 round 62) — functions are keyed by SIGNATURE now. A
6331        // trigger names its function by NAME (a trigger function takes no
6332        // arguments), so the existence check goes through the name index.
6333        if self.functions_named(&def.function).is_empty() {
6334            // v7.39 (round 710) — PG's wording: the FUNCTION is what does
6335            // not exist (`function nosuch_fn() does not exist`), and the
6336            // old message rode `Corrupt`'s on-disk banner besides.
6337            return Err(StorageError::Corrupt(format!(
6338                "function {}() does not exist",
6339                def.function
6340            )));
6341        }
6342        let dup = self
6343            .triggers
6344            .iter()
6345            .position(|t| t.name == def.name && t.table == def.table);
6346        match (dup, or_replace) {
6347            (Some(_), false) => Err(StorageError::Corrupt(format!(
6348                "trigger {:?} already exists on table {:?}",
6349                def.name, def.table
6350            ))),
6351            (Some(i), true) => {
6352                self.triggers[i] = def;
6353                Ok(())
6354            }
6355            (None, _) => {
6356                self.triggers.push(def);
6357                Ok(())
6358            }
6359        }
6360    }
6361
6362    /// v7.12.4 — remove a trigger by `(name, table)`. Returns
6363    /// `true` if one was removed.
6364    pub fn drop_trigger(&mut self, name: &str, table: &str) -> bool {
6365        let before = self.triggers.len();
6366        self.triggers
6367            .retain(|t| !(t.name == name && t.table == table));
6368        before != self.triggers.len()
6369    }
6370
6371    /// v7.39 (round 139) — the catalogued query-rewrite RULEs.
6372    pub fn rules(&self) -> &[RuleDef] {
6373        &self.rules
6374    }
6375
6376    /// v7.39 (round 280) — the catalogued extended-statistics objects.
6377    #[must_use]
6378    pub fn statistics_ext(&self) -> &[StatisticsExtDef] {
6379        &self.statistics_ext
6380    }
6381
6382    /// v7.39 (round 287) — every large object, ascending by OID.
6383    #[must_use]
6384    pub fn large_objects(&self) -> &alloc::collections::BTreeMap<u32, Vec<u8>> {
6385        &self.large_objects
6386    }
6387
6388    /// The bytes of one large object, or `None` when no such OID exists.
6389    #[must_use]
6390    pub fn large_object(&self, oid: u32) -> Option<&[u8]> {
6391        self.large_objects.get(&oid).map(Vec::as_slice)
6392    }
6393
6394    /// Create a large object. `oid` of 0 means "pick one" — PG's
6395    /// `lo_create(0)` / `lo_creat(-1)` spelling. Errors when the
6396    /// requested OID is taken.
6397    pub fn create_large_object(&mut self, oid: u32, bytes: Vec<u8>) -> Result<u32, String> {
6398        let id = if oid == 0 {
6399            self.next_large_object_oid()
6400        } else {
6401            oid
6402        };
6403        if self.large_objects.contains_key(&id) {
6404            return Err(format!("large object {id} already exists"));
6405        }
6406        self.large_objects.insert(id, bytes);
6407        Ok(id)
6408    }
6409
6410    /// Overwrite `len` bytes at `offset` (0-based), growing the object
6411    /// with zero bytes if the write starts past the end — PG's
6412    /// `lo_put` semantics.
6413    pub fn put_large_object(&mut self, oid: u32, offset: usize, data: &[u8]) -> Result<(), String> {
6414        let Some(buf) = self.large_objects.get_mut(&oid) else {
6415            return Err(format!("large object {oid} does not exist"));
6416        };
6417        let end = offset.saturating_add(data.len());
6418        if buf.len() < end {
6419            buf.resize(end, 0);
6420        }
6421        buf[offset..end].copy_from_slice(data);
6422        Ok(())
6423    }
6424
6425    /// v7.39 (round 306) — `lo_truncate`. PG's truncate sets the object
6426    /// to exactly `len` bytes in BOTH directions: it shortens, and it
6427    /// GROWS with zero fill when `len` exceeds the current size
6428    /// (measured — `lo_truncate(fd, 8)` over a 4-byte object leaves
6429    /// eight bytes, the last four zero).
6430    pub fn truncate_large_object(&mut self, oid: u32, len: usize) -> Result<(), String> {
6431        let Some(buf) = self.large_objects.get_mut(&oid) else {
6432            return Err(format!("large object {oid} does not exist"));
6433        };
6434        buf.resize(len, 0);
6435        Ok(())
6436    }
6437
6438    /// Remove a large object. `false` when the OID was not there.
6439    pub fn unlink_large_object(&mut self, oid: u32) -> bool {
6440        self.large_objects.remove(&oid).is_some()
6441    }
6442
6443    /// The next free OID in PG's user band.
6444    /// v7.39 (round 343, V40) — large objects have their own oid band.
6445    /// It used to start at 16_384, which is where user TABLES start, so
6446    /// the first large object and the first table shared an oid — and
6447    /// `pg_largeobject_metadata.oid` is joinable against `pg_class.oid`,
6448    /// so a join across them matched a row that has nothing to do with
6449    /// it. (PG cannot collide: every oid there comes off one counter.)
6450    /// An object already stored keeps the oid it was given; only new
6451    /// ones land in the band.
6452    fn next_large_object_oid(&self) -> u32 {
6453        self.large_objects
6454            .keys()
6455            .next_back()
6456            .map_or(500_000, |m| m.saturating_add(1))
6457    }
6458
6459    /// Register one. `Err(name)` when the name is taken.
6460    pub fn create_statistics_ext(&mut self, def: StatisticsExtDef) -> Result<(), String> {
6461        if self.statistics_ext.iter().any(|s| s.name == def.name) {
6462            return Err(def.name);
6463        }
6464        self.statistics_ext.push(def);
6465        Ok(())
6466    }
6467
6468    /// Drop one by name; false when absent.
6469    pub fn drop_statistics_ext(&mut self, name: &str) -> bool {
6470        let before = self.statistics_ext.len();
6471        self.statistics_ext.retain(|s| s.name != name);
6472        before != self.statistics_ext.len()
6473    }
6474
6475    /// v7.39 (round 139) — register a RULE. Its target relation (table or view)
6476    /// must exist; `or_replace` overwrites a same-(name,table) rule.
6477    pub fn create_rule(&mut self, def: RuleDef, or_replace: bool) -> Result<(), StorageError> {
6478        if !self.by_name.contains_key(&def.table) && !self.views.contains_key(&def.table) {
6479            return Err(StorageError::TableNotFound {
6480                name: def.table.clone(),
6481            });
6482        }
6483        let dup = self
6484            .rules
6485            .iter()
6486            .position(|r| r.name == def.name && r.table == def.table);
6487        match (dup, or_replace) {
6488            (Some(_), false) => Err(StorageError::Corrupt(format!(
6489                "rule {:?} for relation {:?} already exists",
6490                def.name, def.table
6491            ))),
6492            (Some(i), true) => {
6493                self.rules[i] = def;
6494                Ok(())
6495            }
6496            (None, _) => {
6497                self.rules.push(def);
6498                Ok(())
6499            }
6500        }
6501    }
6502
6503    /// v7.39 (round 139) — drop a RULE by `(name, table)`.
6504    pub fn drop_rule(&mut self, name: &str, table: &str) -> bool {
6505        let before = self.rules.len();
6506        self.rules.retain(|r| !(r.name == name && r.table == table));
6507        before != self.rules.len()
6508    }
6509
6510    pub fn create_table(&mut self, schema: TableSchema) -> Result<(), StorageError> {
6511        if self.by_name.contains_key(&schema.name) {
6512            return Err(StorageError::DuplicateTable {
6513                name: schema.name.clone(),
6514            });
6515        }
6516        let idx = self.tables.len();
6517        let name = schema.name.clone();
6518        self.tables.push(Table::new(schema));
6519        self.by_name.insert(name.clone(), idx);
6520        // v7.39 (round 496) — see `dirty_tables`.
6521        self.dirty_tables.insert(name);
6522        // v7.37.15 (Phase C.1) — stamp the new relation with a stable,
6523        // monotonic, never-reused RelId. Pre-increment so ids start at
6524        // 1 (0 = UNASSIGNED); a later DROP TABLE frees the slot but not
6525        // the id.
6526        self.next_rel_id += 1;
6527        let rid = row_header::RelId(self.next_rel_id);
6528        self.tables[idx].set_rel_id(rid);
6529        Ok(())
6530    }
6531
6532    /// v7.39 (round 436) — the session's temporary table of this name wins
6533    /// over a permanent one, as `pg_temp` does in PG's search path and as
6534    /// MySQL's TEMPORARY shadowing does. Every name → index resolution in
6535    /// this catalog goes through here.
6536    fn resolve_index(&self, name: &str) -> Option<usize> {
6537        if let Some(prefix) = &self.temp_prefix {
6538            let mut mangled = String::with_capacity(prefix.len() + name.len());
6539            mangled.push_str(prefix);
6540            mangled.push_str(name);
6541            if let Some(idx) = self.by_name.get(&mangled) {
6542                return Some(*idx);
6543            }
6544        }
6545        self.by_name.get(name).copied()
6546    }
6547
6548    /// v7.39 (round 436) — install the calling session's temp namespace.
6549    /// `None` disables temp resolution entirely (a session that never made
6550    /// one pays a single `Option` check per lookup).
6551    pub fn set_temp_prefix(&mut self, prefix: Option<String>) {
6552        self.temp_prefix = prefix;
6553    }
6554
6555    /// The mangled storage name a temp table of `name` takes in this
6556    /// session, or `None` when the session has no temp namespace.
6557    #[must_use]
6558    pub fn temp_name_for(&self, name: &str) -> Option<String> {
6559        self.temp_prefix
6560            .as_ref()
6561            .map(|p| alloc::format!("{p}{name}"))
6562    }
6563
6564    pub fn get(&self, name: &str) -> Option<&Table> {
6565        let idx = self.resolve_index(name)?;
6566        self.tables.get(idx)
6567    }
6568
6569    pub fn get_mut(&mut self, name: &str) -> Option<&mut Table> {
6570        let idx = self.resolve_index(name)?;
6571        // v7.39 (round 496) — the choke point for changing a table, so the
6572        // record is taken here. Over-approximate on purpose: a caller that
6573        // takes the handle and writes nothing merely carries that table
6574        // through a commit, which is the old behaviour.
6575        let recorded = self.tables.get(idx).map(|t| t.schema().name.clone());
6576        if let Some(n) = recorded {
6577            self.dirty_tables.insert(n);
6578        }
6579        self.tables.get_mut(idx)
6580    }
6581
6582    /// v7.39 (round 496) — the tables changed through this handle since
6583    /// [`Self::clear_dirty_tables`]. See `dirty_tables`.
6584    #[must_use]
6585    pub fn dirty_tables(&self) -> &alloc::collections::BTreeSet<String> {
6586        &self.dirty_tables
6587    }
6588
6589    /// r1059 — mark one table dirty without taking its handle. The
6590    /// rebase/merge paths replace a tx's shadow with a fresh base
6591    /// clone and must carry the tx's OWN dirty window across (the
6592    /// base's set is an ever-growing history, never cleared).
6593    pub fn mark_table_dirty(&mut self, name: &str) {
6594        self.dirty_tables.insert(name.into());
6595    }
6596
6597    /// v7.39 (round 496) — start a fresh recording window. A transaction's
6598    /// shadow calls this at BEGIN so the set means "changed by this tx".
6599    /// 7.38.1 S3.1 — one window covers both records (tables and the
6600    /// non-table families).
6601    pub fn clear_dirty_tables(&mut self) {
6602        self.dirty_tables.clear();
6603        self.dirty_nontable.clear();
6604    }
6605
6606    /// 7.38.1 S3.1 (D4) — record a non-table object as changed by this
6607    /// window. Called from every create/alter/rename/drop of the six
6608    /// [`NonTableKind`] families; a rename records BOTH names.
6609    fn mark_nontable_dirty(&mut self, kind: NonTableKind, name: &str) {
6610        self.dirty_nontable.insert((kind, name.into()));
6611    }
6612
6613    /// 7.38.1 S3.1 (D4) — reconcile the six non-table families with
6614    /// `base` (the latest committed catalog): every entry this window
6615    /// did NOT touch is taken from base — existence, definition and
6616    /// absence alike — so a neighbour's CREATE / ALTER / DROP of a
6617    /// sequence, view, matview, enum, domain or composite type
6618    /// survives a poisoned transaction's COMMIT. Entries this window
6619    /// DID touch keep the shadow's version (the tx's own DDL wins its
6620    /// own objects, exactly like the dirty-table merge above it).
6621    pub fn merge_nontable_objects_from(&mut self, base: &Catalog) {
6622        use NonTableKind as K;
6623        fn merge_map<V: Clone>(
6624            kind: NonTableKind,
6625            dirty: &alloc::collections::BTreeSet<(NonTableKind, String)>,
6626            mine: &mut BTreeMap<String, V>,
6627            theirs: &BTreeMap<String, V>,
6628        ) {
6629            let names: alloc::vec::Vec<String> =
6630                mine.keys().chain(theirs.keys()).cloned().collect();
6631            for n in names {
6632                if dirty.contains(&(kind, n.clone())) {
6633                    continue;
6634                }
6635                match theirs.get(&n) {
6636                    Some(v) => {
6637                        mine.insert(n, v.clone());
6638                    }
6639                    None => {
6640                        mine.remove(&n);
6641                    }
6642                }
6643            }
6644        }
6645        let dirty = self.dirty_nontable.clone();
6646        merge_map(K::Sequence, &dirty, &mut self.sequences, &base.sequences);
6647        merge_map(K::View, &dirty, &mut self.views, &base.views);
6648        merge_map(
6649            K::MaterializedView,
6650            &dirty,
6651            &mut self.materialized_views,
6652            &base.materialized_views,
6653        );
6654        merge_map(K::EnumType, &dirty, &mut self.enum_types, &base.enum_types);
6655        merge_map(
6656            K::DomainType,
6657            &dirty,
6658            &mut self.domain_types,
6659            &base.domain_types,
6660        );
6661        merge_map(
6662            K::CompositeType,
6663            &dirty,
6664            &mut self.composite_types,
6665            &base.composite_types,
6666        );
6667    }
6668
6669    /// v7.39 (round 496) — put `table` in at `name`, replacing any table
6670    /// already there and keeping the rest of the catalog untouched.
6671    ///
6672    /// The commit-time table-granularity merge needs exactly this: take
6673    /// the latest committed catalog, then overwrite only the tables the
6674    /// transaction changed.
6675    pub fn install_table(&mut self, name: &str, table: Table) {
6676        match self.by_name.get(name).copied() {
6677            Some(idx) => self.tables[idx] = table,
6678            None => {
6679                let idx = self.tables.len();
6680                self.tables.push(table);
6681                self.by_name.insert(name.into(), idx);
6682            }
6683        }
6684        self.dirty_tables.insert(name.into());
6685    }
6686
6687    /// v7.37.42 (docker-fair SCALARSQ attack) — resolve a table name to
6688    /// its insertion-order index ONCE, so callers that need to fetch the
6689    /// same table many times (per-row PK probes in correlated scalar
6690    /// subqueries) can avoid the per-call `BTreeMap<String, usize>` string
6691    /// descent. The returned index is stable for the lifetime of the
6692    /// catalog snapshot the caller holds (same engine read guard).
6693    pub fn tables_position_of(&self, name: &str) -> Option<usize> {
6694        self.resolve_index(name)
6695    }
6696
6697    /// Direct positional fetch counterpart to [`tables_position_of`].
6698    /// `idx` must come from `tables_position_of` against the same catalog
6699    /// snapshot — out-of-range returns `None`.
6700    pub fn tables_at(&self, idx: usize) -> Option<&Table> {
6701        self.tables.get(idx)
6702    }
6703
6704    /// v7.34 (crash-recovery P0 #2) — replay a row-level redo log onto
6705    /// this catalog (the [`RowChange`] physical-redo apply primitive that
6706    /// row-level WAL recovery will use in place of statement re-execution).
6707    /// Applies each change in order via the same `Table` mutators the
6708    /// engine used — no uniqueness/FK/parse/plan: the original execution
6709    /// already validated, replay trusts and applies. Positions are
6710    /// physical and only valid when replayed from the matching checkpoint
6711    /// baseline in original order (see [`RowChange`] docs).
6712    ///
6713    /// A change naming an absent table, or whose position is out of range,
6714    /// is a corrupt/misaligned log and surfaces as an error rather than a
6715    /// silent skip.
6716    pub fn apply_redo(&mut self, changes: &[RowChange]) -> Result<(), StorageError> {
6717        // v7.37.5 (mailrs crash-recovery Ask 3) — true batched replay.
6718        // Pre-v7.37.5 each `RowChange::Delete` record ran a fresh
6719        // O(N) PersistentVec rebuild + O(N × indices × log N)
6720        // `rebuild_indices()` — 5000 records × 100k rows × 13 indices
6721        // ≈ 27 min on the mailrs prod-shape WAL.
6722        //
6723        // The strategy: group consecutive changes by table, and for
6724        // each run, compose all the row-level mutations through a
6725        // single "live" tracking vector + a per-table operation log,
6726        // then apply rows + indices ONCE at the end. The result:
6727        //  - DELETE blow-up: O(records × rows × indices × log rows)
6728        //    → O(rows × indices × log rows) — one rebuild per run.
6729        //  - Row-position semantics preserved: positions in a later
6730        //    `Delete` / `Update` record reference the layout produced
6731        //    by every earlier change; we walk the live-vector
6732        //    forward as each change is processed so positions
6733        //    translate correctly to the ORIGINAL row index space.
6734        //
6735        // For correctness, even with this batching `apply_redo`
6736        // remains in-order: a single per-table run only batches
6737        // a contiguous slice of changes targeting that table; a
6738        // mid-run change targeting a DIFFERENT table forces a
6739        // flush of the current run.
6740        let mut runs: alloc::vec::Vec<(String, alloc::vec::Vec<&RowChange>)> =
6741            alloc::vec::Vec::new();
6742        for change in changes {
6743            // v7.39 (flip crash-replay P0) — a replayed tombstone carries
6744            // the xmax the CRASHED process allocated, but this process's
6745            // version cursor restarted; without advancing it past every
6746            // replayed version, `Snapshot::visible`'s "deletion is in the
6747            // future" branch (xmax > snapshot.version) resurrects every
6748            // replayed delete. Same recovery contract as the snapshot
6749            // loader (`observe_persisted_version`, the pg_control-style
6750            // nextXid recovery).
6751            if let RowChange::Tombstone { xmax, .. } = change {
6752                row_header::observe_persisted_version(*xmax);
6753            }
6754            let table = match change {
6755                RowChange::Insert { table, .. }
6756                | RowChange::Update { table, .. }
6757                | RowChange::Delete { table, .. }
6758                | RowChange::Tombstone { table, .. } => table.clone(),
6759            };
6760            if runs.last().map(|(t, _)| t.as_str()) != Some(table.as_str()) {
6761                runs.push((table, alloc::vec::Vec::new()));
6762            }
6763            runs.last_mut().unwrap().1.push(change);
6764        }
6765        for (table_name, run) in runs {
6766            self.apply_redo_run_on_table(&table_name, &run)?;
6767        }
6768        Ok(())
6769    }
6770
6771    /// v7.37.5 — apply a contiguous slice of `RowChange`s all
6772    /// targeting the same `table_name`. Composes row mutations
6773    /// through a single live-tracking vector + a single tail
6774    /// for appended `Insert`s + a single in-place edit set for
6775    /// `Update`s, then writes the final row layout to
6776    /// `self.rows` and rebuilds indices ONCE.
6777    fn apply_redo_run_on_table(
6778        &mut self,
6779        table_name: &str,
6780        run: &[&RowChange],
6781    ) -> Result<(), StorageError> {
6782        // Look up the table once; the unchecked unwrap is safe
6783        // because the caller just resolved `table_name` for each
6784        // change.
6785        let table = self.get_mut(table_name).ok_or_else(|| {
6786            StorageError::Corrupt(alloc::format!("redo: unknown table {table_name:?}"))
6787        })?;
6788        // Live-tracking over both pre-existing rows and tail-
6789        // appended Insert rows. `live[i] = true` initially for
6790        // every existing row. Appended Inserts extend with `true`.
6791        // A `Delete` flips entries to `false` (using the position
6792        // mapping that walks live indices in order). An `Update`
6793        // edits in place — collected into an overlay map keyed by
6794        // ORIGINAL row position so later Updates win.
6795        let original_rows: alloc::vec::Vec<Row<'static>> = table.rows().iter().cloned().collect();
6796        let mut live: alloc::vec::Vec<bool> = alloc::vec![true; original_rows.len()];
6797        let mut tail: alloc::vec::Vec<Row<'static>> = alloc::vec::Vec::new();
6798        // Overlay: index into ORIGINAL row space (existing rows
6799        // 0..original_rows.len()) or into tail (offset
6800        // original_rows.len()). Map -> new values.
6801        let mut overlay: alloc::collections::BTreeMap<usize, alloc::vec::Vec<Value<'static>>> =
6802            alloc::collections::BTreeMap::new();
6803        // v7.37.15 (Epic W durable-tombstone slice) — extra bookkeeping
6804        // ONLY when this run actually carries an in-place `Tombstone`.
6805        // A tombstone keeps its row physically present but stamps `xmax`
6806        // on the header; the run finalizer `set_rows_and_rebuild_indices`
6807        // freezes every header (and reassigns ids), so we must re-stamp
6808        // in a post-pass keyed by RowId. When the run has no tombstone
6809        // (every default gate-off replay) this is all skipped and the
6810        // path below stays byte-for-byte the legacy one.
6811        let has_tomb = run.iter().any(|c| matches!(c, RowChange::Tombstone { .. }));
6812        // Ids of the pre-existing rows, snapshotted parallel to
6813        // `original_rows`, and ids of the tail rows filled from each
6814        // `Insert`'s carried `rowid`. Together they let a tombstone name
6815        // the exact row the writer stamped, independent of the ids the
6816        // finalizer will hand out. (When `!has_tomb`, both stay empty.)
6817        // v7.39 (flip crash-replay P0) — ids are tracked UNCONDITIONALLY
6818        // now: the finalizer preserves them so a later WAL record's
6819        // tombstone can still name rows this record produced.
6820        let orig_rowids: alloc::vec::Vec<row_header::RowId> =
6821            table.rowids().iter().copied().collect();
6822        // Headers snapshotted in lock-step: the finalizer preserves
6823        // them so earlier records' tombstone stamps survive.
6824        let orig_headers: alloc::vec::Vec<row_header::RowHeader> =
6825            table.headers().iter().copied().collect();
6826        let mut tail_rowids: alloc::vec::Vec<row_header::RowId> = alloc::vec::Vec::new();
6827        // (RowId, xmax) of every row this run tombstones.
6828        let mut tomb_targets: alloc::vec::Vec<(row_header::RowId, u64)> = alloc::vec::Vec::new();
6829        // Helper: given a "current" position (i.e. position in
6830        // the post-prior-deletes layout), translate to the
6831        // ABSOLUTE position in the unified live + tail space
6832        // by walking the live vector + tail. Returns None when
6833        // the position is out of range.
6834        fn translate(live: &[bool], tail_len: usize, current_pos: usize) -> Option<usize> {
6835            // Walk live[..] counting live entries until we hit
6836            // current_pos. Then if not yet matched, dip into tail.
6837            let mut seen = 0usize;
6838            for (i, &alive) in live.iter().enumerate() {
6839                if alive {
6840                    if seen == current_pos {
6841                        return Some(i);
6842                    }
6843                    seen += 1;
6844                }
6845            }
6846            // Position lives in tail. tail_len rows in the tail
6847            // are all live (we haven't deleted any tail rows in
6848            // this simplification; if we did, we'd extend `live`).
6849            let off = current_pos - seen;
6850            if off < tail_len {
6851                Some(live.len() + off)
6852            } else {
6853                None
6854            }
6855        }
6856        for change in run {
6857            match *change {
6858                RowChange::Insert { row, rowid, .. } => {
6859                    // Validate against schema before recording the
6860                    // change so a corrupt log surfaces as an error
6861                    // rather than silently mis-applying.
6862                    if row.len() != table.schema().columns.len() {
6863                        return Err(StorageError::ArityMismatch {
6864                            expected: table.schema().columns.len(),
6865                            actual: row.len(),
6866                        });
6867                    }
6868                    tail.push(row.clone());
6869                    // Keep the id lock-step with `tail` so a later
6870                    // tombstone (this run or a later WAL record) can
6871                    // find the row by the id the writer captured.
6872                    tail_rowids.push(*rowid);
6873                }
6874                RowChange::Update { pos, new_row, .. } => {
6875                    if new_row.len() != table.schema().columns.len() {
6876                        return Err(StorageError::ArityMismatch {
6877                            expected: table.schema().columns.len(),
6878                            actual: new_row.len(),
6879                        });
6880                    }
6881                    let abs = translate(&live, tail.len(), *pos).ok_or_else(|| {
6882                        StorageError::Corrupt(alloc::format!(
6883                            "redo: update_row position {pos} out of bounds in table {table_name:?}",
6884                        ))
6885                    })?;
6886                    // Tail edits are applied directly to `tail`
6887                    // (we own it); existing-row edits land in
6888                    // the overlay map keyed by original index.
6889                    if abs < live.len() {
6890                        overlay.insert(abs, new_row.clone());
6891                    } else {
6892                        tail[abs - live.len()] = Row::new(new_row.clone());
6893                    }
6894                }
6895                RowChange::Delete { positions, .. } => {
6896                    // De-dup + sort so the translate walk stays
6897                    // monotone (the second translate doesn't have
6898                    // to redo work the first one did, in principle;
6899                    // we keep it simple here and re-walk per
6900                    // position). Bounds-filter silently mirrors
6901                    // `Table::delete_rows`.
6902                    let mut sorted: alloc::vec::Vec<usize> = positions.clone();
6903                    sorted.sort_unstable();
6904                    sorted.dedup();
6905                    // Walk live[] once per Delete record to
6906                    // translate all positions in this record's
6907                    // post-prior-deletes layout to absolute
6908                    // indices. We MUST defer the live[] flip
6909                    // until after all positions are translated
6910                    // so two positions in the same record
6911                    // (e.g. [3, 7]) reference the same layout.
6912                    let mut to_flip_live: alloc::vec::Vec<usize> = alloc::vec::Vec::new();
6913                    let mut to_flip_tail: alloc::vec::Vec<usize> = alloc::vec::Vec::new();
6914                    // Two-pointer walk: live[i] scanned monotonically,
6915                    // sorted positions consumed in order.
6916                    let mut seen = 0usize;
6917                    let mut sp = sorted.iter().peekable();
6918                    for (i, &alive) in live.iter().enumerate() {
6919                        if !alive {
6920                            continue;
6921                        }
6922                        while let Some(&&p) = sp.peek() {
6923                            if seen == p {
6924                                to_flip_live.push(i);
6925                                sp.next();
6926                            } else {
6927                                break;
6928                            }
6929                        }
6930                        if sp.peek().is_none() {
6931                            break;
6932                        }
6933                        seen += 1;
6934                    }
6935                    // Remaining positions fall into the tail.
6936                    for &p in sp {
6937                        // p >= seen and refers to the (p - seen)-th
6938                        // entry in tail. Filter out-of-bounds.
6939                        let off = p - seen;
6940                        if off < tail.len() {
6941                            to_flip_tail.push(off);
6942                        }
6943                    }
6944                    for i in to_flip_live {
6945                        live[i] = false;
6946                        // Any pending overlay edit for this
6947                        // index is moot — the row is gone.
6948                        overlay.remove(&i);
6949                    }
6950                    // Tail deletes: remove in REVERSE order so
6951                    // shifting indices stay valid.
6952                    to_flip_tail.sort_unstable();
6953                    to_flip_tail.dedup();
6954                    for off in to_flip_tail.into_iter().rev() {
6955                        tail.remove(off);
6956                        {
6957                            // Keep the id vector lock-step with `tail`.
6958                            tail_rowids.remove(off);
6959                        }
6960                        // Re-key tail-relative overlay entries that
6961                        // were past `off` — in practice tail edits
6962                        // are applied directly so the overlay map
6963                        // only holds existing-row keys; nothing to
6964                        // do here.
6965                    }
6966                }
6967                RowChange::Tombstone { rowids, xmax, .. } => {
6968                    // An in-place tombstone leaves the row physically
6969                    // present — it does not touch `live` / `tail` /
6970                    // `overlay`. Record the (id, xmax) targets; the
6971                    // post-finalizer pass re-stamps `xmax` onto the
6972                    // matching row's (otherwise-frozen) header.
6973                    for rid in rowids {
6974                        tomb_targets.push((*rid, *xmax));
6975                    }
6976                }
6977            }
6978        }
6979        // Compose the final row layout: keep existing rows where
6980        // live[i] = true, applying overlay edits in place; then
6981        // append the surviving tail.
6982        let mut new_rows: PersistentVec<Row> = PersistentVec::new();
6983        let mut new_hot_bytes: u64 = 0;
6984        let schema_snapshot = table.schema().clone();
6985        // Parallel to `new_rows` (only built when `has_tomb`): the RowId
6986        // of each row in its FINAL slot, so the post-pass can map a
6987        // tombstone target id → the slot to re-stamp `xmax` on.
6988        let mut final_rowids: alloc::vec::Vec<row_header::RowId> = alloc::vec::Vec::new();
6989        let mut final_headers: alloc::vec::Vec<row_header::RowHeader> = alloc::vec::Vec::new();
6990        for (i, row) in original_rows.into_iter().enumerate() {
6991            if !live[i] {
6992                continue;
6993            }
6994            let final_row = if let Some(new_values) = overlay.remove(&i) {
6995                Row::new(new_values)
6996            } else {
6997                row
6998            };
6999            new_hot_bytes = new_hot_bytes
7000                .saturating_add(row_body_encoded_len(&final_row, &schema_snapshot) as u64);
7001            new_rows.push_mut(final_row);
7002            final_rowids.push(
7003                orig_rowids
7004                    .get(i)
7005                    .copied()
7006                    .unwrap_or(row_header::RowId::UNASSIGNED),
7007            );
7008            final_headers.push(
7009                orig_headers
7010                    .get(i)
7011                    .copied()
7012                    .unwrap_or_else(row_header::RowHeader::frozen),
7013            );
7014        }
7015        for (off, row) in tail.into_iter().enumerate() {
7016            new_hot_bytes =
7017                new_hot_bytes.saturating_add(row_body_encoded_len(&row, &schema_snapshot) as u64);
7018            new_rows.push_mut(row);
7019            final_rowids.push(
7020                tail_rowids
7021                    .get(off)
7022                    .copied()
7023                    .unwrap_or(row_header::RowId::UNASSIGNED),
7024            );
7025            final_headers.push(row_header::RowHeader::frozen());
7026        }
7027        // v7.39 (flip crash-replay P0) — id-preserving finalizer, so a
7028        // LATER WAL record's tombstone still resolves rows this record
7029        // produced (per-statement replay used to reassign ids between
7030        // records, orphaning every cross-record tombstone target).
7031        table.set_rows_and_rebuild_indices_with_rowids(
7032            new_rows,
7033            new_hot_bytes,
7034            &final_rowids,
7035            &final_headers,
7036        );
7037        // v7.37.15 (Epic W durable-tombstone slice) — header-preserving
7038        // re-stamp. `set_rows_and_rebuild_indices` above froze every
7039        // header, so any row this run tombstoned is currently all-
7040        // visible again. Re-apply the `xmax` stamp by matching the
7041        // tombstone's target RowId against the final-slot id map. This
7042        // is what makes a gate-on DELETE durable across replay without
7043        // changing the on-disk snapshot format (headers/ids are still
7044        // NOT serialised — that is the deferred V6 coupling; see below).
7045        if has_tomb && !tomb_targets.is_empty() {
7046            let mut id_to_slot: alloc::collections::BTreeMap<row_header::RowId, usize> =
7047                alloc::collections::BTreeMap::new();
7048            for (slot, rid) in final_rowids.iter().enumerate() {
7049                if *rid != row_header::RowId::UNASSIGNED {
7050                    id_to_slot.insert(*rid, slot);
7051                }
7052            }
7053            let table = self.get_mut(table_name).ok_or_else(|| {
7054                StorageError::Corrupt(alloc::format!("redo: unknown table {table_name:?}"))
7055            })?;
7056            for (rid, xmax) in &tomb_targets {
7057                match id_to_slot.get(rid) {
7058                    Some(&slot) => {
7059                        // First-deleter-wins + bounds handled inside.
7060                        let _ = table.mark_row_deleted(slot, *xmax);
7061                    }
7062                    None => {
7063                        // The target row was not produced by THIS redo
7064                        // run and its id was not in the run-start
7065                        // snapshot — the documented cross-checkpoint
7066                        // limitation: after a checkpoint restore the
7067                        // table's ids are reassigned (not yet persisted
7068                        // in the envelope), so a tombstone naming a
7069                        // pre-checkpoint row cannot be resolved by id.
7070                        // Skipping leaves the row visible (identical to
7071                        // the pre-Epic-W non-durable behaviour); it is
7072                        // never a correctness regression, only an
7073                        // unclosed durability gap the V6 envelope slice
7074                        // closes. Counted for observability.
7075                        UNRESOLVED_TOMBSTONES.fetch_add(1, core::sync::atomic::Ordering::Relaxed);
7076                    }
7077                }
7078            }
7079        }
7080        Ok(())
7081    }
7082
7083    fn table_for_redo(&mut self, name: &str) -> Result<&mut Table, StorageError> {
7084        self.get_mut(name)
7085            .ok_or_else(|| StorageError::Corrupt(alloc::format!("redo: unknown table {name:?}")))
7086    }
7087
7088    /// v7.34 (crash-recovery P0 #2) — enable row-level redo capture on
7089    /// every table (the engine calls this before a mutating statement
7090    /// when persistence is on; idempotent, keeps any in-flight capture).
7091    pub fn enable_redo_all(&mut self) {
7092        for t in &mut self.tables {
7093            t.enable_redo();
7094        }
7095    }
7096
7097    /// v7.34 — drain the row-level redo captured across all tables, in
7098    /// table order then per-table apply order, and stop capturing. The
7099    /// engine calls this after a successful mutating statement and writes
7100    /// the returned [`RowChange`]s to the WAL in place of the SQL text.
7101    pub fn drain_redo(&mut self) -> Vec<RowChange> {
7102        let mut all = Vec::new();
7103        for t in &mut self.tables {
7104            all.extend(t.take_redo());
7105        }
7106        all
7107    }
7108
7109    pub fn table_count(&self) -> usize {
7110        self.tables.len()
7111    }
7112
7113    /// v7.14.0 — remove a table by name. Returns `true` when the
7114    /// table existed (and is now gone), `false` when it didn't.
7115    /// Used by `DROP TABLE` from pg_dump / mysqldump preambles
7116    /// where the dump re-creates schema and starts with
7117    /// `DROP TABLE IF EXISTS`.
7118    pub fn drop_table(&mut self, name: &str) -> bool {
7119        // v7.39 (round 436) — resolve through the session's temp namespace
7120        // first, exactly as a read would: MariaDB's plain `DROP TABLE tmp`
7121        // drops the TEMPORARY one and leaves a permanent namesake standing
7122        // (measured). Removing by the raw name would have dropped the
7123        // permanent table out from under every other session.
7124        let key = match self.temp_prefix.as_ref() {
7125            Some(p) => {
7126                let mangled = alloc::format!("{p}{name}");
7127                if self.by_name.contains_key(&mangled) {
7128                    mangled
7129                } else {
7130                    name.into()
7131                }
7132            }
7133            None => name.into(),
7134        };
7135        let Some(idx) = self.by_name.remove(&key) else {
7136            return false;
7137        };
7138        // v7.39 (round 496) — see `dirty_tables`. Recorded under the
7139        // RESOLVED key, which is what a commit-time merge looks up.
7140        self.dirty_tables.insert(key.clone());
7141        // swap_remove invalidates the trailing index → rebuild
7142        // by_name for affected entries.
7143        self.tables.swap_remove(idx);
7144        // Re-stamp moved table's index slot in by_name.
7145        if idx < self.tables.len() {
7146            let moved_name = self.tables[idx].schema.name.clone();
7147            self.by_name.insert(moved_name, idx);
7148        }
7149        true
7150    }
7151
7152    /// v7.16.2 — rename a table (mailrs round-10 A.5). Updates
7153    /// the schema name, the catalog name → index map, and
7154    /// rewrites every reference dangling at the table name:
7155    ///   * every FK on every OTHER table whose `parent_table`
7156    ///     pointed at the old name now points at the new
7157    ///     name, so FK enforcement keeps working
7158    ///   * every trigger watching the table updates its `table`
7159    ///     field
7160    /// Returns `Ok` on success; `Err(StorageError::TableNotFound)`
7161    /// when the old name isn't in the catalog and
7162    /// `Err(StorageError::DuplicateTable)` when the new name is
7163    /// already taken.
7164    pub fn rename_table(&mut self, old: &str, new: &str) -> Result<(), StorageError> {
7165        if old == new {
7166            return Ok(());
7167        }
7168        if self.by_name.contains_key(new) {
7169            return Err(StorageError::Corrupt(format!(
7170                "rename_table: target name {new:?} already exists"
7171            )));
7172        }
7173        let idx = self
7174            .by_name
7175            .remove(old)
7176            .ok_or_else(|| StorageError::TableNotFound { name: old.into() })?;
7177        self.tables[idx].schema.name = new.to_string();
7178        self.by_name.insert(new.to_string(), idx);
7179        for t in &mut self.tables {
7180            for fk in &mut t.schema.foreign_keys {
7181                if fk.parent_table == old {
7182                    fk.parent_table = new.to_string();
7183                }
7184            }
7185        }
7186        for trig in &mut self.triggers {
7187            if trig.table == old {
7188                trig.table = new.to_string();
7189            }
7190        }
7191        Ok(())
7192    }
7193
7194    /// v7.16.2 — rename an index by name. Walks every table
7195    /// since the index lives on its owning table; updates the
7196    /// name in place. Errors with `IndexNotFound` when no
7197    /// index matches. mailrs round-10 A.5.
7198    pub fn rename_index(&mut self, old: &str, new: &str) -> Result<(), StorageError> {
7199        if old == new {
7200            return Ok(());
7201        }
7202        // Reject the new name if it already exists anywhere.
7203        for t in &self.tables {
7204            if t.indices.iter().any(|i| i.name == new) {
7205                return Err(StorageError::Corrupt(format!(
7206                    "rename_index: target name {new:?} already exists"
7207                )));
7208            }
7209        }
7210        for t in &mut self.tables {
7211            for i in &mut t.indices {
7212                if i.name == old {
7213                    i.name = new.to_string();
7214                    return Ok(());
7215                }
7216            }
7217        }
7218        Err(StorageError::IndexNotFound { name: old.into() })
7219    }
7220
7221    /// v7.14.0 — remove a named index across the catalog.
7222    /// Returns `true` when found + dropped.
7223    pub fn drop_named_index(&mut self, name: &str) -> bool {
7224        for t in &mut self.tables {
7225            let before = t.indices.len();
7226            t.indices.retain(|i| i.name != name);
7227            if t.indices.len() != before {
7228                return true;
7229            }
7230        }
7231        false
7232    }
7233
7234    /// Borrow-free copy of every table's name in catalog order
7235    /// (= insertion order, matching the on-disk encoding).
7236    pub fn table_names(&self) -> Vec<String> {
7237        self.tables.iter().map(|t| t.schema.name.clone()).collect()
7238    }
7239
7240    /// v7.39 (round 436) — the marker every session's temporary-table
7241    /// namespace starts with. Public so the catalog synths can tell a
7242    /// temp table from an ordinary one without knowing the session id.
7243    pub const TEMP_NAME_MARKER: &'static str = "__spg_temp_";
7244
7245    /// v7.39 (round 437) — how a stored table name should appear to the
7246    /// CALLING session in a catalog listing (SHOW TABLES, pg_class,
7247    /// information_schema, …):
7248    ///   * an ordinary table → its own name
7249    ///   * this session's temporary table → its logical name, prefix stripped
7250    ///   * another session's temporary table → `None`, i.e. not listed
7251    ///
7252    /// Measured on both oracles: MariaDB 11 and PG 18 each list the calling
7253    /// session's own temporary tables and neither lists anybody else's.
7254    /// Round 436 stored temp tables under a prefix without teaching the
7255    /// listings about it, so the mangled names leaked to every client.
7256    #[must_use]
7257    pub fn listed_name<'a>(&self, stored: &'a str) -> Option<&'a str> {
7258        if !stored.starts_with(Self::TEMP_NAME_MARKER) {
7259            return Some(stored);
7260        }
7261        let prefix = self.temp_prefix.as_ref()?;
7262        stored.strip_prefix(prefix.as_str())
7263    }
7264
7265    /// The listing names of every table this session may see, in catalog
7266    /// order. See [`Catalog::listed_name`].
7267    #[must_use]
7268    pub fn visible_table_names(&self) -> Vec<String> {
7269        self.tables
7270            .iter()
7271            .filter_map(|t| self.listed_name(&t.schema.name).map(String::from))
7272            .collect()
7273    }
7274
7275    /// v5.1: register a cold-tier segment that already lives in
7276    /// memory (caller did the file read). Returns the
7277    /// `segment_id` that `RowLocator::Cold { segment_id, .. }`
7278    /// will reference — currently this is just the index into
7279    /// `cold_segments`, but treat it as an opaque token.
7280    ///
7281    /// Storage is `no_std`, so file I/O is the caller's
7282    /// responsibility — `spg-server` reads the file and forwards
7283    /// the bytes here. The bytes stay resident in the catalog
7284    /// for the life of the `Catalog`, parsed only once.
7285    pub fn load_segment_bytes(&mut self, bytes: Vec<u8>) -> Result<u32, StorageError> {
7286        let id = u32::try_from(self.cold_segments.len()).map_err(|_| {
7287            StorageError::Corrupt("cold segment count would exceed u32::MAX".into())
7288        })?;
7289        let seg = OwnedSegment::from_bytes(bytes)
7290            .map_err(|e| StorageError::Corrupt(format!("cold segment parse failed: {e}")))?;
7291        self.cold_segments.push(Some(Arc::new(seg)));
7292        Ok(id)
7293    }
7294
7295    /// v6.7.3 — register a cold-tier segment at a specific id. Used
7296    /// by the spg-server manifest-boot path so segments whose
7297    /// neighbouring ids were retired by compaction still get back
7298    /// the same `segment_id` they had pre-restart (the
7299    /// `RowLocator::Cold { segment_id }` baked into the BTree-index
7300    /// snapshot persists across restart and must continue to
7301    /// resolve).
7302    ///
7303    /// Pads the Vec with `None` slots up to `target_id` if needed.
7304    /// Errors when the target slot is already occupied (would
7305    /// stomp another segment), the parse fails, or `target_id`
7306    /// exceeds `u32::MAX`.
7307    pub fn load_segment_bytes_at(
7308        &mut self,
7309        target_id: u32,
7310        bytes: Vec<u8>,
7311    ) -> Result<(), StorageError> {
7312        let seg = OwnedSegment::from_bytes(bytes)
7313            .map_err(|e| StorageError::Corrupt(format!("cold segment parse failed: {e}")))?;
7314        let idx = target_id as usize;
7315        while self.cold_segments.len() <= idx {
7316            self.cold_segments.push(None);
7317        }
7318        if self.cold_segments[idx].is_some() {
7319            return Err(StorageError::Corrupt(format!(
7320                "load_segment_bytes_at: segment_id {target_id} already occupied"
7321            )));
7322        }
7323        self.cold_segments[idx] = Some(Arc::new(seg));
7324        Ok(())
7325    }
7326
7327    /// v6.7.3 — retire a cold-tier segment slot (compaction-driven).
7328    /// The physical file is the caller's concern (typically kept
7329    /// on disk until the next CHECKPOINT writes a manifest that
7330    /// no longer lists it); this just flips the in-memory slot
7331    /// to `None` so later cold lookups for `segment_id` resolve
7332    /// as "unknown" instead of returning a stale row.
7333    ///
7334    /// No-op when the slot is already `None`. Errors only when
7335    /// `segment_id` is out of bounds.
7336    pub fn tombstone_segment(&mut self, segment_id: u32) -> Result<(), StorageError> {
7337        let idx = segment_id as usize;
7338        if idx >= self.cold_segments.len() {
7339            return Err(StorageError::Corrupt(format!(
7340                "tombstone_segment: segment_id {segment_id} out of bounds (len={})",
7341                self.cold_segments.len()
7342            )));
7343        }
7344        self.cold_segments[idx] = None;
7345        Ok(())
7346    }
7347
7348    /// Number of *active* (non-tombstoned) cold segments.
7349    #[must_use]
7350    pub fn cold_segment_count(&self) -> usize {
7351        self.cold_segments.iter().filter(|s| s.is_some()).count()
7352    }
7353
7354    /// v7.37.42 (docker-fair SCALARSQ attack 3) — short-circuit guard
7355    /// for scan loops that conditionally walk the cold tier. Returns
7356    /// `false` when the catalog has never loaded a cold segment (or all
7357    /// segments are tombstoned), so callers can skip the per-table cold
7358    /// PK-index walk entirely on hot-only databases. O(N segments);
7359    /// typical N is small (single-digit) so the check is sub-µs.
7360    #[must_use]
7361    pub fn has_any_cold_segments(&self) -> bool {
7362        self.cold_segments.iter().any(Option::is_some)
7363    }
7364
7365    /// Slot count including tombstones (= the next id the
7366    /// no-arg `load_segment_bytes` would allocate).
7367    #[must_use]
7368    pub fn cold_segment_slot_count(&self) -> usize {
7369        self.cold_segments.len()
7370    }
7371
7372    /// v6.2.7 — list every *active* cold-tier segment id known to
7373    /// this catalog (skips compaction tombstones since v6.7.3).
7374    /// Used by EXPLAIN ANALYZE to annotate scan nodes with the
7375    /// segments they could have walked.
7376    #[must_use]
7377    pub fn cold_segment_ids_global(&self) -> Vec<u32> {
7378        self.cold_segments
7379            .iter()
7380            .enumerate()
7381            .filter_map(|(i, s)| s.as_ref().map(|_| i as u32))
7382            .collect()
7383    }
7384
7385    /// v5.2.1: sum of `Table::hot_bytes` across every table. The v5.2
7386    /// freezer compares this against `SPG_HOT_TIER_BYTES` (parsed at
7387    /// server startup; default 4 GiB) and wakes when the budget is
7388    /// crossed. Pre-freezer (v5.2.1) this is measurement-only — the
7389    /// counter exposes whether the budget is being approached without
7390    /// triggering any demotion.
7391    #[must_use]
7392    pub fn hot_tier_bytes(&self) -> u64 {
7393        self.tables
7394            .iter()
7395            .map(Table::hot_bytes)
7396            .fold(0u64, u64::saturating_add)
7397    }
7398
7399    /// v5.2.2: freeze the **first** `max_rows` rows of `table_name`'s
7400    /// hot tier into a brand-new cold-tier segment. The named `BTree`
7401    /// index supplies the per-row PK (its column must be an integer
7402    /// type — v5.2.2 only supports `IndexKey::Int` PKs, matching the
7403    /// `index_key_as_u64` constraint used by the cold-tier lookup
7404    /// path). On success returns a [`FreezeReport`] with the
7405    /// freshly-allocated segment id, the count of rows that moved,
7406    /// the encoded segment bytes (so the caller can persist them to
7407    /// disk for later reload via `SPG_PRELOAD_COLD_SEGMENT`), and the
7408    /// hot-tier byte delta that was reclaimed.
7409    ///
7410    /// **Semantics**:
7411    /// 1. The first `max_rows` rows (by hot-tier position — same as
7412    ///    insertion order under v4.39 `PersistentVec`) are read.
7413    /// 2. Rows are sorted ascending by PK and serialised into a new
7414    ///    segment via [`encode_segment`].
7415    /// 3. The hot rows are dropped via [`Table::delete_rows`]; the
7416    ///    `rebuild_indices` it triggers regenerates `Hot` locators
7417    ///    for every remaining row (their positions shift down by
7418    ///    `max_rows`). Existing `Cold` locators in this index — from
7419    ///    a previous freeze — are also rebuilt **but with empty
7420    ///    payload** since rebuild reads only `self.rows`; this
7421    ///    routine re-registers them at the end of the call so the
7422    ///    user-visible state preserves all prior cold locators.
7423    /// 4. The new segment is loaded into `self.cold_segments` via
7424    ///    [`Catalog::load_segment_bytes`] (allocating a fresh
7425    ///    `segment_id`). New `Cold` locators are registered on the
7426    ///    named index — one per frozen row.
7427    ///
7428    /// **v5.2.2 limits** (relaxed in later sub-versions):
7429    /// - INSERT-only flow: subsequent UPDATE/DELETE on a frozen row
7430    ///   returns a stale-locator error (no promote-on-write until
7431    ///   v5.2.3).
7432    /// - Single-table scope: callers iterate tables themselves.
7433    /// - All-or-nothing: returns `Err` and leaves catalog unchanged
7434    ///   if any step fails before the atomic swap point.
7435    ///
7436    /// Errors:
7437    /// - [`StorageError::Corrupt`] for missing table/index, non-`BTree`
7438    ///   index, non-integer PK column, `max_rows == 0`, or
7439    ///   `max_rows > row_count`.
7440    /// - The encoder's [`SegmentError`] surfaces as `Corrupt` (the
7441    ///   only realistic source is "a single row is larger than the
7442    ///   page size"; SPG schemas don't hit it in practice).
7443    pub fn freeze_oldest_to_cold(
7444        &mut self,
7445        table_name: &str,
7446        index_name: &str,
7447        max_rows: usize,
7448    ) -> Result<FreezeReport, StorageError> {
7449        // --- validation phase: never mutates ---------------------
7450        if max_rows == 0 {
7451            return Err(StorageError::Corrupt(
7452                "freeze_oldest_to_cold: max_rows must be > 0".into(),
7453            ));
7454        }
7455        let table = self.get(table_name).ok_or_else(|| {
7456            StorageError::Corrupt(format!(
7457                "freeze_oldest_to_cold: table {table_name:?} not found"
7458            ))
7459        })?;
7460        if max_rows > table.rows.len() {
7461            return Err(StorageError::Corrupt(format!(
7462                "freeze_oldest_to_cold: max_rows {max_rows} > row_count {}",
7463                table.rows.len()
7464            )));
7465        }
7466        let idx = table
7467            .indices
7468            .iter()
7469            .find(|i| i.name == index_name)
7470            .ok_or_else(|| {
7471                StorageError::Corrupt(format!(
7472                    "freeze_oldest_to_cold: index {index_name:?} not found on {table_name:?}"
7473                ))
7474            })?;
7475        if !matches!(idx.kind, IndexKind::BTree(_)) {
7476            return Err(StorageError::Corrupt(format!(
7477                "freeze_oldest_to_cold: index {index_name:?} is NSW; only BTree indices may freeze"
7478            )));
7479        }
7480        let column_position = idx.column_position;
7481
7482        // --- segment build phase: reads only --------------------
7483        let schema = table.schema.clone();
7484        let mut to_freeze: Vec<(u64, Vec<u8>, IndexKey)> = Vec::with_capacity(max_rows);
7485        for row_idx in 0..max_rows {
7486            let row = table.rows.get(row_idx).expect("bounds-checked above");
7487            let key = IndexKey::from_value(&row.values[column_position]).ok_or_else(|| {
7488                StorageError::Corrupt(format!(
7489                    "freeze_oldest_to_cold: row {row_idx} has NULL / non-key value in index column"
7490                ))
7491            })?;
7492            let pk_u64 = index_key_as_u64(&key).ok_or_else(|| {
7493                StorageError::Corrupt(format!(
7494                    "freeze_oldest_to_cold: index {index_name:?} column type is non-integer; \
7495                     v5.2.2 cold tier requires IndexKey::Int (Text PK lands in v5.5+)"
7496                ))
7497            })?;
7498            to_freeze.push((pk_u64, encode_row_body_dense(row, &schema), key));
7499        }
7500        // encode_segment requires ascending u64 keys. Sort by PK
7501        // before encoding; the caller's row-position order is not
7502        // necessarily PK order (e.g. workloads that insert random
7503        // PKs).
7504        to_freeze.sort_by_key(|(k, _, _)| *k);
7505        // Reject duplicate PKs — encode_segment also rejects them
7506        // (`SegmentError::UnsortedKey`), but the resulting error
7507        // message there is misleading. Surface a clearer one.
7508        for w in to_freeze.windows(2) {
7509            if w[0].0 == w[1].0 {
7510                return Err(StorageError::Corrupt(format!(
7511                    "freeze_oldest_to_cold: duplicate PK {} in freeze batch",
7512                    w[0].0
7513                )));
7514            }
7515        }
7516        // Snapshot the (key, locator) pairs that will be registered
7517        // post-swap. Cloning the IndexKey out before the move makes
7518        // the registration loop borrow-free.
7519        let post_swap_keys: Vec<IndexKey> = to_freeze.iter().map(|(_, _, k)| k.clone()).collect();
7520        // Segment encode is now infallible w.r.t. ordering. Map the
7521        // `SegmentError` into a `StorageError::Corrupt` so the
7522        // public surface stays one error type.
7523        let seg_rows: Vec<(u64, Vec<u8>)> = to_freeze
7524            .into_iter()
7525            .map(|(k, body, _)| (k, body))
7526            .collect();
7527        let frozen_rows = seg_rows.len();
7528        let (seg_bytes, _meta) = encode_segment(seg_rows.into_iter(), 0.01, SEGMENT_PAGE_BYTES)
7529            .map_err(|e| StorageError::Corrupt(format!("freeze_oldest_to_cold: encode: {e}")))?;
7530
7531        // --- atomic swap phase: mutations only past this point ---
7532        // v5.2.3 made `Table::rebuild_indices` preserve every Cold
7533        // locator across the per-table rebuild, so `delete_rows`
7534        // below no longer wipes prior-freeze cold entries. The pre-
7535        // v5.2.3 capture-then-re-register that used to live here
7536        // was removed in v5.3.1 — keeping it would double-count
7537        // every prior-frozen key's Cold locator on each subsequent
7538        // freeze.
7539        let bytes_before = self.get(table_name).expect("just validated").hot_bytes();
7540        let positions: Vec<usize> = (0..max_rows).collect();
7541        let t_mut = self
7542            .get_mut(table_name)
7543            .expect("just validated; still present");
7544        let removed = t_mut.delete_rows(&positions);
7545        debug_assert_eq!(removed, max_rows, "delete_rows count matches request");
7546        let bytes_after = t_mut.hot_bytes();
7547        let bytes_freed = bytes_before.saturating_sub(bytes_after);
7548
7549        let segment_id = self
7550            .load_segment_bytes(seg_bytes.clone())
7551            .map_err(|e| StorageError::Corrupt(format!("freeze_oldest_to_cold: load: {e}")))?;
7552        let new_cold = post_swap_keys.into_iter().map(|k| {
7553            (
7554                k,
7555                RowLocator::Cold {
7556                    segment_id,
7557                    page_offset: 0,
7558                },
7559            )
7560        });
7561        let t_mut = self.get_mut(table_name).expect("still present");
7562        t_mut.register_cold_locators(index_name, new_cold)?;
7563        // r944 — a freeze has to say that it froze something.
7564        //
7565        // `has_cold_rows_fast()` reads the cached count, and neither
7566        // freeze path touched it, so afterwards it answered "no cold
7567        // rows" while cold rows existed. That predicate gates four join
7568        // paths, and a gate that wrongly declines the cold-aware path
7569        // drops the frozen rows from the answer.
7570        //
7571        // Marking it stale rather than adding to it: stale reads as
7572        // true, which is the safe direction, and this function cannot
7573        // know the exact total (rows may already have been cold). ANALYZE
7574        // recomputes the number.
7575        t_mut.mark_cold_row_count_stale();
7576
7577        Ok(FreezeReport {
7578            segment_id,
7579            frozen_rows,
7580            bytes_freed,
7581            segment_bytes: seg_bytes,
7582        })
7583    }
7584
7585    /// v5.1: borrow the cold segment at `segment_id`. Used by the
7586    /// spg-server preload path to enumerate (key, locator) pairs
7587    /// after loading a segment, so it can call
7588    /// [`Table::register_cold_locators`] without re-parsing the
7589    /// bytes.
7590    #[must_use]
7591    pub fn cold_segment(&self, segment_id: u32) -> Option<&OwnedSegment> {
7592        self.cold_segments
7593            .get(segment_id as usize)
7594            .and_then(|s| s.as_deref())
7595    }
7596
7597    /// v5.1: resolve a single `RowLocator::Cold` to its underlying
7598    /// `Row`. Decoupled from [`Catalog::lookup_by_pk`] so callers
7599    /// iterating a multi-locator slice (e.g. the engine's index
7600    /// seek path) can dispatch per locator instead of getting back
7601    /// only the first row for a key. Returns `None` when the
7602    /// segment isn't registered, the key isn't `u64`-coercible, or
7603    /// the segment doesn't actually carry the key (bloom or page-
7604    /// index reject).
7605    pub fn resolve_cold_locator(
7606        &self,
7607        table_name: &str,
7608        segment_id: u32,
7609        key: &IndexKey,
7610    ) -> Option<Row<'static>> {
7611        let t = self.get(table_name)?;
7612        let u64_key = index_key_as_u64(key)?;
7613        let seg = self.cold_segments.get(segment_id as usize)?.as_ref()?;
7614        let payload = seg.lookup(u64_key)?;
7615        let (row, _) = decode_row_body_dense(&payload, &t.schema, seg.codec_version()).ok()?;
7616        // v7.39 (pg_stat blks knife) — one cold-tier "block read".
7617        self.cold_read_stats
7618            .cold_reads
7619            .fetch_add(1, core::sync::atomic::Ordering::Relaxed);
7620        Some(row)
7621    }
7622
7623    /// v5.1: indexed PK lookup that dispatches per locator,
7624    /// returning the first matching row from either the hot tier
7625    /// (`Table::rows`) or a registered cold segment.
7626    ///
7627    /// The cold path requires the index column to be coercible to
7628    /// a `u64` (the segment's PK type) and the segment payload to
7629    /// be a [`encode_row_body_dense`]-encoded row body for the
7630    /// same schema. v5.1 ships this for BIGINT / INT / SMALLINT
7631    /// PKs; other types fall through to hot-only behavior.
7632    ///
7633    /// Returns `None` if (a) the table or index doesn't exist,
7634    /// (b) the key isn't in the index at all, or (c) the key was
7635    /// resolved to a stale locator (Hot index out of range, Cold
7636    /// segment id unknown, segment lookup miss). Does not surface
7637    /// segment-decode errors — those would indicate corrupted
7638    /// cold-tier files and should be caught at
7639    /// [`Catalog::load_segment_bytes`] time.
7640    pub fn lookup_by_pk(&self, table: &str, index_name: &str, key: &IndexKey) -> Option<Row<'_>> {
7641        let t = self.get(table)?;
7642        let idx = t.indices.iter().find(|i| i.name == index_name)?;
7643        let locators = idx.lookup_eq(key);
7644        let cold_u64_key = index_key_as_u64(key);
7645        for loc in locators {
7646            match *loc {
7647                RowLocator::Hot(i) => {
7648                    if let Some(row) = t.rows.get(i) {
7649                        return Some(row.clone());
7650                    }
7651                }
7652                RowLocator::Cold {
7653                    segment_id,
7654                    page_offset: _,
7655                } => {
7656                    let Some(u64_key) = cold_u64_key else {
7657                        // Key type not coercible to u64 — cold tier
7658                        // only handles BIGINT/INT/SMALLINT in v5.1.
7659                        continue;
7660                    };
7661                    let Some(seg) = self
7662                        .cold_segments
7663                        .get(segment_id as usize)
7664                        .and_then(|s| s.as_deref())
7665                    else {
7666                        // v6.7.3 — `None` slot = compaction
7667                        // retired this segment; the live locator
7668                        // on a freshly-compacted index points to
7669                        // the merged segment_id, so a Cold hit
7670                        // here against a tombstone means the BTree
7671                        // entry hasn't been swapped yet (mid-
7672                        // compaction reader race) or the caller is
7673                        // looking up a stale snapshot. Skip — the
7674                        // next locator in the list, if any, is
7675                        // typically the merged segment.
7676                        continue;
7677                    };
7678                    let Some(payload) = seg.lookup(u64_key) else {
7679                        continue;
7680                    };
7681                    let (row, _) =
7682                        decode_row_body_dense(&payload, &t.schema, seg.codec_version()).ok()?;
7683                    return Some(row);
7684                }
7685            }
7686        }
7687        None
7688    }
7689
7690    /// v5.2.3: promote a frozen row back to the hot tier so an
7691    /// UPDATE / DELETE can mutate it. Reads the cold-tier row body
7692    /// (decoded from its registered segment), pushes it into
7693    /// `table.rows` via [`Table::insert`] (which also adds a fresh
7694    /// `Hot(new_idx)` locator on `index_name`), then retires the
7695    /// shadowed `Cold` locator via
7696    /// [`Table::remove_cold_locators_for_key`]. The cold-tier row
7697    /// in the segment file becomes garbage — recoverable when a
7698    /// future cold-segment compaction job lands.
7699    ///
7700    /// Returns:
7701    /// - `Ok(Some(new_hot_idx))` when the key resolved through a
7702    ///   cold locator and the promote completed. `new_hot_idx` is
7703    ///   the position the row now occupies in `table.rows`.
7704    /// - `Ok(None)` when the key has no Cold locator on the index
7705    ///   (already hot, or wasn't present at all). Callers treat this
7706    ///   as "nothing to do here, fall back to the hot-only path".
7707    ///
7708    /// Errors when the table / index doesn't exist, the index isn't
7709    /// `BTree`, the cold segment is missing / can't decode the row,
7710    /// or the inferred row body fails `Table::insert` validation.
7711    pub fn promote_cold_row(
7712        &mut self,
7713        table_name: &str,
7714        index_name: &str,
7715        key: &IndexKey,
7716    ) -> Result<Option<usize>, StorageError> {
7717        let cold_loc = self.find_cold_locator(table_name, index_name, key)?;
7718        let Some((segment_id, _page_offset)) = cold_loc else {
7719            return Ok(None);
7720        };
7721        let u64_key = index_key_as_u64(key).ok_or_else(|| {
7722            StorageError::Corrupt(
7723                "promote_cold_row: key type not coercible to u64 (cold tier requires integer PK)"
7724                    .into(),
7725            )
7726        })?;
7727        // Read the row body from the segment. Borrow the segment +
7728        // schema short-term so we can then take `&mut self` for the
7729        // hot-side insert.
7730        let schema = self
7731            .get(table_name)
7732            .ok_or_else(|| {
7733                StorageError::Corrupt(format!("promote_cold_row: table {table_name:?} not found"))
7734            })?
7735            .schema
7736            .clone();
7737        let seg = self
7738            .cold_segments
7739            .get(segment_id as usize)
7740            .and_then(|s| s.as_ref())
7741            .ok_or_else(|| {
7742                StorageError::Corrupt(format!(
7743                    "promote_cold_row: segment {segment_id} not registered on catalog"
7744                ))
7745            })?;
7746        let payload = seg.lookup(u64_key).ok_or_else(|| {
7747            StorageError::Corrupt(format!(
7748                "promote_cold_row: key {u64_key} resolves to segment {segment_id} \
7749                 but the segment's bloom/page lookup didn't return a row"
7750            ))
7751        })?;
7752        let (row, _consumed) = decode_row_body_dense(&payload, &schema, seg.codec_version())?;
7753        // Insert the promoted row into the hot tier. `Table::insert`
7754        // appends to `self.rows`, adds a `Hot(new_idx)` locator to
7755        // every BTree index covering the row's keyed columns, and
7756        // increments `hot_bytes`.
7757        let t = self
7758            .get_mut(table_name)
7759            .expect("table existed at lookup time");
7760        t.insert(row)?;
7761        let new_hot_idx =
7762            t.rows.len().checked_sub(1).ok_or_else(|| {
7763                StorageError::Corrupt("promote_cold_row: empty after insert".into())
7764            })?;
7765        // The hot insert added Hot(new_idx) alongside the still-
7766        // present Cold locator. Drop the Cold entry so future
7767        // lookups return only the fresh hot row.
7768        t.remove_cold_locators_for_key(index_name, key)?;
7769        Ok(Some(new_hot_idx))
7770    }
7771
7772    /// v5.2.3: shadow a frozen row's index entry. Used by DELETE
7773    /// when the row to remove lives in a cold-tier segment — the
7774    /// row body stays in the segment file (becoming garbage) but
7775    /// every `Cold` locator for `key` on `index_name` is removed
7776    /// so PK lookups stop returning it.
7777    ///
7778    /// Returns the number of cold locators retired (0 when the key
7779    /// has no cold entries — the DELETE fell on a hot row or a
7780    /// key that was already absent). Errors when the table /
7781    /// index doesn't exist or the index isn't `BTree`.
7782    ///
7783    /// Cold-segment compaction (which merges shadowed-heavy
7784    /// segments and reclaims their disk footprint) lands in a
7785    /// later v5.x sub-version; until then, repeated UPDATE/DELETE
7786    /// of cold rows can amplify cold-segment disk usage by up to
7787    /// 1-2× — still well under typical LSM-tree shadowing because
7788    /// SPG segments are bulk-baked, not write-merged.
7789    pub fn shadow_cold_row(
7790        &mut self,
7791        table_name: &str,
7792        index_name: &str,
7793        key: &IndexKey,
7794    ) -> Result<usize, StorageError> {
7795        let t = self.get_mut(table_name).ok_or_else(|| {
7796            StorageError::Corrupt(format!("shadow_cold_row: table {table_name:?} not found"))
7797        })?;
7798        t.remove_cold_locators_for_key(index_name, key)
7799    }
7800
7801    /// v6.7.4 — read-only slice preparation for the parallel
7802    /// freezer. Walks rows in `row_range`, builds the
7803    /// `(pk_u64, encoded_body, IndexKey)` triples that the
7804    /// coordinator's k-way merge consumes, sorts the slice by
7805    /// `pk_u64`, and returns a [`FreezeSlice`].
7806    ///
7807    /// Caller invariants:
7808    /// - `row_range.end <= table.rows.len()` (caller's job to
7809    ///   compute the partition).
7810    /// - All slices passed to `commit_freeze_slices` must cover a
7811    ///   contiguous half-open range `[0, total_max_rows)` with no
7812    ///   gaps and no overlaps. The coordinator validates this
7813    ///   invariant before committing.
7814    ///
7815    /// `&self`-only — multiple workers can run this concurrently
7816    /// against the same `Catalog` reference under the engine's
7817    /// write lock (workers don't mutate; the coordinator does).
7818    pub fn prepare_freeze_slice(
7819        &self,
7820        table_name: &str,
7821        index_name: &str,
7822        row_range: core::ops::Range<usize>,
7823    ) -> Result<FreezeSlice, StorageError> {
7824        let table = self.get(table_name).ok_or_else(|| {
7825            StorageError::Corrupt(format!(
7826                "prepare_freeze_slice: table {table_name:?} not found"
7827            ))
7828        })?;
7829        let idx = table
7830            .indices
7831            .iter()
7832            .find(|i| i.name == index_name)
7833            .ok_or_else(|| {
7834                StorageError::Corrupt(format!(
7835                    "prepare_freeze_slice: index {index_name:?} not found on {table_name:?}"
7836                ))
7837            })?;
7838        if !matches!(idx.kind, IndexKind::BTree(_)) {
7839            return Err(StorageError::Corrupt(format!(
7840                "prepare_freeze_slice: index {index_name:?} is NSW; only BTree indices may freeze"
7841            )));
7842        }
7843        if row_range.end > table.rows.len() {
7844            return Err(StorageError::Corrupt(format!(
7845                "prepare_freeze_slice: row_range end {} > row_count {}",
7846                row_range.end,
7847                table.rows.len()
7848            )));
7849        }
7850        let column_position = idx.column_position;
7851        let schema = table.schema.clone();
7852        let mut rows: Vec<(u64, Vec<u8>, IndexKey)> = Vec::with_capacity(row_range.len());
7853        for row_idx in row_range.clone() {
7854            let row = table.rows.get(row_idx).expect("bounds-checked above");
7855            let key = IndexKey::from_value(&row.values[column_position]).ok_or_else(|| {
7856                StorageError::Corrupt(format!(
7857                    "prepare_freeze_slice: row {row_idx} has NULL / non-key value in index column"
7858                ))
7859            })?;
7860            let pk_u64 = index_key_as_u64(&key).ok_or_else(|| {
7861                StorageError::Corrupt(format!(
7862                    "prepare_freeze_slice: index {index_name:?} column type is non-integer; \
7863                     v5.2.2 cold tier requires IndexKey::Int (Text PK lands in v5.5+)"
7864                ))
7865            })?;
7866            rows.push((pk_u64, encode_row_body_dense(row, &schema), key));
7867        }
7868        rows.sort_by_key(|(k, _, _)| *k);
7869        Ok(FreezeSlice { row_range, rows })
7870    }
7871
7872    /// v6.7.4 — coordinator commit step. Merges N
7873    /// [`FreezeSlice`]s into one segment via the standard
7874    /// [`encode_segment`] path, atomically swaps the catalog
7875    /// state (delete the union row range + register Cold
7876    /// locators + load the segment).
7877    ///
7878    /// Validates that the slices cover a contiguous, gap-free,
7879    /// overlap-free half-open range starting at index 0 (the
7880    /// freezer always freezes "oldest first" — same semantics as
7881    /// the single-threaded [`Catalog::freeze_oldest_to_cold`]).
7882    ///
7883    /// Empty `slices` → no-op success (returns a zero-row report
7884    /// without mutating). Total row count = `Σ slice.rows.len()`.
7885    pub fn commit_freeze_slices(
7886        &mut self,
7887        table_name: &str,
7888        index_name: &str,
7889        slices: Vec<FreezeSlice>,
7890    ) -> Result<FreezeReport, StorageError> {
7891        // --- validation phase: never mutates ---------------------
7892        let table = self.get(table_name).ok_or_else(|| {
7893            StorageError::Corrupt(format!(
7894                "commit_freeze_slices: table {table_name:?} not found"
7895            ))
7896        })?;
7897        let idx = table
7898            .indices
7899            .iter()
7900            .find(|i| i.name == index_name)
7901            .ok_or_else(|| {
7902                StorageError::Corrupt(format!(
7903                    "commit_freeze_slices: index {index_name:?} not found on {table_name:?}"
7904                ))
7905            })?;
7906        if !matches!(idx.kind, IndexKind::BTree(_)) {
7907            return Err(StorageError::Corrupt(format!(
7908                "commit_freeze_slices: index {index_name:?} is NSW; only BTree indices may freeze"
7909            )));
7910        }
7911        // Validate slice coverage: contiguous from 0, no gaps, no
7912        // overlaps. Allow the caller to pass slices in any order —
7913        // sort by row_range.start first.
7914        let mut ordered = slices;
7915        ordered.sort_by_key(|s| s.row_range.start);
7916        // Drop fully-empty slices that fell out of an uneven
7917        // partition; they carry no data but contribute to the
7918        // contiguity check, so keep them in line.
7919        let mut expected_start = 0usize;
7920        for s in &ordered {
7921            if s.row_range.start != expected_start {
7922                return Err(StorageError::Corrupt(format!(
7923                    "commit_freeze_slices: gap/overlap at row {}; expected start {}",
7924                    s.row_range.start, expected_start
7925                )));
7926            }
7927            expected_start = s.row_range.end;
7928        }
7929        let max_rows = expected_start;
7930        if max_rows > table.rows.len() {
7931            return Err(StorageError::Corrupt(format!(
7932                "commit_freeze_slices: total row range {} exceeds row_count {}",
7933                max_rows,
7934                table.rows.len()
7935            )));
7936        }
7937        if max_rows == 0 {
7938            return Ok(FreezeReport {
7939                segment_id: u32::MAX,
7940                frozen_rows: 0,
7941                bytes_freed: 0,
7942                segment_bytes: Vec::new(),
7943            });
7944        }
7945
7946        // --- segment build phase: reads only --------------------
7947        // K-way merge of already-sorted slices. Each slice's rows
7948        // are ascending by pk_u64; we keep a per-slice cursor and
7949        // pull the next-smallest head until every cursor drains.
7950        let total_rows: usize = ordered.iter().map(|s| s.rows.len()).sum();
7951        if total_rows != max_rows {
7952            return Err(StorageError::Corrupt(format!(
7953                "commit_freeze_slices: total slice rows {total_rows} ≠ row_range coverage {max_rows}"
7954            )));
7955        }
7956        let mut cursors: Vec<usize> = alloc::vec![0; ordered.len()];
7957        let mut merged: Vec<(u64, Vec<u8>, IndexKey)> = Vec::with_capacity(total_rows);
7958        loop {
7959            // Pick the slice whose head row has the smallest key
7960            // and isn't yet exhausted.
7961            let mut pick: Option<usize> = None;
7962            for (i, c) in cursors.iter().enumerate() {
7963                let slice = &ordered[i];
7964                if *c >= slice.rows.len() {
7965                    continue;
7966                }
7967                match pick {
7968                    None => pick = Some(i),
7969                    Some(j) => {
7970                        if slice.rows[*c].0 < ordered[j].rows[cursors[j]].0 {
7971                            pick = Some(i);
7972                        }
7973                    }
7974                }
7975            }
7976            let Some(i) = pick else { break };
7977            let row = ordered[i].rows[cursors[i]].clone();
7978            cursors[i] += 1;
7979            merged.push(row);
7980        }
7981        // Reject duplicate PKs — same error as the single-threaded
7982        // path so callers get a uniform surface.
7983        for w in merged.windows(2) {
7984            if w[0].0 == w[1].0 {
7985                return Err(StorageError::Corrupt(format!(
7986                    "commit_freeze_slices: duplicate PK {} across slices",
7987                    w[0].0
7988                )));
7989            }
7990        }
7991        let post_swap_keys: Vec<IndexKey> = merged.iter().map(|(_, _, k)| k.clone()).collect();
7992        let seg_rows: Vec<(u64, Vec<u8>)> =
7993            merged.into_iter().map(|(k, body, _)| (k, body)).collect();
7994        let frozen_rows = seg_rows.len();
7995        let (seg_bytes, _meta) = encode_segment(seg_rows.into_iter(), 0.01, SEGMENT_PAGE_BYTES)
7996            .map_err(|e| StorageError::Corrupt(format!("commit_freeze_slices: encode: {e}")))?;
7997
7998        // --- atomic swap phase: mutations only past this point ---
7999        let bytes_before = self.get(table_name).expect("just validated").hot_bytes();
8000        let positions: Vec<usize> = (0..max_rows).collect();
8001        let t_mut = self
8002            .get_mut(table_name)
8003            .expect("just validated; still present");
8004        let removed = t_mut.delete_rows(&positions);
8005        debug_assert_eq!(removed, max_rows, "delete_rows count matches request");
8006        let bytes_after = t_mut.hot_bytes();
8007        let bytes_freed = bytes_before.saturating_sub(bytes_after);
8008
8009        let segment_id = self
8010            .load_segment_bytes(seg_bytes.clone())
8011            .map_err(|e| StorageError::Corrupt(format!("commit_freeze_slices: load: {e}")))?;
8012        let new_cold = post_swap_keys.into_iter().map(|k| {
8013            (
8014                k,
8015                RowLocator::Cold {
8016                    segment_id,
8017                    page_offset: 0,
8018                },
8019            )
8020        });
8021        let t_mut = self.get_mut(table_name).expect("still present");
8022        t_mut.register_cold_locators(index_name, new_cold)?;
8023        // r944 — a freeze has to say that it froze something.
8024        //
8025        // `has_cold_rows_fast()` reads the cached count, and neither
8026        // freeze path touched it, so afterwards it answered "no cold
8027        // rows" while cold rows existed. That predicate gates four join
8028        // paths, and a gate that wrongly declines the cold-aware path
8029        // drops the frozen rows from the answer.
8030        //
8031        // Marking it stale rather than adding to it: stale reads as
8032        // true, which is the safe direction, and this function cannot
8033        // know the exact total (rows may already have been cold). ANALYZE
8034        // recomputes the number.
8035        t_mut.mark_cold_row_count_stale();
8036
8037        Ok(FreezeReport {
8038            segment_id,
8039            frozen_rows,
8040            bytes_freed,
8041            segment_bytes: seg_bytes,
8042        })
8043    }
8044
8045    /// v6.7.3 — compact every cold segment on `(table, index)` whose
8046    /// `OwnedSegment::bytes().len()` is below `target_segment_bytes`
8047    /// into a single larger merged segment. Rows present in source
8048    /// segment payloads but no longer referenced by any
8049    /// `RowLocator::Cold` on the index (DELETE'd + frozen rows
8050    /// retired via [`Catalog::shadow_cold_row`]) are GC'd in the
8051    /// merge.
8052    ///
8053    /// **Semantics**:
8054    /// 1. Walk the BTree index to collect every Cold locator that
8055    ///    targets a small (< threshold) segment. Each such
8056    ///    `(key, segment_id)` becomes a row in the merged segment;
8057    ///    payload is looked up from the source segment in-place.
8058    /// 2. Encode the collected rows into one new segment via
8059    ///    [`encode_segment`]; register it via
8060    ///    [`Catalog::load_segment_bytes`] (allocating a fresh
8061    ///    `merged_segment_id` at the end of `cold_segments`).
8062    /// 3. Rewrite the BTree index in one pass: every
8063    ///    `RowLocator::Cold { segment_id ∈ sources }` becomes
8064    ///    `RowLocator::Cold { segment_id = merged_id, page_offset = 0 }`.
8065    ///    Hot locators are untouched.
8066    /// 4. Tombstone every source slot via
8067    ///    [`Catalog::tombstone_segment`]. Source segment payloads
8068    ///    are no longer reachable through the catalog; the on-disk
8069    ///    files are the caller's concern.
8070    ///
8071    /// On fewer than 2 candidate segments the catalog is **not**
8072    /// mutated and a no-op report (`merged_segment_id: None`,
8073    /// `sources: []`) is returned. This is the routine case — a
8074    /// freshly-frozen table has at most 1 small segment, no merge
8075    /// possible.
8076    ///
8077    /// Atomicity: every mutating step runs after the read-only
8078    /// gather phase, so a panic before the merge encode leaves the
8079    /// catalog unchanged. The mutation block itself (load + rewrite +
8080    /// tombstone) takes only `&mut self` — callers serialise the
8081    /// engine write lock outside this function.
8082    ///
8083    /// Errors when the table / index doesn't exist, the index isn't
8084    /// `BTree`, the index column type isn't u64-coercible (cold-tier
8085    /// pre-condition), or a source segment fails its in-place
8086    /// row-body lookup (would indicate prior catalog corruption).
8087    pub fn compact_cold_segments(
8088        &mut self,
8089        table_name: &str,
8090        index_name: &str,
8091        target_segment_bytes: u64,
8092    ) -> Result<CompactReport, StorageError> {
8093        // --- validation phase ----------------------------------
8094        let t = self.get(table_name).ok_or_else(|| {
8095            StorageError::Corrupt(format!(
8096                "compact_cold_segments: table {table_name:?} not found"
8097            ))
8098        })?;
8099        let idx = t
8100            .indices
8101            .iter()
8102            .find(|i| i.name == index_name)
8103            .ok_or_else(|| {
8104                StorageError::Corrupt(format!(
8105                    "compact_cold_segments: index {index_name:?} not found on {table_name:?}"
8106                ))
8107            })?;
8108        let map = match &idx.kind {
8109            IndexKind::BTree(m) => m,
8110            IndexKind::Nsw(_)
8111            | IndexKind::Brin { .. }
8112            | IndexKind::Gin(_)
8113            | IndexKind::GinTrgm(_)
8114            | IndexKind::GinFulltext(_)
8115            | IndexKind::GinJsonb(_)
8116            | IndexKind::BTreeMulti(_) => {
8117                return Err(StorageError::Corrupt(format!(
8118                    "compact_cold_segments: index {index_name:?} is not BTree; \
8119                     compaction applies only to BTree cold-tier indices"
8120                )));
8121            }
8122        };
8123
8124        // --- gather phase --------------------------------------
8125        // Step A: every segment_id this BTree index Cold-references.
8126        let mut referenced_ids: BTreeSet<u32> = BTreeSet::new();
8127        for (_key, locators) in map.iter() {
8128            for loc in locators {
8129                if let RowLocator::Cold { segment_id, .. } = loc {
8130                    referenced_ids.insert(*segment_id);
8131                }
8132            }
8133        }
8134        // Step B: keep only the small + still-active ones.
8135        let candidate_set: BTreeSet<u32> = referenced_ids
8136            .into_iter()
8137            .filter(|id| {
8138                self.cold_segments
8139                    .get(*id as usize)
8140                    .and_then(|s| s.as_deref())
8141                    .is_some_and(|s| (s.bytes().len() as u64) < target_segment_bytes)
8142            })
8143            .collect();
8144        if candidate_set.len() < 2 {
8145            return Ok(CompactReport {
8146                sources: Vec::new(),
8147                merged_segment_id: None,
8148                merged_segment_bytes: Vec::new(),
8149                merged_rows: 0,
8150                deleted_rows_pruned: 0,
8151                bytes_reclaimed_estimate: 0,
8152            });
8153        }
8154        // Step C: pre-count source rows for the deleted-pruned metric.
8155        let mut source_row_count: usize = 0;
8156        let mut source_byte_total: u64 = 0;
8157        for &id in &candidate_set {
8158            let seg = self.cold_segments[id as usize]
8159                .as_ref()
8160                .expect("candidate selected only when slot is Some");
8161            source_row_count = source_row_count.saturating_add(seg.meta().num_rows as usize);
8162            source_byte_total = source_byte_total.saturating_add(seg.bytes().len() as u64);
8163        }
8164        // Step D: collect (key, body) pairs from every live Cold
8165        // locator pointing at a candidate. dedupe by key — one
8166        // BTree key resolves to at most one cold payload (the
8167        // freezer + promote/shadow flow keeps Cold locators
8168        // unique per key).
8169        let mut collected: BTreeMap<u64, (Vec<u8>, IndexKey)> = BTreeMap::new();
8170        for (key, locators) in map.iter() {
8171            for loc in locators {
8172                let RowLocator::Cold { segment_id, .. } = loc else {
8173                    continue;
8174                };
8175                if !candidate_set.contains(segment_id) {
8176                    continue;
8177                }
8178                let u64_key = index_key_as_u64(key).ok_or_else(|| {
8179                    StorageError::Corrupt(format!(
8180                        "compact_cold_segments: index {index_name:?} has non-integer Cold key; \
8181                         cold tier requires IndexKey::Int (Text PK lands in v5.5+)"
8182                    ))
8183                })?;
8184                let seg = self.cold_segments[*segment_id as usize]
8185                    .as_ref()
8186                    .expect("candidate slot guaranteed Some above");
8187                let payload = seg.lookup(u64_key).ok_or_else(|| {
8188                    StorageError::Corrupt(format!(
8189                        "compact_cold_segments: BTree {index_name:?} points key={u64_key} \
8190                         at segment {segment_id} but the segment lookup missed"
8191                    ))
8192                })?;
8193                collected.insert(u64_key, (payload, key.clone()));
8194                break;
8195            }
8196        }
8197        let merged_rows = collected.len();
8198        let deleted_rows_pruned = source_row_count.saturating_sub(merged_rows);
8199
8200        // Step E: encode the merged segment. `BTreeMap<u64, _>`
8201        // iteration is ascending by key, which is what
8202        // `encode_segment` requires.
8203        let seg_rows: Vec<(u64, Vec<u8>)> = collected
8204            .iter()
8205            .map(|(k, (body, _))| (*k, body.clone()))
8206            .collect();
8207        let (seg_bytes, _meta) = encode_segment(seg_rows.into_iter(), 0.01, SEGMENT_PAGE_BYTES)
8208            .map_err(|e| StorageError::Corrupt(format!("compact_cold_segments: encode: {e}")))?;
8209        let merged_bytes_len = seg_bytes.len() as u64;
8210
8211        // --- atomic mutation phase ------------------------------
8212        let merged_segment_id = self
8213            .load_segment_bytes(seg_bytes.clone())
8214            .map_err(|e| StorageError::Corrupt(format!("compact_cold_segments: load: {e}")))?;
8215
8216        // Rewrite the BTree index: every Cold locator pointing at
8217        // a candidate source becomes a Cold locator pointing at
8218        // the merged segment. Use a flat collect-then-replace
8219        // pattern so we never hold a `&self` borrow across the
8220        // `&mut self` write.
8221        let entries: Vec<(IndexKey, crate::posting::PostingList)> = {
8222            let t = self
8223                .get(table_name)
8224                .expect("table existed at the start of this fn");
8225            let idx = t
8226                .indices
8227                .iter()
8228                .find(|i| i.name == index_name)
8229                .expect("index existed at the start of this fn");
8230            let IndexKind::BTree(map) = &idx.kind else {
8231                unreachable!("validated above");
8232            };
8233            map.iter().map(|(k, v)| (k.clone(), v.clone())).collect()
8234        };
8235        let t_mut = self
8236            .get_mut(table_name)
8237            .expect("table existed at the start of this fn");
8238        let idx_mut = t_mut
8239            .indices
8240            .iter_mut()
8241            .find(|i| i.name == index_name)
8242            .expect("index existed at the start of this fn");
8243        let IndexKind::BTree(map_mut) = &mut idx_mut.kind else {
8244            unreachable!("validated above");
8245        };
8246        for (key, locators) in entries {
8247            let mut new_locs = crate::posting::PostingList::new();
8248            let mut changed = false;
8249            for loc in &locators {
8250                match *loc {
8251                    RowLocator::Cold {
8252                        segment_id,
8253                        page_offset: _,
8254                    } if candidate_set.contains(&segment_id) => {
8255                        let replacement = RowLocator::Cold {
8256                            segment_id: merged_segment_id,
8257                            page_offset: 0,
8258                        };
8259                        if !new_locs.contains(replacement) {
8260                            new_locs.push(replacement);
8261                        }
8262                        changed = true;
8263                    }
8264                    other => new_locs.push(other),
8265                }
8266            }
8267            if changed {
8268                map_mut.insert_mut(key, new_locs);
8269            }
8270        }
8271
8272        // Tombstone every source slot. Last step — failures here
8273        // would leave the segment double-referenced in both
8274        // memory + manifest, but `tombstone_segment` only errors
8275        // on out-of-bounds, which we've already validated.
8276        for &id in &candidate_set {
8277            self.tombstone_segment(id)?;
8278        }
8279
8280        let bytes_reclaimed_estimate = source_byte_total.saturating_sub(merged_bytes_len);
8281        Ok(CompactReport {
8282            sources: candidate_set.into_iter().collect(),
8283            merged_segment_id: Some(merged_segment_id),
8284            merged_segment_bytes: seg_bytes,
8285            merged_rows,
8286            deleted_rows_pruned,
8287            bytes_reclaimed_estimate,
8288        })
8289    }
8290
8291    /// Internal helper: scan `(table, index)` for a `Cold` locator
8292    /// keyed by `key`. Returns `Ok(Some((segment_id, page_offset)))`
8293    /// when found, `Ok(None)` when the key has only hot entries
8294    /// or no entries at all, `Err` on the same input-validation
8295    /// errors as the public `promote_cold_row` / `shadow_cold_row`.
8296    fn find_cold_locator(
8297        &self,
8298        table_name: &str,
8299        index_name: &str,
8300        key: &IndexKey,
8301    ) -> Result<Option<(u32, u32)>, StorageError> {
8302        let t = self.get(table_name).ok_or_else(|| {
8303            StorageError::Corrupt(format!("find_cold_locator: table {table_name:?} not found"))
8304        })?;
8305        let idx = t
8306            .indices
8307            .iter()
8308            .find(|i| i.name == index_name)
8309            .ok_or_else(|| {
8310                StorageError::Corrupt(format!(
8311                    "find_cold_locator: index {index_name:?} not found on {table_name:?}"
8312                ))
8313            })?;
8314        if !matches!(idx.kind, IndexKind::BTree(_)) {
8315            return Err(StorageError::Corrupt(format!(
8316                "find_cold_locator: index {index_name:?} is NSW; promote-on-write only applies to BTree indices"
8317            )));
8318        }
8319        for loc in idx.lookup_eq(key) {
8320            if let RowLocator::Cold {
8321                segment_id,
8322                page_offset,
8323            } = *loc
8324            {
8325                return Ok(Some((segment_id, page_offset)));
8326            }
8327        }
8328        Ok(None)
8329    }
8330}
8331
8332/// Coerce an [`IndexKey`] to the `u64` that v5.1 cold-tier
8333/// segments use as their on-disk PK. Returns `None` for keys that
8334/// aren't representable as `u64` — Text PKs need a hash mapping
8335/// the segment writer baked in (deferred to v5.2+), Bool PKs are
8336/// almost never wide enough to be sharded into a cold tier.
8337fn index_key_as_u64(key: &IndexKey) -> Option<u64> {
8338    match key {
8339        // Reinterpret the i64 bit pattern as u64. Cold-tier segments
8340        // are sorted by this u64 view, so the chosen interpretation
8341        // only has to match between insert (bake_segment / freezer)
8342        // and lookup — using cast_unsigned keeps both sides honest
8343        // and silences clippy::cast_sign_loss.
8344        IndexKey::Int(n) => Some(n.cast_unsigned()),
8345        // Text / Bool / Uuid / Bytes / Numeric PKs aren't representable
8346        // as u64 and so can't participate in the u64-sorted cold-tier
8347        // segment PK layout. Same deferral story as Text — lookup falls
8348        // through the in-memory btree.
8349        IndexKey::Text(_)
8350        | IndexKey::Bool(_)
8351        | IndexKey::Uuid(_)
8352        | IndexKey::Bytes(_)
8353        | IndexKey::Numeric(_)
8354        | IndexKey::Null => None,
8355    }
8356}
8357
8358#[derive(Debug, Clone, PartialEq, Eq)]
8359#[non_exhaustive]
8360pub enum StorageError {
8361    DuplicateTable {
8362        name: String,
8363    },
8364    TableNotFound {
8365        name: String,
8366    },
8367    ArityMismatch {
8368        expected: usize,
8369        actual: usize,
8370    },
8371    TypeMismatch {
8372        column: String,
8373        expected: DataType,
8374        actual: DataType,
8375        position: usize,
8376    },
8377    NullInNotNull {
8378        column: String,
8379    },
8380    /// Index with this name already exists on the table.
8381    DuplicateIndex {
8382        name: String,
8383    },
8384    /// Column referenced by an index doesn't exist on the table.
8385    ColumnNotFound {
8386        column: String,
8387    },
8388    /// On-disk format failed to parse — corrupted file, wrong magic, truncated
8389    /// payload, or unknown tag bytes.
8390    Corrupt(String),
8391    /// v6.0.4 — ALTER INDEX targeted an index name that doesn't
8392    /// exist on any table in this catalog.
8393    IndexNotFound {
8394        name: String,
8395    },
8396    /// v6.0.4 — operation requested isn't supported on this index
8397    /// kind / column type (e.g. ALTER INDEX REBUILD on a `BTree`
8398    /// index, or REBUILD WITH (encoding=…) on a non-vector column).
8399    Unsupported(String),
8400    /// v7.39 (round 220) — a CYCLE-less sequence ran past its bound.
8401    /// PG's 2200H phrasing: `nextval: reached maximum value of
8402    /// sequence "s" (n)` (`is_max: false` = the MINVALUE direction).
8403    SequenceExhausted {
8404        name: String,
8405        limit: i64,
8406        is_max: bool,
8407    },
8408}
8409
8410impl fmt::Display for StorageError {
8411    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
8412        match self {
8413            // v7.39 (read01 round 47) — PG's 42P07 wording.
8414            Self::DuplicateTable { name } => write!(f, "relation \"{name}\" already exists"),
8415            // v7.39 (read01 round 47) — PG's wording for a missing relation
8416            // (42P01). DROP TABLE says "table" and raises its own error at
8417            // the engine; every other path (SELECT / ALTER / …) says
8418            // "relation", which is what this carries.
8419            Self::TableNotFound { name } => write!(f, "relation \"{name}\" does not exist"),
8420            Self::ArityMismatch { expected, actual } => write!(
8421                f,
8422                "row arity mismatch: expected {expected} columns, got {actual}"
8423            ),
8424            Self::TypeMismatch {
8425                column,
8426                expected,
8427                actual,
8428                position,
8429            } => write!(
8430                f,
8431                "type mismatch in column {column:?} (position {position}): expected {expected}, got {actual}"
8432            ),
8433            Self::NullInNotNull { column } => {
8434                // v7.39 (SQLSTATE fidelity) — PG's 23502 phrasing (the
8435                // relation-qualified long form is added by engine call
8436                // sites that know the table name).
8437                write!(
8438                    f,
8439                    "null value in column \"{column}\" violates not-null constraint"
8440                )
8441            }
8442            // v7.39 (read01 round 47) — an index is a relation to PG (42P07).
8443            Self::DuplicateIndex { name } => write!(f, "relation \"{name}\" already exists"),
8444            // v7.39 (round 701) — PG's wording, and the same fix `EvalError::
8445            // ColumnNotFound` took in read01 round 81 with the same reason:
8446            // "column not found: x" matches none of the wire layer's `does
8447            // not exist` patterns, so a missing column reached the client as
8448            // the generic error class. The eval-side variant was changed and
8449            // the storage-side one was not, so which sentence you got
8450            // depended on which layer noticed — `CREATE INDEX ix ON t(nope)`
8451            // came out of storage and kept the old spelling.
8452            Self::ColumnNotFound { column } => write!(f, "column \"{column}\" does not exist"),
8453            Self::Corrupt(detail) => write!(f, "corrupt on-disk format: {detail}"),
8454            Self::IndexNotFound { name } => write!(f, "index \"{name}\" does not exist"),
8455            Self::Unsupported(detail) => write!(f, "unsupported: {detail}"),
8456            // v7.39 (round 220) — PG's exact 2200H wording.
8457            Self::SequenceExhausted {
8458                name,
8459                limit,
8460                is_max,
8461            } => write!(
8462                f,
8463                "nextval: reached {} value of sequence \"{name}\" ({limit})",
8464                if *is_max { "maximum" } else { "minimum" }
8465            ),
8466        }
8467    }
8468}
8469
8470impl ColumnSchema {
8471    pub fn new(name: impl Into<String>, ty: DataType, nullable: bool) -> Self {
8472        Self {
8473            name: name.into(),
8474            ty,
8475            nullable,
8476            collation_name: None,
8477            default: None,
8478            runtime_default: None,
8479            auto_increment: false,
8480            user_enum_type: None,
8481            user_domain_type: None,
8482            user_composite_type: None,
8483            acl: Vec::new(),
8484            on_update_runtime: None,
8485            collation: Collation::Binary,
8486            is_unsigned: false,
8487            inline_enum_variants: None,
8488            inline_set_variants: None,
8489            generated_stored_expr: None,
8490            identity_always: false,
8491            default_text: None,
8492            auto_restart: None,
8493            scalar_row_source: false,
8494            mysql_int_width: None,
8495            mysql_fsp: None,
8496        }
8497    }
8498
8499    /// Builder-style helper to attach a default value to an otherwise
8500    /// plain column schema. Used by the engine when CREATE TABLE
8501    /// specifies `column TYPE DEFAULT <expr>`.
8502    #[must_use]
8503    pub fn with_default(mut self, default: Value<'static>) -> Self {
8504        self.default = Some(default);
8505        self
8506    }
8507
8508    /// v7.9.21 — builder for runtime-evaluated defaults
8509    /// (`DEFAULT now()`, `DEFAULT CURRENT_TIMESTAMP`, …).
8510    /// `expr` is the Expr's `Display` form, re-parsed by the
8511    /// engine at each INSERT.
8512    #[must_use]
8513    pub fn with_runtime_default(mut self, expr: impl Into<String>) -> Self {
8514        self.runtime_default = Some(expr.into());
8515        self
8516    }
8517
8518    /// Builder-style helper to mark a column as `AUTO_INCREMENT`.
8519    #[must_use]
8520    pub const fn with_auto_increment(mut self) -> Self {
8521        self.auto_increment = true;
8522        self
8523    }
8524}
8525
8526impl TableSchema {
8527    pub fn new(name: impl Into<String>, columns: Vec<ColumnSchema>) -> Self {
8528        Self {
8529            name: name.into(),
8530            columns,
8531            hot_tier_bytes: None,
8532            foreign_keys: Vec::new(),
8533            uniqueness_constraints: Vec::new(),
8534            exclusion_constraints: Vec::new(),
8535            checks: Vec::new(),
8536            partition_role: None,
8537            policies: Vec::new(),
8538            row_security: false,
8539            force_row_security: false,
8540            owner: None,
8541            acl: Vec::new(),
8542        }
8543    }
8544}
8545
8546// =========================================================================
8547// Persistent binary format for the catalog.
8548//
8549// Layout (little-endian throughout):
8550//
8551//   [magic "SPGDB001" 8 bytes][version u8]
8552//   [table_count u32]
8553//   for each table:
8554//       [name_len u16][name bytes]
8555//       [col_count u16]
8556//       for each col:
8557//           [name_len u16][name bytes]
8558//           [type_tag u8 + optional payload]
8559//               1=Int 2=BigInt 3=Float 4=Text 5=Bool
8560//               6=Vector(u32 dim)
8561//               7=SmallInt
8562//               8=Varchar(u32 max)
8563//               9=Char(u32 size)
8564//               10=Numeric(u8 precision, u8 scale)
8565//               11=Date
8566//               12=Timestamp
8567//           [nullable u8]   0/1
8568//           [default_tag u8] 0=none 1=value (followed by [value_tag u8] + bytes)
8569//       [row_count u32]
8570//       for each row, for each col, one [value_tag u8] + value bytes:
8571//           tag 0 (Null)     → no body
8572//           tag 1 (Int)      → i32 LE
8573//           tag 2 (BigInt)   → i64 LE
8574//           tag 3 (Float)    → f64 LE
8575//           tag 4 (Text)     → u16 LE len + UTF-8 bytes
8576//           tag 5 (Bool)     → u8 0/1
8577//           tag 6 (Vector)   → u32 LE dim + dim×f32 LE
8578//           tag 7 (SmallInt) → i16 LE
8579//           tag 8 (Numeric)  → i128 LE (16 bytes) + u8 scale
8580//           tag 9 (Date)     → i32 LE (days since Unix epoch)
8581//           tag 10 (Timestamp) → i64 LE (microseconds since Unix epoch)
8582//
8583// Bumped to version 3 when NUMERIC was added; to version 4 when
8584// AUTO_INCREMENT (per-column flag) + NSW index `kind` byte landed;
8585// to version 5 when DATE / TIMESTAMP were added; to version 6 when
8586// NSW graph topology started travelling on disk (v2.7); to version 7
8587// when the NSW topology became multi-layer HNSW (v2.13); to version 8
8588// when row encoding switched to schema-driven dense layout (v3.0.2 —
8589// per-row NULL bitmap + per-column fixed-width body, no per-cell type
8590// tag).
8591// =========================================================================
8592
8593const FILE_MAGIC: &[u8; 8] = b"SPGDB001";
8594/// Current catalog snapshot format version emitted by [`Catalog::serialize`].
8595///
8596/// v9 (v5.2) extends v8 by serialising `BTree` index entries directly — every
8597/// `(IndexKey, Vec<RowLocator>)` pair travels on disk with the v5.1
8598/// `RowLocator::write_le` tag-prefixed codec. v8 `BTree` indices stored no
8599/// entries at all (the map was rebuilt from `Table::rows` on load); v9
8600/// preserves on-disk Cold locators so freezer-produced cold-tier index
8601/// entries survive a catalog snapshot round-trip. v8 readers are accepted
8602/// by version dispatch in [`Catalog::deserialize`] — every entry decodes
8603/// as `RowLocator::Hot(_)` via `add_index` rebuild, identical to v5.1
8604/// behaviour.
8605/// v6.7.2 — bumped from 10 to 11 to append per-table
8606/// `hot_tier_bytes: Option<u64>` after the per-table indices
8607/// section. v10 catalogs (v6.7.1) load with `hot_tier_bytes =
8608/// None` for every table (the deserialiser short-circuits when
8609/// version < 11). v11 snapshots written by a pre-v6.7.2 binary
8610/// fail loudly at the version check, matching the v6.1.2 /
8611/// v6.1.4 / v6.2.0 / v6.7.1 envelope-bump upgrade fences.
8612///
8613/// v6.8.0 — bumped from 11 to 12: per-index
8614/// `included_columns: Vec<u16>` appended at the tail of each
8615/// index payload. v11 (= v6.7.2) catalogs load with
8616/// `included_columns = Vec::new()` for every index — same
8617/// "older readers, append-only extension" pattern as the v6.7.2
8618/// hot_tier_bytes byte.
8619/// v7.13.0 — bumped from 22 to 23. mailrs round-5 G3 / G10.
8620/// Per-table appendix gains two new sections:
8621///   * `checks: Vec<String>` — CHECK predicate sources (Display
8622///     form of the AST Expr); re-parsed on INSERT/UPDATE to
8623///     enforce against candidate rows. Same persistence pattern
8624///     as `Index::partial_predicate`.
8625///   * Per `UniquenessConstraint`: trailing `nulls_not_distinct:
8626///     u8` flag for PG 15+ `UNIQUE NULLS NOT DISTINCT (cols)`
8627///     semantics.
8628/// v22 catalogs deserialise with empty `checks` and every UC
8629/// at `nulls_not_distinct = false`.
8630/// v24 introduces:
8631///   * Index kind tag 4 = trigram-GIN (`gin_trgm_ops`-flavoured
8632///     `USING gin` over a TEXT/VARCHAR column). Payload shape is
8633///     identical to tag-3 GIN (String → Vec<RowLocator>); the
8634///     keys are PG-compatible 3-byte trigram shingles instead of
8635///     tsvector lexemes. v23 catalogs deserialise unchanged — no
8636///     v23 writer ever emitted tag 4.
8637/// v25 introduces:
8638///   * Per `TriggerDef`: trailing `enabled: u8` flag (mailrs
8639///     round-9 A.2.b — `ALTER TABLE … { ENABLE | DISABLE }
8640///     TRIGGER …`). v24 catalogs deserialise with every trigger
8641///     `enabled = true`, matching pre-v7.16.1 behaviour.
8642/// v26 introduces (v7.17.0 Phase 1.1):
8643///   * Trailing SEQUENCE catalog block after triggers. Encoded
8644///     as `u32 count` followed by per-sequence:
8645///     `name`, `data_type: u8` (0=SmallInt,1=Int,2=BigInt),
8646///     `start i64`, `increment i64`, `min_value i64`,
8647///     `max_value i64`, `cache i64`, `cycle u8`,
8648///     `owned_by_tag u8` (0=NONE, 1=Column → `table`,`column`),
8649///     `last_value i64`, `is_called u8`. v25-and-below catalogs
8650///     deserialise with an empty sequences map.
8651/// v27 introduces (v7.17.0 Phase 1.2):
8652///   * Trailing VIEW catalog block after sequences. Encoded as
8653///     `u32 count` followed by per-view:
8654///     `name`, `column_count u16`, then column names, then
8655///     `body` long-string. v26-and-below catalogs deserialise
8656///     with an empty views map.
8657/// v28 introduces (v7.17.0 Phase 1.3):
8658///   * Trailing MATERIALIZED VIEW source registry block after
8659///     views. Encoded as `u32 count` followed by per-entry:
8660///     `name`, `body` long-string. The materialised rows live
8661///     as a regular Table of the same name (already covered by
8662///     the pre-existing tables block). v27-and-below catalogs
8663///     deserialise with an empty map.
8664/// v29 introduces (v7.17.0 Phase 1.4):
8665///   * Per-table user_enum_type appendix (after the CHECK
8666///     appendix). Layout: `u16 count` followed by per-binding
8667///     `[u16 col_pos][str enum_name]`. Only columns whose
8668///     `user_enum_type` is Some land here; the catalog stays
8669///     compact for the common no-enum case.
8670///   * Trailing ENUM types catalog block after materialized
8671///     views. Encoded as `u32 count` followed by per-entry:
8672///     `name`, `u16 label_count`, then `label_count` short
8673///     strings. v28-and-below catalogs deserialise with an
8674///     empty enum_types map and every column's
8675///     `user_enum_type = None`.
8676/// v30 introduces (v7.17.0 Phase 1.5):
8677///   * Per-table user_domain_type appendix (after the
8678///     user_enum_type appendix). Same shape as the enum one.
8679///   * Trailing DOMAIN types catalog block after the enum
8680///     block. Encoded as `u32 count` followed by per-entry:
8681///     `name`, `data_type` byte, `nullable u8`,
8682///     `default_present u8` + optional default string,
8683///     `u16 check_count` then `check_count` Display-form
8684///     CHECK strings. v29-and-below catalogs deserialise with
8685///     an empty domain_types map and `user_domain_type = None`.
8686/// v31 introduces (v7.17.0 Phase 1.6):
8687///   * Trailing user-schemas block after the DOMAIN block.
8688///     Encoded as `u32 count` followed by `count` schema-name
8689///     short strings. Built-in schemas (`public`, `pg_catalog`,
8690///     `information_schema`) are NOT serialised — they're
8691///     hardcoded in `is_builtin_schema`. v30-and-below catalogs
8692///     deserialise with an empty user-schemas set.
8693/// v32 introduces (v7.17.0 Phase 2.1):
8694///   * Per-table on_update_runtime appendix (after the
8695///     user_domain_type appendix). Layout: `u16 count` followed
8696///     by per-binding `[u16 col_pos][str expr_src]`. Only
8697///     columns whose `on_update_runtime` is Some land here;
8698///     the catalog stays compact when no MySQL-shaped table
8699///     uses the attribute. v31-and-below catalogs deserialise
8700///     with every column's `on_update_runtime = None`.
8701/// v33 introduces (v7.17.0 Phase 2.2):
8702///   * Index kind tag 5 = fulltext-GIN (MySQL `FULLTEXT KEY`
8703///     surface over a TEXT / VARCHAR column). Payload shape is
8704///     identical to tag-3 / tag-4 GIN (`String → Vec<RowLocator>`);
8705///     the keys are lower-cased word lexemes (same rule as
8706///     `to_tsvector('simple', text)`). v32 catalogs deserialise
8707///     unchanged — no v32 writer ever emitted tag 5, and FULLTEXT
8708///     KEY was silently dropped pre-v7.17 so no rebuild shim is
8709///     needed for round-tripped catalogs.
8710/// v34 introduces (v7.17.0 Phase 2.5):
8711///   * Per-table collation appendix (after the on_update_runtime
8712///     appendix). Sparse layout: only columns whose `collation`
8713///     is non-Binary land here. `u16 count` then per-binding
8714///     `[u16 col_pos][u8 collation_tag]` where the tag matches
8715///     `Collation::TAG_*`. Snapshots written by v33-and-below
8716///     readers deserialise every column with `collation =
8717///     Binary`, preserving the prior byte-wise compare
8718///     semantics. Unknown tags read back as Binary too — keeps
8719///     a forward-compat path if a future v35 adds variants
8720///     and someone rolls back to a v34 reader.
8721/// v35 introduces (v7.17.0 Phase 4.4):
8722///   * Per-table is_unsigned appendix (after the collation
8723///     appendix). Sparse layout: only `is_unsigned = true`
8724///     columns land. `u16 count` then per-binding `[u16 col_pos]`.
8725///     v34-and-below catalogs deserialise every column as
8726///     `is_unsigned = false`, preserving the prior silent-
8727///     accept behaviour for negative inserts on UNSIGNED columns.
8728/// v46 introduces (v7.23, mailrs round-14):
8729///   * Escaped short-string codec — `write_str` lengths >= 0xFFFF
8730///     emit `[u16 0xFFFF][u32 real_len]` so TEXT cells (mail bodies,
8731///     document text) above 64 KiB encode instead of panicking.
8732///     One-way upgrade: v45-and-below readers reject v46 catalogs
8733///     loudly via the version gate; v46 readers decode v45 catalogs
8734///     with the plain-u16 rules (0xFFFF is a legitimate length
8735///     there).
8736/// v47 introduces (v7.27, mailrs round-21):
8737///   * Escaped lengths for the REMAINING u16-length cell payloads —
8738///     BYTEA cells, TEXT[] elements, tsvector lexemes and tsquery
8739///     terms — the same `[u16 0xFFFF][u32 real_len]` escape v46
8740///     gave short strings. Round-14 fixed TEXT and missed these;
8741///     round-21 fired the BYTEA twin during a production migration.
8742///     One-way upgrade, same posture as v46.
8743/// v48 introduces (v7.37.5 β-P2, sentori cutover window):
8744///   * `INTERVAL` becomes a real column type. Catalog tag 34 in
8745///     `write_data_type`; per-row body is a fixed 16 bytes
8746///     (i64 micros + i32 days + i32 months, LE, PG-byte-equal
8747///     field order). The runtime-only days collapse is gone —
8748///     `'1 day'` and `'24 hours'` are stored distinctly. One-way
8749///     upgrade: v47 catalogs without INTERVAL columns deserialise
8750///     identically; v47 readers fed a v48 catalog that contains
8751///     INTERVAL hit the explicit "unknown data type tag: 34"
8752///     fence in `read_data_type`.
8753/// v49 introduces (v7.37.6-B, sentori Epic 2 P0):
8754///   * Per-table partition role appendix(declarative
8755///     `PARTITION BY RANGE` parent / range child / DEFAULT
8756///     child)。Layout, written **after** the inline_set_variants
8757///     appendix and **before** the per-table block close:
8758///       `[u8 role_tag]`
8759///         0 = `None`(普通表,后向兼容默认)
8760///         1 = `Parent`:  `[u8 kind_tag (0=Range)]`
8761///                        `[u16 key_col_count]` `(× u16 col_pos)`
8762///                        `[u16 tmpl_count]` `(× str source)`
8763///         2 = `Range`:   `[str parent_name]` `[Bound]` `[Bound]`
8764///         3 = `Default`: `[str parent_name]`
8765///     `PartitionBound` codec:
8766///       `[u8 bound_tag]` 0=MinValue 1=MaxValue 2=TimestampTz(`[i64 LE micros]`)
8767///     v48-and-below readers stop after the inline_set_variants
8768///     block — they don't see this appendix and deserialise every
8769///     table with `partition_role = None`. v49 writers always emit
8770///     `[0]` for plain tables, so the encoding stays one-byte-cheap.
8771/// v50 introduces (v7.37.7, sentori Epic 3 P1):
8772///   * Per-table `generated_stored_expr` appendix(stored generated
8773///     columns — `GENERATED ALWAYS AS (<expr>) STORED`)。Layout,
8774///     written **after** the partition_role appendix and before
8775///     the per-table block close:
8776///       `[u16 binding_count]`
8777///       `binding_count × { [u16 col_pos][str expr_source] }`
8778///     Sparse — only generated columns land here, so plain-shape
8779///     catalogs stay byte-for-byte identical save for the new
8780///     u16 zero count. v49-and-below readers stop after the
8781///     partition_role appendix; v50 readers default every column
8782///     to `generated_stored_expr = None` when this block is absent.
8783/// v51 introduces (v7.37.8, sentori Epic 5 P2):
8784///   * Per-index tag byte 6 = `GinJsonb`(real posting-list GIN
8785///     over a JSONB column). Payload shape mirrors tag-3 / 4 / 5:
8786///     `[u32 posting_list_count]` then `(str token, u32 locator_count,
8787///     locators …)` per posting list. Same `write_str` /
8788///     `RowLocator::write_le` codec as the rest of the GIN family.
8789///     v50 catalogs never wrote tag 6(the same DDL loaded as a
8790///     BTree fallback); v51 readers see tag 6 explicitly and dispatch
8791///     into `IndexKind::GinJsonb`.
8792/// v52 introduces (v7.37.42-T2 ζ-B composite + domain metasystem):
8793///   * Trailing COMPOSITE-types catalog block after the
8794///     user-schemas block. Encoded as `u32 count` followed by
8795///     per-entry: `name`, `u16 field_count`, then `field_count`
8796///     `[str field_name][data_type]` pairs (`write_data_type` is
8797///     reused). v51-and-below catalogs deserialise with an empty
8798///     composite_types map; v52 readers tolerate v51 catalogs by
8799///     stopping at the schema block (no composite block present
8800///     ⇒ empty map). Composite types are referenced by columns
8801///     via `ColumnSchema.user_composite_type`, mirroring the
8802///     `user_enum_type` / `user_domain_type` pattern. The block
8803///     lands here (not as a per-table appendix) so dropping the
8804///     composite type registers globally and DROP TYPE can find it
8805///     without a table scan.
8806/// v53 introduces (v7.37.16 Epic W — cross-checkpoint tombstone
8807///   durability):
8808///   * Trailing per-table MVCC appendix carrying, for every row,
8809///     its `RowHeader` (`xmin:u64`, `xmax:u64`, `flags:u8`) and its
8810///     stable `RowId` (`u64`), followed by the relation's
8811///     `next_rowid:u64`. Layout per table (after the v50
8812///     generated_stored_expr block, before the table loop closes):
8813///       `[u32 row_count]` (== `Table::rows().len()`, cross-check)
8814///       per row in physical order:
8815///         `[u64 xmin][u64 xmax][u8 flags][u64 rowid]`
8816///       `[u64 next_rowid]`
8817///     v52-and-below catalogs never wrote this block; their reader
8818///     stops after the last per-table appendix and
8819///     `deserialize_rows` leaves every row `RowHeader::frozen()`
8820///     with dense 1..=N ids — the exact pre-v53 contract. A v53
8821///     reader instead reconstructs headers + ids VERBATIM, so a
8822///     tombstone-redo naming a row inserted before the last
8823///     checkpoint resolves by `RowId` across the base-snapshot
8824///     boundary (closing the coupling the Epic W WAL slices deferred
8825///     to this format bump). Because the reader routes on `version`,
8826///     the block is strictly backward-compatible: old images load
8827///     byte-for-byte as before. `SPG_MVCC_INPLACE` is unaffected —
8828///     a gate-off database's rows are all frozen/alive, so
8829///     persisting + restoring their headers is observationally a
8830///     no-op.
8831/// v7.38 (read01 P5.05) — v54 appends a CRC32C over the whole preceding
8832/// image so a corrupted `base.spg` is caught on load instead of silently
8833/// deserialising garbage. Older images (v8..=53) carry no trailer and load
8834/// unchanged.
8835/// v7.39 (round 210) — v72 appends a per-table EXCLUDE-constraint appendix
8836/// (sparse: only tables carrying an EXCLUDE write it) at the very end of the
8837/// per-table block, after the column-ACL appendix. A v71 reader stops before
8838/// it and its tables read back with no exclusion constraints, which is what
8839/// they were.
8840/// v7.39 (round 220) — v73 appends a per-table identity-RESTART appendix
8841/// (sparse: [u16 count] then per entry [u16 col_pos][i64 LE floor]) after
8842/// the EXCLUDE appendix. A v72 reader stops before it; its columns read
8843/// back with no RESTART floor, losing only an un-consumed
8844/// `ALTER … RESTART WITH` across a restart.
8845/// r1039 — v90 adds index-key tags 4 (bytea) and 5 (the canonical
8846/// numeric key), so BYTEA and NUMERIC columns carry a real B-tree
8847/// instead of falling back to a scan. A v89 reader meeting either tag
8848/// reports a corrupt catalog rather than mis-reading it, which is the
8849/// same forward-compatibility story tag 3 (uuid) had at v36.
8850const FILE_VERSION: u8 = 91;
8851
8852/// v7.37 (round 833) — the codec version to decode a row that
8853/// [`encode_row_body_dense`] has just produced.
8854///
8855/// That encoder always writes the newest form, and every decoder gate is
8856/// a `codec_version >= N` feature test, so a freshly encoded row must be
8857/// read at the current version. Cold segments carry their own version in
8858/// their header and keep passing that; this is for in-process round
8859/// trips — sort runs on temp storage — where the bytes never outlive the
8860/// build that wrote them.
8861pub const CURRENT_ROW_CODEC_VERSION: u8 = FILE_VERSION;
8862/// First version that appends the trailing CRC32C integrity trailer.
8863const FILE_VERSION_CRC_TRAILER: u8 = 54;
8864/// Oldest format version [`Catalog::deserialize`] still accepts. v8 is the
8865/// v3.0.2 dense-row layout; pre-v8 catalogs require an offline migration.
8866const MIN_SUPPORTED_FILE_VERSION: u8 = 8;
8867
8868// IndexKey wire format (v9):
8869//   tag 0 = Int  → [i64 LE]
8870//   tag 1 = Text → [u16 LE len + UTF-8 bytes] (via write_str / read_str)
8871//   tag 2 = Bool → [u8 0/1]
8872const INDEX_KEY_TAG_INT: u8 = 0;
8873const INDEX_KEY_TAG_TEXT: u8 = 1;
8874const INDEX_KEY_TAG_BOOL: u8 = 2;
8875/// v7.17.0 — `IndexKey::Uuid([u8; 16])`. Body = raw 16 bytes
8876/// (RFC 4122 byte order). Persisted only in FILE_VERSION 36+
8877/// catalogs.
8878const INDEX_KEY_TAG_UUID: u8 = 3;
8879/// r1039 — `IndexKey::Bytes`. Body = [u32 LE len][raw bytes].
8880/// Persisted only in FILE_VERSION 90+ catalogs.
8881const INDEX_KEY_TAG_BYTES: u8 = 4;
8882/// r1039 — `IndexKey::Numeric`. Body = [u8 class][u8 neg][i32 LE exp]
8883/// [u32 LE digit count][one byte per decimal digit, 0..=9, MSD first].
8884/// Persisted only in FILE_VERSION 90+ catalogs.
8885const INDEX_KEY_TAG_NUMERIC: u8 = 5;
8886/// v7.38.1 (L12) — `IndexKey::Null`, a NULL component inside a
8887/// composite key. No body. Persisted only inside tag-7 multi-index
8888/// payloads, FILE_VERSION 91+.
8889const INDEX_KEY_TAG_NULL: u8 = 6;
8890
8891impl Catalog {
8892    /// Serialize the whole catalog (schema + every row) into a self-contained
8893    /// byte buffer. Format is documented above the impl block.
8894    pub fn serialize(&self) -> Vec<u8> {
8895        let mut out = Vec::with_capacity(64);
8896        out.extend_from_slice(FILE_MAGIC);
8897        out.push(FILE_VERSION);
8898        write_u32(
8899            &mut out,
8900            u32::try_from(self.tables.len()).expect("≤ 4G tables"),
8901        );
8902        for t in &self.tables {
8903            write_str(&mut out, &t.schema.name);
8904            write_u16(
8905                &mut out,
8906                u16::try_from(t.schema.columns.len()).expect("≤ 65k columns/table"),
8907            );
8908            for c in &t.schema.columns {
8909                write_str(&mut out, &c.name);
8910                write_data_type(&mut out, c.ty);
8911                out.push(u8::from(c.nullable));
8912                match &c.default {
8913                    None => out.push(0),
8914                    Some(v) => {
8915                        out.push(1);
8916                        write_value(&mut out, v);
8917                    }
8918                }
8919                out.push(u8::from(c.auto_increment));
8920            }
8921            write_u32(
8922                &mut out,
8923                u32::try_from(t.rows.len()).expect("≤ 4G rows/table"),
8924            );
8925            // v3.0.2 dense row encoding (FILE_VERSION 8): per-row NULL
8926            // bitmap, then tightly-packed bodies. Identical wire format
8927            // as before — extracted into `encode_row_body_dense` so cold-
8928            // tier segments (v5.1+) can share the encoding.
8929            for row in &t.rows {
8930                out.extend_from_slice(&encode_row_body_dense(row, &t.schema));
8931            }
8932            // Index definitions. Per-index payload:
8933            //   [name][col_pos u16][kind u8]
8934            //     kind 0 = B-tree           (no params — rebuilt on load)
8935            //     kind 1 = NSW graph        (u16 M + serialized graph)
8936            // For NSW the graph topology travels on disk so startup
8937            // doesn't re-run the O(n²M) rebuild — see v2.7 notes.
8938            write_u16(
8939                &mut out,
8940                u16::try_from(t.indices.len()).expect("≤ 65k indices/table"),
8941            );
8942            for idx in &t.indices {
8943                write_str(&mut out, &idx.name);
8944                write_u16(
8945                    &mut out,
8946                    u16::try_from(idx.column_position).expect("≤ 65k columns/table"),
8947                );
8948                match &idx.kind {
8949                    IndexKind::BTree(map) => {
8950                        out.push(0);
8951                        // v9: serialise the full PB map. Each entry's
8952                        // RowLocator list travels with the tag-prefixed
8953                        // codec from `row_locator::write_le`, so freezer-
8954                        // produced Cold locators survive a snapshot
8955                        // round-trip. v8 BTree wrote nothing here and
8956                        // rebuilt from rows — v9 readers tolerate v8 by
8957                        // version dispatch in `Catalog::deserialize`.
8958                        write_u32(
8959                            &mut out,
8960                            u32::try_from(map.len()).expect("≤ 4G index entries/index"),
8961                        );
8962                        for (key, locators) in map {
8963                            write_index_key(&mut out, key);
8964                            write_u32(
8965                                &mut out,
8966                                u32::try_from(locators.len()).expect("≤ 4G locators/key"),
8967                            );
8968                            for loc in locators {
8969                                loc.write_le(&mut out);
8970                            }
8971                        }
8972                    }
8973                    // v7.38.1 (L12) — tag byte 7 = BTreeMulti. Payload
8974                    // mirrors the tag-0 BTree encoding, with each key
8975                    // written as `[u16 arity]` followed by that many
8976                    // `write_index_key` components. FILE_VERSION 91+;
8977                    // older catalogs never carried a multi index, so no
8978                    // migration shim is needed.
8979                    IndexKind::BTreeMulti(map) => {
8980                        out.push(7);
8981                        write_u32(
8982                            &mut out,
8983                            u32::try_from(map.len()).expect("≤ 4G index entries/index"),
8984                        );
8985                        for (key, locators) in map {
8986                            write_u16(
8987                                &mut out,
8988                                u16::try_from(key.len()).expect("≤ 65k key components"),
8989                            );
8990                            for component in key.iter() {
8991                                write_index_key(&mut out, component);
8992                            }
8993                            write_u32(
8994                                &mut out,
8995                                u32::try_from(locators.len()).expect("≤ 4G locators/key"),
8996                            );
8997                            for loc in locators {
8998                                loc.write_le(&mut out);
8999                            }
9000                        }
9001                    }
9002                    IndexKind::Nsw(g) => {
9003                        out.push(1);
9004                        write_u16(&mut out, u16::try_from(g.m).expect("≤ 65k NSW neighbours"));
9005                        write_nsw_graph(&mut out, g);
9006                    }
9007                    IndexKind::Brin { column_type, .. } => {
9008                        // v6.7.1 — tag byte 2 = BRIN. Payload is the
9009                        // column type code (1 byte mapping to the
9010                        // shared DataType numeric encoding); no
9011                        // further data — BRIN summaries live in
9012                        // cold segments, not the catalog.
9013                        out.push(2);
9014                        write_data_type(&mut out, *column_type);
9015                    }
9016                    IndexKind::Gin(map) => {
9017                        // v7.12.3 — tag byte 3 = GIN. Payload mirrors
9018                        // the BTree encoding but with String (lexeme
9019                        // word) keys instead of IndexKey. Tag-prefixed
9020                        // RowLocator codec so freezer-produced Cold
9021                        // locators survive snapshot round-trip.
9022                        // FILE_VERSION 21+; v20 catalogs never wrote a
9023                        // GIN index (the AM degraded to BTree fallback
9024                        // pre-v7.12.3), so no migration shim is needed.
9025                        out.push(3);
9026                        write_u32(
9027                            &mut out,
9028                            u32::try_from(map.len()).expect("≤ 4G GIN posting lists"),
9029                        );
9030                        for (word, locators) in map {
9031                            write_str(&mut out, word);
9032                            write_u32(
9033                                &mut out,
9034                                u32::try_from(locators.len()).expect("≤ 4G locators/posting list"),
9035                            );
9036                            for loc in locators {
9037                                loc.write_le(&mut out);
9038                            }
9039                        }
9040                    }
9041                    IndexKind::GinTrgm(map) => {
9042                        // v7.15.0 — tag byte 4 = GinTrgm
9043                        // (`gin_trgm_ops` GIN over a TEXT column).
9044                        // Payload shape is identical to tag-3 GIN —
9045                        // `String → Vec<RowLocator>` posting lists.
9046                        // The String keys are 3-byte trigrams instead
9047                        // of tsvector lexemes; the deserializer
9048                        // dispatches on the tag, not the key shape.
9049                        // FILE_VERSION 24+; v23 catalogs never wrote
9050                        // a trigram-GIN.
9051                        out.push(4);
9052                        write_u32(
9053                            &mut out,
9054                            u32::try_from(map.len()).expect("≤ 4G trigram-GIN posting lists"),
9055                        );
9056                        for (tri, locators) in map {
9057                            write_str(&mut out, tri);
9058                            write_u32(
9059                                &mut out,
9060                                u32::try_from(locators.len()).expect("≤ 4G locators/posting list"),
9061                            );
9062                            for loc in locators {
9063                                loc.write_le(&mut out);
9064                            }
9065                        }
9066                    }
9067                    IndexKind::GinFulltext(map) => {
9068                        // v7.17.0 Phase 2.2 — tag byte 5 =
9069                        // GinFulltext (MySQL `FULLTEXT KEY` GIN
9070                        // over a TEXT/VARCHAR column). Payload
9071                        // shape mirrors tag-3 / tag-4 GIN —
9072                        // `String → Vec<RowLocator>` posting
9073                        // lists keyed by lower-cased word
9074                        // lexemes. FILE_VERSION 33+; v32 catalogs
9075                        // never wrote a fulltext-GIN (FULLTEXT
9076                        // KEY was silently dropped pre-v7.17).
9077                        out.push(5);
9078                        write_u32(
9079                            &mut out,
9080                            u32::try_from(map.len()).expect("≤ 4G fulltext-GIN posting lists"),
9081                        );
9082                        for (lex, locators) in map {
9083                            write_str(&mut out, lex);
9084                            write_u32(
9085                                &mut out,
9086                                u32::try_from(locators.len()).expect("≤ 4G locators/posting list"),
9087                            );
9088                            for loc in locators {
9089                                loc.write_le(&mut out);
9090                            }
9091                        }
9092                    }
9093                    IndexKind::GinJsonb(map) => {
9094                        // v7.37.8 — tag byte 6 = GinJsonb
9095                        // (real posting-list GIN over a JSONB
9096                        // column; sentori Epic 5 P2). Payload
9097                        // shape mirrors tag-3 / 4 / 5 — keys are
9098                        // the canonical `(path, leaf)` tokens
9099                        // from `jsonb_gin::extract_tokens`.
9100                        // FILE_VERSION 51+; v50 catalogs never
9101                        // wrote a JSONB-GIN (the same DDL loaded
9102                        // as a BTree fallback).
9103                        out.push(6);
9104                        write_u32(
9105                            &mut out,
9106                            u32::try_from(map.len()).expect("≤ 4G JSONB-GIN posting lists"),
9107                        );
9108                        for (token, locators) in map {
9109                            write_str(&mut out, token);
9110                            write_u32(
9111                                &mut out,
9112                                u32::try_from(locators.len()).expect("≤ 4G locators/posting list"),
9113                            );
9114                            for loc in locators {
9115                                loc.write_le(&mut out);
9116                            }
9117                        }
9118                    }
9119                }
9120                // v6.8.0 — included_columns appendix per index.
9121                // Layout: [u16 num_included][num × u16 column_position].
9122                // v11 readers stop before this u16 (deserialise loop
9123                // gated on version >= 12); v12+ readers always
9124                // consume it. Empty Vec serialises as a bare 0u16.
9125                write_u16(
9126                    &mut out,
9127                    u16::try_from(idx.included_columns.len()).expect("≤ 65k INCLUDE columns/index"),
9128                );
9129                for col_pos in &idx.included_columns {
9130                    write_u16(
9131                        &mut out,
9132                        u16::try_from(*col_pos).expect("≤ 65k columns/table"),
9133                    );
9134                }
9135                // v6.8.1 — partial_predicate appendix per index.
9136                // Layout: [u8 has_pred][u16 LE len][bytes (if has_pred)].
9137                // Same v12 gate as included_columns.
9138                match &idx.partial_predicate {
9139                    None => out.push(0),
9140                    Some(pred) => {
9141                        out.push(1);
9142                        write_str(&mut out, pred);
9143                    }
9144                }
9145                // v6.8.2 — expression appendix. Same shape as
9146                // partial_predicate.
9147                match &idx.expression {
9148                    None => out.push(0),
9149                    Some(expr) => {
9150                        out.push(1);
9151                        write_str(&mut out, expr);
9152                    }
9153                }
9154                // v7.9.29 — is_unique appendix (FILE_VERSION 16+).
9155                // Single byte 0/1. v15-and-below readers stop before
9156                // this byte; v16 readers always consume it. mailrs K1.
9157                out.push(u8::from(idx.is_unique));
9158                // v7.9.29 — extra_column_positions appendix.
9159                // Layout: [u16 count][count × u16 column_position].
9160                write_u16(
9161                    &mut out,
9162                    u16::try_from(idx.extra_column_positions.len())
9163                        .expect("≤ 65k extra cols / index"),
9164                );
9165                for cp in &idx.extra_column_positions {
9166                    write_u16(&mut out, u16::try_from(*cp).expect("≤ 65k columns/table"));
9167                }
9168                // v7.39 (read01 round 52) — nulls_not_distinct (FILE_VERSION
9169                // 62+). Appended at the end of the per-index block so the v16
9170                // layout above is untouched; v61-and-below readers stop before
9171                // this byte and default the flag to false (NULLS DISTINCT).
9172                out.push(u8::from(idx.nulls_not_distinct));
9173                // v7.39 (round 537) — the key column's ordering clause
9174                // (FILE_VERSION 83+).
9175                out.push(u8::from(idx.descending));
9176                out.push(match idx.nulls_first {
9177                    None => 0,
9178                    Some(true) => 1,
9179                    Some(false) => 2,
9180                });
9181                // v7.39 (round 538) — the key's explicit collation
9182                // (FILE_VERSION 84+).
9183                match &idx.collation {
9184                    Some(c) => {
9185                        out.push(1);
9186                        write_str(&mut out, c);
9187                    }
9188                    None => out.push(0),
9189                }
9190            }
9191            // v6.7.2 — per-table hot_tier_bytes Option<u64>.
9192            // Layout: [u8 has_value][u64 LE value (if has_value)].
9193            // v10 readers stop before this byte (deserialise loop
9194            // gated on version >= 11); v11+ readers always
9195            // consume it.
9196            match t.schema.hot_tier_bytes {
9197                None => out.push(0),
9198                Some(n) => {
9199                    out.push(1);
9200                    out.extend_from_slice(&n.to_le_bytes());
9201                }
9202            }
9203            // v7.6.1 — FOREIGN KEY appendix (catalog FILE_VERSION 13+).
9204            // Layout: [u16 LE fk_count]
9205            //   per fk:
9206            //     [u8 has_name] [str name (if has_name)]
9207            //     [u16 LE local_arity] [u16 LE local_pos]*arity
9208            //     [str parent_table]
9209            //     [u16 LE parent_arity] [u16 LE parent_pos]*arity
9210            //     [u8 on_delete_tag] [u8 on_update_tag]
9211            // Older catalogs (v12 and below) skip this block entirely;
9212            // their reader stops before this byte.
9213            write_u16(
9214                &mut out,
9215                u16::try_from(t.schema.foreign_keys.len()).expect("≤ 65k FKs/table"),
9216            );
9217            for fk in &t.schema.foreign_keys {
9218                match &fk.name {
9219                    None => out.push(0),
9220                    Some(n) => {
9221                        out.push(1);
9222                        write_str(&mut out, n);
9223                    }
9224                }
9225                write_u16(
9226                    &mut out,
9227                    u16::try_from(fk.local_columns.len()).expect("≤ 65k FK columns"),
9228                );
9229                for &p in &fk.local_columns {
9230                    write_u16(&mut out, u16::try_from(p).expect("≤ 65k columns/table"));
9231                }
9232                write_str(&mut out, &fk.parent_table);
9233                write_u16(
9234                    &mut out,
9235                    u16::try_from(fk.parent_columns.len()).expect("≤ 65k FK parent columns"),
9236                );
9237                for &p in &fk.parent_columns {
9238                    write_u16(&mut out, u16::try_from(p).expect("≤ 65k columns/table"));
9239                }
9240                out.push(fk.on_delete.tag());
9241                out.push(fk.on_update.tag());
9242                // v7.38 (read01, T29) — MATCH type tag (FILE_VERSION 55+).
9243                out.push(fk.match_type.tag());
9244                // v7.39 (round 288) — constraint timing (FILE_VERSION 79+).
9245                // One byte, bit 0 = DEFERRABLE, bit 1 = INITIALLY DEFERRED.
9246                out.push(u8::from(fk.deferrable) | (u8::from(fk.initially_deferred) << 1));
9247            }
9248            // v7.9.19 — UniquenessConstraint appendix (catalog
9249            // FILE_VERSION 15+). Layout per table after the FK
9250            // block:
9251            //   [u16 count]
9252            //     per constraint:
9253            //       [u8 is_primary_key]
9254            //       [u16 arity][u16 col_pos]*arity
9255            // Older catalogs (v14 and below) skip this block.
9256            write_u16(
9257                &mut out,
9258                u16::try_from(t.schema.uniqueness_constraints.len())
9259                    .expect("≤ 65k uniqueness constraints/table"),
9260            );
9261            for uc in &t.schema.uniqueness_constraints {
9262                out.push(u8::from(uc.is_primary_key));
9263                write_u16(
9264                    &mut out,
9265                    u16::try_from(uc.columns.len()).expect("≤ 65k cols in uniqueness constraint"),
9266                );
9267                for &p in &uc.columns {
9268                    write_u16(&mut out, u16::try_from(p).expect("≤ 65k columns/table"));
9269                }
9270                // v7.13.0 — `nulls_not_distinct` flag
9271                // (FILE_VERSION 23+). Always written by writers at
9272                // version 23+; deserialise gates on `version >= 23`
9273                // so v22-and-below catalogs round-trip cleanly.
9274                out.push(u8::from(uc.nulls_not_distinct));
9275            }
9276            // v7.9.21 — runtime_default appendix per table.
9277            // Layout: [u16 count] then for each:
9278            //   [u16 col_pos][str expr]
9279            // Only columns whose runtime_default is Some land here;
9280            // catalog stays compact for the common literal-default
9281            // case.
9282            let mut rt_defaults: Vec<(usize, &str)> = Vec::new();
9283            for (i, c) in t.schema.columns.iter().enumerate() {
9284                if let Some(e) = &c.runtime_default {
9285                    rt_defaults.push((i, e.as_str()));
9286                }
9287            }
9288            write_u16(
9289                &mut out,
9290                u16::try_from(rt_defaults.len()).expect("≤ 65k runtime defaults/table"),
9291            );
9292            for (pos, expr) in rt_defaults {
9293                write_u16(&mut out, u16::try_from(pos).expect("≤ 65k columns/table"));
9294                write_str(&mut out, expr);
9295            }
9296            // v7.13.0 — CHECK constraint appendix per table.
9297            // Layout: [u16 count] then `count` Display-form
9298            // expression strings. Re-parsed on every INSERT/UPDATE
9299            // by the engine. FILE_VERSION 23+ only; v22 readers
9300            // never reach this block because the writer also moves
9301            // to v23 in lock-step.
9302            write_u16(
9303                &mut out,
9304                u16::try_from(t.schema.checks.len()).expect("≤ 65k CHECK constraints/table"),
9305            );
9306            for c in &t.schema.checks {
9307                // v7.39 (read01 round 48) — the expr stays in this v23
9308                // appendix (byte layout unchanged for old readers); the
9309                // name rides the v60 constraint-name appendix at the tail.
9310                write_str(&mut out, c.expr.as_str());
9311            }
9312            // v7.17.0 Phase 1.4 — per-table user_enum_type
9313            // appendix. Layout: [u16 count] then
9314            // [u16 col_pos][str enum_name] per binding. Only
9315            // columns whose user_enum_type is Some land here.
9316            let mut enum_bindings: Vec<(usize, &str)> = Vec::new();
9317            for (i, c) in t.schema.columns.iter().enumerate() {
9318                if let Some(e) = &c.user_enum_type {
9319                    enum_bindings.push((i, e.as_str()));
9320                }
9321            }
9322            write_u16(
9323                &mut out,
9324                u16::try_from(enum_bindings.len()).expect("≤ 65k enum-typed columns/table"),
9325            );
9326            for (pos, ename) in enum_bindings {
9327                write_u16(&mut out, u16::try_from(pos).expect("≤ 65k columns/table"));
9328                write_str(&mut out, ename);
9329            }
9330            // v7.17.0 Phase 1.5 — per-table user_domain_type
9331            // appendix. Same layout as the enum one. v29-and-
9332            // below readers stop after the enum appendix.
9333            let mut domain_bindings: Vec<(usize, &str)> = Vec::new();
9334            for (i, c) in t.schema.columns.iter().enumerate() {
9335                if let Some(d) = &c.user_domain_type {
9336                    domain_bindings.push((i, d.as_str()));
9337                }
9338            }
9339            write_u16(
9340                &mut out,
9341                u16::try_from(domain_bindings.len()).expect("≤ 65k domain-typed columns/table"),
9342            );
9343            for (pos, dname) in domain_bindings {
9344                write_u16(&mut out, u16::try_from(pos).expect("≤ 65k columns/table"));
9345                write_str(&mut out, dname);
9346            }
9347            // v7.17.0 Phase 2.1 — per-table on_update_runtime
9348            // appendix. Sparse: only ON UPDATE-bound columns.
9349            let mut on_update_bindings: Vec<(usize, &str)> = Vec::new();
9350            for (i, c) in t.schema.columns.iter().enumerate() {
9351                if let Some(e) = &c.on_update_runtime {
9352                    on_update_bindings.push((i, e.as_str()));
9353                }
9354            }
9355            write_u16(
9356                &mut out,
9357                u16::try_from(on_update_bindings.len()).expect("≤ 65k ON UPDATE columns/table"),
9358            );
9359            for (pos, expr_src) in on_update_bindings {
9360                write_u16(&mut out, u16::try_from(pos).expect("≤ 65k columns/table"));
9361                write_str(&mut out, expr_src);
9362            }
9363            // v7.17.0 Phase 2.5 — per-table collation appendix.
9364            // Sparse: only non-Binary columns land. Layout:
9365            // `[u16 count][u16 col_pos][u8 tag] × count`.
9366            let mut coll_bindings: Vec<(usize, u8)> = Vec::new();
9367            for (i, c) in t.schema.columns.iter().enumerate() {
9368                let tag = match c.collation {
9369                    Collation::Binary => continue,
9370                    Collation::CaseInsensitive => Collation::TAG_CASE_INSENSITIVE,
9371                };
9372                coll_bindings.push((i, tag));
9373            }
9374            write_u16(
9375                &mut out,
9376                u16::try_from(coll_bindings.len()).expect("≤ 65k collation bindings/table"),
9377            );
9378            for (pos, tag) in coll_bindings {
9379                write_u16(&mut out, u16::try_from(pos).expect("≤ 65k columns/table"));
9380                out.push(tag);
9381            }
9382            // v7.17.0 Phase 4.4 — per-table is_unsigned appendix.
9383            // Sparse: only UNSIGNED columns land. Layout:
9384            // `[u16 count][u16 col_pos] × count`.
9385            let mut unsigned_bindings: Vec<usize> = Vec::new();
9386            for (i, c) in t.schema.columns.iter().enumerate() {
9387                if c.is_unsigned {
9388                    unsigned_bindings.push(i);
9389                }
9390            }
9391            write_u16(
9392                &mut out,
9393                u16::try_from(unsigned_bindings.len()).expect("≤ 65k UNSIGNED columns/table"),
9394            );
9395            for pos in unsigned_bindings {
9396                write_u16(&mut out, u16::try_from(pos).expect("≤ 65k columns/table"));
9397            }
9398            // v7.17.0 Phase 3.P0-36 — per-table inline_enum_variants
9399            // appendix. Sparse: only ENUM columns land. Layout:
9400            // `[u16 count] then per binding [u16 col_pos]
9401            // [u16 variant_count] then variant strings`.
9402            // FILE_VERSION 41+; v40 readers never reach this block.
9403            let mut enum_inline_bindings: Vec<(usize, &[String])> = Vec::new();
9404            for (i, c) in t.schema.columns.iter().enumerate() {
9405                if let Some(vs) = &c.inline_enum_variants {
9406                    enum_inline_bindings.push((i, vs.as_slice()));
9407                }
9408            }
9409            write_u16(
9410                &mut out,
9411                u16::try_from(enum_inline_bindings.len()).expect("≤ 65k inline-ENUM columns/table"),
9412            );
9413            for (pos, variants) in enum_inline_bindings {
9414                write_u16(&mut out, u16::try_from(pos).expect("≤ 65k columns/table"));
9415                write_u16(
9416                    &mut out,
9417                    u16::try_from(variants.len()).expect("≤ 65k variants/ENUM"),
9418                );
9419                for v in variants {
9420                    write_str(&mut out, v.as_str());
9421                }
9422            }
9423            // v7.17.0 Phase 3.P0-37 — per-table inline_set_variants
9424            // appendix. Same layout as the inline ENUM block.
9425            // FILE_VERSION 42+; v41 readers never reach this block.
9426            let mut set_inline_bindings: Vec<(usize, &[String])> = Vec::new();
9427            for (i, c) in t.schema.columns.iter().enumerate() {
9428                if let Some(vs) = &c.inline_set_variants {
9429                    set_inline_bindings.push((i, vs.as_slice()));
9430                }
9431            }
9432            write_u16(
9433                &mut out,
9434                u16::try_from(set_inline_bindings.len()).expect("≤ 65k inline-SET columns/table"),
9435            );
9436            for (pos, variants) in set_inline_bindings {
9437                write_u16(&mut out, u16::try_from(pos).expect("≤ 65k columns/table"));
9438                write_u16(
9439                    &mut out,
9440                    u16::try_from(variants.len()).expect("≤ 65k variants/SET"),
9441                );
9442                for v in variants {
9443                    write_str(&mut out, v.as_str());
9444                }
9445            }
9446            // v7.37.6-B — partition role appendix(FILE_VERSION 49+)。
9447            // Layout 详见 FILE_VERSION 49 docstring。普通表 = 单字节 0。
9448            write_partition_role(&mut out, t.schema.partition_role.as_ref());
9449            // v7.37.7 — per-table generated_stored_expr appendix
9450            // (FILE_VERSION 50+). Sparse: only columns whose
9451            // generated_stored_expr is Some land here.
9452            let mut gen_bindings: Vec<(usize, &str)> = Vec::new();
9453            for (i, c) in t.schema.columns.iter().enumerate() {
9454                if let Some(src) = &c.generated_stored_expr {
9455                    gen_bindings.push((i, src.as_str()));
9456                }
9457            }
9458            write_u16(
9459                &mut out,
9460                u16::try_from(gen_bindings.len()).expect("≤ 65k GENERATED STORED columns/table"),
9461            );
9462            for (pos, src) in gen_bindings {
9463                write_u16(&mut out, u16::try_from(pos).expect("≤ 65k columns/table"));
9464                write_str(&mut out, src);
9465            }
9466            // v7.38 (read01) — per-table default_text appendix
9467            // (FILE_VERSION 58+). Sparse: only columns whose default_text
9468            // is Some land here. Mirrors the generated_stored_expr shape.
9469            let mut default_texts: Vec<(usize, &str)> = Vec::new();
9470            for (i, c) in t.schema.columns.iter().enumerate() {
9471                if let Some(src) = &c.default_text {
9472                    default_texts.push((i, src.as_str()));
9473                }
9474            }
9475            write_u16(
9476                &mut out,
9477                u16::try_from(default_texts.len()).expect("≤ 65k defaulted columns/table"),
9478            );
9479            for (pos, src) in default_texts {
9480                write_u16(&mut out, u16::try_from(pos).expect("≤ 65k columns/table"));
9481                write_str(&mut out, src);
9482            }
9483            // v7.39 (RLS) — per-table policy appendix + the two RLS flags
9484            // (FILE_VERSION 59+). Written after the default_text block and
9485            // before the MVCC row appendix, so a v58 reader stops before it.
9486            // Layout: [u8 row_security][u8 force] [u16 policy_count] then per
9487            // policy: [str name][u8 cmd][u8 permissive][u16 role_count]
9488            // (role_count × str) [u8 has_using](+str)[u8 has_check](+str).
9489            out.push(u8::from(t.schema.row_security));
9490            out.push(u8::from(t.schema.force_row_security));
9491            write_u16(
9492                &mut out,
9493                u16::try_from(t.schema.policies.len()).expect("≤ 65k policies/table"),
9494            );
9495            for p in &t.schema.policies {
9496                write_str(&mut out, &p.name);
9497                out.push(p.cmd.to_wire_byte());
9498                out.push(u8::from(p.permissive));
9499                write_u16(
9500                    &mut out,
9501                    u16::try_from(p.roles.len()).expect("≤ 65k roles/policy"),
9502                );
9503                for r in &p.roles {
9504                    write_str(&mut out, r);
9505                }
9506                match &p.using_expr {
9507                    Some(s) => {
9508                        out.push(1);
9509                        write_str(&mut out, s);
9510                    }
9511                    None => out.push(0),
9512                }
9513                match &p.with_check_expr {
9514                    Some(s) => {
9515                        out.push(1);
9516                        write_str(&mut out, s);
9517                    }
9518                    None => out.push(0),
9519                }
9520            }
9521            // v7.37.16 (Epic W) — per-row MVCC header + stable RowId
9522            // appendix (FILE_VERSION 53+). Persists xmin/xmax/flags +
9523            // RowId for every row so a tombstone naming a pre-checkpoint
9524            // row survives a serialize→deserialize base restore
9525            // (cross-checkpoint tombstone durability). `headers` /
9526            // `rowids` are lock-step parallel to `rows` (invariant held
9527            // at every mutation boundary), so the count is `rows.len()`
9528            // and the zipped walk visits them in physical row order —
9529            // the same order the rows block above was written in. v52
9530            // readers never reach this block (the writer also moves to
9531            // v53 in lock-step); a v53 reader restores headers + ids
9532            // verbatim instead of freezing + dense-assigning.
9533            debug_assert_eq!(
9534                t.rows.len(),
9535                t.headers.len(),
9536                "headers must be lock-step with rows at serialize"
9537            );
9538            debug_assert_eq!(
9539                t.rows.len(),
9540                t.rowids.len(),
9541                "rowids must be lock-step with rows at serialize"
9542            );
9543            write_u32(
9544                &mut out,
9545                u32::try_from(t.rows.len()).expect("≤ 4G rows/table"),
9546            );
9547            for (h, rid) in t.headers.iter().zip(t.rowids.iter()) {
9548                out.extend_from_slice(&h.xmin.to_le_bytes());
9549                out.extend_from_slice(&h.xmax.to_le_bytes());
9550                out.push(h.flags);
9551                out.extend_from_slice(&rid.0.to_le_bytes());
9552            }
9553            out.extend_from_slice(
9554                &t.next_rowid
9555                    .load(core::sync::atomic::Ordering::Relaxed)
9556                    .to_le_bytes(),
9557            );
9558            // v7.39 (read01 round 48) — constraint-name appendix
9559            // (FILE_VERSION 60+). Index-aligned to the CHECK and
9560            // uniqueness-constraint appendices written above, so the
9561            // existing byte layouts stay untouched and a v59 catalog still
9562            // decodes (its constraints just come back unnamed).
9563            // Layout: [u16 check_count] then per check
9564            //         [u8 has_name] ([str name] when has_name)
9565            //         [u16 uc_count] then per uc the same pair.
9566            write_u16(
9567                &mut out,
9568                u16::try_from(t.schema.checks.len()).expect("≤ 65k CHECK constraints/table"),
9569            );
9570            for c in &t.schema.checks {
9571                match &c.name {
9572                    Some(n) => {
9573                        out.push(1);
9574                        write_str(&mut out, n);
9575                    }
9576                    None => out.push(0),
9577                }
9578            }
9579            write_u16(
9580                &mut out,
9581                u16::try_from(t.schema.uniqueness_constraints.len())
9582                    .expect("≤ 65k uniqueness constraints/table"),
9583            );
9584            for uc in &t.schema.uniqueness_constraints {
9585                match &uc.name {
9586                    Some(n) => {
9587                        out.push(1);
9588                        write_str(&mut out, n);
9589                    }
9590                    None => out.push(0),
9591                }
9592            }
9593            // v7.39 (read01 round 56) — user_composite_type appendix
9594            // (FILE_VERSION 63+). Sparse, at the very end of the per-table
9595            // block: only composite-typed columns land here, so a v62 reader
9596            // stops before it and its composite columns stay plain JSON.
9597            let mut comp_bindings: Vec<(usize, &str)> = Vec::new();
9598            for (i, c) in t.schema.columns.iter().enumerate() {
9599                if let Some(n) = &c.user_composite_type {
9600                    comp_bindings.push((i, n.as_str()));
9601                }
9602            }
9603            write_u16(
9604                &mut out,
9605                u16::try_from(comp_bindings.len()).expect("≤ 65k composite-typed columns/table"),
9606            );
9607            for (pos, n) in comp_bindings {
9608                write_u16(&mut out, u16::try_from(pos).expect("≤ 65k columns/table"));
9609                write_str(&mut out, n);
9610            }
9611            // v7.39 (read01 round 57) — owner + ACL appendix (FILE_VERSION
9612            // 64+), at the very end of the per-table block so a v63 reader
9613            // stops before it (its tables then read back owner-less, i.e.
9614            // owned by the login role, with no grants — which is exactly what
9615            // they were).
9616            match &t.schema.owner {
9617                Some(o) => {
9618                    out.push(1);
9619                    write_str(&mut out, o);
9620                }
9621                None => out.push(0),
9622            }
9623            write_u16(
9624                &mut out,
9625                u16::try_from(t.schema.acl.len()).expect("≤ 65k aclitems/table"),
9626            );
9627            for a in &t.schema.acl {
9628                write_str(&mut out, &a.grantee);
9629                write_u16(&mut out, a.privs);
9630                write_u16(&mut out, a.grantable);
9631                write_str(&mut out, &a.grantor);
9632            }
9633            // v7.39 (read01 round 59) — COLUMN acl appendix (FILE_VERSION 65+),
9634            // sparse: only columns that carry a grant land here, so a v64 reader
9635            // stops before it and its columns read back un-granted, which is
9636            // what they were.
9637            let granted: Vec<(usize, &ColumnSchema)> = t
9638                .schema
9639                .columns
9640                .iter()
9641                .enumerate()
9642                .filter(|(_, c)| !c.acl.is_empty())
9643                .collect();
9644            write_u16(
9645                &mut out,
9646                u16::try_from(granted.len()).expect("≤ 65k granted columns/table"),
9647            );
9648            for (pos, c) in granted {
9649                write_u16(&mut out, u16::try_from(pos).expect("≤ 65k columns/table"));
9650                write_u16(
9651                    &mut out,
9652                    u16::try_from(c.acl.len()).expect("≤ 65k aclitems/column"),
9653                );
9654                for a in &c.acl {
9655                    write_str(&mut out, &a.grantee);
9656                    write_u16(&mut out, a.privs);
9657                    write_u16(&mut out, a.grantable);
9658                    write_str(&mut out, &a.grantor);
9659                }
9660            }
9661            // v7.39 (round 210) — EXCLUDE-constraint appendix (FILE_VERSION
9662            // 72+), at the very end of the per-table block so a v71 reader
9663            // stops before it and its tables read back with no exclusion
9664            // constraints. Layout: [u16 excl_count] then per constraint
9665            // [str name] [u8 has_method](+str) [u16 elem_count] then per
9666            // element [u16 col_pos][str op].
9667            write_u16(
9668                &mut out,
9669                u16::try_from(t.schema.exclusion_constraints.len())
9670                    .expect("≤ 65k exclusion constraints/table"),
9671            );
9672            for ex in &t.schema.exclusion_constraints {
9673                write_str(&mut out, &ex.name);
9674                match &ex.method {
9675                    Some(m) => {
9676                        out.push(1);
9677                        write_str(&mut out, m);
9678                    }
9679                    None => out.push(0),
9680                }
9681                write_u16(
9682                    &mut out,
9683                    u16::try_from(ex.elements.len()).expect("≤ 65k elements/exclusion"),
9684                );
9685                for (pos, op) in &ex.elements {
9686                    write_u16(&mut out, u16::try_from(*pos).expect("≤ 65k columns/table"));
9687                    write_str(&mut out, op);
9688                }
9689            }
9690            // v7.39 (round 220) — identity-RESTART appendix (FILE_VERSION
9691            // 73+), sparse: only columns carrying a RESTART floor land here.
9692            let restarts: Vec<(usize, i64)> = t
9693                .schema
9694                .columns
9695                .iter()
9696                .enumerate()
9697                .filter_map(|(i, c)| c.auto_restart.map(|n| (i, n)))
9698                .collect();
9699            write_u16(
9700                &mut out,
9701                u16::try_from(restarts.len()).expect("≤ 65k restart columns/table"),
9702            );
9703            for (pos, n) in restarts {
9704                write_u16(&mut out, u16::try_from(pos).expect("≤ 65k columns/table"));
9705                out.extend_from_slice(&n.to_le_bytes());
9706            }
9707            // v7.39 (round 386, type-fidelity epic P1) — per-table
9708            // mysql_int_width appendix (FILE_VERSION 81+). Sparse: only
9709            // TINYINT / MEDIUMINT columns land. Layout:
9710            // `[u16 count]([u16 col_pos][u8 width_tag]) × count`
9711            // (tag 0 = Tiny, 1 = Medium). v80-and-below readers stop after
9712            // the identity-RESTART appendix, leaving every column at None.
9713            let int_widths: Vec<(usize, u8)> = t
9714                .schema
9715                .columns
9716                .iter()
9717                .enumerate()
9718                .filter_map(|(i, c)| {
9719                    c.mysql_int_width.map(|w| {
9720                        let tag = match w {
9721                            MysqlIntWidth::Tiny => 0u8,
9722                            MysqlIntWidth::Medium => 1u8,
9723                            MysqlIntWidth::Small => 2u8,
9724                            MysqlIntWidth::Int => 3u8,
9725                            MysqlIntWidth::Big => 4u8,
9726                        };
9727                        (i, tag)
9728                    })
9729                })
9730                .collect();
9731            write_u16(
9732                &mut out,
9733                u16::try_from(int_widths.len()).expect("≤ 65k narrow-int columns/table"),
9734            );
9735            for (pos, tag) in int_widths {
9736                write_u16(&mut out, u16::try_from(pos).expect("≤ 65k columns/table"));
9737                out.push(tag);
9738            }
9739            // v7.39 (round 424, type-fidelity epic) — per-table mysql_fsp
9740            // appendix (FILE_VERSION 82+). Sparse: only MySQL-declared
9741            // temporal columns land. Layout:
9742            // `[u16 count]([u16 col_pos][u8 fsp]) × count`, fsp in 0..=6.
9743            // v81-and-below readers stop after the int-width appendix,
9744            // leaving every column at None (PG microsecond behaviour).
9745            let fsps: Vec<(usize, u8)> = t
9746                .schema
9747                .columns
9748                .iter()
9749                .enumerate()
9750                .filter_map(|(i, c)| c.mysql_fsp.map(|p| (i, p)))
9751                .collect();
9752            write_u16(
9753                &mut out,
9754                u16::try_from(fsps.len()).expect("≤ 65k temporal columns/table"),
9755            );
9756            for (pos, fsp) in fsps {
9757                write_u16(&mut out, u16::try_from(pos).expect("≤ 65k columns/table"));
9758                out.push(fsp);
9759            }
9760            // v7.39 (round 652) — CHECK-validated appendix (FILE_VERSION
9761            // 87+). Sparse the other way round from the ones above: the
9762            // common case is every constraint validated, so only the
9763            // NOT VALID ones are written, by their index into the CHECK
9764            // appendix. Layout: `[u16 count]([u16 check_idx]) × count`.
9765            let unvalidated: Vec<usize> = t
9766                .schema
9767                .checks
9768                .iter()
9769                .enumerate()
9770                .filter_map(|(i, c)| (!c.validated).then_some(i))
9771                .collect();
9772            write_u16(
9773                &mut out,
9774                u16::try_from(unvalidated.len()).expect("≤ 65k CHECK constraints/table"),
9775            );
9776            for idx in unvalidated {
9777                write_u16(&mut out, u16::try_from(idx).expect("≤ 65k CHECK/table"));
9778            }
9779            // v7.39 (round 677) — per-column collation names (FILE_VERSION
9780            // 88+). Sparse: only the columns that were written with an
9781            // explicit `COLLATE` appear, so a table that declares none pays
9782            // two bytes. Layout: `[u16 count]([u16 col_idx][str]) × count`.
9783            //
9784            // Without this the declaration survives CREATE TABLE and dies
9785            // at the next restart — measured: a column declared
9786            // `COLLATE "C"` reported attcollation 950 in the session that
9787            // created it and 100 after a reload.
9788            let collated: Vec<(usize, &str)> = t
9789                .schema
9790                .columns
9791                .iter()
9792                .enumerate()
9793                .filter_map(|(i, c)| c.collation_name.as_deref().map(|n| (i, n)))
9794                .collect();
9795            write_u16(
9796                &mut out,
9797                u16::try_from(collated.len()).expect("≤ 65k columns/table"),
9798            );
9799            for (idx, name) in collated {
9800                write_u16(&mut out, u16::try_from(idx).expect("≤ 65k columns/table"));
9801                write_str(&mut out, name);
9802            }
9803            // v7.39 (round 711) — PK/UNIQUE constraint timing (FILE_VERSION
9804            // 89+). Dense, one byte per uniqueness constraint in
9805            // declaration order, the same bit layout the FK block has
9806            // carried since round 288: bit 0 = DEFERRABLE, bit 1 =
9807            // INITIALLY DEFERRED. A v88 reader stops before it.
9808            write_u16(
9809                &mut out,
9810                u16::try_from(t.schema.uniqueness_constraints.len())
9811                    .expect("≤ 65k uniqueness constraints/table"),
9812            );
9813            for uc in &t.schema.uniqueness_constraints {
9814                out.push(u8::from(uc.deferrable) | (u8::from(uc.initially_deferred) << 1));
9815            }
9816        }
9817        // v7.12.4 — catalog-wide appendix: user-defined functions
9818        // then triggers. FILE_VERSION 22+ only. v21 and earlier
9819        // readers stop after the last table; v22 readers always
9820        // consume two `u32` counts (possibly zero).
9821        //
9822        // Function entry layout:
9823        //   [str name] [str args_repr] [str returns]
9824        //   [str language] [str body]
9825        // Trigger entry layout:
9826        //   [str name] [str table] [str timing]
9827        //   [u16 event_count] (event_count × str)
9828        //   [str for_each] [str function]
9829        write_u32(
9830            &mut out,
9831            u32::try_from(self.functions.len()).expect("≤ 4G functions"),
9832        );
9833        for fd in self.functions.values() {
9834            write_str(&mut out, &fd.name);
9835            write_str(&mut out, &fd.args_repr);
9836            write_str(&mut out, &fd.returns);
9837            write_str(&mut out, &fd.language);
9838            write_str_long(&mut out, &fd.body);
9839        }
9840        write_u32(
9841            &mut out,
9842            u32::try_from(self.triggers.len()).expect("≤ 4G triggers"),
9843        );
9844        for td in &self.triggers {
9845            write_str(&mut out, &td.name);
9846            write_str(&mut out, &td.table);
9847            write_str(&mut out, &td.timing);
9848            write_u16(
9849                &mut out,
9850                u16::try_from(td.events.len()).expect("≤ 65k events / trigger"),
9851            );
9852            for ev in &td.events {
9853                write_str(&mut out, ev);
9854            }
9855            write_str(&mut out, &td.for_each);
9856            write_str(&mut out, &td.function);
9857            // v7.13.0 — `UPDATE OF cols` filter
9858            // (FILE_VERSION 23+). v22 readers omit; v23 writers
9859            // always emit (possibly zero).
9860            write_u16(
9861                &mut out,
9862                u16::try_from(td.update_columns.len()).expect("≤ 65k cols / trigger"),
9863            );
9864            for c in &td.update_columns {
9865                write_str(&mut out, c);
9866            }
9867            // v7.16.1 — TriggerDef.enabled (FILE_VERSION 25+).
9868            out.push(u8::from(td.enabled));
9869            // v7.39 (round 138) — WHEN condition text (FILE_VERSION 70+).
9870            write_str(&mut out, &td.when_condition);
9871        }
9872        // v7.17.0 Phase 1.1 — SEQUENCE catalog block (FILE_VERSION 26+).
9873        write_u32(
9874            &mut out,
9875            u32::try_from(self.sequences.len()).expect("≤ 4G sequences"),
9876        );
9877        for seq in self.sequences.values() {
9878            write_str(&mut out, &seq.name);
9879            out.push(match seq.data_type {
9880                SequenceDataType::SmallInt => 0,
9881                SequenceDataType::Int => 1,
9882                SequenceDataType::BigInt => 2,
9883            });
9884            out.extend_from_slice(&seq.start.to_le_bytes());
9885            out.extend_from_slice(&seq.increment.to_le_bytes());
9886            out.extend_from_slice(&seq.min_value.to_le_bytes());
9887            out.extend_from_slice(&seq.max_value.to_le_bytes());
9888            out.extend_from_slice(&seq.cache.to_le_bytes());
9889            out.push(u8::from(seq.cycle));
9890            match &seq.owned_by {
9891                None => out.push(0),
9892                Some((table, column)) => {
9893                    out.push(1);
9894                    write_str(&mut out, table);
9895                    write_str(&mut out, column);
9896                }
9897            }
9898            out.extend_from_slice(&seq.last_value.to_le_bytes());
9899            out.push(u8::from(seq.is_called));
9900        }
9901        // v7.17.0 Phase 1.2 — VIEW catalog block (FILE_VERSION 27+).
9902        write_u32(
9903            &mut out,
9904            u32::try_from(self.views.len()).expect("≤ 4G views"),
9905        );
9906        for view in self.views.values() {
9907            write_str(&mut out, &view.name);
9908            write_u16(
9909                &mut out,
9910                u16::try_from(view.columns.len()).expect("≤ 65k cols / view"),
9911            );
9912            for c in &view.columns {
9913                write_str(&mut out, c);
9914            }
9915            write_str_long(&mut out, &view.body);
9916            // v7.39 (round 132, FILE_VERSION 69+) — WITH CHECK OPTION marker.
9917            out.push(view.check_option);
9918        }
9919        // v7.17.0 Phase 1.3 — MATERIALIZED VIEW source registry
9920        // (FILE_VERSION 28+). The backing rows live as a regular
9921        // table of the same name already in the tables block.
9922        write_u32(
9923            &mut out,
9924            u32::try_from(self.materialized_views.len()).expect("≤ 4G materialized views"),
9925        );
9926        for (name, body) in &self.materialized_views {
9927            write_str(&mut out, name);
9928            write_str_long(&mut out, body);
9929        }
9930        // v7.17.0 Phase 1.4 — ENUM types catalog block
9931        // (FILE_VERSION 29+).
9932        write_u32(
9933            &mut out,
9934            u32::try_from(self.enum_types.len()).expect("≤ 4G enum types"),
9935        );
9936        for e in self.enum_types.values() {
9937            write_str(&mut out, &e.name);
9938            write_u16(
9939                &mut out,
9940                u16::try_from(e.labels.len()).expect("≤ 65k labels / enum"),
9941            );
9942            for l in &e.labels {
9943                write_str(&mut out, l);
9944            }
9945        }
9946        // v7.17.0 Phase 1.5 — DOMAIN types catalog block
9947        // (FILE_VERSION 30+).
9948        write_u32(
9949            &mut out,
9950            u32::try_from(self.domain_types.len()).expect("≤ 4G domain types"),
9951        );
9952        for d in self.domain_types.values() {
9953            write_str(&mut out, &d.name);
9954            write_data_type(&mut out, d.base_type);
9955            out.push(u8::from(d.nullable));
9956            match &d.default {
9957                None => out.push(0),
9958                Some(s) => {
9959                    out.push(1);
9960                    write_str(&mut out, s);
9961                }
9962            }
9963            write_u16(
9964                &mut out,
9965                u16::try_from(d.checks.len()).expect("≤ 65k CHECKs / domain"),
9966            );
9967            for c in &d.checks {
9968                write_str(&mut out, &c.expr);
9969                // v7.39 (round 260) — the constraint name (FILE_VERSION 75+).
9970                write_str(&mut out, &c.name);
9971            }
9972            // v7.39 (round 259) — the parent domain (FILE_VERSION 74+).
9973            match &d.base_domain {
9974                None => out.push(0),
9975                Some(s) => {
9976                    out.push(1);
9977                    write_str(&mut out, s);
9978                }
9979            }
9980        }
9981        // v7.17.0 Phase 1.6 — user-schemas registry
9982        // (FILE_VERSION 31+). Built-ins are hardcoded in
9983        // `is_builtin_schema` and not persisted.
9984        write_u32(
9985            &mut out,
9986            u32::try_from(self.schemas.len()).expect("≤ 4G schemas"),
9987        );
9988        for name in &self.schemas {
9989            write_str(&mut out, name);
9990        }
9991        // v7.37.42-T2 ζ-B — COMPOSITE types catalog block
9992        // (FILE_VERSION 52+). Each entry: name, u16 field_count,
9993        // then field_count `[str field_name][data_type]` pairs.
9994        write_u32(
9995            &mut out,
9996            u32::try_from(self.composite_types.len()).expect("≤ 4G composite types"),
9997        );
9998        for c in self.composite_types.values() {
9999            write_str(&mut out, &c.name);
10000            write_u16(
10001                &mut out,
10002                u16::try_from(c.fields.len()).expect("≤ 65k fields / composite"),
10003            );
10004            for (i, (fname, fty)) in c.fields.iter().enumerate() {
10005                write_str(&mut out, fname);
10006                write_data_type(&mut out, *fty);
10007                // v7.39 (round 264) — the field's user type (v76+).
10008                match c.field_user_types.get(i).and_then(Option::as_ref) {
10009                    None => out.push(0),
10010                    Some(n) => {
10011                        out.push(1);
10012                        write_str(&mut out, n);
10013                    }
10014                }
10015            }
10016        }
10017        // v7.39 (read01 round 50) — COMMENT store (FILE_VERSION 61+).
10018        // Catalog-wide, written last (before the CRC trailer) so every older
10019        // reader stops before it. Layout: [u32 count] then [str key][str text].
10020        write_u32(
10021            &mut out,
10022            u32::try_from(self.comments.len()).expect("≤ 4G comments"),
10023        );
10024        for (k, v) in &self.comments {
10025            write_str(&mut out, k);
10026            write_str_long(&mut out, v);
10027        }
10028        // v7.39 (read01 round 60) — non-table ACLs (FILE_VERSION 66+), catalog-
10029        // wide and written last so a v65 reader stops before them. The sequence
10030        // block itself sits mid-image and cannot grow without breaking older
10031        // readers, so a sequence's owner + ACL rides here, keyed by name.
10032        let acl_out = |out: &mut Vec<u8>, acl: &[AclItem]| {
10033            write_u16(out, u16::try_from(acl.len()).expect("≤ 65k aclitems"));
10034            for a in acl {
10035                write_str(out, &a.grantee);
10036                write_u16(out, a.privs);
10037                write_u16(out, a.grantable);
10038                write_str(out, &a.grantor);
10039            }
10040        };
10041        let owned: Vec<&SequenceDef> = self
10042            .sequences
10043            .values()
10044            .filter(|s| s.owner.is_some() || !s.acl.is_empty())
10045            .collect();
10046        write_u32(
10047            &mut out,
10048            u32::try_from(owned.len()).expect("≤ 4G sequences"),
10049        );
10050        for seq in owned {
10051            write_str(&mut out, &seq.name);
10052            match &seq.owner {
10053                Some(o) => {
10054                    out.push(1);
10055                    write_str(&mut out, o);
10056                }
10057                None => out.push(0),
10058            }
10059            acl_out(&mut out, &seq.acl);
10060        }
10061        acl_out(&mut out, &self.schema_acl);
10062        acl_out(&mut out, &self.database_acl);
10063        // v7.39 (read01 round 61) — FUNCTION owner + ACL (FILE_VERSION 67+).
10064        // The function block sits mid-image like the sequence one, so this
10065        // rides the catalog-wide tail too, keyed by name.
10066        let fns: Vec<&FunctionDef> = self
10067            .functions
10068            .values()
10069            .filter(|f| f.owner.is_some() || !f.acl.is_empty())
10070            .collect();
10071        write_u32(&mut out, u32::try_from(fns.len()).expect("≤ 4G functions"));
10072        for f in fns {
10073            // v7.39 (read01 round 62) — keyed by SIGNATURE now: two overloads
10074            // have two ACLs.
10075            write_str(&mut out, &function_signature_key(&f.name, &f.args_repr));
10076            match &f.owner {
10077                Some(o) => {
10078                    out.push(1);
10079                    write_str(&mut out, o);
10080                }
10081                None => out.push(0),
10082            }
10083            acl_out(&mut out, &f.acl);
10084        }
10085        // v7.39 (round 139) — RULE catalog block (FILE_VERSION 71+), catalog-
10086        // wide and written last (right before the CRC trailer) so every older
10087        // reader stops cleanly before it. Layout: [u32 count] then per rule
10088        // [str name][str table][str event][u8 instead][str when]
10089        // [u16 cmd_count]([str cmd] × cmd_count).
10090        write_u32(
10091            &mut out,
10092            u32::try_from(self.rules.len()).expect("≤ 4G rules"),
10093        );
10094        for r in &self.rules {
10095            write_str(&mut out, &r.name);
10096            write_str(&mut out, &r.table);
10097            write_str(&mut out, &r.event);
10098            out.push(u8::from(r.instead));
10099            write_str(&mut out, &r.when_condition);
10100            write_u16(
10101                &mut out,
10102                u16::try_from(r.commands.len()).expect("≤ 65k commands / rule"),
10103            );
10104            for c in &r.commands {
10105                write_str(&mut out, c);
10106            }
10107        }
10108        // v7.39 (round 280) — extended-statistics block (FILE_VERSION
10109        // 77+), appended after the RULE block for the same reason: an
10110        // older reader stops cleanly before it. Layout: [u32 count]
10111        // then per object [str name][str table][u16 n]([str kind] × n)
10112        // [u16 m]([str column] × m).
10113        write_u32(
10114            &mut out,
10115            u32::try_from(self.statistics_ext.len()).expect("≤ 4G statistics objects"),
10116        );
10117        for st in &self.statistics_ext {
10118            write_str(&mut out, &st.name);
10119            write_str(&mut out, &st.table);
10120            write_u16(
10121                &mut out,
10122                u16::try_from(st.kinds.len()).expect("≤ 65k kinds"),
10123            );
10124            for k in &st.kinds {
10125                write_str(&mut out, k);
10126            }
10127            write_u16(
10128                &mut out,
10129                u16::try_from(st.columns.len()).expect("≤ 65k columns"),
10130            );
10131            for c in &st.columns {
10132                write_str(&mut out, c);
10133            }
10134        }
10135        // v7.39 (round 287) — large-object block (FILE_VERSION 78+),
10136        // appended after the statistics block for the same reason: an
10137        // older reader stops cleanly before it. Layout: [u32 count]
10138        // then per object [u32 oid][u32 len][len bytes].
10139        write_u32(
10140            &mut out,
10141            u32::try_from(self.large_objects.len()).expect("≤ 4G large objects"),
10142        );
10143        for (oid, bytes) in &self.large_objects {
10144            write_u32(&mut out, *oid);
10145            write_u32(
10146                &mut out,
10147                u32::try_from(bytes.len()).expect("≤ 4G per object"),
10148            );
10149            out.extend_from_slice(bytes);
10150        }
10151        // v7.39 (round 322, V46) — function-attribute block (FILE_VERSION
10152        // 80+), appended last for the same reason as every block before
10153        // it: an older reader stops cleanly ahead of it and simply sees
10154        // functions with PG's default attributes. Only functions that
10155        // declared something non-default are written. Layout: [u32 count]
10156        // then per function [str signature_key][u8 volatility][u8 flags]
10157        // [u8 parallel][f64 cost or NaN][f64 rows or NaN], where flags bit
10158        // 0 = strict, 1 = security definer, 2 = leakproof.
10159        let attr_fns: Vec<(&String, &FunctionDef)> = self
10160            .functions
10161            .iter()
10162            .filter(|(_, f)| {
10163                f.volatility != FN_VOLATILE
10164                    || f.strict
10165                    || f.security_definer
10166                    || f.leakproof
10167                    || f.parallel != FN_PARALLEL_UNSAFE
10168                    || f.cost.is_some()
10169                    || f.rows.is_some()
10170            })
10171            .collect();
10172        write_u32(
10173            &mut out,
10174            u32::try_from(attr_fns.len()).expect("≤ 4G functions"),
10175        );
10176        for (key, f) in attr_fns {
10177            write_str(&mut out, key);
10178            out.push(f.volatility);
10179            let flags = u8::from(f.strict)
10180                | (u8::from(f.security_definer) << 1)
10181                | (u8::from(f.leakproof) << 2);
10182            out.push(flags);
10183            out.push(f.parallel);
10184            out.extend_from_slice(&f.cost.unwrap_or(f64::NAN).to_le_bytes());
10185            out.extend_from_slice(&f.rows.unwrap_or(f64::NAN).to_le_bytes());
10186        }
10187        // v7.38 (read01 P5.05) — CRC32C trailer over the whole image so a
10188        // corrupted snapshot is rejected on load. FILE_VERSION is >= the
10189        // trailer version, so this always runs for freshly-written images.
10190        // v7.39 (round 547) — pg_db_role_setting (FILE_VERSION 85+),
10191        // catalog-wide and written LAST so a v84 reader stops before it.
10192        // Layout: [u32 scopes] then [str database][str role][u32 params]
10193        // then [str name][str value] per param.
10194        write_u32(
10195            &mut out,
10196            u32::try_from(self.db_role_settings.len()).expect("≤ 4G scopes"),
10197        );
10198        for ((db, role), params) in &self.db_role_settings {
10199            write_str(&mut out, db);
10200            write_str(&mut out, role);
10201            write_u32(&mut out, u32::try_from(params.len()).expect("≤ 4G params"));
10202            for (name, value) in params {
10203                write_str(&mut out, name);
10204                write_str(&mut out, value);
10205            }
10206        }
10207        // v7.39 (round 550) — replication slots (FILE_VERSION 86+),
10208        // written LAST so a v85 reader stops before them.
10209        write_u32(
10210            &mut out,
10211            u32::try_from(self.replication_slots.len()).expect("≤ 4G slots"),
10212        );
10213        for (name, (plugin, slot_type)) in &self.replication_slots {
10214            write_str(&mut out, name);
10215            write_str(&mut out, plugin);
10216            write_str(&mut out, slot_type);
10217        }
10218        let crc = spg_crypto::crc32c::crc32c(&out);
10219        write_u32(&mut out, crc);
10220        out
10221    }
10222
10223    /// Deserialize a previously-serialized catalog. Rejects bad magic, version
10224    /// mismatch, unknown tags, truncation, and trailing bytes.
10225    pub fn deserialize(buf: &[u8]) -> Result<Self, StorageError> {
10226        let mut cur = Cursor::new(buf);
10227        let magic = cur.take(8)?;
10228        if magic != FILE_MAGIC {
10229            return Err(StorageError::Corrupt(format!(
10230                "bad magic: expected SPGDB001, got {magic:?}"
10231            )));
10232        }
10233        let version = cur.read_u8()?;
10234        if !(MIN_SUPPORTED_FILE_VERSION..=FILE_VERSION).contains(&version) {
10235            return Err(StorageError::Corrupt(format!(
10236                "unsupported file version: {version} (supported: {MIN_SUPPORTED_FILE_VERSION}..={FILE_VERSION})"
10237            )));
10238        }
10239        // v7.23/v7.27 — escape decoding is version-gated (see
10240        // STR_LEN_ESCAPE / Cursor::codec_version).
10241        cur.codec_version = version;
10242        let table_count = cur.read_u32()? as usize;
10243        let mut cat = Self::new();
10244        for _ in 0..table_count {
10245            deserialize_table(&mut cur, &mut cat, version)?;
10246        }
10247        // v7.37.15 (Phase C.1) — stamp dense stable RelIds on load.
10248        // Pre-V6 envelopes carry no ids; a dense 1..=N assignment is
10249        // sufficient while RelId is process-local bookkeeping (the V6
10250        // envelope, Phase C.6, will round-trip real ids). Sets the
10251        // allocator above the loaded ids so a post-load CREATE TABLE
10252        // never collides.
10253        for (i, t) in cat.tables.iter_mut().enumerate() {
10254            t.set_rel_id(row_header::RelId((i as u64) + 1));
10255        }
10256        cat.next_rel_id = cat.tables.len() as u64;
10257        // v7.12.4 — catalog-wide function + trigger appendix.
10258        // FILE_VERSION 22+ only; v21 and earlier catalogs stop
10259        // after the last table.
10260        if version >= 22 {
10261            let fn_count = cur.read_u32()? as usize;
10262            for _ in 0..fn_count {
10263                let name = cur.read_str()?;
10264                let args_repr = cur.read_str()?;
10265                let returns = cur.read_str()?;
10266                let language = cur.read_str()?;
10267                let body = cur.read_str_long()?;
10268                let key = function_signature_key(&name, &args_repr);
10269                cat.functions.insert(
10270                    key,
10271                    FunctionDef {
10272                        name,
10273                        args_repr,
10274                        returns,
10275                        language,
10276                        body,
10277                        owner: None,
10278                        acl: Vec::new(),
10279                        volatility: FN_VOLATILE,
10280                        strict: false,
10281                        security_definer: false,
10282                        leakproof: false,
10283                        parallel: FN_PARALLEL_UNSAFE,
10284                        cost: None,
10285                        rows: None,
10286                    },
10287                );
10288            }
10289            let trg_count = cur.read_u32()? as usize;
10290            for _ in 0..trg_count {
10291                let name = cur.read_str()?;
10292                let table = cur.read_str()?;
10293                let timing = cur.read_str()?;
10294                let ev_count = cur.read_u16()? as usize;
10295                let mut events = Vec::with_capacity(ev_count);
10296                for _ in 0..ev_count {
10297                    events.push(cur.read_str()?);
10298                }
10299                let for_each = cur.read_str()?;
10300                let function = cur.read_str()?;
10301                // v7.13.0 — trailing `UPDATE OF cols` filter
10302                // (FILE_VERSION 23+ only; v22 catalogs omit and
10303                // deserialise with an empty vec).
10304                let update_columns = if version >= 23 {
10305                    let n = cur.read_u16()? as usize;
10306                    let mut cols = Vec::with_capacity(n);
10307                    for _ in 0..n {
10308                        cols.push(cur.read_str()?);
10309                    }
10310                    cols
10311                } else {
10312                    Vec::new()
10313                };
10314                // v7.16.1 — TriggerDef.enabled (FILE_VERSION 25+).
10315                // v24-and-below catalogs deserialise with `true`
10316                // — pre-v7.16.1 every trigger always fired.
10317                let enabled = if version >= 25 {
10318                    cur.read_u8()? != 0
10319                } else {
10320                    true
10321                };
10322                // v7.39 (round 138) — WHEN condition text added at FILE_VERSION
10323                // 70; older catalogs read back empty (no WHEN filter).
10324                let when_condition = if version >= 70 {
10325                    cur.read_str()?
10326                } else {
10327                    String::new()
10328                };
10329                cat.triggers.push(TriggerDef {
10330                    name,
10331                    table,
10332                    timing,
10333                    events,
10334                    for_each,
10335                    function,
10336                    update_columns,
10337                    enabled,
10338                    when_condition,
10339                });
10340            }
10341        }
10342        // v7.17.0 Phase 1.1 — SEQUENCE block (FILE_VERSION 26+).
10343        // v25-and-below catalogs omit; we leave the map empty.
10344        if version >= 26 {
10345            let seq_count = cur.read_u32()? as usize;
10346            for _ in 0..seq_count {
10347                let name = cur.read_str()?;
10348                let data_type = match cur.read_u8()? {
10349                    0 => SequenceDataType::SmallInt,
10350                    1 => SequenceDataType::Int,
10351                    2 => SequenceDataType::BigInt,
10352                    other => {
10353                        return Err(StorageError::Corrupt(format!(
10354                            "unknown SEQUENCE data-type tag {other}"
10355                        )));
10356                    }
10357                };
10358                let start = cur.read_i64()?;
10359                let increment = cur.read_i64()?;
10360                let min_value = cur.read_i64()?;
10361                let max_value = cur.read_i64()?;
10362                let cache = cur.read_i64()?;
10363                let cycle = cur.read_u8()? != 0;
10364                let owned_by = match cur.read_u8()? {
10365                    0 => None,
10366                    1 => {
10367                        let t = cur.read_str()?;
10368                        let c = cur.read_str()?;
10369                        Some((t, c))
10370                    }
10371                    other => {
10372                        return Err(StorageError::Corrupt(format!(
10373                            "unknown SEQUENCE owned-by tag {other}"
10374                        )));
10375                    }
10376                };
10377                let last_value = cur.read_i64()?;
10378                let is_called = cur.read_u8()? != 0;
10379                cat.sequences.insert(
10380                    name.clone(),
10381                    SequenceDef {
10382                        name,
10383                        data_type,
10384                        start,
10385                        increment,
10386                        min_value,
10387                        max_value,
10388                        cache,
10389                        cycle,
10390                        owned_by,
10391                        last_value,
10392                        is_called,
10393                        owner: None,
10394                        acl: Vec::new(),
10395                    },
10396                );
10397            }
10398        }
10399        // v7.17.0 Phase 1.2 — VIEW block (FILE_VERSION 27+).
10400        // v26-and-below catalogs omit; we leave the map empty.
10401        if version >= 27 {
10402            let view_count = cur.read_u32()? as usize;
10403            for _ in 0..view_count {
10404                let name = cur.read_str()?;
10405                let col_count = cur.read_u16()? as usize;
10406                let mut columns = Vec::with_capacity(col_count);
10407                for _ in 0..col_count {
10408                    columns.push(cur.read_str()?);
10409                }
10410                let body = cur.read_str_long()?;
10411                // v7.39 (round 132) — check-option marker added at FILE_VERSION
10412                // 69; older catalogs default to 0 (no check option).
10413                let check_option = if version >= 69 { cur.read_u8()? } else { 0 };
10414                cat.views.insert(
10415                    name.clone(),
10416                    ViewDef {
10417                        name,
10418                        columns,
10419                        body,
10420                        check_option,
10421                    },
10422                );
10423            }
10424        }
10425        // v7.17.0 Phase 1.3 — MATERIALIZED VIEW source registry
10426        // (FILE_VERSION 28+). v27-and-below catalogs omit.
10427        if version >= 28 {
10428            let mv_count = cur.read_u32()? as usize;
10429            for _ in 0..mv_count {
10430                let name = cur.read_str()?;
10431                let body = cur.read_str_long()?;
10432                cat.materialized_views.insert(name, body);
10433            }
10434        }
10435        // v7.17.0 Phase 1.4 — ENUM types catalog block
10436        // (FILE_VERSION 29+).
10437        if version >= 29 {
10438            let etype_count = cur.read_u32()? as usize;
10439            for _ in 0..etype_count {
10440                let name = cur.read_str()?;
10441                let label_count = cur.read_u16()? as usize;
10442                let mut labels = Vec::with_capacity(label_count);
10443                for _ in 0..label_count {
10444                    labels.push(cur.read_str()?);
10445                }
10446                cat.enum_types
10447                    .insert(name.clone(), EnumDef { name, labels });
10448            }
10449        }
10450        // v7.17.0 Phase 1.5 — DOMAIN types catalog block
10451        // (FILE_VERSION 30+).
10452        if version >= 30 {
10453            let dtype_count = cur.read_u32()? as usize;
10454            for _ in 0..dtype_count {
10455                let name = cur.read_str()?;
10456                let base_type = cur.read_data_type()?;
10457                let nullable = cur.read_u8()? != 0;
10458                let default = match cur.read_u8()? {
10459                    0 => None,
10460                    1 => Some(cur.read_str()?),
10461                    other => {
10462                        return Err(StorageError::Corrupt(format!(
10463                            "unknown DOMAIN default tag {other}"
10464                        )));
10465                    }
10466                };
10467                let check_count = cur.read_u16()? as usize;
10468                let mut checks: Vec<DomainCheck> = Vec::with_capacity(check_count);
10469                for i in 0..check_count {
10470                    let expr = cur.read_str()?;
10471                    // v7.39 (round 260) — names arrived in FILE_VERSION 75.
10472                    // An older catalog gets PG's auto-naming applied to the
10473                    // checks it stored, which is what they would have been.
10474                    let cname = if version >= 75 {
10475                        cur.read_str()?
10476                    } else if i == 0 {
10477                        alloc::format!("{name}_check")
10478                    } else {
10479                        alloc::format!("{name}_check{i}")
10480                    };
10481                    checks.push(DomainCheck { name: cname, expr });
10482                }
10483                // v7.39 (round 259) — the parent domain. Absent before
10484                // FILE_VERSION 74; an older catalog reads as a domain over
10485                // a scalar, which is what it was.
10486                let base_domain = if version >= 74 {
10487                    match cur.read_u8()? {
10488                        0 => None,
10489                        1 => Some(cur.read_str()?),
10490                        other => {
10491                            return Err(StorageError::Corrupt(alloc::format!(
10492                                "domain base_domain tag {other}"
10493                            )));
10494                        }
10495                    }
10496                } else {
10497                    None
10498                };
10499                cat.domain_types.insert(
10500                    name.clone(),
10501                    DomainDef {
10502                        name,
10503                        base_type,
10504                        nullable,
10505                        default,
10506                        checks,
10507                        base_domain,
10508                    },
10509                );
10510            }
10511        }
10512        // v7.17.0 Phase 1.6 — user-schemas registry
10513        // (FILE_VERSION 31+).
10514        if version >= 31 {
10515            let sch_count = cur.read_u32()? as usize;
10516            for _ in 0..sch_count {
10517                let name = cur.read_str()?;
10518                cat.schemas.insert(name);
10519            }
10520        }
10521        // v7.37.42-T2 ζ-B — COMPOSITE types catalog block
10522        // (FILE_VERSION 52+). v51-and-below readers stop at the
10523        // user-schemas block; v52 readers fed a v51 catalog see no
10524        // composite block and default to an empty map.
10525        if version >= 52 {
10526            let ctype_count = cur.read_u32()? as usize;
10527            for _ in 0..ctype_count {
10528                let name = cur.read_str()?;
10529                let field_count = cur.read_u16()? as usize;
10530                let mut fields = Vec::with_capacity(field_count);
10531                let mut field_user_types: Vec<Option<String>> = Vec::with_capacity(field_count);
10532                for _ in 0..field_count {
10533                    let fname = cur.read_str()?;
10534                    let fty = cur.read_data_type()?;
10535                    // v7.39 (round 264) — present from FILE_VERSION 76.
10536                    let ut = if version >= 76 {
10537                        match cur.read_u8()? {
10538                            0 => None,
10539                            1 => Some(cur.read_str()?),
10540                            other => {
10541                                return Err(StorageError::Corrupt(alloc::format!(
10542                                    "composite field user-type tag {other}"
10543                                )));
10544                            }
10545                        }
10546                    } else {
10547                        None
10548                    };
10549                    fields.push((fname, fty));
10550                    field_user_types.push(ut);
10551                }
10552                cat.composite_types.insert(
10553                    name.clone(),
10554                    CompositeDef {
10555                        name,
10556                        fields,
10557                        field_user_types,
10558                    },
10559                );
10560            }
10561        }
10562        // v7.39 (read01 round 50) — COMMENT store (FILE_VERSION 61+).
10563        if version >= 61 {
10564            let comment_count = cur.read_u32()? as usize;
10565            for _ in 0..comment_count {
10566                let key = cur.read_str()?;
10567                let text = cur.read_str_long()?;
10568                cat.comments.insert(key, text);
10569            }
10570        }
10571        // v7.39 (read01 round 60) — non-table ACLs (FILE_VERSION 66+).
10572        if version >= 66 {
10573            let read_acl = |cur: &mut Cursor| -> Result<Vec<AclItem>, StorageError> {
10574                let n = cur.read_u16()? as usize;
10575                let mut acl = Vec::with_capacity(n);
10576                for _ in 0..n {
10577                    let grantee = cur.read_str()?;
10578                    let privs = cur.read_u16()?;
10579                    let grantable = cur.read_u16()?;
10580                    let grantor = cur.read_str()?;
10581                    acl.push(AclItem {
10582                        grantee,
10583                        privs,
10584                        grantable,
10585                        grantor,
10586                    });
10587                }
10588                Ok(acl)
10589            };
10590            let seq_count = cur.read_u32()? as usize;
10591            for _ in 0..seq_count {
10592                let name = cur.read_str()?;
10593                let owner = if cur.read_u8()? == 1 {
10594                    Some(cur.read_str()?)
10595                } else {
10596                    None
10597                };
10598                let acl = read_acl(&mut cur)?;
10599                if let Some(seq) = cat.sequences.get_mut(&name) {
10600                    seq.owner = owner;
10601                    seq.acl = acl;
10602                }
10603            }
10604            cat.schema_acl = read_acl(&mut cur)?;
10605            cat.database_acl = read_acl(&mut cur)?;
10606            // v7.39 (read01 round 61) — FUNCTION owner + ACL (v67+; keyed by
10607            // signature from v68, when overloads became possible).
10608            if version >= 67 {
10609                let fn_count = cur.read_u32()? as usize;
10610                for _ in 0..fn_count {
10611                    let name = cur.read_str()?;
10612                    let owner = if cur.read_u8()? == 1 {
10613                        Some(cur.read_str()?)
10614                    } else {
10615                        None
10616                    };
10617                    let acl = read_acl(&mut cur)?;
10618                    // v7.39 (round 315, V19) — the stored key was computed
10619                    // by whichever formula was current when the image was
10620                    // written. A miss is not "no such function": before the
10621                    // multi-word fix, `f(double precision)` keyed as
10622                    // `f(precision)`, so an older image's grants would land
10623                    // nowhere and vanish silently. Fall back to matching by
10624                    // the old formula, which re-attaches them.
10625                    let target = resolve_stored_function_key(&cat.functions, &name);
10626                    if let Some(k) = target
10627                        && let Some(f) = cat.functions.get_mut(&k)
10628                    {
10629                        f.owner = owner;
10630                        f.acl = acl;
10631                    }
10632                }
10633            }
10634        }
10635        // v7.39 (round 139) — RULE catalog block (FILE_VERSION 71+), read from
10636        // the tail right before the CRC trailer. Pre-71 images stop before it.
10637        if version >= 71 {
10638            let rule_count = cur.read_u32()? as usize;
10639            for _ in 0..rule_count {
10640                let name = cur.read_str()?;
10641                let table = cur.read_str()?;
10642                let event = cur.read_str()?;
10643                let instead = cur.read_u8()? != 0;
10644                let when_condition = cur.read_str()?;
10645                let cmd_count = cur.read_u16()? as usize;
10646                let mut commands = Vec::with_capacity(cmd_count);
10647                for _ in 0..cmd_count {
10648                    commands.push(cur.read_str()?);
10649                }
10650                cat.rules.push(RuleDef {
10651                    name,
10652                    table,
10653                    event,
10654                    instead,
10655                    when_condition,
10656                    commands,
10657                });
10658            }
10659        }
10660        // v7.39 (round 280) — extended-statistics block (FILE_VERSION
10661        // 77+). Pre-77 images stop before it.
10662        if version >= 77 {
10663            let count = cur.read_u32()? as usize;
10664            for _ in 0..count {
10665                let name = cur.read_str()?;
10666                let table = cur.read_str()?;
10667                let nk = cur.read_u16()? as usize;
10668                let mut kinds = Vec::with_capacity(nk);
10669                for _ in 0..nk {
10670                    kinds.push(cur.read_str()?);
10671                }
10672                let nc = cur.read_u16()? as usize;
10673                let mut columns = Vec::with_capacity(nc);
10674                for _ in 0..nc {
10675                    columns.push(cur.read_str()?);
10676                }
10677                cat.statistics_ext.push(StatisticsExtDef {
10678                    name,
10679                    table,
10680                    kinds,
10681                    columns,
10682                });
10683            }
10684        }
10685        // v7.39 (round 287) — large-object block (FILE_VERSION 78+).
10686        // Pre-78 images stop before it.
10687        if version >= 78 {
10688            let count = cur.read_u32()? as usize;
10689            for _ in 0..count {
10690                let oid = cur.read_u32()?;
10691                let len = cur.read_u32()? as usize;
10692                let bytes = cur.read_bytes(len)?;
10693                cat.large_objects.insert(oid, bytes);
10694            }
10695        }
10696        // v7.39 (round 322, V46) — function-attribute block (FILE_VERSION
10697        // 80+). Pre-80 images stop before it and keep PG's defaults.
10698        if version >= 80 {
10699            let count = cur.read_u32()? as usize;
10700            for _ in 0..count {
10701                let key = cur.read_str()?;
10702                let volatility = cur.read_u8()?;
10703                let flags = cur.read_u8()?;
10704                let parallel = cur.read_u8()?;
10705                let cost = f64::from_le_bytes(cur.read_bytes(8)?.try_into().unwrap_or([0; 8]));
10706                let rows = f64::from_le_bytes(cur.read_bytes(8)?.try_into().unwrap_or([0; 8]));
10707                if let Some(f) = cat.functions.get_mut(&key) {
10708                    f.volatility = volatility;
10709                    f.strict = flags & 1 != 0;
10710                    f.security_definer = flags & 2 != 0;
10711                    f.leakproof = flags & 4 != 0;
10712                    f.parallel = parallel;
10713                    f.cost = (!cost.is_nan()).then_some(cost);
10714                    f.rows = (!rows.is_nan()).then_some(rows);
10715                }
10716            }
10717        }
10718        // v7.39 (round 547) — pg_db_role_setting (FILE_VERSION 85+).
10719        // Pre-85 images stop before it and carry no GUC defaults.
10720        if version >= 85 {
10721            let scopes = cur.read_u32()? as usize;
10722            for _ in 0..scopes {
10723                let db = cur.read_str()?;
10724                let role = cur.read_str()?;
10725                let params = cur.read_u32()? as usize;
10726                let mut m: BTreeMap<String, String> = BTreeMap::new();
10727                for _ in 0..params {
10728                    let name = cur.read_str()?;
10729                    let value = cur.read_str()?;
10730                    m.insert(name, value);
10731                }
10732                if !m.is_empty() {
10733                    cat.db_role_settings.insert((db, role), m);
10734                }
10735            }
10736        }
10737        // v7.39 (round 550) — replication slots (FILE_VERSION 86+).
10738        if version >= 86 {
10739            let count = cur.read_u32()? as usize;
10740            for _ in 0..count {
10741                let name = cur.read_str()?;
10742                let plugin = cur.read_str()?;
10743                let slot_type = cur.read_str()?;
10744                cat.replication_slots.insert(name, (plugin, slot_type));
10745            }
10746        }
10747        // v7.38 (read01 P5.05) — v54+ images end with a CRC32C over every
10748        // preceding byte; verify it before accepting the snapshot. Older
10749        // images have no trailer and fall through to the trailing-byte check.
10750        if version >= FILE_VERSION_CRC_TRAILER {
10751            let crc_start = cur.pos;
10752            let stored = cur.read_u32()?;
10753            let computed = spg_crypto::crc32c::crc32c(&buf[..crc_start]);
10754            if computed != stored {
10755                return Err(StorageError::Corrupt(format!(
10756                    "base snapshot CRC mismatch: computed {computed:#010x}, stored {stored:#010x}"
10757                )));
10758            }
10759        }
10760        if cur.pos < buf.len() {
10761            return Err(StorageError::Corrupt(format!(
10762                "trailing bytes: {} unread",
10763                buf.len() - cur.pos
10764            )));
10765        }
10766        Ok(cat)
10767    }
10768}
10769
10770#[cfg(test)]
10771mod tests;