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.39.11 — PG's `int2vector`: the type its catalogs use for
264    /// `pg_index.indkey` and `pg_index.indoption`. It IS an array of
265    /// `smallint` — `a.attnum = ANY (i.indkey)` is how Django, Rails,
266    /// sqlalchemy and every hand-written schema-diff query ask which
267    /// columns an index covers — but its output function prints the
268    /// elements space-separated with no braces, and its subscripts
269    /// start at 0 rather than 1. Carrying it as `text` (which SPG did
270    /// through 7.39.10) got the printing right and made every array
271    /// operation raise; carrying it as `smallint[]` would trade one
272    /// of those for the other. It is its own type here for the same
273    /// reason it is one there.
274    Int2Vector,
275    /// v7.39.11 — PG's `oidvector`: `pg_index.indclass`,
276    /// `pg_index.indcollation`, `pg_proc.proargtypes`. `int2vector`
277    /// with `oid` elements; see [`DataType::Int2Vector`].
278    OidVector,
279    /// v7.37.5 β-P4 — `INTERVAL[]` — single-dimension array of
280    /// `IntervalSpan { months, days, micros }`. PG wire OID 1187
281    /// (`_interval`). Catalog tag 35 + per-cell body
282    /// `[u16 count][per elem: u8 null + (if non-null) 16-byte
283    /// interval body in LE PG-byte-equal field order]`.
284    /// FILE_VERSION 48+.
285    IntervalArray,
286    /// v7.37.5 γ — full PG array-of-scalar family. Catalog tags
287    /// 36..48; wire OIDs from PG `pg_type.dat`. Per-element body
288    /// uses the scalar's existing `write_value_body` shape.
289    /// FILE_VERSION 48+ (same window as β; no separate bump).
290    BoolArray, // PG `_bool`        OID 1000, tag 36
291    SmallIntArray,    // PG `_int2`        OID 1005, tag 37
292    FloatArray,       // PG `_float8`      OID 1022, tag 38
293    NumericArray,     // PG `_numeric`     OID 1231, tag 39
294    DateArray,        // PG `_date`        OID 1182, tag 40
295    TimestampArray,   // PG `_timestamp`   OID 1115, tag 41
296    TimestamptzArray, // PG `_timestamptz` OID 1185, tag 42
297    UuidArray,        // PG `_uuid`        OID 2951, tag 43
298    JsonArray,        // PG `_json`        OID 199,  tag 44
299    JsonbArray,       // PG `_jsonb`       OID 3807, tag 45
300    BytesArray,       // PG `_bytea`       OID 1001, tag 46
301    VarcharArray,     // PG `_varchar`     OID 1015, tag 47
302    CharArray,        // PG `_bpchar`      OID 1014, tag 48
303    /// v7.37.5 δ — PG 14+ multirange types. A multirange is an
304    /// ordered collection of non-overlapping ranges of the same
305    /// element kind (e.g. `int4multirange(int4range(1,5),
306    /// int4range(10,15))` → `{[1,5),[10,15)}`). The same DataType
307    /// variant covers all six builtin multiranges; `RangeKind`
308    /// pins the element type so encode/decode/display can route
309    /// off one switch (parallel to `Range(RangeKind)`).
310    /// Wire OIDs: int4multirange=4451, int8multirange=4537,
311    /// nummultirange=4536, tsmultirange=4533, tstzmultirange=4534,
312    /// datemultirange=4535. Catalog tag 49 + 1-byte RangeKind on
313    /// the dense type-tag side. FILE_VERSION 48+ (same window as
314    /// β/γ, no separate bump).
315    Multirange(RangeKind),
316    /// v7.37.5 ε — PG geometry scalar family. Mirrors PG's seven
317    /// builtin geometric types one-for-one. Body shapes (LE):
318    ///   Point   = 16 B fixed (f64 x + f64 y)            OID 600
319    ///   Lseg    = 32 B fixed (Point p1 + Point p2)      OID 601
320    ///   Path    = varlena ([u8 closed][u32 n][Point*n]) OID 602
321    ///   Box     = 32 B fixed (Point ur + Point ll)      OID 603
322    ///   Polygon = varlena ([u32 n][Point*n])            OID 604
323    ///   Line    = 24 B fixed (f64 a + f64 b + f64 c)    OID 628
324    ///   Circle  = 24 B fixed (Point center + f64 r)     OID 718
325    /// Catalog tags 50..56. FILE_VERSION 48+ (same window as β/γ/δ;
326    /// no separate bump). Geometric operators (`<->` / `@>` / `&&`
327    /// / `<<` / `>>` / `~=`) are a planner-integration follow-up,
328    /// parallel to the Range operator defer in e2e_pg_range.rs.
329    Point,
330    Lseg,
331    Path,
332    PgBox,
333    Polygon,
334    Line,
335    Circle,
336    /// v7.37.5 ζ-A — PG network address family. Body shapes (LE):
337    ///   Inet     = 18 B fixed (u8 family + u8 bits + 16 B addr)  OID 869
338    ///   Cidr     = 18 B fixed (same shape as Inet; CIDR rejects
339    ///                          host bits at parse / coerce)       OID 650
340    ///   Macaddr  = 6 B fixed                                      OID 829
341    ///   Macaddr8 = 8 B fixed (EUI-64)                             OID 774
342    /// Catalog tags 57-60. FILE_VERSION 48+. `family = 4` is IPv4
343    /// (uses the first 4 bytes of the 16-B addr slot, rest 0);
344    /// `family = 6` is IPv6 (full 16 B).
345    Inet,
346    Cidr,
347    Macaddr,
348    Macaddr8,
349    /// v7.39 (read01 pg_lsn.c) — PG `pg_lsn` (WAL location). 8 bytes,
350    /// rendered `%X/%X`. Catalog tag 66. OID 3220.
351    PgLsn,
352    /// v7.37.5 ζ-A — PG bit string. Body = `[u32 nbits][ceil(nbits/8) bytes]`,
353    /// big-endian within each byte (matches PG binary).
354    ///   Bit         OID 1560 (fixed-length, but SPG carries the
355    ///                         length per cell — column declaration
356    ///                         `BIT(n)` constrains at coerce time)
357    ///   BitVarying  OID 1562 (variable-length, declared as `VARBIT`)
358    /// Catalog tags 61-62.
359    /// v7.39 (round 281) — `BIT(n)`: a FIXED-length bit string. `0`
360    /// means the type was written without a typmod, which PG treats as
361    /// `bit(1)`. Column assignment requires the length to match
362    /// exactly; an explicit cast pads or truncates instead.
363    Bit(u32),
364    /// v7.39 (round 281) — `BIT VARYING(n)`: `n` is a MAXIMUM, and `0`
365    /// means unbounded (`varbit` with no typmod).
366    BitVarying(u32),
367    /// v7.37.5 ζ-A — PG `xml`. Body identical to TEXT (storage is
368    /// the verbatim XML string; no parse-time validation). Only
369    /// the wire OID (142) differs. Catalog tag 63.
370    Xml,
371    /// v7.37.5 ζ-A — PG `"char"` (the internal single-byte type,
372    /// distinct from `CHAR(n)` / `BPCHAR`). Body = 1 byte raw.
373    /// OID 18. Catalog tag 64.
374    Char1,
375    /// v7.37.5 ζ-A — `MONEY[]`. Body = `[u16 count][per elem: u8 null
376    /// + (non-null) i64 LE cents]`. OID 791. Catalog tag 65.
377    MoneyArray,
378    /// v7.12.0: PG `tsvector` — ordered, deduplicated set of
379    /// `(lexeme, positions, weight)` tuples. PG wire OID 3614.
380    /// Catalog FILE_VERSION 20+. Storage shape is row-codec
381    /// tag 22; the schema-agnostic `write_value` path emits tag
382    /// 18. Literal: `'foo:1 bar:2,3'::tsvector` (PG external
383    /// form). G-CRIT-3 entry — v7.12.0 only ships the type +
384    /// codec; matching `@@` lands in v7.12.2.
385    TsVector,
386    /// v7.12.0: PG `tsquery` — parse tree of lexemes joined by
387    /// `&` `|` `!` and phrase operators. PG wire OID 3615.
388    /// Catalog FILE_VERSION 20+.
389    TsQuery,
390    /// v7.17.0: PG `uuid` — 128-bit identifier stored as
391    /// `Value::Uuid([u8; 16])`. PG wire OID 2950. Canonical
392    /// text form is lowercase 8-4-4-4-12 hyphenated; input
393    /// also accepts uppercase, unhyphenated, and brace-wrapped
394    /// forms (`{xxxx…}`). Catalog FILE_VERSION 36+; tag 24 on
395    /// the dense type-tag side, tag 20 on the schema-agnostic
396    /// value side. The drop-in PG/MySQL surface for Django /
397    /// Rails / Hibernate "id UUID PRIMARY KEY DEFAULT
398    /// gen_random_uuid()" default-PK pattern.
399    Uuid,
400    /// v7.17.0 Phase 3.P0-32: PG `time` (without time zone) — i64
401    /// microseconds since 00:00:00. PG wire OID 1083. Display:
402    /// canonical zero-padded `HH:MM:SS` when fractional is zero,
403    /// `HH:MM:SS.ffffff` otherwise. Catalog FILE_VERSION 37+;
404    /// tag 25 on the dense type-tag side, tag 21 on the schema-
405    /// agnostic value side. The wall-clock-of-day half of PG's
406    /// date/time triplet (date / time / timestamp).
407    Time,
408    /// v7.17.0 Phase 3.P0-33: MySQL `YEAR` — u16 in range
409    /// 1901..=2155 plus the special zero-year sentinel 0. No
410    /// dedicated PG OID (advertised as INT4 / OID 23 on the wire
411    /// — psql renders integers, MySQL CLI renders 4-digit
412    /// zero-padded text). Display always 4 digits: `0000` for the
413    /// zero-year, `1985` / `2007` / etc otherwise. Catalog
414    /// FILE_VERSION 38+; tag 26 on the dense type-tag side, tag
415    /// 22 on the schema-agnostic value side.
416    Year,
417    /// v7.17.0 Phase 3.P0-34: PG `time with time zone` (TIMETZ) —
418    /// i64 microseconds since 00:00:00 in the local wall clock
419    /// PLUS i32 offset-from-UTC in seconds. PG wire OID 1266.
420    /// Display: `HH:MM:SS[.ffffff]±HH[:MM]` (PG `timetz_out`).
421    /// Range: offset in ±50400 seconds (±14 hours). Catalog
422    /// FILE_VERSION 39+; tag 27 on the dense type-tag side, tag
423    /// 23 on the schema-agnostic value side.
424    TimeTz,
425    /// v7.17.0 Phase 3.P0-35: PG `money` — i64 cents (locale-
426    /// independent storage). PG wire OID 790. Display: en_US
427    /// locale (`$N,NNN.CC`, negative → `-$1.23`). Input accepts
428    /// `$N.NN`, `$N,NNN.NN`, bare integer (treated as major
429    /// units), optional leading `-`. Range: full i64. Catalog
430    /// FILE_VERSION 40+; tag 28 on the dense type-tag side, tag
431    /// 24 on the schema-agnostic value side.
432    Money,
433    /// v7.17.0 Phase 3.P0-38: PG range type. The same DataType
434    /// variant covers all six builtin ranges (int4range,
435    /// int8range, numrange, tsrange, tstzrange, daterange) —
436    /// `RangeKind` pins the element type so encode / decode /
437    /// display can route off one switch. Catalog FILE_VERSION
438    /// 43+; tag 29 + a 1-byte RangeKind on the dense type-tag
439    /// side, tag 25 on the schema-agnostic value side.
440    Range(RangeKind),
441    /// v7.17.0 Phase 3.P0-39: PG `hstore` extension type — flat
442    /// `text => text` map with NULL value support. Catalog
443    /// FILE_VERSION 44+; tag 30 on the dense type-tag side, tag
444    /// 26 on the schema-agnostic value side. The contrib OID is
445    /// installation-dependent in real PG; SPG advertises it via
446    /// dynamic lookup, falling back to TEXT (OID 25) on the wire
447    /// when the installed `hstore` extension hasn't claimed an
448    /// OID yet.
449    Hstore,
450    /// v7.17.0 Phase 3.P0-40: PG `int[][]` — 2-dimensional INT
451    /// matrix. Storage: row-major Vec<Vec<Option<i32>>>. All
452    /// rows must share the same column count. Wire OID 1007
453    /// (same as INT[]; the dimension count travels in the data
454    /// header, not the OID). Catalog FILE_VERSION 45+; tag 31
455    /// on the dense type-tag side, tag 27 on the schema-agnostic
456    /// value side.
457    IntArray2D,
458    /// v7.17.0 Phase 3.P0-40: PG `bigint[][]` — 2-dimensional
459    /// BIGINT matrix. Storage / OID / tags mirror IntArray2D.
460    /// Tag 32 dense, tag 28 schema-agnostic.
461    BigIntArray2D,
462    /// v7.17.0 Phase 3.P0-40: PG `text[][]` — 2-dimensional TEXT
463    /// matrix. Storage: row-major Vec<Vec<Option<String>>>.
464    /// Tag 33 dense, tag 29 schema-agnostic.
465    TextArray2D,
466    /// v7.39 (read01 round 75) — `bool[][]`. BOOL is the ONE element type whose
467    /// ARRAY rendering differs from its scalar one (`t` vs `true`), so a
468    /// text-backed 2-D cannot be PG-faithful for it: rendering the whole array
469    /// wants `t`, and subscripting a cell to text wants `false`. Every other
470    /// element type renders the same either way, which is why this is the only
471    /// typed 2-D variant SPG needs.
472    BoolArray2D,
473}
474
475/// v7.17.0 Phase 3.P0-38 — pins the element type of a range value
476/// or column. Wire OIDs: Int4=3904, Int8=3926, Num=3906,
477/// Ts=3908, TsTz=3910, Date=3912.
478#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
479pub enum RangeKind {
480    Int4,
481    Int8,
482    Num,
483    Ts,
484    TsTz,
485    Date,
486}
487
488impl RangeKind {
489    pub const fn tag(self) -> u8 {
490        match self {
491            Self::Int4 => 0,
492            Self::Int8 => 1,
493            Self::Num => 2,
494            Self::Ts => 3,
495            Self::TsTz => 4,
496            Self::Date => 5,
497        }
498    }
499    pub const fn from_tag(t: u8) -> Option<Self> {
500        Some(match t {
501            0 => Self::Int4,
502            1 => Self::Int8,
503            2 => Self::Num,
504            3 => Self::Ts,
505            4 => Self::TsTz,
506            5 => Self::Date,
507            _ => return None,
508        })
509    }
510    pub const fn keyword(self) -> &'static str {
511        match self {
512            Self::Int4 => "INT4RANGE",
513            Self::Int8 => "INT8RANGE",
514            Self::Num => "NUMRANGE",
515            Self::Ts => "TSRANGE",
516            Self::TsTz => "TSTZRANGE",
517            Self::Date => "DATERANGE",
518        }
519    }
520}
521
522impl fmt::Display for DataType {
523    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
524        match self {
525            Self::SmallInt => f.write_str("SMALLINT"),
526            Self::Int => f.write_str("INT"),
527            Self::BigInt => f.write_str("BIGINT"),
528            Self::Xid => f.write_str("XID"),
529            Self::Xid8 => f.write_str("XID8"),
530            Self::Oid => f.write_str("OID"),
531            Self::OidArray => f.write_str("OID[]"),
532            Self::Int2Vector => f.write_str("INT2VECTOR"),
533            Self::OidVector => f.write_str("OIDVECTOR"),
534            Self::Float => f.write_str("FLOAT"),
535            Self::Real => f.write_str("REAL"),
536            Self::Text => f.write_str("TEXT"),
537            Self::Varchar(n) => write!(f, "VARCHAR({n})"),
538            Self::Char(n) => write!(f, "CHAR({n})"),
539            Self::Bool => f.write_str("BOOL"),
540            Self::Vector { dim, encoding } => match encoding {
541                VecEncoding::F32 => write!(f, "VECTOR({dim})"),
542                VecEncoding::Sq8 => write!(f, "VECTOR({dim}) USING SQ8"),
543                VecEncoding::F16 => write!(f, "VECTOR({dim}) USING HALF"),
544            },
545            Self::Numeric { precision, scale } => {
546                if *scale == 0 {
547                    write!(f, "NUMERIC({precision})")
548                } else {
549                    write!(f, "NUMERIC({precision}, {scale})")
550                }
551            }
552            Self::Date => f.write_str("DATE"),
553            Self::Timestamp => f.write_str("TIMESTAMP"),
554            Self::Timestamptz => f.write_str("TIMESTAMPTZ"),
555            Self::Name => f.write_str("NAME"),
556            Self::Interval => f.write_str("INTERVAL"),
557            Self::Json => f.write_str("JSON"),
558            Self::Jsonb => f.write_str("JSONB"),
559            Self::Bytes => f.write_str("BYTEA"),
560            Self::TextArray => f.write_str("TEXT[]"),
561            Self::IntArray => f.write_str("INT[]"),
562            Self::BigIntArray => f.write_str("BIGINT[]"),
563            Self::IntervalArray => f.write_str("INTERVAL[]"),
564            Self::BoolArray => f.write_str("BOOL[]"),
565            Self::SmallIntArray => f.write_str("SMALLINT[]"),
566            Self::FloatArray => f.write_str("FLOAT[]"),
567            Self::NumericArray => f.write_str("NUMERIC[]"),
568            Self::DateArray => f.write_str("DATE[]"),
569            Self::TimestampArray => f.write_str("TIMESTAMP[]"),
570            Self::TimestamptzArray => f.write_str("TIMESTAMPTZ[]"),
571            Self::UuidArray => f.write_str("UUID[]"),
572            Self::JsonArray => f.write_str("JSON[]"),
573            Self::JsonbArray => f.write_str("JSONB[]"),
574            Self::BytesArray => f.write_str("BYTEA[]"),
575            Self::VarcharArray => f.write_str("VARCHAR[]"),
576            Self::CharArray => f.write_str("CHAR[]"),
577            Self::Multirange(k) => f.write_str(match k {
578                RangeKind::Int4 => "INT4MULTIRANGE",
579                RangeKind::Int8 => "INT8MULTIRANGE",
580                RangeKind::Num => "NUMMULTIRANGE",
581                RangeKind::Ts => "TSMULTIRANGE",
582                RangeKind::TsTz => "TSTZMULTIRANGE",
583                RangeKind::Date => "DATEMULTIRANGE",
584            }),
585            Self::Point => f.write_str("POINT"),
586            Self::Lseg => f.write_str("LSEG"),
587            Self::Path => f.write_str("PATH"),
588            Self::PgBox => f.write_str("BOX"),
589            Self::Polygon => f.write_str("POLYGON"),
590            Self::Line => f.write_str("LINE"),
591            Self::Circle => f.write_str("CIRCLE"),
592            Self::Inet => f.write_str("INET"),
593            Self::Cidr => f.write_str("CIDR"),
594            Self::Macaddr => f.write_str("MACADDR"),
595            Self::Macaddr8 => f.write_str("MACADDR8"),
596            Self::PgLsn => f.write_str("PG_LSN"),
597            Self::Bit(0) => f.write_str("BIT"),
598            Self::Bit(n) => write!(f, "BIT({n})"),
599            Self::BitVarying(0) => f.write_str("VARBIT"),
600            Self::BitVarying(n) => write!(f, "VARBIT({n})"),
601            Self::Xml => f.write_str("XML"),
602            Self::Char1 => f.write_str("\"char\""),
603            Self::MoneyArray => f.write_str("MONEY[]"),
604            Self::TsVector => f.write_str("TSVECTOR"),
605            Self::TsQuery => f.write_str("TSQUERY"),
606            Self::Uuid => f.write_str("UUID"),
607            Self::Time => f.write_str("TIME"),
608            Self::Year => f.write_str("YEAR"),
609            Self::TimeTz => f.write_str("TIMETZ"),
610            Self::Money => f.write_str("MONEY"),
611            Self::Range(k) => f.write_str(k.keyword()),
612            Self::Hstore => f.write_str("HSTORE"),
613            Self::IntArray2D => f.write_str("INT[][]"),
614            Self::BigIntArray2D => f.write_str("BIGINT[][]"),
615            Self::TextArray2D => f.write_str("TEXT[][]"),
616            Self::BoolArray2D => f.write_str("BOOL[][]"),
617        }
618    }
619}
620
621/// v7.12.0 — one entry in a `Value::TsVector`. The lexeme is the
622/// (already-tokenised + stemmed in v7.12.1+) word; `positions` is
623/// a strictly-ascending list of 1-based positions; `weight` is the
624/// PG weight letter (A=3, B=2, C=1, D=0) — v7.12.0 defaults every
625/// lexeme to D, the v7.12.2 ranking path consumes the weight.
626#[derive(Debug, Clone, PartialEq, Eq)]
627pub struct TsLexeme {
628    pub word: String,
629    pub positions: Vec<u16>,
630    pub weight: u8,
631}
632
633/// v7.12.0 — parse tree for a PG `tsquery`. v7.12.0 ships the
634/// type + codec only; the `to_tsquery` / `plainto_tsquery` lexer
635/// lands in v7.12.1 and the `@@` evaluator in v7.12.2.
636#[derive(Debug, Clone, PartialEq, Eq)]
637pub enum TsQueryAst {
638    /// Single lexeme term. The `weight_mask` is the PG-style
639    /// bitmask of accepted weights (`A=1<<3`, `B=1<<2`, `C=1<<1`,
640    /// `D=1<<0`); `0` = any weight. v7.12.0 always sets it to 0.
641    Term {
642        word: String,
643        weight_mask: u8,
644    },
645    And(Box<TsQueryAst>, Box<TsQueryAst>),
646    Or(Box<TsQueryAst>, Box<TsQueryAst>),
647    Not(Box<TsQueryAst>),
648    /// `phrase <distance> phrase`. v7.12.0 only persists this; the
649    /// match semantics arrive in v7.12.2 alongside `@@`.
650    Phrase {
651        left: Box<TsQueryAst>,
652        right: Box<TsQueryAst>,
653        distance: u16,
654    },
655}
656
657/// v7.38.19 — whether an `interval` is finite, and if not, which way.
658///
659/// PostgreSQL has no NaN interval — measured, not assumed: `'nan'::interval`
660/// is a syntax error on 18.4 while `'infinity'` and `'-infinity'` parse —
661/// so this carries three states where `NumericKind` carries four.
662#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Default)]
663pub enum IntervalKind {
664    #[default]
665    Finite,
666    NegInf,
667    PosInf,
668}
669
670impl IntervalKind {
671    /// PostgreSQL's own representation of the two infinities, measured
672    /// off the wire rather than read out of its source.
673    ///
674    /// ```text
675    /// COPY (SELECT 'infinity'::interval)  TO STDOUT (FORMAT binary)
676    ///   … 7fffffffffffffff 7fffffff 7fffffff
677    /// COPY (SELECT '-infinity'::interval) TO STDOUT (FORMAT binary)
678    ///   … 8000000000000000 80000000 80000000
679    /// COPY (SELECT '1 day'::interval)     TO STDOUT (FORMAT binary)
680    ///   … 0000000000000000 00000001 00000000
681    /// ```
682    ///
683    /// All three fields at their extreme, which is why SPG can carry an
684    /// explicit `kind` in memory -- so the compiler names every site
685    /// that has to decide what infinity means there -- and still write
686    /// sixteen bytes on disk and on the wire. No finite interval reaches
687    /// the triple: PostgreSQL reserves it, so no value PostgreSQL ever
688    /// produced holds it either, and a file written before this version
689    /// cannot contain one.
690    #[must_use]
691    pub const fn from_fields(months: i32, days: i32, micros: i64) -> Self {
692        if micros == i64::MAX && days == i32::MAX && months == i32::MAX {
693            Self::PosInf
694        } else if micros == i64::MIN && days == i32::MIN && months == i32::MIN {
695            Self::NegInf
696        } else {
697            Self::Finite
698        }
699    }
700
701    /// The three fields this kind is written as. `Finite` hands back
702    /// what it was given.
703    #[must_use]
704    pub const fn to_fields(self, months: i32, days: i32, micros: i64) -> (i32, i32, i64) {
705        match self {
706            Self::Finite => (months, days, micros),
707            Self::PosInf => (i32::MAX, i32::MAX, i64::MAX),
708            Self::NegInf => (i32::MIN, i32::MIN, i64::MIN),
709        }
710    }
711
712    #[must_use]
713    pub const fn is_finite(self) -> bool {
714        matches!(self, Self::Finite)
715    }
716
717    /// Where this kind sits in the total order.
718    ///
719    /// v7.38.19 — PostgreSQL 18.4, measured: `'-infinity' < '-100 years'`
720    /// and `'infinity' > '100 years'` are both true, and `'infinity' =
721    /// 'infinity'` is true. So the rank decides first and the numbers
722    /// only speak between two finite values.
723    ///
724    /// Every comparison of two intervals asks THIS -- the ordering
725    /// comparator, the value comparator and the binary operators each
726    /// had their own copy of the span arithmetic, and three copies of a
727    /// question is how they come to disagree.
728    #[must_use]
729    pub const fn rank(self) -> i8 {
730        match self {
731            Self::NegInf => -1,
732            Self::Finite => 0,
733            Self::PosInf => 1,
734        }
735    }
736}
737
738/// A row-cell value, including SQL `NULL`. `Float` uses `f64`; NaN compares
739/// non-equal to itself (PG behaviour) — `PartialEq` is derived so callers
740/// must opt into NaN-aware comparison if they need stronger guarantees.
741///
742/// v7.37.42-arena Phase 1: parameterised on `'arena` so heap-bearing
743/// variants (Text/Json/Xml/Bytes/Vector/BitString.bytes) can borrow from
744/// a per-query bump arena (`Cow::Borrowed(&'arena ...)`). Persistent /
745/// catalog Values use `Value<'static>` (alias `ValueOwned`) with
746/// `Cow::Owned(...)`. Phase 1 keeps Range/Multirange recursive `Box<Value>`
747/// at `'static` (owned) — arena migration deferred to a later phase.
748/// Array-of-Option<String> variants (TextArray etc.) also stay owned in
749/// Phase 1; their nested shape is awkward for the simple Cow lift and the
750/// SCALARSQ hot path doesn't touch them.
751/// v7.38 (read01, T6) — the IEEE-style class of a NUMERIC value. `Finite` is the
752/// ordinary fixed-point case; the specials mirror PG's `'NaN'` / `'Infinity'` /
753/// `'-Infinity'`. Derived `PartialEq` gives `NaN == NaN` — correct for NUMERIC
754/// (unlike float's NaN ≠ NaN); the total order (`-Inf < finite < +Inf < NaN`)
755/// lives in the comparison paths, not in `Ord`.
756#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Hash)]
757pub enum NumericKind {
758    #[default]
759    Finite,
760    NaN,
761    PosInf,
762    NegInf,
763}
764
765#[derive(Debug, Clone, PartialEq)]
766#[non_exhaustive]
767pub enum Value<'arena> {
768    SmallInt(i16),
769    Int(i32),
770    BigInt(i64),
771    Float(f64),
772    /// v7.38 (read01, T-float4) — PG `real` (32-bit IEEE float).
773    Real(f32),
774    Text(Cow<'arena, str>),
775    Bool(bool),
776    Vector(Cow<'arena, [f32]>),
777    /// v6.0.1: 8-bit scalar-quantised vector cell. Lives in
778    /// columns declared `VECTOR(N) USING SQ8`. Layout per cell:
779    /// `Sq8Vector { min: f32, max: f32, bytes: Vec<u8> }` —
780    /// 4× compression vs `Vector(Vec<f32>)`. The wire layer
781    /// dequantises to `f32` on SELECT; INSERT path quantises
782    /// incoming `Vector(Vec<f32>)` cells into this variant.
783    Sq8Vector(crate::quantize::Sq8Vector),
784    /// v6.0.3: IEEE-754 binary16 vector cell. Lives in columns
785    /// declared `VECTOR(N) USING HALF`. Stores raw u16 LE bits
786    /// (2× compression vs `Vector(Vec<f32>)`). Wire / display
787    /// paths dequantise to f32 bit-exactly; INSERT path converts
788    /// incoming f32 vectors at the engine boundary.
789    HalfVector(crate::halfvec::HalfVector),
790    /// Exact fixed-point decimal. `scaled` holds the value as
791    /// `actual * 10^scale` so the storage type is always integral —
792    /// arithmetic never falls back to floating-point. v7.38 (read01, T6) —
793    /// `kind` classifies the value as finite (the common case, using
794    /// `scaled`/`scale`) or one of PG's NUMERIC specials (NaN / ±Infinity),
795    /// which ignore `scaled`/`scale` (canonicalized to 0).
796    Numeric {
797        scaled: i128,
798        /// v7.39 (round 271) — widened from u8. PG's numeric carries a
799        /// display scale up to 16383; at u8 a literal with 256 decimal
800        /// places could not be represented at all, and the conversion
801        /// aborted the query with an internal error.
802        scale: u16,
803        kind: NumericKind,
804    },
805    /// v7.38 (read01, T3) — an exact NUMERIC whose mantissa overflows `i128`
806    /// (PG's NUMERIC is unbounded). Boxed so the common finite case keeps its
807    /// small footprint; specials never take this form (they stay `Numeric`).
808    NumericBig(alloc::boxed::Box<crate::bignum::BigNumeric>),
809    /// Days since the Unix epoch (1970-01-01). Negative for earlier dates.
810    Date(i32),
811    /// Microseconds since the Unix epoch (1970-01-01T00:00:00Z).
812    Timestamp(i64),
813    /// Calendar span: `months` + `days` + `micros`. Three fields are
814    /// required for PG byte-equal: `'1 day'` ≠ `'24 hours'` (DST,
815    /// month-boundary, and the on-wire `pg_type` `interval` are all
816    /// `i64 micros + i32 days + i32 months`). v7.37.5 β widened from
817    /// `{months, micros}`; column storage lands in the same window.
818    Interval {
819        months: i32,
820        days: i32,
821        micros: i64,
822        /// v7.38.19 — finite, or one of the two infinities.
823        ///
824        /// PostgreSQL 17 gave `interval` an infinite value and SPG had
825        /// none, so `'infinity'::interval` was refused outright and the
826        /// subtraction error the ledger described was one symptom of
827        /// that, not the defect.
828        ///
829        /// A field beside the numbers rather than a sentinel inside
830        /// them, which is the shape `Value::Numeric` already uses for
831        /// exactly this question — and a field on THIS variant rather
832        /// than a new one, so the compiler names every site that has to
833        /// decide what infinity means there. A new variant would have
834        /// compiled everywhere on the first try and let a `_` arm
835        /// answer for it at one of a hundred and five of them.
836        kind: IntervalKind,
837    },
838    /// v4.9 `JSON` — raw JSON text. No structural validation
839    /// happens at the storage layer; whatever the parser hands us
840    /// round-trips verbatim. Equality is byte-wise.
841    Json(Cow<'arena, str>),
842    /// v7.10.4 `BYTEA` — raw binary blob. Equality is byte-wise.
843    /// Layout matches `Text`'s length-prefixed shape (`[u32 LE
844    /// len][bytes]`) under tag 18; the engine accepts PG hex
845    /// literals (`'\xDEADBEEF'`) and escape literals at the
846    /// coercion boundary.
847    Bytes(Cow<'arena, [u8]>),
848    /// v7.10.9 `TEXT[]` — single-dimension TEXT array with
849    /// optional NULL elements. Equality is element-wise. PG's
850    /// NULL-element comparison semantics: NULL ≠ NULL inside
851    /// arrays under `=`, so `[NULL] != [NULL]` (the engine
852    /// honours this).
853    TextArray(Vec<Option<String>>),
854    /// v7.11.12 `INT[]` — single-dimension i32 array with optional
855    /// NULL elements. Codec mirrors TextArray with i32 LE per
856    /// element instead of length-prefixed UTF-8.
857    IntArray(Vec<Option<i32>>),
858    /// v7.11.12 `BIGINT[]` — single-dimension i64 array with optional
859    /// NULL elements.
860    BigIntArray(Vec<Option<i64>>),
861    /// v7.37.5 β-P4 `INTERVAL[]` — single-dimension array of
862    /// `IntervalSpan { months, days, micros }` with optional NULL
863    /// elements. PG external form quotes each non-NULL element
864    /// (`{"1 day","24:00:00",NULL}`) because interval text contains
865    /// spaces and colons. Storage codec follows the BigIntArray
866    /// shape with a 16-byte per-element body.
867    IntervalArray(Vec<Option<IntervalSpan>>),
868    /// v7.37.5 γ — single-dimension arrays of the remaining PG
869    /// scalar types. Each carries `Vec<Option<T>>` with the
870    /// scalar's natural Rust shape; element NULLs are first-class
871    /// (per PG: `{1,NULL,3}` is a 3-element array, not a 2-element
872    /// one). Codec follows the IntervalArray shape — `[u16 count]
873    /// [per elem: u8 null + (non-null) scalar body]`.
874    BoolArray(Vec<Option<bool>>),
875    SmallIntArray(Vec<Option<i16>>),
876    /// v7.39.11 — PG `int2vector`. An array of `smallint` that prints
877    /// space-separated and subscripts from 0; see
878    /// [`DataType::Int2Vector`]. PG's own vectors never hold NULLs, so
879    /// the elements are plain.
880    Int2Vector(Vec<i16>),
881    /// v7.39.11 — PG `oidvector`; see [`Value::Int2Vector`].
882    OidVector(Vec<u32>),
883    FloatArray(Vec<Option<f64>>),
884    /// PG `NUMERIC[]` — `(scaled: i128, scale: u16)` per element.
885    NumericArray(Vec<Option<(i128, u16)>>),
886    DateArray(Vec<Option<i32>>),
887    TimestampArray(Vec<Option<i64>>),
888    TimestamptzArray(Vec<Option<i64>>),
889    UuidArray(Vec<Option<[u8; 16]>>),
890    JsonArray(Vec<Option<String>>),
891    JsonbArray(Vec<Option<String>>),
892    BytesArray(Vec<Option<Vec<u8>>>),
893    VarcharArray(Vec<Option<String>>),
894    CharArray(Vec<Option<String>>),
895    /// v7.37.5 δ — PG 14+ multirange. `ranges` is a Vec of
896    /// non-overlapping bounds spans of the shared `kind`. PG's
897    /// canonical text form is `{[a,b),[c,d),...}` (comma-separated
898    /// ranges in braces; `{}` for the empty multirange). SPG's
899    /// constructor enforces no overlap/coalescing — for now the
900    /// engine trusts the caller (mirrors PG's `_construct_array`
901    /// pattern). Catalog tag 49 + 1-byte RangeKind on the dense
902    /// type-tag side; schema-less path is unreachable (multirange
903    /// is column-typed only).
904    Multirange {
905        kind: RangeKind,
906        ranges: Vec<RangeSpan>,
907    },
908    /// v7.37.5 ε — PG geometry scalars. Per-type Vec/struct shape;
909    /// codec body shape is described on the matching DataType
910    /// variant. PG canonical text forms:
911    ///   Point   `(x,y)`
912    ///   Lseg    `[(x1,y1),(x2,y2)]`
913    ///   Path    open `[(x,y),(x,y),...]` / closed `((x,y),(x,y),...)`
914    ///   Box     `(ux,uy),(lx,ly)` (PG normalises to upper-right + lower-left)
915    ///   Polygon `((x,y),(x,y),...)` (implicit closed)
916    ///   Line    `{a,b,c}` (Ax + By + C = 0)
917    ///   Circle  `<(x,y),r>`
918    Point(Point2D),
919    Lseg(Point2D, Point2D),
920    /// `closed = true` is `((p,p,...))`; `false` is `[(p,p,...)]`.
921    Path {
922        points: Vec<Point2D>,
923        closed: bool,
924    },
925    /// PG `box` — stored as `(upper_right, lower_left)` (PG's
926    /// normalised order). The engine accepts both endpoint
927    /// orderings at parse time and normalises here.
928    PgBox(Point2D, Point2D),
929    Polygon(Vec<Point2D>),
930    Line {
931        a: f64,
932        b: f64,
933        c: f64,
934    },
935    Circle {
936        center: Point2D,
937        radius: f64,
938    },
939    /// v7.37.5 ζ-A — PG `inet`. `family = 4` (IPv4) or `6` (IPv6).
940    /// `bits` is the netmask bit count (0..=32 for IPv4, 0..=128
941    /// for IPv6). `addr` is right-padded with zeros when family=4
942    /// (first 4 bytes are the address).
943    Inet {
944        family: u8,
945        bits: u8,
946        addr: [u8; 16],
947    },
948    /// v7.37.5 ζ-A — PG `cidr`. Same shape as Inet; CIDR's
949    /// invariant (host bits zero) is enforced at parse / coerce.
950    Cidr {
951        family: u8,
952        bits: u8,
953        addr: [u8; 16],
954    },
955    /// v7.37.5 ζ-A — PG `macaddr`. 6 bytes (XX:XX:XX:XX:XX:XX).
956    Macaddr([u8; 6]),
957    /// v7.37.5 ζ-A — PG `macaddr8`. 8 bytes (EUI-64).
958    Macaddr8([u8; 8]),
959    /// v7.39 (read01 pg_lsn.c) — PG `pg_lsn`, a 64-bit WAL location.
960    PgLsn(u64),
961    /// v7.39 (read01 ruleutils.c) — PG `regclass`: an OID-typed relation
962    /// reference that renders as the relation name. SPG carries BOTH
963    /// (the synthetic oid for catalog joins, the name for display) so
964    /// `conrelid = 't'::regclass` and `'t'::regclass::text` agree.
965    /// Eval-only (no column storage).
966    RegClass(i64, alloc::boxed::Box<str>),
967    /// v7.39 (round 342, V65) — PG `regproc`: an OID-typed FUNCTION
968    /// reference that renders as the function name. Same dual shape
969    /// [`Value::RegClass`] carries, and for the same reason: without the
970    /// oid half, `pg_proc.oid = 'f'::regproc` cannot join, and a callee
971    /// cannot tell `pg_get_functiondef('f'::regproc)` — which PG answers
972    /// — from `pg_get_functiondef('f')` — which PG rejects.
973    /// Eval-only (no column storage).
974    RegProc(i64, alloc::boxed::Box<str>),
975    /// v7.39 (round 648) — PG `regtype`: an OID-typed TYPE reference
976    /// that renders as the type name. The third of the shape
977    /// [`Value::RegClass`] and [`Value::RegProc`] carry, and the one
978    /// that was missing it: `::regtype` produced a plain `Value::Text`
979    /// holding the canonical name, so `'text'::regtype::oid` tried to
980    /// parse the NAME as a number and answered `invalid input syntax
981    /// for type oid: "text"` where PG answers 25. `pg_typeof` on one
982    /// said `text` rather than `regtype` for the same reason.
983    ///
984    /// Eval-only (no column storage).
985    RegType(i64, alloc::boxed::Box<str>),
986    /// v7.39 (round 512) — PG `xid` and `cid`, the transaction and command
987    /// ids the `xmin` / `xmax` / `cmin` / `cmax` system columns carry.
988    ///
989    /// Their own types rather than integers, because PG deliberately gives
990    /// them almost no operators: measured on PG18, `xmin + 1` is "operator
991    /// does not exist: xid + integer", `xmin > 0` likewise, `xmin::bigint`
992    /// is "cannot cast type xid to bigint", and there is no `max(xid)`.
993    /// Carrying them as BigInt would quietly allow all four.
994    ///
995    /// Eval-only (no column storage).
996    Xid(u32),
997    Cid(u32),
998    /// v7.39 (round 511) — PG `tid`, the physical row identity `ctid`
999    /// carries: a block number and a one-based offset inside it, rendered
1000    /// `(block,offset)`.
1001    ///
1002    /// It is a real type rather than a two-field record because the idiom
1003    /// that makes `ctid` worth having — `DELETE … WHERE ctid NOT IN (SELECT
1004    /// min(ctid) … GROUP BY key)` — needs `min()` over it, and PG has no
1005    /// `min(record)`. Ordering is by block then offset, so `(0,2) < (0,9) <
1006    /// (0,10)`; a text form would order those `(0,10) < (0,2) < (0,9)` and
1007    /// the dedup would keep the wrong row.
1008    ///
1009    /// Eval-only (no column storage).
1010    Tid(u32, u32),
1011    /// v7.37.5 ζ-A — PG `bit` / `bit varying`. `nbits` is the
1012    /// actual bit count; `bytes` is the packed representation
1013    /// (big-endian within each byte; final byte right-padded
1014    /// with 0s if `nbits % 8 != 0`).
1015    BitString {
1016        nbits: u32,
1017        bytes: Cow<'arena, [u8]>,
1018    },
1019    /// v7.37.5 ζ-A — PG `xml`. Stored verbatim as a string; no
1020    /// parse-time validation (matches the SPG JSON convention).
1021    Xml(Cow<'arena, str>),
1022    /// v7.37.5 ζ-A — PG `"char"` (internal single-byte type,
1023    /// distinct from CHAR(n)).
1024    Char1(u8),
1025    /// v7.38 (read01, T11) — PG `bpchar` / CHAR(n): blank-padded fixed-length
1026    /// string. Stored space-padded to the declared width (as PG does + for wire
1027    /// display); length / comparison / ::text / concat all ignore the trailing
1028    /// blanks (handled at those sites).
1029    BpChar(Cow<'arena, str>),
1030    /// v7.37.5 ζ-A — PG `money[]`.
1031    MoneyArray(Vec<Option<i64>>),
1032    /// v7.12.0 `tsvector` — sorted-by-word, deduped lexeme set with
1033    /// positions + weights. The engine enforces sort/dedup on
1034    /// construction; consumers can rely on `lexemes.windows(2)`
1035    /// being strictly ascending by `word`.
1036    TsVector(Vec<TsLexeme>),
1037    /// v7.12.0 `tsquery` — boolean / phrase parse tree over
1038    /// lexemes. Engine builds via `to_tsquery` family.
1039    TsQuery(TsQueryAst),
1040    /// v7.17.0 `uuid` — 128-bit identifier. Stored as 16 bytes
1041    /// (big-endian / network-byte order, same as RFC 4122).
1042    /// Display normalises to canonical lowercase 8-4-4-4-12
1043    /// hyphenated form. Equality is byte-wise.
1044    Uuid([u8; 16]),
1045    /// v7.17.0 Phase 3.P0-32 — PG `time` (without time zone) —
1046    /// i64 microseconds since 00:00:00. Range 0..86_400_000_000.
1047    /// Display: `HH:MM:SS` zero-padded, with optional `.ffffff`
1048    /// suffix when fractional is non-zero.
1049    Time(i64),
1050    /// v7.17.0 Phase 3.P0-33 — MySQL `YEAR` — u16 in range
1051    /// 1901..=2155 plus the special zero-year sentinel 0.
1052    /// Display always 4 digits zero-padded (`0000` for the
1053    /// sentinel; `1985`/`2007` otherwise).
1054    Year(u16),
1055    /// v7.17.0 Phase 3.P0-34 — PG `time with time zone` — i64
1056    /// microseconds since 00:00:00 in the LOCAL wall clock PLUS
1057    /// an i32 offset-from-UTC in seconds. PG preserves the
1058    /// offset on output, so the wall-clock value is NOT shifted
1059    /// to UTC at storage time. Offset range: ±50400 seconds
1060    /// (±14 hours).
1061    TimeTz {
1062        us: i64,
1063        offset_secs: i32,
1064    },
1065    /// v7.17.0 Phase 3.P0-35 — PG `money` — i64 cents
1066    /// (locale-independent storage; the en_US locale renders on
1067    /// display via `$N,NNN.CC`).
1068    Money(i64),
1069    /// v7.17.0 Phase 3.P0-39 — PG `hstore` value: flat
1070    /// `text => text` map with NULL value support. Insertion
1071    /// order preserved on input; duplicate keys take last-write-
1072    /// wins at parse time.
1073    Hstore(Vec<(String, Option<String>)>),
1074    /// v7.17.0 Phase 3.P0-40 — 2D INT matrix (row-major).
1075    IntArray2D(Vec<Vec<Option<i32>>>),
1076    /// v7.17.0 Phase 3.P0-40 — 2D BIGINT matrix (row-major).
1077    BigIntArray2D(Vec<Vec<Option<i64>>>),
1078    /// v7.17.0 Phase 3.P0-40 — 2D TEXT matrix (row-major).
1079    TextArray2D(Vec<Vec<Option<String>>>),
1080    /// v7.39 (read01 round 75) — see `DataType::BoolArray2D`.
1081    BoolArray2D(Vec<Vec<Option<bool>>>),
1082    /// v7.17.0 Phase 3.P0-38 — PG range value. One shape covers
1083    /// all six builtin range types; `kind` pins the element type
1084    /// (must match the column's `DataType::Range(kind)`).
1085    /// `lower` / `upper` are `None` for the unbounded sides;
1086    /// `lower_inc` / `upper_inc` mirror the canonical PG
1087    /// `[` / `(` / `]` / `)` bracket inclusivity. `empty=true`
1088    /// supersedes all other fields (the empty range has no
1089    /// bounds).
1090    Range {
1091        kind: RangeKind,
1092        // v7.37.42-arena Phase 1: Range bounds stay owned ('static).
1093        // Recursive arena lifetimes are awkward to migrate at this
1094        // phase and the SCALARSQ hot path doesn't construct ranges.
1095        lower: Option<alloc::boxed::Box<Value<'static>>>,
1096        upper: Option<alloc::boxed::Box<Value<'static>>>,
1097        lower_inc: bool,
1098        upper_inc: bool,
1099        empty: bool,
1100    },
1101    /// v7.38 (read01, T9) — a composite / record value (a `row(...)`
1102    /// constructor or a whole-row reference). Fields are `(name, value)`; the
1103    /// names are `f1..fN` for an anonymous `row(...)` or the source column
1104    /// names for a table row. Transient — flows through row_to_json / to_json
1105    /// and the composite text form `(a,b)`; not a storable column type here.
1106    Composite(alloc::vec::Vec<(alloc::string::String, Value<'static>)>),
1107    Null,
1108}
1109
1110/// Owned `Value` — heap-bearing variants are `Cow::Owned`. Used everywhere
1111/// a Value must outlive a query-scoped arena (catalog defaults, persistent
1112/// storage, public APIs).
1113pub type ValueOwned = Value<'static>;
1114
1115/// v7.37.5 ε — PG `point` building block. Shared by every other
1116/// geometric type (lseg / path / box / polygon / circle all
1117/// reduce to compositions of `Point2D`). Packed `{x: f64, y: f64}`,
1118/// 16 B, on-disk LE field order matches the PG binary point
1119/// format byte-for-byte (so a future binary BIND path lands
1120/// without rearrangement).
1121#[derive(Debug, Clone, Copy, PartialEq)]
1122pub struct Point2D {
1123    pub x: f64,
1124    pub y: f64,
1125}
1126
1127/// v7.37.5 δ — single-range bounds without the kind tag. Used as
1128/// the element type of `Value::Multirange { kind, ranges }` so a
1129/// multirange carries one shared `RangeKind` plus N bounds-only
1130/// spans (saves 1 byte/elem vs duplicating the kind). The five
1131/// other fields mirror `Value::Range` exactly.
1132#[derive(Debug, Clone, PartialEq)]
1133pub struct RangeSpan {
1134    // v7.37.42-arena Phase 1: stays owned ('static) — same rationale as
1135    // Range bounds above.
1136    pub lower: Option<alloc::boxed::Box<Value<'static>>>,
1137    pub upper: Option<alloc::boxed::Box<Value<'static>>>,
1138    pub lower_inc: bool,
1139    pub upper_inc: bool,
1140    pub empty: bool,
1141}
1142
1143/// v7.37.5 β-P4 — element type for `Value::IntervalArray`. Mirrors
1144/// the `{months, days, micros}` shape of scalar `Value::Interval`,
1145/// broken out as a named struct so `IntervalArray`'s element type
1146/// is concrete (24 bytes, packed) instead of an enum-boxed Value.
1147/// All three dimensions are independent — `IntervalSpan { days: 1,
1148/// .. }` is distinct from `IntervalSpan { micros: 86_400_000_000,
1149/// .. }` per PG byte-equal.
1150#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1151pub struct IntervalSpan {
1152    pub months: i32,
1153    pub days: i32,
1154    pub micros: i64,
1155    /// v7.38.19 — see [`IntervalKind`].
1156    pub kind: IntervalKind,
1157}
1158
1159impl<'arena> Value<'arena> {
1160    /// Type tag, or `None` for `NULL` (unknown at value level).
1161    pub fn data_type(&self) -> Option<DataType> {
1162        match self {
1163            Self::SmallInt(_) => Some(DataType::SmallInt),
1164            Self::Int(_) => Some(DataType::Int),
1165            Self::BigInt(_) => Some(DataType::BigInt),
1166            Self::Float(_) => Some(DataType::Float),
1167            Self::Real(_) => Some(DataType::Real),
1168            // `Text` covers both unbounded TEXT and bounded VARCHAR/CHAR
1169            // — the constraint lives on the column schema, not the value.
1170            Self::Text(_) => Some(DataType::Text),
1171            Self::Bool(_) => Some(DataType::Bool),
1172            Self::Vector(v) => Some(DataType::Vector {
1173                dim: u32::try_from(v.len()).expect("vector dim ≤ u32"),
1174                encoding: VecEncoding::F32,
1175            }),
1176            Self::Sq8Vector(q) => Some(DataType::Vector {
1177                dim: u32::try_from(q.bytes.len()).expect("vector dim ≤ u32"),
1178                encoding: VecEncoding::Sq8,
1179            }),
1180            Self::HalfVector(h) => Some(DataType::Vector {
1181                dim: u32::try_from(h.dim()).expect("vector dim ≤ u32"),
1182                encoding: VecEncoding::F16,
1183            }),
1184            // `Value::Numeric` doesn't carry its precision (the column
1185            // schema does); we surface precision=0 as "unknown" and let
1186            // the engine reconcile against the column type at coercion
1187            // time.
1188            // v7.39 (round 273) — a VALUE's display scale is unsigned and
1189            // never exceeds PG's 16383 ceiling, so it always fits the
1190            // signed declared-scale field this describes itself with.
1191            Self::Numeric { scale, .. } => Some(DataType::Numeric {
1192                precision: 0,
1193                scale: i16::try_from(*scale).unwrap_or(i16::MAX),
1194            }),
1195            Self::NumericBig(b) => Some(DataType::Numeric {
1196                precision: 0,
1197                scale: i16::try_from(b.scale()).unwrap_or(i16::MAX),
1198            }),
1199            Self::Date(_) => Some(DataType::Date),
1200            Self::Timestamp(_) => Some(DataType::Timestamp),
1201            Self::Interval { .. } => Some(DataType::Interval),
1202            Self::Json(_) => Some(DataType::Json),
1203            Self::Bytes(_) => Some(DataType::Bytes),
1204            Self::TextArray(_) => Some(DataType::TextArray),
1205            Self::IntArray(_) => Some(DataType::IntArray),
1206            Self::BigIntArray(_) => Some(DataType::BigIntArray),
1207            Self::IntervalArray(_) => Some(DataType::IntervalArray),
1208            Self::BoolArray(_) => Some(DataType::BoolArray),
1209            Self::SmallIntArray(_) => Some(DataType::SmallIntArray),
1210            Self::Int2Vector(_) => Some(DataType::Int2Vector),
1211            Self::OidVector(_) => Some(DataType::OidVector),
1212            Self::FloatArray(_) => Some(DataType::FloatArray),
1213            Self::NumericArray(_) => Some(DataType::NumericArray),
1214            Self::DateArray(_) => Some(DataType::DateArray),
1215            Self::TimestampArray(_) => Some(DataType::TimestampArray),
1216            Self::TimestamptzArray(_) => Some(DataType::TimestamptzArray),
1217            Self::UuidArray(_) => Some(DataType::UuidArray),
1218            Self::JsonArray(_) => Some(DataType::JsonArray),
1219            Self::JsonbArray(_) => Some(DataType::JsonbArray),
1220            Self::BytesArray(_) => Some(DataType::BytesArray),
1221            Self::VarcharArray(_) => Some(DataType::VarcharArray),
1222            Self::CharArray(_) => Some(DataType::CharArray),
1223            Self::Multirange { kind, .. } => Some(DataType::Multirange(*kind)),
1224            Self::Point(_) => Some(DataType::Point),
1225            Self::Lseg(_, _) => Some(DataType::Lseg),
1226            Self::Path { .. } => Some(DataType::Path),
1227            Self::PgBox(_, _) => Some(DataType::PgBox),
1228            Self::Polygon(_) => Some(DataType::Polygon),
1229            Self::Line { .. } => Some(DataType::Line),
1230            Self::Circle { .. } => Some(DataType::Circle),
1231            Self::Inet { .. } => Some(DataType::Inet),
1232            Self::Cidr { .. } => Some(DataType::Cidr),
1233            Self::Macaddr(_) => Some(DataType::Macaddr),
1234            Self::Macaddr8(_) => Some(DataType::Macaddr8),
1235            Self::PgLsn(_) => Some(DataType::PgLsn),
1236            // BitString could be either Bit or BitVarying; column
1237            // schema decides. Default to BitVarying when called
1238            // schema-less (rare; storage path is always
1239            // schema-aware so this only matters for diagnostics).
1240            Self::BitString { .. } => Some(DataType::BitVarying(0)),
1241            Self::Xml(_) => Some(DataType::Xml),
1242            Self::Char1(_) => Some(DataType::Char1),
1243            // BpChar reports its declared width from the padded length.
1244            Self::BpChar(s) => Some(DataType::Char(
1245                u32::try_from(s.chars().count()).unwrap_or(0),
1246            )),
1247            Self::MoneyArray(_) => Some(DataType::MoneyArray),
1248            Self::TsVector(_) => Some(DataType::TsVector),
1249            Self::TsQuery(_) => Some(DataType::TsQuery),
1250            Self::Uuid(_) => Some(DataType::Uuid),
1251            Self::Time(_) => Some(DataType::Time),
1252            Self::Year(_) => Some(DataType::Year),
1253            Self::TimeTz { .. } => Some(DataType::TimeTz),
1254            Self::Money(_) => Some(DataType::Money),
1255            Self::Range { kind, .. } => Some(DataType::Range(*kind)),
1256            Self::Hstore(_) => Some(DataType::Hstore),
1257            Self::IntArray2D(_) => Some(DataType::IntArray2D),
1258            Self::BigIntArray2D(_) => Some(DataType::BigIntArray2D),
1259            Self::TextArray2D(_) => Some(DataType::TextArray2D),
1260            Self::BoolArray2D(_) => Some(DataType::BoolArray2D),
1261            // v7.38 (read01, T9) — a transient composite/record has no storable
1262            // column DataType (it flows through row_to_json / to_json).
1263            Self::Composite(_) => None,
1264            // v7.39 (read01 ruleutils.c) — regclass is eval-only (dual
1265            // oid+name shape); no column storage type.
1266            // v7.39 (round 640) — `xid` became a column type, so its value
1267            // has a DataType to answer with. `cid` and `tid` are equally
1268            // legal column types on PG (measured: `CREATE TABLE t (a cid,
1269            // b tid)` is accepted), but SPG's grammar has no keyword for
1270            // them yet; they stay eval-only rather than half-declared.
1271            Self::Xid(_) => Some(DataType::Xid),
1272            Self::RegClass(..)
1273            | Self::RegProc(..)
1274            | Self::RegType(..)
1275            | Self::Tid(..)
1276            | Self::Cid(_) => None,
1277            Self::Null => None,
1278        }
1279    }
1280
1281    pub const fn is_null(&self) -> bool {
1282        matches!(self, Self::Null)
1283    }
1284
1285    /// v7.37.42-arena Phase 1: lift any `Value<'arena>` (possibly
1286    /// borrowing from a bump arena) into a fully-owned `Value<'static>`.
1287    /// Used at boundaries that must outlive the per-query arena
1288    /// (catalog write, public QueryResult emit, sqlx materialise).
1289    ///
1290    /// For the recursive Range/Multirange variants — bounds are already
1291    /// `Box<Value<'static>>` per Phase 1 design, so we just rebuild the
1292    /// outer enum at `'static`.
1293    pub fn into_owned(self) -> Value<'static> {
1294        match self {
1295            Value::SmallInt(n) => Value::SmallInt(n),
1296            Value::Int(n) => Value::Int(n),
1297            Value::BigInt(n) => Value::BigInt(n),
1298            Value::Float(f) => Value::Float(f),
1299            Value::Real(f) => Value::Real(f),
1300            Value::Text(s) => Value::Text(Cow::Owned(s.into_owned())),
1301            Value::Bool(b) => Value::Bool(b),
1302            Value::Vector(v) => Value::Vector(Cow::Owned(v.into_owned())),
1303            Value::Sq8Vector(q) => Value::Sq8Vector(q),
1304            Value::HalfVector(h) => Value::HalfVector(h),
1305            Value::Numeric {
1306                scaled,
1307                scale,
1308                kind,
1309            } => Value::Numeric {
1310                scaled,
1311                scale,
1312                kind,
1313            },
1314            Value::NumericBig(b) => Value::NumericBig(b),
1315            Value::Date(d) => Value::Date(d),
1316            Value::Timestamp(t) => Value::Timestamp(t),
1317            Value::Interval {
1318                months,
1319                days,
1320                micros,
1321                kind,
1322            } => Value::Interval {
1323                months,
1324                days,
1325                micros,
1326                kind,
1327            },
1328            Value::Json(s) => Value::Json(Cow::Owned(s.into_owned())),
1329            Value::Bytes(b) => Value::Bytes(Cow::Owned(b.into_owned())),
1330            Value::TextArray(v) => Value::TextArray(v),
1331            Value::IntArray(v) => Value::IntArray(v),
1332            Value::BigIntArray(v) => Value::BigIntArray(v),
1333            Value::IntervalArray(v) => Value::IntervalArray(v),
1334            Value::BoolArray(v) => Value::BoolArray(v),
1335            Value::SmallIntArray(v) => Value::SmallIntArray(v),
1336            Value::Int2Vector(v) => Value::Int2Vector(v),
1337            Value::OidVector(v) => Value::OidVector(v),
1338            Value::FloatArray(v) => Value::FloatArray(v),
1339            Value::NumericArray(v) => Value::NumericArray(v),
1340            Value::DateArray(v) => Value::DateArray(v),
1341            Value::TimestampArray(v) => Value::TimestampArray(v),
1342            Value::TimestamptzArray(v) => Value::TimestamptzArray(v),
1343            Value::UuidArray(v) => Value::UuidArray(v),
1344            Value::JsonArray(v) => Value::JsonArray(v),
1345            Value::JsonbArray(v) => Value::JsonbArray(v),
1346            Value::BytesArray(v) => Value::BytesArray(v),
1347            Value::VarcharArray(v) => Value::VarcharArray(v),
1348            Value::CharArray(v) => Value::CharArray(v),
1349            Value::Multirange { kind, ranges } => Value::Multirange { kind, ranges },
1350            // v7.38 (read01, T9) — Composite fields are already `Value<'static>`.
1351            Value::Composite(fields) => Value::Composite(fields),
1352            Value::RegClass(oid, name) => Value::RegClass(oid, name),
1353            Value::Tid(b, o) => Value::Tid(b, o),
1354            Value::Xid(x) => Value::Xid(x),
1355            Value::Cid(c) => Value::Cid(c),
1356            Value::RegProc(oid, name) => Value::RegProc(oid, name),
1357            Value::RegType(oid, name) => Value::RegType(oid, name),
1358            Value::Point(p) => Value::Point(p),
1359            Value::Lseg(a, b) => Value::Lseg(a, b),
1360            Value::Path { points, closed } => Value::Path { points, closed },
1361            Value::PgBox(a, b) => Value::PgBox(a, b),
1362            Value::Polygon(p) => Value::Polygon(p),
1363            Value::Line { a, b, c } => Value::Line { a, b, c },
1364            Value::Circle { center, radius } => Value::Circle { center, radius },
1365            Value::Inet { family, bits, addr } => Value::Inet { family, bits, addr },
1366            Value::Cidr { family, bits, addr } => Value::Cidr { family, bits, addr },
1367            Value::Macaddr(m) => Value::Macaddr(m),
1368            Value::Macaddr8(m) => Value::Macaddr8(m),
1369            Value::PgLsn(l) => Value::PgLsn(l),
1370            Value::BitString { nbits, bytes } => Value::BitString {
1371                nbits,
1372                bytes: Cow::Owned(bytes.into_owned()),
1373            },
1374            Value::Xml(s) => Value::Xml(Cow::Owned(s.into_owned())),
1375            Value::Char1(c) => Value::Char1(c),
1376            Value::BpChar(s) => Value::BpChar(Cow::Owned(s.into_owned())),
1377            Value::MoneyArray(v) => Value::MoneyArray(v),
1378            Value::TsVector(v) => Value::TsVector(v),
1379            Value::TsQuery(q) => Value::TsQuery(q),
1380            Value::Uuid(u) => Value::Uuid(u),
1381            Value::Time(t) => Value::Time(t),
1382            Value::Year(y) => Value::Year(y),
1383            Value::TimeTz { us, offset_secs } => Value::TimeTz { us, offset_secs },
1384            Value::Money(m) => Value::Money(m),
1385            Value::Range {
1386                kind,
1387                lower,
1388                upper,
1389                lower_inc,
1390                upper_inc,
1391                empty,
1392            } => Value::Range {
1393                kind,
1394                lower,
1395                upper,
1396                lower_inc,
1397                upper_inc,
1398                empty,
1399            },
1400            Value::Hstore(h) => Value::Hstore(h),
1401            Value::IntArray2D(a) => Value::IntArray2D(a),
1402            Value::BigIntArray2D(a) => Value::BigIntArray2D(a),
1403            Value::TextArray2D(a) => Value::TextArray2D(a),
1404            Value::BoolArray2D(a) => Value::BoolArray2D(a),
1405            Value::Null => Value::Null,
1406        }
1407    }
1408
1409    /// v7.37.42-arena Phase 4 — copy heap payloads into the supplied
1410    /// bump arena, yielding a `Value<'a>` whose Cow-variant payloads
1411    /// are arena-borrowed (or stay as small owned scalars for the
1412    /// `Copy`-able variants).
1413    ///
1414    /// Used at the catalog ↔ ephemeral boundary: a `ColumnSchema.default`
1415    /// is `Value<'static>` but INSERT-time eval may want it stamped into
1416    /// the per-statement arena alongside other arena-built scalars.
1417    ///
1418    /// Allocates only into the supplied arena; the input `&self` keeps
1419    /// its own storage. For `Copy`-able / nested-owned variants the
1420    /// implementation falls back to `clone()` (the nested heap blocks
1421    /// stay on the global allocator, which is fine — the boundary
1422    /// requirement is just "no aliasing of caller-owned strings").
1423    pub fn clone_into<'a>(&self, arena: &'a bumpalo::Bump) -> Value<'a> {
1424        match self {
1425            Value::Text(s) => Value::Text(Cow::Borrowed(arena.alloc_str(s))),
1426            Value::Json(s) => Value::Json(Cow::Borrowed(arena.alloc_str(s))),
1427            Value::Xml(s) => Value::Xml(Cow::Borrowed(arena.alloc_str(s))),
1428            Value::BpChar(s) => Value::BpChar(Cow::Borrowed(arena.alloc_str(s))),
1429            Value::Bytes(b) => {
1430                let slot = arena.alloc_slice_copy::<u8>(b);
1431                Value::Bytes(Cow::Borrowed(slot))
1432            }
1433            Value::Vector(v) => {
1434                let slot = arena.alloc_slice_copy::<f32>(v);
1435                Value::Vector(Cow::Borrowed(slot))
1436            }
1437            Value::BitString { nbits, bytes } => {
1438                let slot = arena.alloc_slice_copy::<u8>(bytes);
1439                Value::BitString {
1440                    nbits: *nbits,
1441                    bytes: Cow::Borrowed(slot),
1442                }
1443            }
1444            // Copy-able scalars + variants whose nested heap blocks are
1445            // `'static` regardless of `'arena` (TextArray, JsonArray,
1446            // Hstore, TsVector, Range bounds, …). Clone the heap block
1447            // via the standard `into_owned()` path then lift the
1448            // resulting `Value<'static>` to `Value<'a>` via the Cow
1449            // variance — `'static` covers any lifetime.
1450            other => other.clone().into_owned(),
1451        }
1452    }
1453}
1454
1455impl Value<'static> {
1456    /// v7.37.42-arena Phase 1 — owned-Text constructor. The variant now
1457    /// holds `Cow<'arena, str>`, so the previous `Value::Text(String)`
1458    /// shape no longer compiles directly. This helper preserves the
1459    /// historical ergonomics: `Value::text("foo")` or
1460    /// `Value::text(String::from("foo"))`.
1461    pub fn text<S: Into<String>>(s: S) -> Self {
1462        Value::Text(Cow::Owned(s.into()))
1463    }
1464
1465    /// v7.38 (read01, T6) — a finite NUMERIC from its fixed-point parts.
1466    pub const fn numeric(scaled: i128, scale: u16) -> Self {
1467        Value::Numeric {
1468            scaled,
1469            scale,
1470            kind: NumericKind::Finite,
1471        }
1472    }
1473
1474    /// v7.38 (read01, T6) — a special NUMERIC (NaN / ±Infinity). The fixed-point
1475    /// fields are canonicalized to 0 so equal specials compare byte-identical.
1476    pub const fn numeric_special(kind: NumericKind) -> Self {
1477        Value::Numeric {
1478            scaled: 0,
1479            scale: 0,
1480            kind,
1481        }
1482    }
1483
1484    /// v7.37.42-arena Phase 1 — owned-Json constructor (mirrors `text`).
1485    pub fn json<S: Into<String>>(s: S) -> Self {
1486        Value::Json(Cow::Owned(s.into()))
1487    }
1488
1489    /// v7.37.42-arena Phase 1 — owned-Xml constructor.
1490    pub fn xml<S: Into<String>>(s: S) -> Self {
1491        Value::Xml(Cow::Owned(s.into()))
1492    }
1493
1494    /// v7.37.42-arena Phase 1 — owned-Bytes constructor.
1495    pub fn bytes<B: Into<Vec<u8>>>(b: B) -> Self {
1496        Value::Bytes(Cow::Owned(b.into()))
1497    }
1498
1499    /// v7.37.42-arena Phase 1 — owned-Vector constructor.
1500    pub fn vector<V: Into<Vec<f32>>>(v: V) -> Self {
1501        Value::Vector(Cow::Owned(v.into()))
1502    }
1503
1504    /// v7.37.42-arena Phase 1 — owned-BitString constructor.
1505    pub fn bit_string<B: Into<Vec<u8>>>(nbits: u32, bytes: B) -> Self {
1506        Value::BitString {
1507            nbits,
1508            bytes: Cow::Owned(bytes.into()),
1509        }
1510    }
1511}
1512
1513/// One table row — values are positional and must match
1514/// `TableSchema.columns` in length and (modulo NULL) in `DataType`.
1515///
1516/// v7.37.42-arena Phase 1: parameterised on `'arena` so per-query rows
1517/// can borrow from a bump arena. The owned shape (`Row<'static>`, alias
1518/// `RowOwned`) is what catalog storage, public APIs, and tests use.
1519#[derive(Debug, Clone, PartialEq)]
1520pub struct Row<'arena> {
1521    pub values: Vec<Value<'arena>>,
1522}
1523
1524/// Owned `Row` — values are `Value<'static>`. Used everywhere a row must
1525/// outlive a query-scoped arena.
1526pub type RowOwned = Row<'static>;
1527
1528impl<'arena> Row<'arena> {
1529    pub const fn new(values: Vec<Value<'arena>>) -> Self {
1530        Self { values }
1531    }
1532
1533    pub fn len(&self) -> usize {
1534        self.values.len()
1535    }
1536
1537    pub fn is_empty(&self) -> bool {
1538        self.values.is_empty()
1539    }
1540}
1541
1542impl<'arena> Row<'arena> {
1543    /// v7.37.42-arena Phase 4 — copy every cell into the supplied bump
1544    /// arena, yielding a `Row<'a>` whose Cow-payloads are arena-borrowed.
1545    /// Boundary helper for catalog defaults → DML eval handoff and
1546    /// arena-local row scratch.
1547    pub fn clone_into<'a>(&self, arena: &'a bumpalo::Bump) -> Row<'a> {
1548        Row {
1549            values: self.values.iter().map(|v| v.clone_into(arena)).collect(),
1550        }
1551    }
1552
1553    /// v7.37.42-arena Phase 4 — lift this `Row<'arena>` to a fully-owned
1554    /// `Row<'static>` for catalog write / WAL serialisation. Equivalent
1555    /// to `Row::from_arena(self)` but consumes by value at any lifetime
1556    /// (callers can write `row.into_owned()` mirroring `Value::into_owned`).
1557    pub fn into_owned(self) -> Row<'static> {
1558        Row {
1559            values: self.values.into_iter().map(Value::into_owned).collect(),
1560        }
1561    }
1562}
1563
1564impl Row<'static> {
1565    /// v7.37.42-arena Phase 1 — lift any `Row<'arena>` (possibly arena-
1566    /// borrowed) into a fully-owned `Row<'static>`. Mirrors
1567    /// `Value::into_owned`.
1568    pub fn from_arena(row: Row<'_>) -> Self {
1569        Self {
1570            values: row.values.into_iter().map(Value::into_owned).collect(),
1571        }
1572    }
1573}
1574
1575/// Each bool is an independent, separately-persisted column attribute
1576/// (`nullable`, `auto_increment`, `is_unsigned`, `identity_always`) that the
1577/// catalog appendix reads and writes by name. Packing them into a bitflags
1578/// word would buy nothing and would put a decoding step between the on-disk
1579/// format and every reader of the schema.
1580#[allow(clippy::struct_excessive_bools)]
1581#[derive(Debug, Clone, PartialEq)]
1582pub struct ColumnSchema {
1583    pub name: String,
1584    pub ty: DataType,
1585    pub nullable: bool,
1586    /// Optional `DEFAULT` value, frozen at CREATE TABLE time. `None`
1587    /// means "no default" (so omitted columns become NULL, or error
1588    /// out when the column is NOT NULL). Literal defaults take this
1589    /// path.
1590    ///
1591    /// v7.37.42-arena Phase 1: explicitly `Value<'static>` — catalog
1592    /// defaults must outlive any per-query arena.
1593    pub default: Option<Value<'static>>,
1594    /// v7.9.21 — for DEFAULT expressions that need INSERT-time
1595    /// evaluation (e.g. `DEFAULT now()`, `DEFAULT CURRENT_TIMESTAMP`),
1596    /// the Display form of the expression. The engine re-parses
1597    /// it on each INSERT default-fill, evaluates against an empty
1598    /// row context, and coerces to the column type. mailrs G4.
1599    /// Persisted in catalog FILE_VERSION 15+; older catalogs
1600    /// deserialise with None.
1601    pub runtime_default: Option<String>,
1602    /// MySQL-style `AUTO_INCREMENT`. When set, an INSERT that leaves
1603    /// this column unbound (or sets it to NULL) gets the next integer
1604    /// computed from the column's current max + 1.
1605    /// v7.39 (round 676) — the collation NAME as written, when the column
1606    /// carried an explicit `COLLATE`.
1607    ///
1608    /// `spg_sql::Collation` cannot carry it: it is a two-variant MySQL enum
1609    /// and `from_collation_name` folds `C`, `POSIX`, `en_US` and `default`
1610    /// all into `Binary`. Without the name `pg_attribute.attcollation` can
1611    /// only ever report the type's default, which is what F36 records as
1612    /// "the declaration is taken and ignored".
1613    ///
1614    /// None means the column was written without a `COLLATE` clause and
1615    /// takes its type's collation. Persisted through the v88 appendix,
1616    /// which costs two bytes for a table that declares none.
1617    pub collation_name: Option<String>,
1618    pub auto_increment: bool,
1619    /// v7.17.0 Phase 1.4 — when the column is bound to a user-
1620    /// defined ENUM type (the parser saw an unknown type ident
1621    /// and the engine resolved it against `catalog.enum_types`),
1622    /// this carries the enum name so INSERT/UPDATE can validate
1623    /// the cell value against the enum's labels. `ty` is
1624    /// `DataType::Text` in that case. Persisted in catalog
1625    /// FILE_VERSION 29+; older catalogs deserialise with None.
1626    pub user_enum_type: Option<String>,
1627    /// v7.17.0 Phase 1.5 — when the column is bound to a user-
1628    /// defined DOMAIN (the parser saw an unknown type ident and
1629    /// the engine resolved it against `catalog.domain_types`),
1630    /// this carries the domain name. `ty` is the domain's base
1631    /// type; INSERT/UPDATE re-evaluates the domain's CHECK list
1632    /// + NOT NULL against the cell value. Persisted in catalog
1633    /// FILE_VERSION 30+; older catalogs deserialise with None.
1634    pub user_domain_type: Option<String>,
1635    /// v7.39 (read01 round 56) — when the column is bound to a user-defined
1636    /// COMPOSITE type. `ty` stays `DataType::Jsonb` (the on-disk form), but the
1637    /// engine REHYDRATES the stored JSON into a `Value::Composite` on read, so
1638    /// field access `(p).x`, `= ROW(…)`, ordering and the canonical `(2,b)`
1639    /// text form all work — they were already implemented on Value::Composite;
1640    /// what was missing was that the column never recorded WHICH composite type
1641    /// it holds (this field's doc comment existed for two releases, the field
1642    /// itself did not). Persisted in the composite-column appendix
1643    /// (FILE_VERSION 63+); older catalogs deserialise with None.
1644    pub user_composite_type: Option<String>,
1645    /// v7.39 (read01 round 59) — column-level privileges (PG
1646    /// `pg_attribute.attacl`). `GRANT SELECT (pub) ON t TO dan` lands here and
1647    /// does NOT touch the table's `relacl`. Empty = no column grant, which is
1648    /// every column until one is made.
1649    pub acl: Vec<AclItem>,
1650    /// v7.17.0 Phase 2.1 — MySQL `ON UPDATE CURRENT_TIMESTAMP`
1651    /// column attribute. When `Some(expr_src)`, an UPDATE that
1652    /// does NOT bind this column overrides the new value with
1653    /// the engine-evaluated expression (always `now()` in
1654    /// v7.17.0). Stored as Display-form source so storage
1655    /// stays free of spg-sql; the engine re-parses at UPDATE
1656    /// time. Persisted in catalog FILE_VERSION 32+; older
1657    /// catalogs deserialise with None — preserves the existing
1658    /// "silent ignore" behaviour for snapshots written before
1659    /// the upgrade.
1660    pub on_update_runtime: Option<String>,
1661    /// v7.17.0 Phase 2.5 — text collation. Pre-2.5 SPG accepted
1662    /// `COLLATE <name>` clauses but discarded the name, so a
1663    /// column declared `COLLATE "case_insensitive"` (or any
1664    /// MySQL `_ci` collation) still compared byte-wise — a
1665    /// Tier-S silent failure where `WHERE name = 'foo'` never
1666    /// matched stored `'Foo'`. This carries the parser-derived
1667    /// classification so the engine's WHERE evaluator can route
1668    /// text equality through a case-aware compare. `Binary` (the
1669    /// default) preserves the prior byte-wise behaviour. Only
1670    /// CaseInsensitive lands in the catalog appendix — Binary
1671    /// columns stay implicit, keeping snapshots compact.
1672    /// Persisted in catalog FILE_VERSION 34+; older catalogs
1673    /// deserialise every column as `Binary`.
1674    pub collation: Collation,
1675    /// v7.17.0 Phase 4.4 — MySQL `UNSIGNED` modifier flag. Drives
1676    /// engine-side INSERT / UPDATE range enforcement (rejects
1677    /// negative values on UNSIGNED int columns). Pre-4.4 the
1678    /// parser consumed and discarded the keyword silently, so
1679    /// every UNSIGNED column quietly accepted negatives — a
1680    /// Tier-A correctness drift. Sparse: only UNSIGNED columns
1681    /// land in the catalog appendix; the default `false` keeps
1682    /// snapshots compact for the common signed-int path.
1683    /// Persisted in catalog FILE_VERSION 35+; older catalogs
1684    /// deserialise every column as `is_unsigned = false`.
1685    pub is_unsigned: bool,
1686    /// v7.17.0 Phase 3.P0-36 — MySQL inline `ENUM('a','b','c')`
1687    /// value list. Distinct from `user_enum_type` (which points
1688    /// to a separately CREATE TYPE'd PG enum); this carries the
1689    /// column-local list MySQL DDL declares inline. When `Some`,
1690    /// `ty` is `DataType::Text` and INSERT/UPDATE validates the
1691    /// cell value against this list. Variant ORDER is preserved
1692    /// (MySQL uses it for `ORDER BY col`). Sparse: only ENUM
1693    /// columns land in the catalog appendix.
1694    /// Persisted in catalog FILE_VERSION 41+; older catalogs
1695    /// deserialise with None — preserves silent-drop behaviour
1696    /// for snapshots written before P0-36.
1697    pub inline_enum_variants: Option<Vec<String>>,
1698    /// v7.17.0 Phase 3.P0-37 — MySQL inline `SET('a','b','c')`
1699    /// variant list. Storage is TEXT (canonical comma-joined in
1700    /// definition order, de-duplicated). INSERT/UPDATE validates
1701    /// every comma-separated token against this list. Sparse:
1702    /// only SET columns land in the catalog appendix.
1703    /// Persisted in catalog FILE_VERSION 42+; older catalogs
1704    /// deserialise with None.
1705    pub inline_set_variants: Option<Vec<String>>,
1706    /// v7.37.7(sentori Epic 3 P1)— `GENERATED ALWAYS AS (<expr>)
1707    /// STORED` computed-column source. When `Some`, INSERT / UPDATE
1708    /// recompute the cell against the candidate row(re-parse the
1709    /// stored Display form and evaluate)and overwrite any
1710    /// user-supplied value, matching PG's stored-generated-column
1711    /// semantics. `None` (the default) preserves the regular
1712    /// "column value is whatever the caller passed" path.
1713    /// Persisted in catalog FILE_VERSION 50+; older catalogs
1714    /// deserialise with None.
1715    pub generated_stored_expr: Option<String>,
1716    /// v7.38 (read01) — `GENERATED ALWAYS AS IDENTITY`. Both identity
1717    /// flavours set `auto_increment`; this additionally marks the ALWAYS
1718    /// flavour, whose explicit INSERT value PG rejects ("cannot insert a
1719    /// non-DEFAULT value into column …") unless `OVERRIDING SYSTEM VALUE`.
1720    /// `false` (serial / `BY DEFAULT`) keeps the permissive path. In-memory
1721    /// only for now — not yet in the catalog appendix, so a reloaded table
1722    /// deserialises as `false` (the pre-existing permissive behaviour).
1723    pub identity_always: bool,
1724    /// v7.38 (read01) — the DEFAULT expression's source text, deparsed to
1725    /// PG-compatible form at CREATE TABLE time (e.g. `0`, `(3 + 4)`,
1726    /// `'hi'::text`, `now()`, `CURRENT_DATE`). Distinct from `default`
1727    /// (the coerced value the INSERT path fills) and `runtime_default`
1728    /// (the recompute-per-row Display form): those lose the source
1729    /// spelling, so `information_schema.columns.column_default` /
1730    /// `pg_attrdef` / `pg_get_expr` reported the coerced render
1731    /// (`0.00` for `numeric(10,2) DEFAULT 0`) instead of PG's `0`.
1732    /// `None` for a column with no explicit default. Persisted in catalog
1733    /// FILE_VERSION 58+; older catalogs deserialise with None.
1734    pub default_text: Option<String>,
1735    /// v7.39 (round 220) — `ALTER TABLE … ALTER COLUMN … RESTART [WITH n]`
1736    /// on an identity column. SPG's identity allocation is a max+1 scan;
1737    /// this floor lifts the next allocated value to at least `n`
1738    /// (`max(max+1, n)`) — exactly what a dump-restore RESTART needs, and
1739    /// safer than PG for a backward RESTART (no duplicate-key landmine).
1740    /// Persisted in the FILE_VERSION 73+ sparse appendix; older catalogs
1741    /// deserialise with None.
1742    pub auto_restart: Option<i64>,
1743    /// v7.39 (read01 round 78) — this column is the ONLY column of a FROM item
1744    /// that calls a function returning a BASE type, so the item's row type IS
1745    /// this column: a whole-row reference collapses to the value
1746    /// (`SELECT j FROM jsonb_array_elements('[1]') AS j` → `1`, PG). Runtime
1747    /// only — a catalogued table column is never one, and it is not persisted.
1748    pub scalar_row_source: bool,
1749    /// v7.39 (round 386, type-fidelity epic P1) — the declared MySQL narrow
1750    /// integer width (TINYINT / MEDIUMINT) whose range the storage `ty`
1751    /// (SmallInt / Int) is too wide to enforce. `None` for every other
1752    /// column. Drives the epic-P2 write-path range check. Persisted in the
1753    /// FILE_VERSION 81+ sparse appendix; older catalogs deserialise as None.
1754    pub mysql_int_width: Option<MysqlIntWidth>,
1755    /// v7.39 (round 424, type-fidelity epic) — the declared MySQL
1756    /// fractional-seconds precision of a temporal column: `DATETIME(3)` is
1757    /// `Some(3)`, a BARE `DATETIME` / `TIME` / `TIMESTAMP` is `Some(0)`
1758    /// (MySQL's default is zero — the fraction is dropped on write), and
1759    /// `None` means "not a MySQL-declared temporal column", which is every
1760    /// PG column and leaves microsecond behaviour untouched.
1761    ///
1762    /// Drives write-path truncation (toward zero) and render padding
1763    /// (exactly this many digits, `.000` when the fraction is zero).
1764    /// Persisted in the FILE_VERSION 82+ sparse appendix; older catalogs
1765    /// deserialise as None.
1766    pub mysql_fsp: Option<u8>,
1767    /// v7.39.2 — this column was DECLARED `TIMESTAMP` in a MySQL
1768    /// session.
1769    ///
1770    /// MySQL and MariaDB both keep `timestamp` and `datetime` apart in
1771    /// `SHOW CREATE TABLE`, `SHOW COLUMNS` and `information_schema`
1772    /// (measured on 9.7.2 and 12.3.3); SPG stores both as
1773    /// `DataType::Timestamp` and so reported `datetime` for both. A
1774    /// client dumping and reloading had the column's declared type
1775    /// SILENTLY CHANGED — and MySQL's TIMESTAMP is not DATETIME: it has
1776    /// a different range and converts to and from UTC.
1777    ///
1778    /// What this records is the SPELLING, which is the half a dump
1779    /// round-trips. The storage and the semantics are unchanged, and
1780    /// that gap is written down rather than papered over.
1781    ///
1782    /// Persisted in the FILE_VERSION 93+ sparse appendix; older
1783    /// catalogs deserialise as `false`.
1784    pub mysql_declared_timestamp: bool,
1785    /// v7.39.3 — a MySQL `FLOAT(m,d)` / `DOUBLE(m,d)`'s declared pair.
1786    ///
1787    /// The digits are NOT a display hint, which is what SPG's comment
1788    /// claimed and 7.39.2 recorded as a residual: MySQL 9.7.2 ROUNDS on
1789    /// write (3.14159265358979 into either stores 3.14) and refuses a
1790    /// value wider than `m` with errno 1264. SPG accepted the syntax and
1791    /// kept the full double, so a column declared for money held more
1792    /// precision than the schema said and every reader saw a different
1793    /// number from MySQL's.
1794    ///
1795    /// Persisted in the FILE_VERSION 94+ sparse appendix; older catalogs
1796    /// deserialise as None, which is "no declared pair".
1797    pub mysql_float_md: Option<(u8, u8)>,
1798}
1799
1800/// v7.17.0 Phase 2.5 — column-level text collation. Drives the
1801/// engine's WHERE / GROUP BY equality routing for `Value::Text`.
1802/// Only two variants are modelled in v7.17:
1803///   * `Binary`  — byte-wise comparison (the SPG default;
1804///                 matches PG `COLLATE "C"` / `pg_catalog.default`
1805///                 and MySQL `*_bin`).
1806///   * `CaseInsensitive` — ASCII case-folded comparison (like
1807///                 MySQL `*_ci` collations; PG has NO built-in
1808///                 collation of this name — round-761 audit: a
1809///                 nondeterministic ICU collation must be CREATEd
1810///                 there first). Non-ASCII bytes
1811///                 still compare byte-wise; full ICU folding is
1812///                 out of v7.17 scope.
1813/// New variants append at the end — older catalogs read missing
1814/// columns as `Binary`.
1815#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1816pub enum Collation {
1817    Binary,
1818    CaseInsensitive,
1819}
1820
1821/// v7.39 (round 386, type-fidelity epic P1) — the declared MySQL narrow
1822/// integer type for a column whose storage `DataType` cannot express it.
1823/// MySQL `TINYINT` (i8, -128..127) collapses to `DataType::SmallInt` (i16)
1824/// and `MEDIUMINT` (24-bit) to `DataType::Int` (i32) — both wider than the
1825/// declared type, so a range check against `ty` alone accepts out-of-range
1826/// values (`INSERT 128 INTO TINYINT` is stored silently where MariaDB
1827/// strict raises ERROR 1264). This annotation records the lost width so the
1828/// write path (epic P2) can enforce the real bounds. `SMALLINT` / `INT` /
1829/// `BIGINT` need no marker — their storage `DataType` is already faithful.
1830/// Sparse: only TINYINT / MEDIUMINT columns carry it; persisted in the
1831/// FILE_VERSION 81+ appendix, older catalogs deserialise as None.
1832#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1833pub enum MysqlIntWidth {
1834    /// MySQL `TINYINT` — signed -128..127, unsigned 0..255. Storage i16.
1835    Tiny,
1836    /// MySQL `SMALLINT UNSIGNED` — 0..65535. Storage widened to i32 (a
1837    /// signed SMALLINT keeps `DataType::SmallInt` and carries no marker).
1838    Small,
1839    /// MySQL `MEDIUMINT` — signed -8388608..8388607, unsigned 0..16777215.
1840    /// Storage i32.
1841    Medium,
1842    /// MySQL `INT UNSIGNED` — 0..4294967295. Storage widened to i64 (a
1843    /// signed INT keeps `DataType::Int` and carries no marker).
1844    Int,
1845    /// v7.39 (round 471, epic P4b) — MySQL `BIGINT UNSIGNED` —
1846    /// 0..18446744073709551615. i64 stops at 2^63-1, so the storage tag is
1847    /// widened to `Numeric` (i128-backed, scale 0), which already compares,
1848    /// orders, indexes and renders as an exact integer. A signed BIGINT
1849    /// keeps `DataType::BigInt` and carries no marker.
1850    Big,
1851}
1852
1853/// v7.39 (round 363, M4 P1) — MySQL's default accent- and
1854/// case-insensitive fold (`utf8mb4_uca1400_ai_ci`).
1855///
1856/// This is the primitive M4 rests on: a session on the MySQL dialect
1857/// compares, groups, sorts and de-duplicates text by its FOLDED form, so
1858/// `Foo` = `foo` = `FOO` and, because the default collation is accent-
1859/// insensitive too, `Bär` = `bar`. The later stages (read path, then the
1860/// UNIQUE / index write path) all route through here so they cannot fold
1861/// differently from one another.
1862///
1863/// The fold is more than case + strip-combining: MariaDB EXPANDS some
1864/// letters — `ß` → `ss`, `æ` → `ae`, `œ` → `oe` — which is why the result
1865/// is built as a `String` rather than mapped char-for-char. Every mapping
1866/// below was measured on MariaDB 11 (`'Bär'='bar'` is 1, `'straße'=
1867/// 'strasse'` is 1, `'a'='æ'` is 0, `'s'='ß'` is 0). Characters with no
1868/// entry keep their lower-cased self, so ASCII and unknown scripts pass
1869/// through unchanged.
1870#[must_use]
1871pub fn mysql_ci_fold(s: &str) -> String {
1872    let mut out = String::with_capacity(s.len());
1873    for ch in s.chars() {
1874        // Lower-case first (`À` → `à`, `Æ` → `æ`), then fold the base.
1875        for lc in ch.to_lowercase() {
1876            match fold_latin_base(lc) {
1877                Some(base) => out.push_str(base),
1878                None => out.push(lc),
1879            }
1880        }
1881    }
1882    out
1883}
1884
1885/// The fold used to COMPARE / GROUP / de-dup text on the MySQL dialect:
1886/// case- and accent-insensitive, and **trailing spaces significant**.
1887///
1888/// v7.38.17 — this used to strip trailing spaces first, and its comment
1889/// said why: "measured on MariaDB 11". MariaDB's default collation is
1890/// PAD SPACE, so that measurement was right about MariaDB. SPG
1891/// advertises `8.0.0-spg-v…` on the MySQL wire, and MySQL 8.0's default
1892/// `utf8mb4_0900_ai_ci` is **NO PAD**. The rule had been calibrated
1893/// against the engine we do not claim to be.
1894///
1895/// Measured today, MySQL 9.7.2 against MariaDB 12.3.2, each in its own
1896/// default collation, over rows `'alpha'` and `'alpha  '`:
1897///
1898/// | | MySQL | MariaDB |
1899/// |---|---|---|
1900/// | `WHERE s = 'alpha'` | 1 | 1,2 |
1901/// | `s IN ('alpha','beta')` | 1,3,4 | 1,2,3,4 |
1902/// | `COUNT(DISTINCT s)` | 3 | 2 |
1903/// | `GROUP BY s` groups | 3 | 2 |
1904/// | `JOIN ON v.s = r.s` | 1/10, 2/20 | all four pairs |
1905///
1906/// SPG answered MariaDB's four and MySQL's join — the same question
1907/// decided differently by two paths, which is the shape v7.38.13,
1908/// v7.38.14 and v7.38.16 were each spent on.
1909///
1910/// `CHAR(n)` is a separate question and keeps its old answer: BOTH
1911/// engines ignore a CHAR's trailing spaces, because that is a property
1912/// of the TYPE rather than of the collation. Use
1913/// [`mysql_compare_fold_char`] for a `BpChar` cell.
1914///
1915/// Only literal spaces ever padded — a tab is significant either way —
1916/// and neither function is used by `LIKE`, whose pattern treats a
1917/// trailing space literally.
1918/// Whether a collation of this NAME orders by bytes.
1919///
1920/// v7.38.18 (S0) — pure string classification, and it lives here because
1921/// storage has to ask it: an index whose column collates by a locale
1922/// cannot key on the raw text, and the write path is here. The engine's
1923/// `collate::is_byte_wise` delegates to this one, for the reason the SQL
1924/// type spellings have one owner.
1925///
1926/// `C`, `POSIX`, MySQL's `binary` and every `_bin` family member. The
1927/// encoding suffix rides along: PG publishes `C.utf8` beside `C`.
1928pub fn collation_is_byte_wise(collation: &str) -> bool {
1929    let name = collation.trim();
1930    let base = name.split(['.', '@']).next().unwrap_or(name);
1931    base.eq_ignore_ascii_case("C")
1932        || base.eq_ignore_ascii_case("POSIX")
1933        || base.eq_ignore_ascii_case("binary")
1934        || base
1935            .rsplit_once('_')
1936            .is_some_and(|(_, tail)| tail.eq_ignore_ascii_case("bin"))
1937}
1938
1939/// v7.38.18 (S0/S2) — does an index on a column of this collation key
1940/// by an ICU SORT KEY rather than by the raw text?
1941///
1942/// True for a locale collation (`en_US.utf8`, `de_DE`), which orders by
1943/// rules a byte comparison cannot express.
1944///
1945/// False for byte-wise names, and false for MySQL's folding collations
1946/// (`utf8mb4_0900_ai_ci` and family). Those fold rather than collate,
1947/// and the engine has folded them since v7.37 — routing them here made
1948/// an indexed `s = 'ALPHA'` over the MySQL wire answer nothing where
1949/// MySQL 9.7.1 answers one row, because ICU at PG's strength does not
1950/// call `ALPHA` and `alpha` equal.
1951///
1952/// One owner for the same reason the byte-wise question has one: the
1953/// engine builds the PROBE and this crate builds the ENTRIES, and a
1954/// probe built in another space finds nothing — which reads exactly
1955/// like "no matching rows".
1956pub fn collation_uses_sort_key(collation: &str) -> bool {
1957    if collation_is_byte_wise(collation) {
1958        return false;
1959    }
1960    let name = collation.trim();
1961    let base = name.split(['.', '@']).next().unwrap_or(name);
1962    let lower = base.to_ascii_lowercase();
1963    !(lower.ends_with("_ci") || lower.ends_with("_cs"))
1964}
1965
1966pub fn mysql_compare_fold(s: &str) -> String {
1967    mysql_ci_fold(s)
1968}
1969
1970/// The comparison form of one text value under the MySQL default
1971/// collation, or `None` for a value that is not text.
1972///
1973/// v7.38.18 — one function, applied to each side SEPARATELY, because
1974/// the pair is not the unit. Several sites matched
1975/// `(Text, Text) | (BpChar, BpChar)` and folded a pair; a CHAR compared
1976/// against a VARCHAR or against a literal is neither shape, so it fell
1977/// through and was compared by bytes — with the CHAR still carrying its
1978/// padding. `CASE c WHEN 'ALPHA'` on a `CHAR(8)` holding `'alpha'`
1979/// answered ELSE where MySQL 9.7.2 answers the branch.
1980///
1981/// Folding per value also states the rule correctly: whether trailing
1982/// spaces count is a property of EACH side's own type, so a pair whose
1983/// sides differ has two answers rather than one.
1984pub fn mysql_fold_value(v: &Value<'_>) -> Option<String> {
1985    match v {
1986        Value::BpChar(s) => Some(mysql_compare_fold_char(s)),
1987        Value::Text(s) => Some(mysql_compare_fold(s)),
1988        _ => None,
1989    }
1990}
1991
1992/// [`mysql_compare_fold`] for a `CHAR(n)` cell, whose trailing spaces
1993/// are padding rather than data.
1994///
1995/// Measured on both engines: over `'alpha'` and `'alpha  '` in a
1996/// `CHAR(8)`, `WHERE s = 'alpha'` returns both rows and
1997/// `COUNT(DISTINCT s)` is 2 (four rows folding to two values) — MySQL
1998/// 9.7.2 and MariaDB 12.3.2 agree, unlike the VARCHAR case above.
1999pub fn mysql_compare_fold_char(s: &str) -> String {
2000    mysql_ci_fold(s.trim_end_matches(' '))
2001}
2002
2003/// The base letter(s) a lower-cased Latin character folds to, or `None`
2004/// when it is already a base / has no fold. Expansions (`ß` → `ss`) are
2005/// why this returns a string.
2006fn fold_latin_base(c: char) -> Option<&'static str> {
2007    Some(match c {
2008        'à' | 'á' | 'â' | 'ã' | 'ä' | 'å' | 'ā' | 'ă' | 'ą' => "a",
2009        'æ' => "ae",
2010        'ç' | 'ć' | 'č' | 'ĉ' | 'ċ' => "c",
2011        'ð' | 'ď' | 'đ' => "d",
2012        'è' | 'é' | 'ê' | 'ë' | 'ē' | 'ĕ' | 'ė' | 'ę' | 'ě' => "e",
2013        'ĝ' | 'ğ' | 'ġ' | 'ģ' => "g",
2014        'ì' | 'í' | 'î' | 'ï' | 'ĩ' | 'ī' | 'ĭ' | 'į' => "i",
2015        'ĵ' => "j",
2016        'ķ' => "k",
2017        'ł' | 'ĺ' | 'ļ' | 'ľ' => "l",
2018        'ñ' | 'ń' | 'ņ' | 'ň' => "n",
2019        'ò' | 'ó' | 'ô' | 'õ' | 'ö' | 'ø' | 'ō' | 'ŏ' | 'ő' => "o",
2020        'œ' => "oe",
2021        'ŕ' | 'ŗ' | 'ř' => "r",
2022        'ś' | 'š' | 'ŝ' | 'ş' => "s",
2023        'ß' => "ss",
2024        'ţ' | 'ť' | 'ŧ' => "t",
2025        'ù' | 'ú' | 'û' | 'ü' | 'ũ' | 'ū' | 'ŭ' | 'ů' | 'ű' | 'ų' => "u",
2026        'ý' | 'ÿ' => "y",
2027        'ź' | 'ž' | 'ż' => "z",
2028        _ => return None,
2029    })
2030}
2031
2032#[allow(clippy::derivable_impls)]
2033impl Default for Collation {
2034    fn default() -> Self {
2035        Self::Binary
2036    }
2037}
2038
2039impl Collation {
2040    /// Wire tag persisted in the FILE_VERSION 34+ catalog appendix.
2041    /// Stable: future variants append above the recognised range
2042    /// and unknown tags read back as `Binary` for forward-compat
2043    /// on rollback.
2044    pub const TAG_BINARY: u8 = 0;
2045    pub const TAG_CASE_INSENSITIVE: u8 = 1;
2046}
2047
2048/// v7.39 (RLS) — the command a policy applies to. `ALL` is the default and
2049/// covers every command; the others scope the policy to one statement kind.
2050/// Persisted as a single byte in the policy appendix (FILE_VERSION 59+).
2051#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2052pub enum PolicyCmd {
2053    All,
2054    Select,
2055    Insert,
2056    Update,
2057    Delete,
2058}
2059
2060impl PolicyCmd {
2061    /// PG `pg_policy.polcmd` single-char encoding.
2062    #[must_use]
2063    pub const fn as_pg_char(self) -> char {
2064        match self {
2065            Self::All => '*',
2066            Self::Select => 'r',
2067            Self::Insert => 'a',
2068            Self::Update => 'w',
2069            Self::Delete => 'd',
2070        }
2071    }
2072
2073    /// PG `pg_policies.cmd` word form.
2074    #[must_use]
2075    pub const fn as_pg_word(self) -> &'static str {
2076        match self {
2077            Self::All => "ALL",
2078            Self::Select => "SELECT",
2079            Self::Insert => "INSERT",
2080            Self::Update => "UPDATE",
2081            Self::Delete => "DELETE",
2082        }
2083    }
2084
2085    #[must_use]
2086    pub const fn to_wire_byte(self) -> u8 {
2087        match self {
2088            Self::All => 0,
2089            Self::Select => 1,
2090            Self::Insert => 2,
2091            Self::Update => 3,
2092            Self::Delete => 4,
2093        }
2094    }
2095
2096    #[must_use]
2097    pub const fn from_wire_byte(b: u8) -> Option<Self> {
2098        match b {
2099            0 => Some(Self::All),
2100            1 => Some(Self::Select),
2101            2 => Some(Self::Insert),
2102            3 => Some(Self::Update),
2103            4 => Some(Self::Delete),
2104            _ => None,
2105        }
2106    }
2107}
2108
2109/// v7.39 (RLS) — one `CREATE POLICY` object, stored per table. The `using_expr`
2110/// / `with_check_expr` hold the qualifying expression's `Display` form
2111/// (re-parsed and evaluated per row at enforcement time, exactly like
2112/// `TableSchema.checks`); `None` means the clause was absent. `roles` empty =
2113/// PUBLIC. Persisted in the policy appendix (FILE_VERSION 59+).
2114#[derive(Debug, Clone, PartialEq)]
2115pub struct PolicyDef {
2116    pub name: String,
2117    pub cmd: PolicyCmd,
2118    /// `true` = PERMISSIVE (default, OR-combined), `false` = RESTRICTIVE
2119    /// (AND-combined).
2120    pub permissive: bool,
2121    pub roles: Vec<String>,
2122    pub using_expr: Option<String>,
2123    pub with_check_expr: Option<String>,
2124}
2125
2126#[derive(Debug, Clone, PartialEq)]
2127pub struct TableSchema {
2128    pub name: String,
2129    pub columns: Vec<ColumnSchema>,
2130    /// v6.7.2 — per-table hot-tier byte budget override. `None`
2131    /// falls through to the global `SPG_HOT_TIER_BYTES` setting;
2132    /// `Some(n)` overrides it for this specific table. Set via
2133    /// `ALTER TABLE t SET hot_tier_bytes = X`. Persisted in
2134    /// catalog FILE_VERSION 11+.
2135    pub hot_tier_bytes: Option<u64>,
2136    /// v7.6.1 — FOREIGN KEY constraints declared on this table.
2137    /// Engine maintains this in lock-step with `spg-sql`'s parser
2138    /// AST; the storage layer carries the on-disk shape so a
2139    /// catalog snapshot round-trips without external mapping.
2140    /// Persisted in catalog FILE_VERSION 13+. Older catalogs
2141    /// deserialise with an empty vec.
2142    pub foreign_keys: Vec<ForeignKeyConstraint>,
2143    /// v7.9.19 — composite UNIQUE / PRIMARY KEY constraints
2144    /// declared at the table level. Each entry's leading column
2145    /// has a BTree index (created via the constraint), and INSERT
2146    /// path enforces the full-tuple uniqueness via a scan keyed
2147    /// by the leading column. Persisted in catalog FILE_VERSION
2148    /// 15+. Older catalogs (≤ 14) deserialise with an empty vec.
2149    pub uniqueness_constraints: Vec<UniquenessConstraint>,
2150    /// v7.39 (round 210) — `EXCLUDE` constraints declared at the table level.
2151    /// Enforced on INSERT/UPDATE by a full live-row scan re-checking each
2152    /// element's operator (no equality index can answer overlap). Persisted
2153    /// in catalog FILE_VERSION 72+; older catalogs deserialise with an empty
2154    /// vec.
2155    pub exclusion_constraints: Vec<ExclusionConstraint>,
2156    /// v7.13.0 — `CHECK (<expr>)` predicates declared on this
2157    /// table. Both column-level inline `CHECK (…)` and
2158    /// table-level `CHECK (…)` fold into this list. Each entry
2159    /// is the AST Expr's `Display` form, re-parsed on every
2160    /// INSERT/UPDATE and evaluated against the candidate row.
2161    /// A false / NULL result rejects the mutation (PG semantics).
2162    /// Persisted in catalog FILE_VERSION 23+. Older catalogs
2163    /// deserialise with an empty vec. v7.39 (read01 round 48) — each entry
2164    /// now carries the user's constraint name too (FILE_VERSION 60+).
2165    pub checks: Vec<CheckConstraint>,
2166    /// v7.37.6-B — declarative partition role(sentori Epic 2 P0).
2167    /// `None` = 普通表(后向兼容,< v49 catalog 默认 None)。
2168    /// `Some(Parent { … })` = `CREATE TABLE p (...) PARTITION BY RANGE (key_col)` 父表 —
2169    /// 父表自己 `rows` 永远空,INSERT 在引擎层路由到命中的 child。
2170    /// `Some(Range { … })` = `CREATE TABLE c PARTITION OF p FOR VALUES FROM (a) TO (b)` 范围子表。
2171    /// `Some(Default { … })` = `CREATE TABLE c PARTITION OF p DEFAULT` 兜底子表。
2172    /// 持久化于 FILE_VERSION 49+。
2173    pub partition_role: Option<PartitionRole>,
2174    /// v7.39 (RLS) — `CREATE POLICY` objects on this table, independent of the
2175    /// `row_security` flag (PG stores policies even on non-RLS tables; they
2176    /// only take effect once RLS is enabled). Persisted in the policy appendix
2177    /// (FILE_VERSION 59+). Older catalogs deserialise with an empty vec.
2178    pub policies: Vec<PolicyDef>,
2179    /// v7.39 (RLS) — `ALTER TABLE … ENABLE ROW LEVEL SECURITY`
2180    /// (PG `pg_class.relrowsecurity`). Fresh table = `false`.
2181    pub row_security: bool,
2182    /// v7.39 (RLS) — `ALTER TABLE … FORCE ROW LEVEL SECURITY`
2183    /// (PG `pg_class.relforcerowsecurity`); subjects the table owner to RLS
2184    /// too. Fresh table = `false`.
2185    pub force_row_security: bool,
2186    /// v7.39 (read01 round 57, ACL) — the role that owns this table: whoever
2187    /// ran CREATE TABLE (PG `pg_class.relowner`). The owner holds every
2188    /// privilege implicitly and is the only role that may ALTER / DROP it.
2189    /// `None` = an image written before FILE_VERSION 64, which predates roles
2190    /// entirely; those tables read back as owned by the login role.
2191    pub owner: Option<String>,
2192    /// v7.39 (read01 round 57, ACL) — explicit GRANTs on this table
2193    /// (PG `pg_class.relacl`). EMPTY means "never granted": PG leaves relacl
2194    /// NULL while only the owner's implicit privileges apply, and materialises
2195    /// the whole list — owner's default entry included — on the first GRANT.
2196    /// Once materialised it stays, even after every grant is revoked.
2197    pub acl: Vec<AclItem>,
2198}
2199
2200/// v7.39 (read01 round 57) — one PG `aclitem`: what `grantee` may do to a
2201/// table, and who granted it. Renders as `grantee=privs/grantor`, with an
2202/// EMPTY grantee meaning PUBLIC (`=r/owner`).
2203#[derive(Debug, Clone, PartialEq, Eq)]
2204pub struct AclItem {
2205    /// The role the privileges are held by. Empty string = PUBLIC.
2206    pub grantee: String,
2207    /// Bitmask over `priv_bits`: which privileges are held.
2208    pub privs: u16,
2209    /// Bitmask over `priv_bits`: which of them carry WITH GRANT OPTION
2210    /// (PG renders those with a trailing `*` — `r*`).
2211    pub grantable: u16,
2212    /// The role that ran the GRANT.
2213    pub grantor: String,
2214}
2215
2216/// v7.39 (read01 round 57) — the table-privilege bits, in PG's `aclitem`
2217/// rendering order (`arwdDxtm`). The order matters: `relacl` output is
2218/// byte-compared against PG.
2219pub mod priv_bits {
2220    pub const INSERT: u16 = 1 << 0; // a
2221    pub const SELECT: u16 = 1 << 1; // r
2222    pub const UPDATE: u16 = 1 << 2; // w
2223    pub const DELETE: u16 = 1 << 3; // d
2224    pub const TRUNCATE: u16 = 1 << 4; // D
2225    pub const REFERENCES: u16 = 1 << 5; // x
2226    pub const TRIGGER: u16 = 1 << 6; // t
2227    pub const MAINTAIN: u16 = 1 << 7; // m
2228    /// v7.39 (read01 round 60) — the non-table privileges. They share the
2229    /// bitmask because an aclitem is an aclitem whatever it hangs off; which
2230    /// bits are MEANINGFUL depends on the object (a sequence has r / w / U, a
2231    /// schema has U / C, a database has C / c / T).
2232    pub const USAGE: u16 = 1 << 8; // U
2233    pub const CREATE: u16 = 1 << 9; // C
2234    pub const CONNECT: u16 = 1 << 10; // c
2235    pub const TEMPORARY: u16 = 1 << 11; // T
2236    pub const EXECUTE: u16 = 1 << 12; // X
2237    /// Every TABLE privilege — what `GRANT ALL ON <table>` grants and what a
2238    /// table's owner holds.
2239    pub const ALL: u16 =
2240        INSERT | SELECT | UPDATE | DELETE | TRUNCATE | REFERENCES | TRIGGER | MAINTAIN;
2241    /// `GRANT ALL ON SEQUENCE` — PG renders a sequence owner's default as `rwU`.
2242    pub const ALL_SEQUENCE: u16 = SELECT | UPDATE | USAGE;
2243    /// `GRANT ALL ON SCHEMA` — `UC`.
2244    pub const ALL_SCHEMA: u16 = USAGE | CREATE;
2245    /// `GRANT ALL ON DATABASE` — `CTc`.
2246    pub const ALL_DATABASE: u16 = CREATE | CONNECT | TEMPORARY;
2247    /// `GRANT ALL ON FUNCTION` — just `X`.
2248    pub const ALL_FUNCTION: u16 = EXECUTE;
2249}
2250
2251/// v7.37.6-B — partition 三态(parent / range child / default child)。
2252#[derive(Debug, Clone, PartialEq, Eq)]
2253pub enum PartitionRole {
2254    Parent {
2255        kind: PartitionKind,
2256        /// 父表 columns 中 key 列的下标(单列 v7.37.6-B,
2257        /// `Vec` 为将来扩多列预留)。
2258        key_column_positions: Vec<usize>,
2259        /// `CREATE INDEX ON parent (…)` 的 Display-form 源串。
2260        /// child 创建时再 parse + 在 child 上 execute,这样 future
2261        /// child 也自动继承父表索引。fan-out 实施在引擎层。
2262        index_template_sources: Vec<String>,
2263    },
2264    Range {
2265        parent_name: String,
2266        /// 半开区间下界(`>=`,SQL `FROM (lower)`).
2267        lower: PartitionBound,
2268        /// 半开区间上界(`<`,SQL `TO (upper)`).
2269        upper: PartitionBound,
2270    },
2271    /// v7.37.16 (16.1) — LIST child:行属于本 child iff key ∈ values。
2272    /// `values` 在 child 创建时从 SQL `FOR VALUES IN (lit, …)` 求值;
2273    /// 跟 PG 一样,显式 NULL ∈ values 由 caller 单独处理(不在
2274    /// PartitionBound 内表达 NULL)。
2275    List {
2276        parent_name: String,
2277        values: Vec<PartitionBound>,
2278    },
2279    /// v7.39 (round 645) — PG 表继承的 CHILD:`CREATE TABLE c (…)
2280    /// INHERITS (p1, p2)`。跟分区 child 的三个本质区别(实测 PG18):
2281    ///   * 父表**自己有行**(分区父表永远空),所以父表的联合体要含自身;
2282    ///   * `INSERT INTO 父表` **不路由**到 child(分区会路由);
2283    ///   * `DROP TABLE 父表` 不带 CASCADE **报错**(分区父表连子表一起删)。
2284    /// 多父继承合法,故 `parent_names` 是 Vec;`pg_inherits.inhseqno`
2285    /// 正是父表在这个列表里的位置(1-based)。
2286    Inherits {
2287        parent_names: Vec<String>,
2288    },
2289    /// v7.37.16 (16.2) — HASH child:行属于本 child iff
2290    /// `pg_compatible_hash(key) mod modulus == remainder`。
2291    /// PG 强制 `0 ≤ remainder < modulus`;parser/DDL 层先 gate。
2292    Hash {
2293        parent_name: String,
2294        modulus: u32,
2295        remainder: u32,
2296    },
2297    Default {
2298        parent_name: String,
2299    },
2300}
2301
2302/// v7.37.6-B — 分区策略。
2303///
2304/// - `Range`:半开区间 `[lower, upper)`(v7.37.6-B 初始)
2305/// - `List` (v7.37.16):枚举集合 — 行属于 partition iff key ∈ children list
2306/// - `Hash` (v7.37.16):`hash(key) mod modulus == remainder`
2307#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2308pub enum PartitionKind {
2309    Range,
2310    List,
2311    Hash,
2312}
2313
2314/// v7.37.6-B — partition 边界 literal。
2315///
2316/// v7.37.6-B 仅 `TimestampTz`(i64 microseconds since epoch);
2317/// v7.37.16 (16.6) 加全 PG 内建可比类型,匹配 `Value` 的对应 variant
2318/// 以避免 LIST membership 比较时的类型转换。
2319///
2320/// `MinValue` / `MaxValue` 对应 SQL `MINVALUE` / `MAXVALUE`,仅
2321/// Range 策略有意义(LIST 无 minvalue/maxvalue 概念,HASH 不
2322/// 使用 PartitionBound)。
2323#[derive(Debug, Clone, PartialEq, Eq)]
2324pub enum PartitionBound {
2325    MinValue,
2326    MaxValue,
2327    TimestampTz(i64),
2328    /// v7.37.16 (16.6) — BIGINT partition key.
2329    BigInt(i64),
2330    /// v7.37.16 (16.6) — INTEGER partition key (also covers
2331    /// `SERIAL` since SPG decomposes it to INTEGER + sequence).
2332    Int(i32),
2333    /// v7.37.16 (16.6) — SMALLINT partition key.
2334    SmallInt(i16),
2335    /// v7.37.16 (16.6) — DATE partition key. Stored as days
2336    /// since the Unix epoch (matches `Value::Date`).
2337    Date(i32),
2338    /// v7.37.16 (16.6) — TEXT / VARCHAR partition key.
2339    Text(alloc::string::String),
2340}
2341
2342impl PartitionBound {
2343    /// v7.37.16 (16.6) — true iff this bound's underlying value
2344    /// equals `other`'s. Used for LIST partition membership
2345    /// checks. Returns false for `MinValue` / `MaxValue`
2346    /// (sentinels — never literal equality).
2347    #[must_use]
2348    pub fn equals_value(&self, other: &Value<'_>) -> bool {
2349        match (self, other) {
2350            (PartitionBound::TimestampTz(a), Value::Timestamp(b)) => a == b,
2351            (PartitionBound::BigInt(a), Value::BigInt(b)) => a == b,
2352            (PartitionBound::Int(a), Value::Int(b)) => a == b,
2353            (PartitionBound::SmallInt(a), Value::SmallInt(b)) => a == b,
2354            (PartitionBound::Date(a), Value::Date(b)) => a == b,
2355            (PartitionBound::Text(a), Value::Text(b)) => a.as_str() == b.as_ref(),
2356            _ => false,
2357        }
2358    }
2359}
2360
2361/// v7.9.19 — composite UNIQUE / PRIMARY KEY constraint persisted
2362/// on the table schema. The leading column always has a BTree
2363/// index (created at CREATE TABLE time); INSERT enforcement
2364/// scans that index for collisions on the full column tuple.
2365/// v7.39 (read01 round 48) — a `CHECK` constraint: the SQL name the user
2366/// gave it (via `ADD CONSTRAINT <name> CHECK (...)` or the inline
2367/// `CONSTRAINT <name> CHECK (...)` form) plus the predicate source. `None`
2368/// name = unnamed, in which case `pg_constraint` synthesises PG's
2369/// `<table>_<col>_check` form. Names are persisted in the constraint-name
2370/// appendix (FILE_VERSION 60+); older catalogs deserialise with `None`.
2371#[derive(Debug, Clone, PartialEq, Eq)]
2372pub struct CheckConstraint {
2373    pub name: Option<String>,
2374    /// The AST Expr's `Display` form, re-parsed on every INSERT/UPDATE.
2375    pub expr: String,
2376    /// v7.39 (round 652) — `false` for a constraint added `NOT VALID`: the
2377    /// rows already in the table were never scanned against it, and
2378    /// `pg_constraint.convalidated` says so. It does NOT weaken the check on
2379    /// new rows — INSERT and UPDATE enforce it either way, as in PG.
2380    /// `VALIDATE CONSTRAINT` does the deferred scan and flips it. Persisted
2381    /// by the FILE_VERSION 87 appendix; older catalogs deserialise as `true`,
2382    /// which is what every constraint they could hold actually was.
2383    pub validated: bool,
2384}
2385
2386#[derive(Debug, Clone, PartialEq, Eq)]
2387pub struct UniquenessConstraint {
2388    /// `true` when this constraint was declared as `PRIMARY KEY`
2389    /// (vs `UNIQUE`). Semantically PK implies NOT NULL on all
2390    /// referenced columns; the engine enforces that at CREATE
2391    /// TABLE time.
2392    pub is_primary_key: bool,
2393    /// Column positions on the parent table. ≥ 1 element. For
2394    /// single-column UNIQUE this is exactly one position; the
2395    /// BTree index alone enforces it.
2396    pub columns: Vec<usize>,
2397    /// v7.13.0 — `UNIQUE NULLS NOT DISTINCT` modifier
2398    /// (mailrs round-5 G10; PG 15+ surface). When `true`, two
2399    /// rows whose constrained columns are all NULL collide on
2400    /// the constraint. Default (`false`) is the SQL-standard
2401    /// `NULLS DISTINCT` behaviour where any NULL passes.
2402    /// Persisted in catalog FILE_VERSION 23+.
2403    pub nulls_not_distinct: bool,
2404    /// v7.39 (read01 round 48) — the constraint's SQL name when the user
2405    /// supplied one (`ADD CONSTRAINT <name> PRIMARY KEY/UNIQUE (...)`, or
2406    /// the inline `CONSTRAINT <name>` form). `None` = unnamed, in which
2407    /// case `pg_constraint` synthesises PG's `<table>_pkey` /
2408    /// `<table>_<col>_key` form. DROP CONSTRAINT resolves the stored name
2409    /// first and falls back to the synthesised one, so catalogs written
2410    /// before this field (< FILE_VERSION 60) keep working unchanged.
2411    pub name: Option<String>,
2412    /// v7.39 (round 711) — `[NOT] DEFERRABLE`. Round 621 taught the parser
2413    /// to CONSUME the clause on PK/UNIQUE (the FK path had stored it since
2414    /// round 288); this is the storing half. Persisted in the v89 timing
2415    /// appendix.
2416    pub deferrable: bool,
2417    /// `INITIALLY DEFERRED`: the check belongs to COMMIT, not the
2418    /// statement, unless `SET CONSTRAINTS … IMMEDIATE` pulls it in.
2419    pub initially_deferred: bool,
2420}
2421
2422/// v7.39 (round 210) — an `EXCLUDE` constraint. Forbids two distinct live
2423/// rows from satisfying, for EVERY element, `new.col <op> existing.col`
2424/// (e.g. `EXCLUDE USING gist (during WITH &&)` = no two `during` ranges
2425/// overlap). Unlike a uniqueness constraint the operator is not equality,
2426/// so enforcement is a full live-row scan re-checking the operator (a real
2427/// GiST index that answers overlap in O(log n) is a later perf phase). A
2428/// NULL in any element column exempts the row (matching PG / UNIQUE NULL
2429/// semantics). Persisted in catalog FILE_VERSION 72+.
2430#[derive(Debug, Clone, PartialEq, Eq)]
2431pub struct ExclusionConstraint {
2432    /// The constraint's SQL name. PG auto-names an unnamed EXCLUDE
2433    /// `<table>_<leading-col>_excl`; the engine synthesises that at CREATE
2434    /// TABLE time so this is always populated.
2435    pub name: String,
2436    /// Access method spelled after `USING` (`gist`, `spgist`, …), lower-cased.
2437    /// `None` = no `USING` clause. Purely cosmetic for enforcement; it round-
2438    /// trips into `pg_get_constraintdef`.
2439    pub method: Option<String>,
2440    /// One `(column-position, operator-spelling)` pair per element, in
2441    /// declaration order. The operator spelling is the wire token (`&&`,
2442    /// `=`, `@>`, `<@`, `&<`, `&>`) evaluated against each existing row.
2443    pub elements: Vec<(usize, String)>,
2444}
2445
2446/// v7.6.1 — Storage-layer mirror of `spg_sql::ast::ForeignKeyConstraint`.
2447/// The engine's CREATE TABLE path translates between the two; keeping
2448/// them separate preserves the no-deps boundary between
2449/// `spg-storage` and `spg-sql`.
2450#[derive(Debug, Clone, PartialEq, Eq)]
2451pub struct ForeignKeyConstraint {
2452    /// Optional user-supplied constraint name (`CONSTRAINT <name>`
2453    /// prefix). Used by `ALTER TABLE DROP CONSTRAINT <name>` in
2454    /// v7.6.8; ignored by enforcement.
2455    pub name: Option<String>,
2456    /// Positions of local columns in this table's column list.
2457    /// Same arity as `parent_columns`.
2458    pub local_columns: Vec<usize>,
2459    /// Referenced parent table name.
2460    pub parent_table: String,
2461    /// Positions of parent columns in the parent's column list.
2462    /// Engine resolves these at CREATE TABLE time (after the parent
2463    /// schema is known) so enforcement paths can skip the name
2464    /// lookup on every row.
2465    pub parent_columns: Vec<usize>,
2466    /// Referential action when a parent row is deleted.
2467    pub on_delete: FkAction,
2468    /// Referential action when a parent row's referenced columns
2469    /// are updated.
2470    pub on_update: FkAction,
2471    /// v7.38 (read01, T29) — `MATCH SIMPLE | FULL`. Defaults to `Simple`.
2472    pub match_type: MatchType,
2473    /// v7.39 (round 288) — `[NOT] DEFERRABLE`.
2474    pub deferrable: bool,
2475    /// `INITIALLY DEFERRED`: the check runs at COMMIT rather than at
2476    /// the statement, unless `SET CONSTRAINTS … IMMEDIATE` pulls it in.
2477    pub initially_deferred: bool,
2478}
2479
2480/// v7.38 (read01, T29) — FK MATCH type. Mirrors `spg_sql::ast::MatchType`.
2481#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
2482pub enum MatchType {
2483    #[default]
2484    Simple,
2485    Full,
2486}
2487
2488impl MatchType {
2489    /// On-disk tag byte (catalog appendix, `FILE_VERSION` 55+).
2490    pub const fn tag(self) -> u8 {
2491        match self {
2492            Self::Simple => 0,
2493            Self::Full => 1,
2494        }
2495    }
2496    pub const fn from_tag(b: u8) -> Option<Self> {
2497        Some(match b {
2498            0 => Self::Simple,
2499            1 => Self::Full,
2500            _ => return None,
2501        })
2502    }
2503}
2504
2505/// v7.6.1 — referential action tag. Mirrors `spg_sql::ast::FkAction`.
2506#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2507pub enum FkAction {
2508    Restrict,
2509    Cascade,
2510    SetNull,
2511    SetDefault,
2512    NoAction,
2513}
2514
2515impl FkAction {
2516    /// On-disk tag byte (v13 catalog appendix).
2517    pub const fn tag(self) -> u8 {
2518        match self {
2519            Self::Restrict => 0,
2520            Self::Cascade => 1,
2521            Self::SetNull => 2,
2522            Self::SetDefault => 3,
2523            Self::NoAction => 4,
2524        }
2525    }
2526    pub const fn from_tag(b: u8) -> Option<Self> {
2527        Some(match b {
2528            0 => Self::Restrict,
2529            1 => Self::Cascade,
2530            2 => Self::SetNull,
2531            3 => Self::SetDefault,
2532            4 => Self::NoAction,
2533            _ => return None,
2534        })
2535    }
2536}
2537
2538impl TableSchema {
2539    pub fn column_position(&self, name: &str) -> Option<usize> {
2540        self.columns.iter().position(|c| c.name == name)
2541    }
2542}
2543
2544/// Key type accepted by secondary indices. Float / NULL / Vector values
2545/// can't participate in a B-tree index — `f64` is only `PartialOrd`, NULL
2546/// has SQL-three-valued semantics, and Vector belongs to the (future) HNSW
2547/// path. Index lookups on those columns fall back to full scan.
2548#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
2549pub enum IndexKey {
2550    Int(i64),
2551    Text(String),
2552    Bool(bool),
2553    /// v7.17.0 — `Value::Uuid` index key. Comparison is byte-wise
2554    /// (RFC 4122 byte order) so PRIMARY KEY UUID lookups land on
2555    /// the same fast-path as Int / Text.
2556    Uuid([u8; 16]),
2557    /// r1039 — `Value::Bytes` (bytea). PG orders bytea by plain byte
2558    /// comparison, shorter-prefix first (`'' < \x00 < \x0000 < \x01ff <
2559    /// \xff`, measured on 18.4), which is exactly `Vec<u8>`'s `Ord`.
2560    Bytes(Vec<u8>),
2561    /// r1039 — exact decimal, in the canonical form described on
2562    /// [`NumericKey`].
2563    ///
2564    /// r1040 — BOXED, and the box is load-bearing for every OTHER index.
2565    /// A `NumericKey` is 48 bytes against `Text(String)`'s 24, so inline
2566    /// it set the size of the whole enum and every B-tree node in every
2567    /// index grew with it: 32 bytes per key to 48, align 8 to 16.
2568    /// Measured through the release sweep, `SELECT pad FROM t ORDER BY
2569    /// id` over 400,000 rows — a walk of the primary key's index — went
2570    /// 39.4-40.6 ms to 42.3-44.1, in both leg orders. The indirection is
2571    /// charged to numeric keys, which are new, instead of to every index
2572    /// that existed already.
2573    Numeric(alloc::boxed::Box<NumericKey>),
2574    /// v7.38.1 (L12) — a NULL component INSIDE a composite key, and
2575    /// nothing else. `IndexKey::from_value(Value::Null)` still returns
2576    /// `None`, so single-column B-trees never hold one, and no probe
2577    /// path ever BUILDS one (`col = NULL` is not a match in SQL) — the
2578    /// variant is only reachable through a composite key's component
2579    /// list, where it exists so that a row like `(2, 3, NULL)` stays
2580    /// findable by a PREFIX probe on `(w, d)`. Declared last: slice
2581    /// `Ord` then sorts NULL components after every value, PG's
2582    /// NULLS LAST.
2583    Null,
2584}
2585
2586/// r1039 — an exact-decimal index key, canonical so that representation
2587/// equality IS value equality.
2588///
2589/// That property is the whole reason this is a struct rather than the
2590/// `(scaled, scale)` pair the value carries. `1.5` and `1.50` are the
2591/// same NUMERIC (PG18.4: `1.5::numeric = 1.50::numeric` is true) and
2592/// arrive here as `(15, 1)` and `(150, 2)`. A B-tree keyed on the raw
2593/// pair would file them apart, so `WHERE n = 1.5` would miss a row stored
2594/// as `1.50` — an index changing the answer, which is the one thing an
2595/// index may never do. `BigNumeric::cmp` carries the same warning and
2596/// declines to implement `Ord` for exactly this reason; a KEY cannot
2597/// decline, so it normalizes instead.
2598///
2599/// Canonical form: significant decimal digits with no leading and no
2600/// trailing zeros, most significant first, plus the decimal exponent of
2601/// the leading digit. Zero is the empty digit vector with `neg == false`
2602/// and `exp == 0`, so there is no `-0`.
2603///
2604/// Ordering is PG's, measured: `-Infinity < -1 < 0 < 1 < Infinity < NaN`,
2605/// and `NaN = NaN`.
2606#[derive(Debug, Clone, PartialEq, Eq)]
2607pub struct NumericKey {
2608    /// 0 = -Infinity, 1 = finite, 2 = +Infinity, 3 = NaN. Ordering the
2609    /// classes by this byte is what puts NaN on top, where PG keeps it.
2610    class: u8,
2611    /// Finite only, and never set for zero.
2612    neg: bool,
2613    /// Decimal exponent of the leading significant digit; 0 for zero.
2614    exp: i32,
2615    /// r1040 — the first [`HEAD_DIGITS`] significant digits, LEFT-ALIGNED
2616    /// (multiplied up so the leading digit always sits at 10^36). That
2617    /// alignment is what makes an integer comparison of two heads the same
2618    /// answer as a digit-by-digit one: `12` and `1` become 1.2e36 and
2619    /// 1.0e36, which order the way the digit strings do, where the bare
2620    /// integers 12 and 1 would not.
2621    ///
2622    /// Zero for the value zero and for every special.
2623    ///
2624    /// This started as a `Vec<u8>` of digits, which is correct and cost
2625    /// an allocation per key and a slice comparison per sort comparison.
2626    /// `ORDER BY <numeric>` builds one key per row and compares n log n
2627    /// times: 200,000 rows measured 65.4 ms against 39.6 for the f64
2628    /// projection that had been returning rows in the wrong order.
2629    head: u128,
2630    /// Significant digits past the 37th, one per byte, no trailing zeros.
2631    /// Empty for everything an `i128` mantissa can hold with room to
2632    /// spare — and an empty `Vec` does not allocate, which is the point.
2633    tail: Vec<u8>,
2634}
2635
2636/// Significant digits carried in [`NumericKey::head`]. 37 is the most
2637/// that can be left-aligned inside a `u128`: the largest such value is
2638/// 9.99…e36, and `u128::MAX` is 3.4e38.
2639const HEAD_DIGITS: u32 = 37;
2640/// `10^36` — where a left-aligned leading digit sits.
2641const HEAD_SCALE: u128 = 1_000_000_000_000_000_000_000_000_000_000_000_000;
2642
2643/// The `class` byte of [`NumericKey`], in PG's order.
2644const NUM_CLASS_NEG_INF: u8 = 0;
2645const NUM_CLASS_FINITE: u8 = 1;
2646const NUM_CLASS_POS_INF: u8 = 2;
2647const NUM_CLASS_NAN: u8 = 3;
2648
2649impl NumericKey {
2650    /// The key for a `Value::Numeric`'s three fields.
2651    ///
2652    /// Public because the ORDER BY key wants the same canonical form the
2653    /// index key uses: two sort keys that disagree about which of two
2654    /// NUMERICs is larger is the same class of defect as an index that
2655    /// disagrees with a scan, and one definition is how they stay honest.
2656    #[must_use]
2657    pub fn from_numeric(scaled: i128, scale: u16, kind: NumericKind) -> Self {
2658        match kind {
2659            NumericKind::Finite => {
2660                let mut buf = [0u8; 40];
2661                let n = digits_of_u128(scaled.unsigned_abs(), &mut buf);
2662                Self::finite(scaled < 0, &buf[..n], i32::from(scale))
2663            }
2664            NumericKind::NaN => Self::special(NUM_CLASS_NAN),
2665            NumericKind::PosInf => Self::special(NUM_CLASS_POS_INF),
2666            NumericKind::NegInf => Self::special(NUM_CLASS_NEG_INF),
2667        }
2668    }
2669
2670    /// The key for an exact integer — no scale, so no rounding.
2671    #[must_use]
2672    pub fn from_i128(n: i128) -> Self {
2673        let mut buf = [0u8; 40];
2674        let len = digits_of_u128(n.unsigned_abs(), &mut buf);
2675        Self::finite(n < 0, &buf[..len], 0)
2676    }
2677
2678    /// The key for a mantissa that overflowed `i128`. The two
2679    /// representations of one value land on one key.
2680    #[must_use]
2681    pub fn from_big(b: &crate::bignum::BigNumeric) -> Self {
2682        let (neg, limbs, scale) = b.parts();
2683        Self::finite(neg, &digits_of_limbs(limbs), i32::from(scale))
2684    }
2685
2686    /// The `f64` this key means, for the one comparison PG defines that
2687    /// way: `numeric` against `float8` demotes the numeric.
2688    ///
2689    /// Lossy by construction — that is the point, and it is why nothing
2690    /// else uses it.
2691    #[must_use]
2692    #[allow(clippy::cast_precision_loss)]
2693    pub fn to_f64(&self) -> f64 {
2694        match self.class {
2695            NUM_CLASS_NAN => return f64::NAN,
2696            NUM_CLASS_POS_INF => return f64::INFINITY,
2697            NUM_CLASS_NEG_INF => return f64::NEG_INFINITY,
2698            _ => {}
2699        }
2700        if self.head == 0 {
2701            return 0.0;
2702        }
2703        // `head` is `d.ddd… × 10^36`; the value is that leading digit and
2704        // its followers at `exp`. The tail is below f64's resolution by
2705        // construction (it starts at the 38th significant digit).
2706        let mantissa = self.head as f64 / HEAD_SCALE as f64;
2707        let out = mantissa * pow10_f64(self.exp);
2708        if self.neg { -out } else { out }
2709    }
2710
2711    /// The significant decimal digits, most significant first — the form
2712    /// the catalog codec writes, and the one `from_parts` reads back.
2713    #[must_use]
2714    pub fn digits(&self) -> Vec<u8> {
2715        let mut out = Vec::new();
2716        if self.head != 0 {
2717            let mut h = self.head;
2718            for _ in 0..HEAD_DIGITS {
2719                let d = u8::try_from(h / HEAD_SCALE).unwrap_or(0);
2720                out.push(d);
2721                h = (h % HEAD_SCALE) * 10;
2722            }
2723            while out.last() == Some(&0) {
2724                out.pop();
2725            }
2726        }
2727        out.extend_from_slice(&self.tail);
2728        out
2729    }
2730
2731    /// The wire parts, for the catalog codec.
2732    #[must_use]
2733    pub fn parts(&self) -> (u8, bool, i32) {
2734        (self.class, self.neg, self.exp)
2735    }
2736
2737    /// Rebuild from the wire parts. Returns `None` on parts that are not
2738    /// canonical, so a corrupt catalog cannot smuggle in a key whose `Eq`
2739    /// and `Ord` disagree.
2740    #[must_use]
2741    pub fn from_parts(class: u8, neg: bool, exp: i32, digits: &[u8]) -> Option<Self> {
2742        if class > NUM_CLASS_NAN || digits.iter().any(|d| *d > 9) {
2743            return None;
2744        }
2745        if class != NUM_CLASS_FINITE && (neg || exp != 0 || !digits.is_empty()) {
2746            return None;
2747        }
2748        if digits.is_empty() {
2749            if neg || exp != 0 {
2750                return None;
2751            }
2752            return Some(Self::special(class));
2753        }
2754        if digits[0] == 0 || digits[digits.len() - 1] == 0 {
2755            return None;
2756        }
2757        Some(Self {
2758            class,
2759            neg,
2760            exp,
2761            head: head_of(digits),
2762            tail: digits.iter().skip(HEAD_DIGITS as usize).copied().collect(),
2763        })
2764    }
2765
2766    /// Canonicalize `(-1)^neg · <digits as an integer> · 10^-scale`.
2767    ///
2768    /// `digits` is most-significant-first and may carry leading and
2769    /// trailing zeros; both are stripped, which is what makes `1.5` and
2770    /// `1.50` land on the same key.
2771    fn finite(neg: bool, digits: &[u8], scale: i32) -> Self {
2772        let lead = digits.iter().position(|d| *d != 0).unwrap_or(digits.len());
2773        let digits = &digits[lead..];
2774        if digits.is_empty() {
2775            return Self::special(NUM_CLASS_FINITE);
2776        }
2777        // The leading digit's exponent, taken BEFORE trailing zeros go:
2778        // dropping low-order digits does not move the leading one.
2779        let exp = i32::try_from(digits.len()).unwrap_or(i32::MAX) - 1 - scale;
2780        let mut end = digits.len();
2781        while end > 0 && digits[end - 1] == 0 {
2782            end -= 1;
2783        }
2784        let digits = &digits[..end];
2785        Self {
2786            class: NUM_CLASS_FINITE,
2787            neg,
2788            exp,
2789            head: head_of(digits),
2790            tail: digits.iter().skip(HEAD_DIGITS as usize).copied().collect(),
2791        }
2792    }
2793
2794    fn special(class: u8) -> Self {
2795        Self {
2796            class,
2797            neg: false,
2798            exp: 0,
2799            head: 0,
2800            tail: Vec::new(),
2801        }
2802    }
2803}
2804
2805/// The first [`HEAD_DIGITS`] of `digits`, left-aligned so the leading one
2806/// sits at `10^36`.
2807fn head_of(digits: &[u8]) -> u128 {
2808    let mut head: u128 = 0;
2809    let take = (HEAD_DIGITS as usize).min(digits.len());
2810    for d in &digits[..take] {
2811        head = head * 10 + u128::from(*d);
2812    }
2813    for _ in take..HEAD_DIGITS as usize {
2814        head *= 10;
2815    }
2816    head
2817}
2818
2819/// Decimal digits of `mag` into `buf`, most significant first; returns how
2820/// many were written. Zero writes none.
2821///
2822/// r1040 — split at `u64` on purpose. A `u128` divide is a called routine,
2823/// not an instruction, and this loop runs once per digit per key.
2824fn digits_of_u128(mag: u128, buf: &mut [u8; 40]) -> usize {
2825    if mag == 0 {
2826        return 0;
2827    }
2828    let mut rev = [0u8; 40];
2829    let mut n = 0usize;
2830    let mut big = mag;
2831    // Peel nineteen digits at a time — the most a `u64` holds — so the
2832    // wide divide runs at most twice.
2833    while big > u128::from(u64::MAX) {
2834        let mut chunk = u64::try_from(big % 10_000_000_000_000_000_000_u128).unwrap_or(0);
2835        big /= 10_000_000_000_000_000_000_u128;
2836        for _ in 0..19 {
2837            rev[n] = u8::try_from(chunk % 10).unwrap_or(0);
2838            chunk /= 10;
2839            n += 1;
2840        }
2841    }
2842    let mut small = u64::try_from(big).unwrap_or(0);
2843    while small > 0 {
2844        rev[n] = u8::try_from(small % 10).unwrap_or(0);
2845        small /= 10;
2846        n += 1;
2847    }
2848    for i in 0..n {
2849        buf[i] = rev[n - 1 - i];
2850    }
2851    n
2852}
2853
2854/// Decimal digits of a base-10^9 little-endian limb vector, most
2855/// significant first. Every limb but the leading one is padded to its
2856/// full nine digits — that padding is the whole point, since a limb of 5
2857/// in the middle of a number means `000000005`.
2858fn digits_of_limbs(limbs: &[u32]) -> Vec<u8> {
2859    let mut out = Vec::new();
2860    let mut buf = [0u8; 40];
2861    for (i, limb) in limbs.iter().enumerate().rev() {
2862        let n = digits_of_u128(u128::from(*limb), &mut buf);
2863        if i + 1 == limbs.len() {
2864            out.extend_from_slice(&buf[..n]);
2865        } else {
2866            out.extend(core::iter::repeat_n(0u8, 9 - n));
2867            out.extend_from_slice(&buf[..n]);
2868        }
2869    }
2870    out
2871}
2872
2873/// `10^e` as an `f64`, for any `e` a canonical key can carry.
2874#[allow(clippy::cast_precision_loss)]
2875fn pow10_f64(e: i32) -> f64 {
2876    let mut out = 1.0_f64;
2877    let mag = e.unsigned_abs();
2878    for _ in 0..mag {
2879        out *= 10.0;
2880    }
2881    if e < 0 { 1.0 / out } else { out }
2882}
2883
2884impl Ord for NumericKey {
2885    fn cmp(&self, other: &Self) -> core::cmp::Ordering {
2886        use core::cmp::Ordering;
2887        if self.class != other.class {
2888            return self.class.cmp(&other.class);
2889        }
2890        if self.class != NUM_CLASS_FINITE {
2891            // Each of the three specials is a single value, and PG holds
2892            // `'NaN'::numeric = 'NaN'::numeric` true.
2893            return Ordering::Equal;
2894        }
2895        // Zero first: it is stored with `neg == false` and `exp == 0`, so
2896        // the magnitude comparison below would put it above every value
2897        // smaller than 1 rather than between the negatives and positives.
2898        match (self.head == 0, other.head == 0) {
2899            (true, true) => return Ordering::Equal,
2900            (true, false) => {
2901                return if other.neg {
2902                    Ordering::Greater
2903                } else {
2904                    Ordering::Less
2905                };
2906            }
2907            (false, true) => {
2908                return if self.neg {
2909                    Ordering::Less
2910                } else {
2911                    Ordering::Greater
2912                };
2913            }
2914            (false, false) => {}
2915        }
2916        match (self.neg, other.neg) {
2917            (false, true) => return Ordering::Greater,
2918            (true, false) => return Ordering::Less,
2919            _ => {}
2920        }
2921        // Same sign, both non-zero: more integer digits is bigger, and at
2922        // equal exponent the left-aligned heads compare as one integer —
2923        // the alignment is what makes that the same answer as comparing
2924        // the digit strings. The tail only speaks when the first 37
2925        // significant digits are identical.
2926        let mag = self
2927            .exp
2928            .cmp(&other.exp)
2929            .then_with(|| self.head.cmp(&other.head))
2930            .then_with(|| self.tail.cmp(&other.tail));
2931        if self.neg { mag.reverse() } else { mag }
2932    }
2933}
2934
2935impl PartialOrd for NumericKey {
2936    fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
2937        Some(self.cmp(other))
2938    }
2939}
2940
2941impl IndexKey {
2942    /// v7.37.43 (INSUBQ B-4) — inline-friendly BigInt fast path.
2943    /// `try_count_star_pk_in_subquery_fast` (and any other hot loop
2944    /// probing an integer PK) already holds an `i64`; this builds the
2945    /// `IndexKey` without going through the generic `from_value`
2946    /// dispatch tree.
2947    #[inline]
2948    pub fn from_i64(n: i64) -> Self {
2949        Self::Int(n)
2950    }
2951
2952    /// r1039 — the key a value takes when the INDEXED COLUMN is `ty`, or
2953    /// `None` when it takes none (→ the caller falls back to a scan).
2954    ///
2955    /// Every key under one index comes from one column, so they all live
2956    /// in one key SPACE. A probe built in a different space finds nothing
2957    /// — and "nothing" is indistinguishable from "no matching rows",
2958    /// which is how round 564 and r1037 both turned an index into a wrong
2959    /// answer (a TEXT key sought against a DATE-keyed and a UUID-keyed
2960    /// index).
2961    ///
2962    /// The two spaces this round adds make that trap reachable again from
2963    /// a new direction: `WHERE n = 2` on a NUMERIC column produces
2964    /// `Value::Int`, and an integer key would look in a space nothing
2965    /// lives in. So NUMERIC columns take integers by converting them
2966    /// exactly, and refuse anything they cannot convert; BYTEA columns
2967    /// take only `Value::Bytes`; and no other column may be keyed in
2968    /// either of the two new spaces.
2969    ///
2970    /// Use this wherever the key comes from a LITERAL or from another
2971    /// table's value. [`IndexKey::from_value`] stays right for building
2972    /// the index itself, where the value is the column's own.
2973    pub fn from_value_for_column(v: &Value<'_>, ty: DataType) -> Option<Self> {
2974        match ty {
2975            DataType::Numeric { .. } => match v {
2976                Value::SmallInt(n) => Some(Self::exact_int_key(i128::from(*n))),
2977                Value::Int(n) => Some(Self::exact_int_key(i128::from(*n))),
2978                Value::BigInt(n) => Some(Self::exact_int_key(i128::from(*n))),
2979                Value::Numeric { .. } | Value::NumericBig(_) => Self::from_value(v),
2980                // Float included: `2.0::float8` and `2.0::numeric` are not
2981                // the same value to a B-tree, and rounding one into the
2982                // other's space is how a seek reaches the wrong row.
2983                _ => None,
2984            },
2985            DataType::Bytes => match v {
2986                Value::Bytes(b) => Some(Self::Bytes(b.to_vec())),
2987                _ => None,
2988            },
2989            _ => match Self::from_value(v) {
2990                Some(Self::Numeric(_) | Self::Bytes(_)) => None,
2991                other => other,
2992            },
2993        }
2994    }
2995
2996    /// An integer as a NUMERIC key. Exact by construction — no scale, no
2997    /// rounding — which is why the conversion is allowed at all.
2998    fn exact_int_key(n: i128) -> Self {
2999        Self::Numeric(alloc::boxed::Box::new(NumericKey::from_i128(n)))
3000    }
3001
3002    pub fn from_value(v: &Value<'_>) -> Option<Self> {
3003        match v {
3004            // v7.37.43 (INSUBQ B-4) — BigInt hits first (the dominant
3005            // INSUBQ shape probes PK as BigInt). Tiny micro-win.
3006            Value::BigInt(n) => Some(Self::Int(*n)),
3007            Value::SmallInt(n) => Some(Self::Int(i64::from(*n))),
3008            Value::Int(n) => Some(Self::Int(i64::from(*n))),
3009            Value::Text(s) => Some(Self::Text(s.clone().into_owned())),
3010            // v7.38 (read01, T11) — bpchar keys compare blank-insensitively.
3011            Value::BpChar(s) => Some(Self::Text(s.trim_end_matches(' ').to_string())),
3012            Value::Bool(b) => Some(Self::Bool(*b)),
3013            // Date/Timestamp use their integer storage repr as the
3014            // index key — same order semantics, same comparison.
3015            Value::Date(d) => Some(Self::Int(i64::from(*d))),
3016            Value::Timestamp(t) => Some(Self::Int(*t)),
3017            // v7.17.0: UUID indexable via byte-wise ordering. Lookup
3018            // on `id = '...'::uuid` resolves through the secondary
3019            // index rather than full-scan.
3020            Value::Uuid(b) => Some(Self::Uuid(*b)),
3021            // v7.17.0 Phase 3.P0-32: TIME indexable via i64 — same
3022            // order semantics as Date/Timestamp.
3023            Value::Time(us) => Some(Self::Int(*us)),
3024            // v7.17.0 Phase 3.P0-33: YEAR indexable as i64 — u16
3025            // widens losslessly and gives the natural calendar
3026            // ordering.
3027            Value::Year(y) => Some(Self::Int(i64::from(*y))),
3028            // v7.17.0 Phase 3.P0-34: TIMETZ indexable by its
3029            // UTC-equivalent microseconds (local wall - offset).
3030            // Without normalising, two values for the same
3031            // physical instant in different zones would sort
3032            // wrong. Matches PG's TIMETZ index behaviour.
3033            Value::TimeTz { us, offset_secs } => {
3034                Some(Self::Int(us - i64::from(*offset_secs) * 1_000_000))
3035            }
3036            // v7.17.0 Phase 3.P0-35: MONEY indexable as i64 cents
3037            // (no scaling needed — natural numeric ordering).
3038            Value::Money(c) => Some(Self::Int(*c)),
3039            // v7.17.0 Phase 3.P0-38: ranges are NOT indexable in
3040            // v7.17.0 — they'd need a custom comparator (PG uses
3041            // SP-GiST for this). Skip.
3042            Value::Range { .. } => None,
3043            // v7.17.0 Phase 3.P0-39: hstore is NOT indexable in
3044            // v7.17.0 — map columns need GIN with bespoke ops.
3045            Value::Hstore(_) => None,
3046            // r1039 — exact decimals index through the canonical
3047            // [`NumericKey`], which is what makes `1.5` and `1.50` one key.
3048            Value::NumericBig(b) => Some(Self::Numeric(alloc::boxed::Box::new(NumericKey::from_big(b)))),
3049            Value::Numeric {
3050                scaled,
3051                scale,
3052                kind,
3053            } => Some(Self::Numeric(alloc::boxed::Box::new(
3054                NumericKey::from_numeric(*scaled, *scale, *kind),
3055            ))),
3056            // r1039 — bytea orders by plain byte comparison, which is
3057            // `Vec<u8>`'s own.
3058            Value::Bytes(b) => Some(Self::Bytes(b.to_vec())),
3059            // v7.17.0 Phase 3.P0-40: 2D arrays aren't indexable.
3060            Value::IntArray2D(_)
3061            | Value::BigIntArray2D(_)
3062            | Value::TextArray2D(_)
3063            | Value::BoolArray2D(_) => None,
3064            // v7.37.5 β-P4: INTERVAL[] isn't indexable (PG uses
3065            // GIN/intarray for array-contains queries; SPG plans
3066            // that as a separate axis under v7.37.8 GIN-on-jsonb).
3067            Value::IntervalArray(_) => None,
3068            // v7.37.5 γ — none of the array-of-scalar family is
3069            // B-tree indexable. Same reason as IntervalArray: PG
3070            // serves array-contains / array-overlap queries via
3071            // GIN, and SPG's GIN axis lands in v7.37.8.
3072            Value::BoolArray(_)
3073            | Value::SmallIntArray(_)
3074            | Value::Int2Vector(_)
3075            | Value::OidVector(_)
3076            | Value::FloatArray(_)
3077            | Value::NumericArray(_)
3078            | Value::DateArray(_)
3079            | Value::TimestampArray(_)
3080            | Value::TimestamptzArray(_)
3081            | Value::UuidArray(_)
3082            | Value::JsonArray(_)
3083            | Value::JsonbArray(_)
3084            | Value::BytesArray(_)
3085            | Value::VarcharArray(_)
3086            | Value::CharArray(_)
3087            // v7.37.5 δ — multirange not indexable (PG uses GiST/
3088            // SP-GiST + a custom operator class; SPG plans the same
3089            // axis under v7.37.8 with ranges).
3090            | Value::Multirange { .. }
3091            // v7.37.5 ε — geometric scalars not B-tree indexable
3092            // (PG uses GiST/SP-GiST for these too; SPG plans the
3093            // same axis under v7.37.8).
3094            | Value::Point(_)
3095            | Value::Lseg(_, _)
3096            | Value::Path { .. }
3097            | Value::PgBox(_, _)
3098            | Value::Polygon(_)
3099            | Value::Line { .. }
3100            | Value::Circle { .. }
3101            // v7.37.5 ζ-A — network / bit / xml / "char" / money[].
3102            // INET / CIDR / MACADDR / MACADDR8 could be B-tree
3103            // indexable (PG does this), but the byte-wise compare
3104            // family-blind would mis-order IPv4 vs IPv6; left as
3105            // a follow-up under v7.37.8 GIN window.
3106            | Value::Inet { .. }
3107            | Value::Cidr { .. }
3108            | Value::Macaddr(_)
3109            | Value::Macaddr8(_)
3110            | Value::PgLsn(_)
3111            | Value::BitString { .. }
3112            | Value::Xml(_)
3113            | Value::Char1(_)
3114            | Value::MoneyArray(_)
3115            | Value::Composite(_)
3116            | Value::Tid(..)
3117            | Value::Xid(_)
3118            | Value::Cid(_)
3119            | Value::RegClass(..)
3120            | Value::RegProc(..)
3121            | Value::RegType(..) => None,
3122            // Interval isn't index-eligible (and can't reach this path
3123            // through column storage anyway). Float / Real stay out
3124            // because `f64` is only `PartialOrd`.
3125            Value::Null
3126            | Value::Float(_)
3127            | Value::Vector(_)
3128            | Value::Sq8Vector(_)
3129            | Value::HalfVector(_)
3130            | Value::Interval { .. }
3131            | Value::Json(_)
3132            | Value::TextArray(_)
3133            | Value::IntArray(_)
3134            | Value::BigIntArray(_)
3135            | Value::TsVector(_)
3136            | Value::TsQuery(_)
3137            | Value::Real(_) => None,
3138        }
3139    }
3140}
3141
3142/// A single-column secondary index. v2.0 carries either a B-tree map
3143/// (the default — used for equality / range lookups on scalar columns)
3144/// or a navigable-small-world graph (used for kNN over vector
3145/// columns).
3146#[derive(Debug, Clone)]
3147pub struct Index {
3148    pub name: String,
3149    pub column_position: usize,
3150    pub kind: IndexKind,
3151    /// v6.8.0 — column positions of `INCLUDE (col1, col2, …)`
3152    /// non-key columns. Carries the planner's "this query is
3153    /// covered by the index" signal; lookup paths still resolve
3154    /// via the `RowLocator` to fetch the row body, but EXPLAIN
3155    /// surfaces the covered-scan annotation so operators can
3156    /// confirm the planner sees the coverage.
3157    ///
3158    /// Empty `Vec` = no `INCLUDE` clause (the legacy shape). v12
3159    /// catalog snapshots deserialise with an empty vec.
3160    pub included_columns: Vec<usize>,
3161    /// v6.8.1 — partial-index predicate stored as its canonical
3162    /// Display form (the engine re-parses it on the maintenance
3163    /// path). `None` = unconditional index (the legacy shape).
3164    /// Persisted as `[u8 has_pred][u16 LE len][bytes]` on the
3165    /// catalog snapshot (FILE_VERSION 12, appended after
3166    /// `included_columns`).
3167    pub partial_predicate: Option<String>,
3168    /// v6.8.2 — expression-index key, stored as the expression's
3169    /// canonical Display form. `None` = bare column-reference
3170    /// index (the legacy shape). Persisted alongside
3171    /// `partial_predicate` on the v12 catalog snapshot.
3172    pub expression: Option<String>,
3173    /// v7.39 (read01 round 52) — `CREATE UNIQUE INDEX … NULLS NOT DISTINCT`
3174    /// (PG 15+): a NULL in the key no longer exempts the row, so two
3175    /// all-NULL keys collide. Default `false` = SQL-standard NULLS DISTINCT.
3176    /// Persisted in the index appendix (FILE_VERSION 62+); older catalogs
3177    /// deserialise with `false`.
3178    pub nulls_not_distinct: bool,
3179    /// v7.39 (round 537) — the key column's ordering clause, as written.
3180    ///
3181    /// SPG's index does not scan in a direction, so this changes no
3182    /// lookup; `pg_indexes.indexdef` is a reproduction of the DDL and
3183    /// dropping the clause made `CREATE INDEX i ON t (a DESC NULLS
3184    /// LAST)` read back as `(a)` — a dump lost it and a schema diff saw
3185    /// drift every run. `nulls_first` is `None` when the statement did
3186    /// not say, in which case PG's default applies and neither word is
3187    /// rendered.
3188    pub descending: bool,
3189    pub nulls_first: Option<bool>,
3190    /// v7.39 (round 538) — an explicit `COLLATE` on the key, as written.
3191    /// SPG orders text by bytes, so it changes no comparison; PG prints
3192    /// it because a named collation and an inherited one are different
3193    /// objects even where they sort identically.
3194    pub collation: Option<String>,
3195    /// v7.9.29 — `CREATE UNIQUE INDEX …`. When true the engine
3196    /// rejects INSERTs whose key already appears in this index
3197    /// (combined with `partial_predicate` when present — only
3198    /// rows matching the predicate enter the uniqueness check).
3199    /// Catalog FILE_VERSION 16+; older snapshots deserialise
3200    /// with `false`. mailrs K1.
3201    pub is_unique: bool,
3202    /// v7.9.29 — extra (non-leading) column positions for
3203    /// multi-column indexes (`CREATE INDEX … (a, b, c)`). The
3204    /// planner today still only uses the leading
3205    /// `column_position` for index seeks, but UNIQUE INDEX
3206    /// enforcement walks the full tuple so partial-unique
3207    /// invariants like CalDAV `(calendar_id, uid,
3208    /// recurrence_id)` are enforced correctly. Catalog
3209    /// FILE_VERSION 16+; older snapshots deserialise empty.
3210    pub extra_column_positions: Vec<usize>,
3211    /// v7.39.11 — each extra key column's `DESC` / `NULLS FIRST`,
3212    /// positionally aligned with `extra_column_positions`. An empty
3213    /// vec, and any position past its end, means the PG default:
3214    /// ascending, nulls last.
3215    ///
3216    /// SPG's index does not scan in a per-column direction, so this
3217    /// changes no lookup — the same reason `descending` exists for the
3218    /// LEADING column. `pg_get_indexdef` is a reproduction of the DDL,
3219    /// and without this `CREATE INDEX i ON t (a, b DESC)` read back as
3220    /// `(a, b)`: a dump lost the clause and a schema diff saw drift
3221    /// every run. Reported by sentori against 7.39.10; round 537 fixed
3222    /// the identical thing for the leading column.
3223    pub extra_orders: Vec<KeyOrder>,
3224}
3225
3226/// v7.39.11 — one index key column's ordering clause, as written.
3227#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
3228pub struct KeyOrder {
3229    pub descending: bool,
3230    /// `None` when the statement did not say, in which case PG's
3231    /// default applies and neither word is rendered.
3232    pub nulls_first: Option<bool>,
3233}
3234
3235/// Default neighbor degree (M) for the NSW graph. Picked at construction
3236/// time and persisted with the index.
3237pub const NSW_DEFAULT_M: usize = 16;
3238
3239/// v5.2.2: outcome of a successful [`Catalog::freeze_oldest_to_cold`]
3240/// call. The catalog state has already been mutated by the time this
3241/// is returned (hot rows dropped + segment registered + Cold locators
3242/// flipped). The caller's only remaining concern is `segment_bytes` —
3243/// persist them to disk under `<db>.spg/segments/seg_<id>.spg` so a
3244/// future restart can reload via the v5.1 `SPG_PRELOAD_COLD_SEGMENT`
3245/// path. (v5.3's manifest will subsume this manual step.)
3246#[derive(Debug, Clone)]
3247pub struct FreezeReport {
3248    /// Id allocated by [`Catalog::load_segment_bytes`] for the new
3249    /// cold-tier segment. Stable across the call's success path.
3250    pub segment_id: u32,
3251    /// Number of rows that moved hot → cold. Equals the `max_rows`
3252    /// the caller asked for (the API is strict on the count).
3253    pub frozen_rows: usize,
3254    /// Hot-tier bytes reclaimed by the freeze — the
3255    /// [`Table::hot_bytes`] delta before vs after. Useful to feed
3256    /// back into the freezer's budget check on the next tick.
3257    pub bytes_freed: u64,
3258    /// Encoded segment bytes, byte-identical to what
3259    /// [`encode_segment`] produced. The catalog already owns a
3260    /// copy inside `cold_segments`; this hand-off lets the caller
3261    /// persist them without re-encoding.
3262    pub segment_bytes: Vec<u8>,
3263}
3264
3265/// v6.7.4 — read-only output of [`Catalog::prepare_freeze_slice`].
3266/// Carries every row body + key in a contiguous hot-row range,
3267/// already encoded and sorted by PK so the coordinator's merge
3268/// step is a k-way merge over already-sorted streams.
3269///
3270/// `Vec<FreezeSlice>` from N independent workers feeds
3271/// [`Catalog::commit_freeze_slices`], which concats + encodes the
3272/// merged segment + atomically swaps the catalog state.
3273#[derive(Debug, Clone)]
3274pub struct FreezeSlice {
3275    /// Hot-row index range this slice covered (half-open, in the
3276    /// table's `rows: PersistentVec` ordering at call time). The
3277    /// commit step uses this to compute the union range that
3278    /// gets passed to [`Table::delete_rows`].
3279    pub row_range: core::ops::Range<usize>,
3280    /// `(pk_u64, encoded_row_body, IndexKey)` triples, sorted
3281    /// ascending by `pk_u64`. Per-slice sort happens inside
3282    /// `prepare_freeze_slice`; the coordinator does only a
3283    /// k-way merge to reach the global PK ordering
3284    /// [`encode_segment`] requires.
3285    pub rows: Vec<(u64, Vec<u8>, IndexKey)>,
3286}
3287
3288/// v6.7.3 — outcome of a [`Catalog::compact_cold_segments`] call.
3289/// The catalog state has already been mutated when this is returned:
3290/// the merged segment is loaded into `cold_segments`, the source
3291/// segment slots are tombstoned (`None`), and every BTree-index
3292/// `RowLocator::Cold` that previously pointed at a source now
3293/// points at the merged segment. The caller's remaining job is to
3294/// persist `merged_segment_bytes` under
3295/// `<db>.spg/segments/seg_<merged_segment_id>.spg` and update the
3296/// in-memory `segment_id → path` map (remove the source ids, add
3297/// the merged id) so the next CHECKPOINT writes a manifest that
3298/// no longer lists the retired sources.
3299///
3300/// On a no-op (fewer than 2 candidate segments under the threshold),
3301/// `merged_segment_id` is `None` and `sources` is empty; the
3302/// catalog was not mutated.
3303#[derive(Debug, Clone)]
3304pub struct CompactReport {
3305    /// Source segment ids that were merged + tombstoned.
3306    pub sources: Vec<u32>,
3307    /// Id allocated for the merged segment. `None` on no-op.
3308    pub merged_segment_id: Option<u32>,
3309    /// Encoded merged-segment bytes (empty on no-op).
3310    pub merged_segment_bytes: Vec<u8>,
3311    /// Number of rows that landed in the merged segment.
3312    pub merged_rows: usize,
3313    /// `Σ source.num_rows − merged_rows`. Rows present in source
3314    /// segment payloads but unreferenced by any live BTree
3315    /// `Cold` locator — DELETE'd-but-still-frozen rows that
3316    /// compaction GC'd during the merge.
3317    pub deleted_rows_pruned: usize,
3318    /// `Σ source.bytes() − merged.bytes()`. Estimate of on-disk
3319    /// space the merge will reclaim once the source segment files
3320    /// are GC'd. Saturating subtract — never negative.
3321    pub bytes_reclaimed_estimate: u64,
3322}
3323
3324#[derive(Debug, Clone)]
3325pub enum IndexKind {
3326    /// v4.40: structural-sharing B-tree over `IndexKey`. Replaces the v0.8
3327    /// `BTreeMap<IndexKey, Vec<usize>>` — `Index::clone` is now an `Arc`
3328    /// bump regardless of index size, so `Catalog::clone` inside the
3329    /// v4.34 auto-commit wrap stays O(1) even for tables with secondary
3330    /// indices (the case that bottlenecked v4.39 at 1M rows in the
3331    /// sweep).
3332    ///
3333    /// v5.1: value type widened from `Vec<usize>` to `Vec<RowLocator>` so
3334    /// a single key can point to a mix of hot-tier rows (`RowLocator::Hot`,
3335    /// equivalent to the pre-v5 `usize` row index) and cold-tier rows
3336    /// (`RowLocator::Cold { segment_id, page_offset }`) once the v5.2
3337    /// freezer starts producing them. Pre-v5.2 only `Hot` entries appear
3338    /// — the on-disk encoding stays at `FILE_VERSION` 8 (raw u64 row index)
3339    /// because every locator round-trips through `RowLocator::from_legacy_v8_u64`
3340    /// without information loss. `FILE_VERSION` 9 with tagged encoding lands
3341    /// alongside the first freezer commit (v5.1 step 2b / v5.2).
3342    BTree(PersistentBTreeMap<IndexKey, crate::posting::PostingList>),
3343    /// Navigable-small-world graph for vector kNN search.
3344    Nsw(NswGraph),
3345    /// v6.7.1 — BRIN (Block Range INdex). Pure metadata: BRIN
3346    /// indexes carry NO in-memory key→locator map. The (min,
3347    /// max) summaries live in each cold-tier segment's v2
3348    /// envelope sidecar; the BRIN entry in `Table.indices` only
3349    /// records THAT a BRIN index exists on this column so the
3350    /// segment encoder + planner can opt into the summary path.
3351    Brin {
3352        /// The cell type at `column_position` at CREATE INDEX time.
3353        /// Used by the planner to type-check WHERE-clause range
3354        /// predicates against the BRIN-indexed column.
3355        column_type: DataType,
3356        /// v7.38.11 — one `(min, max)` per [`BRIN_RANGE_ROWS`] slots of
3357        /// the hot tier, so a range predicate can skip the ranges that
3358        /// cannot contain a match.
3359        ///
3360        /// Maintenance is WIDEN-ONLY and that is the whole safety
3361        /// argument: an insert widens its range, an update widens, and
3362        /// a delete leaves the range alone. A range left wider than the
3363        /// rows it now covers is correct and merely less selective —
3364        /// which is exactly PG's contract for a lossy index, since the
3365        /// predicate is re-checked on every row the summary lets
3366        /// through. A summary may over-report; it can never
3367        /// under-report, so no matching row can be skipped.
3368        ///
3369        /// `None` for a range whose rows carry no comparable key (all
3370        /// NULL, say), and such a range is never skipped.
3371        summaries: alloc::vec::Vec<Option<(i64, i64)>>,
3372    },
3373    /// v7.12.3 — GIN inverted index over a `tsvector` column.
3374    ///
3375    /// Storage shape: `lexeme word → Vec<RowLocator>`. The posting
3376    /// list per word is appended in row-order, so range scans are
3377    /// O(matching rows) once the per-word lookup is done. Multi-
3378    /// term queries intersect / union posting lists.
3379    ///
3380    /// `IndexKey::from_value(TsVector)` returns `None` — GIN doesn't
3381    /// participate in `try_index_seek` (which is BTree-equality-keyed).
3382    /// The engine consults this index through `try_gin_lookup` on
3383    /// `WHERE col @@ tsquery` predicates instead.
3384    ///
3385    /// Backed by a `PersistentBTreeMap` so `Catalog::clone` (the
3386    /// per-write snapshot) stays O(1) — same structural-sharing
3387    /// invariant as BTree.
3388    Gin(PersistentBTreeMap<alloc::string::String, crate::posting::PostingList>),
3389    /// v7.15.0 — `USING gin (col gin_trgm_ops)` over a `TEXT`
3390    /// column. Posting lists map `trigram` (PG-compatible 3-byte
3391    /// shingle on the lower-cased + space-padded input) to row
3392    /// locators. The planner uses this index to accelerate
3393    /// `WHERE col LIKE '…'` / `ILIKE '…'` / `similarity(col, q) >
3394    /// t` — every literal run of length ≥ 1 in the pattern
3395    /// produces a trigram set, the engine intersects the posting
3396    /// lists, and the LIKE / similarity predicate is re-evaluated
3397    /// per candidate row to filter the over-approximation.
3398    /// Persisted via tag-4 index payload in `FILE_VERSION` 24+.
3399    GinTrgm(PersistentBTreeMap<alloc::string::String, crate::posting::PostingList>),
3400    /// v7.17.0 Phase 2.2 — MySQL `FULLTEXT KEY (col)` over a
3401    /// `TEXT` / `VARCHAR` column. Posting lists map
3402    /// `tsvector('simple') lexeme` to row locators. At insert /
3403    /// build time the engine derives the lexemes from the cell
3404    /// via the same lower-case tokenisation rule as
3405    /// `to_tsvector('simple', ...)` — the column itself stays a
3406    /// plain text type on disk (mysqldump round-trips would be
3407    /// broken otherwise). The planner uses this index to
3408    /// accelerate MySQL-shape `MATCH(col) AGAINST('term')`
3409    /// queries by mapping them onto the existing tsquery `@@`
3410    /// walker. Persisted via tag-5 index payload in
3411    /// `FILE_VERSION` 33+.
3412    GinFulltext(PersistentBTreeMap<alloc::string::String, crate::posting::PostingList>),
3413    /// v7.37.8(sentori Epic 5 P2)— `USING gin (col)` over a
3414    /// `JSON` / `JSONB` column. Posting lists map a canonical
3415    /// `(path, leaf)` token(see [`crate::jsonb_gin::extract_tokens`])
3416    /// to row locators so the planner can resolve
3417    /// `<col> @> <jsonb_literal>` to a candidate row set via
3418    /// posting-list intersection + per-row `json::contains`
3419    /// re-verification. Pre-7.37.8 the same DDL loaded as a
3420    /// BTree fallback so `pg_dump` JSONB-GIN scripts kept loading
3421    /// without query-time acceleration. Persisted via tag-6 index
3422    /// payload in `FILE_VERSION` 51+.
3423    GinJsonb(PersistentBTreeMap<alloc::string::String, crate::posting::PostingList>),
3424    /// v7.38.1 (L12) — a REAL multi-column B-tree: the key is the whole
3425    /// column tuple, `[leading, extras…]`, ordered lexicographically by
3426    /// slice `Ord`. That ordering is the entire design: every key
3427    /// sharing a prefix is contiguous, so an equality on a PREFIX of
3428    /// the columns is one `O(log N)` descent plus a bounded walk, and a
3429    /// full-tuple equality is a point `get`. The single-column `BTree`
3430    /// kind used to stand in for multi-column DDL by keying on the
3431    /// leading column only and carrying the rest as metadata — TPC-C's
3432    /// `customer (c_w_id, c_d_id, c_last, c_first)` then answered a
3433    /// three-column equality with every row of one warehouse and a
3434    /// per-row filter over 30 000 candidates.
3435    ///
3436    /// Rows where any component column is NULL (or of an unkeyable
3437    /// type) are NOT entered: this index serves `=` probes, and in SQL
3438    /// `col = v` never selects a NULL. Uniqueness keeps its own
3439    /// full-tuple walk with NULLS-DISTINCT semantics on the
3440    /// enforcement path, exactly as before.
3441    ///
3442    /// Persisted via tag-7 index payload in `FILE_VERSION` 91+.
3443    BTreeMulti(PersistentBTreeMap<alloc::boxed::Box<[IndexKey]>, crate::posting::PostingList>),
3444}
3445
3446impl IndexKind {
3447    /// v7.31 (memory campaign, C2) — bytes this index variant holds
3448    /// resident in RAM, computed by walking its OWN structure rather
3449    /// than a parametric guess made by the engine. Replaces the old
3450    /// `spg_admin::memory_stats` inline match, which charged NSW with
3451    /// a stale `m_max_0 * 8` per node (neighbour slots are `u32` = 4 B
3452    /// since v6.1.x, and most nodes never fill `m_max_0`) and lumped
3453    /// every GIN family index into a flat 1 KiB token — a gross
3454    /// undercount for the text-heavy posting lists that dominate
3455    /// mailrs' footprint. Per-entry container overhead uses the
3456    /// 3-word (24 B on 64-bit) `Vec`/`String` header as the charge.
3457    ///
3458    /// O(index entries): operator/monitoring surface (`memory_stats` /
3459    /// `spg_memory_stats`), not a query path.
3460    #[must_use]
3461    pub fn approx_resident_bytes(&self) -> u64 {
3462        const HEADER: usize = 24; // Vec/String 3-word header on 64-bit.
3463        let loc = core::mem::size_of::<RowLocator>();
3464        match self {
3465            IndexKind::BTree(map) => {
3466                let key = core::mem::size_of::<IndexKey>();
3467                map.iter()
3468                    .map(|(_, locs)| (key + HEADER + locs.len() * loc) as u64)
3469                    .sum()
3470            }
3471            // v7.38.1 (L12) — multi keys own a boxed slice of components.
3472            IndexKind::BTreeMulti(map) => {
3473                let key = core::mem::size_of::<IndexKey>();
3474                map.iter()
3475                    .map(|(k, locs)| (HEADER + k.len() * key + HEADER + locs.len() * loc) as u64)
3476                    .sum()
3477            }
3478            IndexKind::Nsw(g) => {
3479                // `levels` is one byte per node; each layer's adjacency
3480                // is a `Vec<u32>` per node whose actual length we walk
3481                // (the dense layer-0 list dominates, but upper layers
3482                // are sparse — the old estimate ignored that).
3483                let mut b = g.levels.len() as u64;
3484                for layer in &g.layers {
3485                    for nbrs in layer.iter() {
3486                        b += (HEADER + nbrs.len() * core::mem::size_of::<u32>()) as u64;
3487                    }
3488                }
3489                b
3490            }
3491            // BRIN carries NO in-memory key→locator map (the (min,max)
3492            // summaries live in cold-segment sidecars on disk); the
3493            // resident footprint is just the column-type token.
3494            IndexKind::Brin { .. } => core::mem::size_of::<DataType>() as u64,
3495            IndexKind::Gin(map)
3496            | IndexKind::GinTrgm(map)
3497            | IndexKind::GinFulltext(map)
3498            | IndexKind::GinJsonb(map) => map
3499                .iter()
3500                .map(|(word, postings)| {
3501                    (word.len() + HEADER + HEADER + postings.len() * loc) as u64
3502                })
3503                .sum(),
3504        }
3505    }
3506}
3507
3508/// Multi-layer HNSW graph (v2.13). Each node is assigned a `top_level`;
3509/// it appears in layers `0..=top_level`. Higher layers are sparser, so
3510/// search starts from the entry at the top layer, greedy-descends to
3511/// layer 0, and beam-searches there. Layer 0 keeps a larger neighbour
3512/// budget (`m_max_0 = 2 * m` per the HNSW paper); upper layers cap at
3513/// `m`. The struct name stays `NswGraph` so external users / on-disk
3514/// callers don't have to track a rename — the algorithm changed, the
3515/// data slot didn't.
3516#[derive(Debug, Clone)]
3517pub struct NswGraph {
3518    /// Max neighbours per node on layers ≥ 1.
3519    pub m: usize,
3520    /// Max neighbours on layer 0 (the dense bottom layer). HNSW
3521    /// convention: `m_max_0 = 2 * m`.
3522    pub m_max_0: usize,
3523    /// Entry point — the node that sits on the topmost layer. Search
3524    /// always starts here.
3525    pub entry: Option<usize>,
3526    /// Top layer of the entry node (== `layers.len() - 1` when populated).
3527    pub entry_level: u8,
3528    /// `levels[i]` = top layer of node `i`. Nodes whose vector cell is
3529    /// NULL / non-Vector have `levels[i] = 0` and no neighbour entries.
3530    ///
3531    /// v5.5.0: backed by `PersistentVec` so `NswGraph::clone` (and the
3532    /// `Catalog::clone` on every group-commit write that contains it) is O(1)
3533    /// structural-sharing instead of an O(N) element copy.
3534    pub levels: PersistentVec<u8>,
3535    /// `layers[l][i]` = neighbours of node `i` at layer `l`. Inner vec
3536    /// is empty when node `i` doesn't reach layer `l`.
3537    ///
3538    /// v5.5.0: the per-node middle dimension (the O(N) one) is a
3539    /// `PersistentVec`; the outer layer dimension stays a plain `Vec`
3540    /// (layer count ≤ 8, so its clone is O(1) in practice) and the inner
3541    /// neighbour list stays a `Vec` (bounded by `m_max_0`).
3542    ///
3543    /// v6.1.x: neighbour slot widened from `usize` (8 B on 64-bit) to
3544    /// `u32` (4 B). Row indices are catalog-bounded by `u32::MAX` (4G
3545    /// rows per table); the cast at the NSW boundary asserts this. At
3546    /// 1M dim-128 SQ8, layer 0 adjacency alone shrinks by ~128 MiB
3547    /// — the largest single contribution to the v6.0.5-measured
3548    /// 624 MiB ambition gap. On-disk format already used u32 LE, so
3549    /// this is a pure in-memory layout change; no `FILE_VERSION` bump.
3550    pub layers: Vec<PersistentVec<Vec<u32>>>,
3551}
3552
3553impl NswGraph {
3554    fn new(m: usize) -> Self {
3555        Self {
3556            m,
3557            m_max_0: m.saturating_mul(2),
3558            entry: None,
3559            entry_level: 0,
3560            levels: PersistentVec::new(),
3561            layers: alloc::vec![PersistentVec::new()],
3562        }
3563    }
3564
3565    /// Max-neighbour budget for layer `l`.
3566    pub const fn cap_for_layer(&self, layer: u8) -> usize {
3567        if layer == 0 { self.m_max_0 } else { self.m }
3568    }
3569}
3570
3571/// Deterministic level assignment, seeded on the row index so the same
3572/// insert order reproduces the same topology. Distribution is roughly
3573/// HNSW-flavoured with `mL ≈ 1/ln(M) ≈ 0.36` for M=16: each 4-bit
3574/// chunk that comes up zero promotes the node one layer (so P(level ≥
3575/// L) ≈ (1/16)^L).
3576#[allow(clippy::verbose_bit_mask)] // clippy suggests trailing_zeros(); we need an explicit MAX cap and a stable distribution shape.
3577pub fn nsw_assign_level(row_idx: usize) -> u8 {
3578    const MAX_LEVEL: u8 = 7; // 7 ⇒ ~16^7 ≈ 2.7e8 expected nodes between promotions; ample.
3579    // SplitMix-style mixer — cheap and seedable.
3580    let mut x = (row_idx as u64).wrapping_mul(0x9E37_79B9_7F4A_7C15);
3581    x ^= x >> 30;
3582    x = x.wrapping_mul(0xBF58_476D_1CE4_E5B9);
3583    x ^= x >> 27;
3584    x = x.wrapping_mul(0x94D0_49BB_1331_11EB);
3585    x ^= x >> 31;
3586    // Count contiguous low-end zero nibbles (4-bit chunks). Each zero
3587    // nibble has probability 1/16, mirroring HNSW's `mL ≈ 1/ln(M)` for
3588    // M=16. `trailing_zeros / 4` would lose the ordering when x = 0, so
3589    // a plain loop with a cap is clearer.
3590    let mut level: u8 = 0;
3591    while x & 0xF == 0 && level < MAX_LEVEL {
3592        level += 1;
3593        x >>= 4;
3594    }
3595    level
3596}
3597
3598/// v7.38.1 (L12) — the composite key `values` takes in a multi-column
3599/// B-tree over `[lead, extras…]`. A NULL component keys as
3600/// [`IndexKey::Null`] (declared to sort last, PG's NULLS LAST) so the
3601/// row stays findable by prefix probes on the columns before it. `None`
3602/// = some non-null component has no key form; the row is then not
3603/// entered, which is why creation gates every component column's type
3604/// through [`multi_component_type_ok`].
3605pub(crate) fn compose_multi_key(
3606    values: &[Value<'_>],
3607    lead: usize,
3608    extras: &[usize],
3609) -> Option<alloc::boxed::Box<[IndexKey]>> {
3610    let mut comps: Vec<IndexKey> = Vec::with_capacity(1 + extras.len());
3611    for pos in core::iter::once(lead).chain(extras.iter().copied()) {
3612        let v = values.get(pos)?;
3613        if matches!(v, Value::Null) {
3614            comps.push(IndexKey::Null);
3615        } else {
3616            comps.push(IndexKey::from_value(v)?);
3617        }
3618    }
3619    Some(comps.into_boxed_slice())
3620}
3621
3622/// v7.38.1 (L12) — component-type gate for multi-column B-trees: every
3623/// NON-NULL value of these types keys through `IndexKey::from_value`,
3624/// so a row can only be absent from the index when creation raced a
3625/// type this list does not name. Deliberately conservative — a type
3626/// outside the list simply keeps its index on the leading-column path.
3627pub(crate) fn multi_component_type_ok(ty: DataType) -> bool {
3628    matches!(
3629        ty,
3630        DataType::SmallInt
3631            | DataType::Int
3632            | DataType::BigInt
3633            | DataType::Text
3634            | DataType::Varchar(_)
3635            | DataType::Char(_)
3636            | DataType::Bool
3637            | DataType::Uuid
3638            | DataType::Date
3639            | DataType::Timestamp
3640    )
3641}
3642
3643impl Index {
3644    /// Any key this B-tree currently holds, or `None` if it holds none.
3645    ///
3646    /// A probe built from a query literal has to be the same SHAPE as the
3647    /// keys the maintenance side made, or `lookup_eq` misses every row and
3648    /// the caller reads the empty answer as "no rows match". One stored
3649    /// key settles it: an index keys one expression, whose values are one
3650    /// type.
3651    pub fn sample_key(&self) -> Option<&IndexKey> {
3652        match &self.kind {
3653            IndexKind::BTree(map) => map.iter().next().map(|(k, _)| k),
3654            _ => None,
3655        }
3656    }
3657
3658    /// v7.38.19 — the largest integer key this index holds.
3659    ///
3660    /// For the one question it answers — what number comes next for a
3661    /// `serial` column — a tree already knows, and knew all along.
3662    /// [`Table::next_auto_value`] read every row instead:
3663    ///
3664    /// ```text
3665    ///   rows in the table    one INSERT      PostgreSQL 18
3666    ///      1,000              1.831 ms          1.245
3667    ///     10,000              1.814             1.289
3668    ///     50,000              2.703             1.386
3669    ///    200,000              3.666             1.375
3670    /// ```
3671    ///
3672    /// Theirs is flat because a sequence is a counter. Ours grew with
3673    /// the table, so an ingest workload got slower the longer it ran.
3674    ///
3675    /// A dead row version's key is still in the tree, so this can be
3676    /// HIGHER than the maximum over live rows. That is the safe
3677    /// direction — it hands out a value no row has ever held — and it
3678    /// is the direction PostgreSQL goes too, which never reuses a
3679    /// number a deleted row was given.
3680    ///
3681    /// `None` = no B-tree, or its keys are not integers, and the caller
3682    /// falls back to the scan.
3683    pub fn max_int_key(&self) -> Option<i64> {
3684        let IndexKind::BTree(map) = &self.kind else {
3685            return None;
3686        };
3687        match map.iter_rev().next()? {
3688            (IndexKey::Int(n), _) => Some(*n),
3689            _ => None,
3690        }
3691    }
3692
3693    fn new_btree(name: String, column_position: usize) -> Self {
3694        Self {
3695            name,
3696            column_position,
3697            kind: IndexKind::BTree(PersistentBTreeMap::new()),
3698            included_columns: Vec::new(),
3699            partial_predicate: None,
3700            expression: None,
3701            is_unique: false,
3702            nulls_not_distinct: false,
3703            descending: false,
3704            nulls_first: None,
3705            collation: None,
3706            extra_column_positions: Vec::new(),
3707            extra_orders: Vec::new(),
3708        }
3709    }
3710
3711    /// v7.38.1 (L12) — a real multi-column B-tree shell. The caller
3712    /// sets `extra_column_positions` before the first row enters; the
3713    /// key arity is `1 + extras` from then on.
3714    fn new_btree_multi(name: String, column_position: usize) -> Self {
3715        Self {
3716            kind: IndexKind::BTreeMulti(PersistentBTreeMap::new()),
3717            ..Self::new_btree(name, column_position)
3718        }
3719    }
3720
3721    /// v7.38.1 (L12) — the composite key this row takes in a
3722    /// [`IndexKind::BTreeMulti`] index. NULL components key as
3723    /// [`IndexKey::Null`] so prefix probes still find the row; `None`
3724    /// only when a non-null component produces no key, which creation's
3725    /// component-type gate makes unreachable for well-formed indexes.
3726    pub fn multi_key_for_row(&self, values: &[Value<'_>]) -> Option<alloc::boxed::Box<[IndexKey]>> {
3727        compose_multi_key(values, self.column_position, &self.extra_column_positions)
3728    }
3729
3730    fn new_nsw(name: String, column_position: usize, m: usize) -> Self {
3731        Self {
3732            name,
3733            column_position,
3734            kind: IndexKind::Nsw(NswGraph::new(m)),
3735            included_columns: Vec::new(),
3736            partial_predicate: None,
3737            expression: None,
3738            is_unique: false,
3739            nulls_not_distinct: false,
3740            descending: false,
3741            nulls_first: None,
3742            collation: None,
3743            extra_column_positions: Vec::new(),
3744            extra_orders: Vec::new(),
3745        }
3746    }
3747
3748    /// v6.7.1 — BRIN index constructor. BRIN carries no in-memory
3749    /// data; the `column_type` snapshot is used by the segment
3750    /// encoder + planner for type-checking range predicates.
3751    fn new_brin(name: String, column_position: usize, column_type: DataType) -> Self {
3752        Self {
3753            name,
3754            column_position,
3755            kind: IndexKind::Brin {
3756                column_type,
3757                summaries: alloc::vec::Vec::new(),
3758            },
3759            included_columns: Vec::new(),
3760            partial_predicate: None,
3761            expression: None,
3762            is_unique: false,
3763            nulls_not_distinct: false,
3764            descending: false,
3765            nulls_first: None,
3766            collation: None,
3767            extra_column_positions: Vec::new(),
3768            extra_orders: Vec::new(),
3769        }
3770    }
3771
3772    /// v7.12.3 — GIN inverted-index constructor. Empty posting-list
3773    /// map; caller (typically [`Table::add_gin_index`] or
3774    /// [`Table::restore_gin_index`]) populates it from existing rows
3775    /// or from a deserialised snapshot.
3776    fn new_gin(name: String, column_position: usize) -> Self {
3777        Self {
3778            name,
3779            column_position,
3780            kind: IndexKind::Gin(PersistentBTreeMap::new()),
3781            included_columns: Vec::new(),
3782            partial_predicate: None,
3783            expression: None,
3784            is_unique: false,
3785            nulls_not_distinct: false,
3786            descending: false,
3787            nulls_first: None,
3788            collation: None,
3789            extra_column_positions: Vec::new(),
3790            extra_orders: Vec::new(),
3791        }
3792    }
3793
3794    /// v7.15.0 — `gin_trgm_ops`-flavoured GIN constructor. Same
3795    /// shape as `new_gin` but the posting-list keys are 3-byte
3796    /// trigram shingles (`pg_trgm`-compatible) and the column
3797    /// type is `TEXT` / `VARCHAR` (not `TSVECTOR`).
3798    fn new_gin_trgm(name: String, column_position: usize) -> Self {
3799        Self {
3800            name,
3801            column_position,
3802            kind: IndexKind::GinTrgm(PersistentBTreeMap::new()),
3803            included_columns: Vec::new(),
3804            partial_predicate: None,
3805            expression: None,
3806            is_unique: false,
3807            nulls_not_distinct: false,
3808            descending: false,
3809            nulls_first: None,
3810            collation: None,
3811            extra_column_positions: Vec::new(),
3812            extra_orders: Vec::new(),
3813        }
3814    }
3815
3816    /// v7.17.0 Phase 2.2 — MySQL `FULLTEXT KEY` GIN constructor.
3817    /// Same shape as `new_gin_trgm` but the posting-list keys
3818    /// are lower-cased word lexemes (`to_tsvector('simple', col)`
3819    /// equivalent) instead of trigrams, and the column type is
3820    /// `TEXT` / `VARCHAR` (not `TSVECTOR`).
3821    fn new_gin_fulltext(name: String, column_position: usize) -> Self {
3822        Self {
3823            name,
3824            column_position,
3825            kind: IndexKind::GinFulltext(PersistentBTreeMap::new()),
3826            included_columns: Vec::new(),
3827            partial_predicate: None,
3828            expression: None,
3829            is_unique: false,
3830            nulls_not_distinct: false,
3831            descending: false,
3832            nulls_first: None,
3833            collation: None,
3834            extra_column_positions: Vec::new(),
3835            extra_orders: Vec::new(),
3836        }
3837    }
3838
3839    /// v7.37.8(sentori Epic 5 P2)— JSONB-GIN constructor. Same
3840    /// shape as the other GIN-family indexes; posting-list keys
3841    /// are the canonical `(path, leaf)` tokens emitted by
3842    /// `crate::jsonb_gin::extract_tokens`. Maintains posting
3843    /// lists from `Value::Json` cells(JSONB is a synonym for the
3844    /// same in-memory string-backed Value).
3845    fn new_gin_jsonb(name: String, column_position: usize) -> Self {
3846        Self {
3847            name,
3848            column_position,
3849            kind: IndexKind::GinJsonb(PersistentBTreeMap::new()),
3850            included_columns: Vec::new(),
3851            partial_predicate: None,
3852            expression: None,
3853            is_unique: false,
3854            nulls_not_distinct: false,
3855            descending: false,
3856            nulls_first: None,
3857            collation: None,
3858            extra_column_positions: Vec::new(),
3859            extra_orders: Vec::new(),
3860        }
3861    }
3862
3863    /// v7.34.4 — descending-order iterator over `(IndexKey, locators)`
3864    /// pairs for a BTree index, with O(log N) descent to the rightmost
3865    /// leaf and lazy emission thereafter. Returns an empty iterator
3866    /// for non-BTree index kinds — callers handle both uniformly.
3867    /// Used by the ORDER BY `<indexed col>` DESC + LIMIT N executor
3868    /// path: walking only the first N matches off the rightmost leaf
3869    /// avoids the per-row materialisation + partial-sort cost on
3870    /// large tables (mailrs `content_worker` at 250 k rows).
3871    pub fn iter_desc(
3872        &self,
3873    ) -> alloc::boxed::Box<dyn Iterator<Item = (&IndexKey, &crate::posting::PostingList)> + '_>
3874    {
3875        match &self.kind {
3876            IndexKind::BTree(m) => alloc::boxed::Box::new(m.iter_rev()),
3877            // v7.38.1 (L12) — projecting the leading component of a
3878            // composite key preserves order: keys sort by the whole
3879            // tuple, so the leading component is non-increasing here
3880            // (non-decreasing in iter_asc), exactly what an ORDER BY
3881            // on the leading column needs.
3882            IndexKind::BTreeMulti(m) => {
3883                alloc::boxed::Box::new(m.iter_rev().map(|(k, l)| (&k[0], l)))
3884            }
3885            IndexKind::Nsw(_)
3886            | IndexKind::Brin { .. }
3887            | IndexKind::Gin(_)
3888            | IndexKind::GinTrgm(_)
3889            | IndexKind::GinFulltext(_)
3890            | IndexKind::GinJsonb(_) => alloc::boxed::Box::new(core::iter::empty()),
3891        }
3892    }
3893
3894    /// v7.34.4 — ascending-order iterator over `(IndexKey, locators)`
3895    /// pairs. Mirror of `iter_desc` for ORDER BY ... ASC + LIMIT N.
3896    pub fn iter_asc(
3897        &self,
3898    ) -> alloc::boxed::Box<dyn Iterator<Item = (&IndexKey, &crate::posting::PostingList)> + '_>
3899    {
3900        match &self.kind {
3901            IndexKind::BTree(m) => alloc::boxed::Box::new(m.iter()),
3902            // v7.38.1 (L12) — see iter_desc: the leading component of
3903            // a tuple-sorted walk is itself in order.
3904            IndexKind::BTreeMulti(m) => alloc::boxed::Box::new(m.iter().map(|(k, l)| (&k[0], l))),
3905            IndexKind::Nsw(_)
3906            | IndexKind::Brin { .. }
3907            | IndexKind::Gin(_)
3908            | IndexKind::GinTrgm(_)
3909            | IndexKind::GinFulltext(_)
3910            | IndexKind::GinJsonb(_) => alloc::boxed::Box::new(core::iter::empty()),
3911        }
3912    }
3913
3914    /// Look up the locators stored under `key` (B-tree only). Returns
3915    /// an empty slice when the key is absent or the index isn't a
3916    /// BTree — callers can treat both cases uniformly.
3917    ///
3918    /// v5.1: return type widened from `&[usize]` to `&[RowLocator]`.
3919    /// Pre-v5.2 callers can read the slice and `.as_hot().unwrap()`
3920    /// each entry (no `Cold` variants exist until the freezer lands);
3921    /// post-v5.2 callers dispatch hot vs. cold per locator.
3922    pub fn lookup_eq(&self, key: &IndexKey) -> &crate::posting::PostingList {
3923        match &self.kind {
3924            IndexKind::BTree(m) => m.get(key).map_or(&EMPTY_POSTINGS, |l| l),
3925            // BRIN / NSW / GIN / trigram-GIN / fulltext-GIN have
3926            // no IndexKey-keyed map; lookup is a no-op. GIN uses
3927            // [`Index::gin_lookup_word`] instead.
3928            IndexKind::Nsw(_)
3929            | IndexKind::Brin { .. }
3930            | IndexKind::Gin(_)
3931            | IndexKind::GinTrgm(_)
3932            | IndexKind::GinFulltext(_)
3933            | IndexKind::GinJsonb(_)
3934            | IndexKind::BTreeMulti(_) => &EMPTY_POSTINGS,
3935        }
3936    }
3937
3938    /// v7.37.43 (INSUBQ B-2) — specialised lookup for integer-PK probes.
3939    /// `try_count_star_pk_in_subquery_fast` already holds an `i64` (the
3940    /// inner survivor key); skip the `IndexKey::from_value` enum-dispatch
3941    /// trip and build the key inline. ~20 ns × N_survivors saved on
3942    /// the INSUBQ hot loop.
3943    #[inline]
3944    pub fn lookup_eq_i64(&self, n: i64) -> &crate::posting::PostingList {
3945        match &self.kind {
3946            IndexKind::BTree(m) => m.get(&IndexKey::Int(n)).map_or(&EMPTY_POSTINGS, |l| l),
3947            IndexKind::Nsw(_)
3948            | IndexKind::Brin { .. }
3949            | IndexKind::Gin(_)
3950            | IndexKind::GinTrgm(_)
3951            | IndexKind::GinFulltext(_)
3952            | IndexKind::GinJsonb(_)
3953            | IndexKind::BTreeMulti(_) => &EMPTY_POSTINGS,
3954        }
3955    }
3956
3957    /// v7.38 (perf, index range scan) — flatten the row locators for every key
3958    /// in `[lo, hi]` (bounds per `core::ops::Bound`) via the BTree's `O(log N +
3959    /// k)` range walk. Returns `None` once more than `cap` locators accumulate
3960    /// — a "this range isn't selective enough, seq-scan instead" signal that
3961    /// stops a wide range from materialising a near-full table's worth of rows
3962    /// through the index. BTree only (other kinds → None).
3963    pub fn lookup_range_capped(
3964        &self,
3965        lo: core::ops::Bound<&IndexKey>,
3966        hi: core::ops::Bound<&IndexKey>,
3967        cap: usize,
3968    ) -> Option<Vec<RowLocator>> {
3969        self.lookup_range_capped_by(lo, hi, cap, |_| true)
3970    }
3971
3972    /// v7.39 (round 490) — the same range walk, but the caller decides
3973    /// which locators are worth carrying, and the cap counts only those.
3974    ///
3975    /// A BTree index holds one locator per row VERSION. On a churned table
3976    /// the dead versions are still in there: round 490 measured a
3977    /// 1000-row range handing back 61 000 locators after 60
3978    /// delete-and-reinsert cycles with the background vacuum switched off.
3979    /// Every caller then dropped the dead ones — the mutation paths and the
3980    /// SELECT range path all test `is_row_visible` and `continue` — but only
3981    /// after they had been collected into a `Vec`, sorted, and walked.
3982    ///
3983    /// Handing the predicate down means the walk keeps ~1000, and the cap
3984    /// (which exists so an index walk never costs more than the scan it
3985    /// replaces) is once again measured in rows a caller will actually look
3986    /// at. Round 461 had to add the dead count to the budget to stop the
3987    /// seek being refused outright; with the filter here that compensation
3988    /// is no longer needed.
3989    pub fn lookup_range_capped_by(
3990        &self,
3991        lo: core::ops::Bound<&IndexKey>,
3992        hi: core::ops::Bound<&IndexKey>,
3993        cap: usize,
3994        keep: impl Fn(RowLocator) -> bool,
3995    ) -> Option<Vec<RowLocator>> {
3996        match &self.kind {
3997            IndexKind::BTree(m) => {
3998                let mut out: Vec<RowLocator> = Vec::new();
3999                for (_, locs) in m.range(lo, hi) {
4000                    out.extend(locs.iter().copied().filter(|l| keep(*l)));
4001                    if out.len() > cap {
4002                        return None;
4003                    }
4004                }
4005                Some(out)
4006            }
4007            IndexKind::Nsw(_)
4008            | IndexKind::Brin { .. }
4009            | IndexKind::Gin(_)
4010            | IndexKind::GinTrgm(_)
4011            | IndexKind::GinFulltext(_)
4012            | IndexKind::GinJsonb(_)
4013            | IndexKind::BTreeMulti(_) => None,
4014        }
4015    }
4016
4017    /// v7.38.1 (L12) — full-tuple point lookup on a [`IndexKind::BTreeMulti`]
4018    /// index. `key` must carry exactly as many components as the index
4019    /// has columns; anything else (including a probe against a
4020    /// non-multi index) finds nothing, and "nothing" here is safe
4021    /// because the caller falls back to a scan, never to an answer.
4022    pub fn lookup_eq_multi(&self, key: &[IndexKey]) -> &crate::posting::PostingList {
4023        match &self.kind {
4024            IndexKind::BTreeMulti(m) if key.len() == 1 + self.extra_column_positions.len() => {
4025                m.get_by(key).map_or(&EMPTY_POSTINGS, |l| l)
4026            }
4027            _ => &EMPTY_POSTINGS,
4028        }
4029    }
4030
4031    /// v7.38.1 (L12) — locators for every key whose leading components
4032    /// equal `prefix`, on a [`IndexKind::BTreeMulti`] index. Slice
4033    /// ordering keeps a prefix's keys contiguous, so this is one
4034    /// descent to `[prefix]` and a walk that stops at the first key
4035    /// leaving the prefix. Same cap/keep contract as
4036    /// [`Index::lookup_range_capped_by`]: `None` = not selective
4037    /// enough (or not a multi index), fall back.
4038    pub fn lookup_prefix_capped_by(
4039        &self,
4040        prefix: &[IndexKey],
4041        cap: usize,
4042        keep: impl Fn(RowLocator) -> bool,
4043    ) -> Option<Vec<RowLocator>> {
4044        let IndexKind::BTreeMulti(m) = &self.kind else {
4045            return None;
4046        };
4047        if prefix.is_empty() || prefix.len() > 1 + self.extra_column_positions.len() {
4048            return None;
4049        }
4050        let lo: alloc::boxed::Box<[IndexKey]> = prefix.to_vec().into_boxed_slice();
4051        let mut out: Vec<RowLocator> = Vec::new();
4052        for (k, locs) in m.range(core::ops::Bound::Included(&lo), core::ops::Bound::Unbounded) {
4053            if k.len() < prefix.len() || k[..prefix.len()] != *prefix {
4054                break;
4055            }
4056            out.extend(locs.iter().copied().filter(|l| keep(*l)));
4057            if out.len() > cap {
4058                return None;
4059            }
4060        }
4061        Some(out)
4062    }
4063
4064    /// v7.38.19 — a RANGE on the composite tree's leading column.
4065    ///
4066    /// Tuples order lexicographically, so every key whose first
4067    /// component is `x` sorts at or after the one-element tuple `[x]`
4068    /// and before `[x']` for any larger `x'`. That makes a leading-
4069    /// column range one contiguous run, walked exactly like the
4070    /// single-column range walk — the only difference is that the
4071    /// comparison is against `k[0]` rather than the whole key.
4072    ///
4073    /// Without this, `WHERE project_id > 90` on a table whose only
4074    /// index was `(project_id, kind)` read every row: 4.067 ms against
4075    /// PostgreSQL 18's 0.220, on a predicate matching nothing. The same
4076    /// query with a single-column index took 0.165, which is what says
4077    /// the range was never the problem.
4078    pub fn lookup_leading_range_capped_by(
4079        &self,
4080        lo: core::ops::Bound<&IndexKey>,
4081        hi: core::ops::Bound<&IndexKey>,
4082        cap: usize,
4083        keep: impl Fn(RowLocator) -> bool,
4084    ) -> Option<Vec<RowLocator>> {
4085        let IndexKind::BTreeMulti(m) = &self.kind else {
4086            return None;
4087        };
4088        // The start of the run. An EXCLUDED lower bound cannot be
4089        // handed to the map as-is: `[x]` sorts BEFORE `[x, y]`, so
4090        // excluding `[x]` would still admit every tuple that begins
4091        // with `x`. Start at `[x]` included and drop those tuples by
4092        // the per-key test below, which compares the component.
4093        let lo_key: Option<alloc::boxed::Box<[IndexKey]>> = match lo {
4094            core::ops::Bound::Included(k) | core::ops::Bound::Excluded(k) => {
4095                Some(alloc::vec![k.clone()].into_boxed_slice())
4096            }
4097            core::ops::Bound::Unbounded => None,
4098        };
4099        let start = match &lo_key {
4100            Some(k) => core::ops::Bound::Included(k),
4101            None => core::ops::Bound::Unbounded,
4102        };
4103        let mut out: Vec<RowLocator> = Vec::new();
4104        for (k, locs) in m.range(start, core::ops::Bound::Unbounded) {
4105            let Some(first) = k.first() else { continue };
4106            match lo {
4107                core::ops::Bound::Excluded(b) if first == b => continue,
4108                _ => {}
4109            }
4110            match hi {
4111                core::ops::Bound::Included(b) if first > b => break,
4112                core::ops::Bound::Excluded(b) if first >= b => break,
4113                _ => {}
4114            }
4115            out.extend(locs.iter().copied().filter(|l| keep(*l)));
4116            if out.len() > cap {
4117                return None;
4118            }
4119        }
4120        Some(out)
4121    }
4122
4123    /// v7.39 (round 560) — the index range as (key, locator) pairs.
4124    ///
4125    /// `lookup_range_capped_by` throws the KEY away and returns only
4126    /// locators, so a query whose projection is exactly the indexed
4127    /// column still goes to the row store for a value the walk already
4128    /// had in hand — paying per row for something the index knows.
4129    ///
4130    /// Uncapped on purpose: an index-only walk touches no row, so the
4131    /// selectivity ceiling that keeps a seek from being worse than the
4132    /// scan it replaces does not apply to it.
4133    ///
4134    /// v7.39 (round 562) — and it does not collect, either. This
4135    /// returned a `Vec<(IndexKey, RowLocator)>`: for a 100k-row range,
4136    /// 100k key clones into a `Vec::new()` that doubles its way up to
4137    /// several MB, all to be walked once and dropped. A profile of the
4138    /// server serving that query put 20% of the connection thread's CPU
4139    /// on the collect alone, with another 18% in the allocator beside
4140    /// it. The caller consumes the pairs in order and needs the key
4141    /// only by reference, so it can have the walk itself.
4142    pub fn range_keyed(
4143        &self,
4144        lo: core::ops::Bound<&IndexKey>,
4145        hi: core::ops::Bound<&IndexKey>,
4146    ) -> Option<impl Iterator<Item = (&IndexKey, RowLocator)> + '_> {
4147        match &self.kind {
4148            IndexKind::BTree(m) => Some(
4149                m.range(lo, hi)
4150                    .flat_map(|(k, locs)| locs.iter().map(move |l| (k, *l))),
4151            ),
4152            IndexKind::Nsw(_)
4153            | IndexKind::Brin { .. }
4154            | IndexKind::Gin(_)
4155            | IndexKind::GinTrgm(_)
4156            | IndexKind::GinFulltext(_)
4157            | IndexKind::GinJsonb(_)
4158            | IndexKind::BTreeMulti(_) => None,
4159        }
4160    }
4161
4162    /// v7.12.3 — GIN posting-list lookup. Returns the row locators
4163    /// whose `tsvector` cell contains `word`. Empty when the word is
4164    /// absent from the index or this isn't a GIN index.
4165    pub fn gin_lookup_word(&self, word: &str) -> &crate::posting::PostingList {
4166        match &self.kind {
4167            // v7.17.0 Phase 2.2 — fulltext-GIN shares the same
4168            // lexeme-keyed posting list shape as the
4169            // tsvector-typed GIN, so the same lookup applies.
4170            IndexKind::Gin(m) | IndexKind::GinFulltext(m) => {
4171                m.get(&String::from(word)).map_or(&EMPTY_POSTINGS, |l| l)
4172            }
4173            IndexKind::BTree(_)
4174            | IndexKind::Nsw(_)
4175            | IndexKind::Brin { .. }
4176            | IndexKind::GinTrgm(_)
4177            | IndexKind::GinJsonb(_)
4178            | IndexKind::BTreeMulti(_) => &EMPTY_POSTINGS,
4179        }
4180    }
4181
4182    /// v7.15.0 — trigram-GIN posting-list lookup. Returns the row
4183    /// locators whose indexed `TEXT` cell contains the trigram
4184    /// `tri`. Empty when the trigram is absent or this isn't a
4185    /// trigram-GIN index.
4186    pub fn gin_trgm_lookup(&self, tri: &str) -> &crate::posting::PostingList {
4187        match &self.kind {
4188            IndexKind::GinTrgm(m) => m.get(&String::from(tri)).map_or(&EMPTY_POSTINGS, |l| l),
4189            IndexKind::BTree(_)
4190            | IndexKind::Nsw(_)
4191            | IndexKind::Brin { .. }
4192            | IndexKind::Gin(_)
4193            | IndexKind::GinFulltext(_)
4194            | IndexKind::GinJsonb(_)
4195            | IndexKind::BTreeMulti(_) => &EMPTY_POSTINGS,
4196        }
4197    }
4198
4199    /// v7.37.8(sentori Epic 5 P2)— JSONB-GIN posting-list lookup.
4200    /// Returns the row locators whose indexed JSONB cell carries
4201    /// the canonical `token`(see [`crate::jsonb_gin::extract_tokens`]).
4202    /// Empty when the token is absent or this isn't a JSONB-GIN
4203    /// index. Planners drive `<col> @> <jsonb_literal>` through here.
4204    pub fn gin_jsonb_lookup(&self, token: &str) -> &crate::posting::PostingList {
4205        match &self.kind {
4206            IndexKind::GinJsonb(m) => m.get(&String::from(token)).map_or(&EMPTY_POSTINGS, |l| l),
4207            IndexKind::BTree(_)
4208            | IndexKind::Nsw(_)
4209            | IndexKind::Brin { .. }
4210            | IndexKind::Gin(_)
4211            | IndexKind::GinTrgm(_)
4212            | IndexKind::GinFulltext(_)
4213            | IndexKind::BTreeMulti(_) => &EMPTY_POSTINGS,
4214        }
4215    }
4216
4217    /// Borrow the NSW graph (if this is an NSW index). Callers that need
4218    /// the graph for a kNN search go through here.
4219    pub const fn nsw(&self) -> Option<&NswGraph> {
4220        match &self.kind {
4221            IndexKind::Nsw(g) => Some(g),
4222            IndexKind::BTree(_)
4223            | IndexKind::Brin { .. }
4224            | IndexKind::Gin(_)
4225            | IndexKind::GinTrgm(_)
4226            | IndexKind::GinFulltext(_)
4227            | IndexKind::GinJsonb(_)
4228            | IndexKind::BTreeMulti(_) => None,
4229        }
4230    }
4231
4232    /// v6.7.1 — true when this index is a BRIN (block range) index.
4233    /// Used by the segment encoder to opt into BRIN sidecar emission
4234    /// at freeze time, and by the planner to opt into page-skipping
4235    /// on range predicates.
4236    pub const fn is_brin(&self) -> bool {
4237        matches!(self.kind, IndexKind::Brin { .. })
4238    }
4239
4240    /// v7.15.0 — true when this index is a trigram GIN
4241    /// (`gin_trgm_ops`-flavoured). Used by the LIKE planner to
4242    /// opt into trigram acceleration.
4243    pub const fn is_gin_trgm(&self) -> bool {
4244        matches!(self.kind, IndexKind::GinTrgm(_))
4245    }
4246
4247    /// v7.12.3 — true when this index is a GIN inverted index.
4248    /// Used by the planner to opt into posting-list acceleration on
4249    /// `WHERE col @@ tsquery` predicates.
4250    pub const fn is_gin(&self) -> bool {
4251        matches!(self.kind, IndexKind::Gin(_))
4252    }
4253
4254    /// v7.17.0 Phase 2.2 — true when this index is a fulltext
4255    /// GIN over a TEXT / VARCHAR column (MySQL `FULLTEXT KEY`
4256    /// surface). Used by the planner to opt the FULLTEXT-indexed
4257    /// column into MATCH AGAINST acceleration.
4258    pub const fn is_gin_fulltext(&self) -> bool {
4259        matches!(self.kind, IndexKind::GinFulltext(_))
4260    }
4261
4262    /// v7.37.8(sentori Epic 5 P2)— true when this index is a
4263    /// real JSONB-GIN(posting-list backed). Used by the planner
4264    /// to opt `<col> @> <jsonb_literal>` into posting-list seek.
4265    pub const fn is_gin_jsonb(&self) -> bool {
4266        matches!(self.kind, IndexKind::GinJsonb(_))
4267    }
4268}
4269
4270/// In-memory table: schema + a persistent row vector + secondary indices.
4271///
4272/// v4.39: `rows` is a [`PersistentVec`] (Bitmapped Vector Trie, 32-way) so
4273/// `Table::clone()` is `O(1)` — the whole reason for v4.39's existence is
4274/// to make `Catalog::clone()` cheap inside the v4.34 auto-commit wrap.
4275///
4276/// v5.2.1: `hot_bytes` tracks the encoded byte size of every row currently
4277/// in [`Self::rows`], summed over rows. Updated incrementally by `insert`
4278/// (+= encoded row size), `delete_rows` (-= removed rows' encoded sizes),
4279/// and `update_row` (-= old size, += new size). The value is what the
4280/// v5.2 freezer reads to decide when to demote cold rows — when the
4281/// catalog-wide sum crosses `SPG_HOT_TIER_BYTES` (default 4 GiB) the
4282/// freezer thread wakes. v5.2.1 ships measurement only; the freezer
4283/// itself lands in v5.2.2. Stored as `u64` so a single field clone in
4284/// `Catalog::clone` stays at the O(1) invariant v4.39 built.
4285/// v7.34 (crash-recovery P0 #2) — one row-level physical redo record.
4286/// Row-level redo replaces statement-based WAL replay (which re-executes
4287/// each SQL through the full engine — O(records × catalog_rows), the
4288/// superlinear recovery hang root-caused on the mailrs crash-recovery
4289/// P0). A `RowChange` is the exact storage mutation the engine applied
4290/// (`Table::insert` / `update_row` / `delete_rows`); replaying it on a
4291/// catalog restored from the matching checkpoint reproduces the state
4292/// WITHOUT re-validating uniqueness/FK/parse/plan — O(changed rows).
4293///
4294/// Positions are physical, not key-based: `serialize`/`deserialize`
4295/// preserve row order exactly (rows written + read back in `self.rows`
4296/// order) and the mutation ops are deterministic, so the same op sequence
4297/// replayed from the same checkpoint reproduces the same positions. This
4298/// matches PostgreSQL's physical redo and supports tables with no primary
4299/// key. (Caveat handled at replay integration: a post-checkpoint cold-tier
4300/// freeze shifts hot positions and must itself be logged or fenced by a
4301/// checkpoint — see `row-level-redo-design`.)
4302/// ## v7.37.15 (Epic W slice 1) — additive MVCC identity metadata
4303///
4304/// Each variant now also carries, additively, the stable
4305/// [`RowId`](row_header::RowId) of the affected row(s) and the
4306/// **writer version** (`xmin` for an insert, `xmax` for a
4307/// delete/update). This is the codec foundation for making
4308/// in-place MVCC tombstones durable across crash/upgrade recovery.
4309///
4310/// Two important properties for the durability path:
4311///
4312/// 1. **Replay resolution is UNCHANGED.** `apply_redo_run_on_table`
4313///    still resolves every change by physical `pos`/`positions`
4314///    exactly as before. The new metadata is *carried but unused*
4315///    by replay in this slice; resolving-by-`RowId` and
4316///    header-preserving replay are later slices.
4317/// 2. **Backward compatibility.** A redo payload written by
4318///    pre-Epic-W code carries no metadata; [`decode_redo_log`]
4319///    fills `rowid`/`rowids` with [`RowId::UNASSIGNED`](row_header::RowId::UNASSIGNED)
4320///    (empty for `Delete`) and `writer_version` with `0`. See the
4321///    codec version gate in [`encode_redo_log`]/[`decode_redo_log`].
4322///
4323/// The `writer_version` is captured as `0` at the storage layer
4324/// (`Table::insert`/`delete_rows`/`update_row` don't have the
4325/// committing `TxId`), then **stamped with the real committing
4326/// version by the engine** after it drains the statement's changes
4327/// (Epic W slice 2 — [`RowChange::set_writer_version`], driven from
4328/// `Engine::writer_version_for_current_stmt`). All changes from one
4329/// statement share the one version. Replay still resolves by
4330/// physical position and does not read `writer_version` — that is a
4331/// later slice (header-preserving replay).
4332#[derive(Debug, Clone, PartialEq)]
4333pub enum RowChange {
4334    /// Append `row` to `table`.
4335    Insert {
4336        table: String,
4337        row: Row<'static>,
4338        /// Epic W: stable id the appended row will receive.
4339        /// [`RowId::UNASSIGNED`](row_header::RowId::UNASSIGNED) when
4340        /// decoded from a pre-Epic-W redo payload.
4341        rowid: row_header::RowId,
4342        /// Epic W: writer version (`xmin`). `0` until the writing
4343        /// `TxId` is threaded to the storage layer (later slice).
4344        writer_version: u64,
4345    },
4346    /// Replace the row at physical `pos` in `table` with `new_row`.
4347    Update {
4348        table: String,
4349        pos: usize,
4350        new_row: Vec<Value<'static>>,
4351        /// Epic W: stable id of the row at `pos`.
4352        /// [`RowId::UNASSIGNED`](row_header::RowId::UNASSIGNED) when
4353        /// decoded from a pre-Epic-W redo payload.
4354        rowid: row_header::RowId,
4355        /// Epic W: writer version (`xmax` of the superseded tuple).
4356        /// `0` until the writing `TxId` is threaded (later slice).
4357        writer_version: u64,
4358    },
4359    /// Remove the rows at the given physical `positions` from `table`.
4360    Delete {
4361        table: String,
4362        positions: Vec<usize>,
4363        /// Epic W: stable ids parallel to `positions` (same length,
4364        /// [`RowId::UNASSIGNED`](row_header::RowId::UNASSIGNED) for an
4365        /// out-of-bounds input position). **Empty** when decoded from
4366        /// a pre-Epic-W redo payload (no metadata was recorded).
4367        rowids: Vec<row_header::RowId>,
4368        /// Epic W: writer version (`xmax`). `0` until the writing
4369        /// `TxId` is threaded to the storage layer (later slice).
4370        writer_version: u64,
4371    },
4372    /// v7.37.15 (Epic W durable-tombstone slice) — an **in-place MVCC
4373    /// delete**: the row(s) named by `rowids` are NOT physically
4374    /// removed; their header `xmax` is stamped so newer snapshots stop
4375    /// seeing them (vacuum reclaims later). This is the redo shape of
4376    /// the gate-on (`SPG_MVCC_INPLACE`) DELETE / UPDATE-old-version /
4377    /// ON-CONFLICT paths, which call [`Table::mark_row_deleted`]
4378    /// instead of `delete_rows`.
4379    ///
4380    /// Unlike `Delete`, the target is named by **stable `RowId`**, not
4381    /// physical position: a tombstone keeps the slot, so position would
4382    /// be ambiguous after later compaction, and the header-preserving
4383    /// replay must re-find the exact row the writer tombstoned. On
4384    /// replay the id is matched against the ids the same redo run
4385    /// produced (an `Insert`'s `rowid`, or the table's ids snapshotted
4386    /// at run start); an id that cannot be resolved is skipped and
4387    /// counted (see `apply_redo_run_on_table`) — this is the documented
4388    /// cross-checkpoint limitation until the V6 envelope persists ids.
4389    Tombstone {
4390        table: String,
4391        /// Stable ids of the tombstoned rows (from `self.rowids()[pos]`
4392        /// at capture). Never empty for a recorded tombstone.
4393        rowids: Vec<row_header::RowId>,
4394        /// The version stamped into each target row's header `xmax`
4395        /// (the deleting statement's writer version).
4396        xmax: u64,
4397    },
4398}
4399
4400impl RowChange {
4401    /// v7.39 (round 736) — which table this change applies to.
4402    #[must_use]
4403    pub fn table_name(&self) -> &str {
4404        match self {
4405            Self::Insert { table, .. }
4406            | Self::Update { table, .. }
4407            | Self::Delete { table, .. }
4408            | Self::Tombstone { table, .. } => table,
4409        }
4410    }
4411
4412    /// v7.37.15 (Epic W slice 2) — stamp the committing writer
4413    /// version onto this change. Every change drained from a single
4414    /// statement shares one version (the statement's `xmin`/`xmax`),
4415    /// so the engine calls this on each drained change with the value
4416    /// from [`Engine::writer_version_for_current_stmt`]. Additive
4417    /// metadata only: replay still resolves by physical position and
4418    /// does not read `writer_version` (that is a later slice).
4419    pub fn set_writer_version(&mut self, v: u64) {
4420        match self {
4421            RowChange::Insert { writer_version, .. }
4422            | RowChange::Update { writer_version, .. }
4423            | RowChange::Delete { writer_version, .. } => *writer_version = v,
4424            // A tombstone captures `xmax` directly from the deleting
4425            // statement's version at record time (via
4426            // `mark_row_deleted`), so it already equals `v`. Keep the
4427            // "one statement, one version" invariant mechanical by
4428            // asserting agreement in debug builds rather than silently
4429            // overwriting a possibly-different value.
4430            RowChange::Tombstone { xmax, .. } => {
4431                debug_assert_eq!(
4432                    *xmax, v,
4433                    "tombstone xmax must match the statement writer version"
4434                );
4435                *xmax = v;
4436            }
4437        }
4438    }
4439}
4440
4441/// v7.37.15 (Epic W slice 1) — leading marker byte of the
4442/// metadata-carrying redo layout. A **pre-Epic-W** redo payload leads
4443/// with `FILE_VERSION` (8..=52 today, rising ~1 per release); this
4444/// marker is `0xFF` and can therefore never collide with a real
4445/// `FILE_VERSION`, so [`decode_redo_log`] tells the two layouts apart
4446/// by inspecting the first byte alone. The compile-time assertion
4447/// below makes the "never collide" invariant a hard build gate: if
4448/// `FILE_VERSION` ever climbs toward `0xFF` the build breaks and forces
4449/// a redesign long before an ambiguity could ship.
4450const REDO_META_MARKER: u8 = 0xFF;
4451/// v7.37.15 (Epic W slice 1) — version of the metadata-carrying redo
4452/// layout that follows [`REDO_META_MARKER`]. Bumped when the per-change
4453/// metadata shape changes; an unknown value is a hard decode error.
4454const REDO_META_VERSION: u8 = 1;
4455
4456/// v7.37.15 (Epic W durable-tombstone slice) — process-wide count of
4457/// [`RowChange::Tombstone`] targets that `apply_redo` could NOT resolve
4458/// to a row by `RowId`. A non-zero value is expected only across a
4459/// checkpoint boundary (the table's ids are reassigned on deserialize
4460/// and the V6 envelope does not yet persist them), where a tombstone
4461/// naming a pre-checkpoint row is left visible rather than mis-applied.
4462/// Surfaced for observability; never affects correctness of the resolved
4463/// tombstones. Read via [`unresolved_tombstone_count`].
4464static UNRESOLVED_TOMBSTONES: core::sync::atomic::AtomicU64 = core::sync::atomic::AtomicU64::new(0);
4465
4466/// v7.39 (flip crash-replay P0) — observability read for the replay
4467/// tombstones that could not be resolved to a row (each one is a
4468/// resurrected delete).
4469#[must_use]
4470pub fn unresolved_tombstones() -> u64 {
4471    UNRESOLVED_TOMBSTONES.load(core::sync::atomic::Ordering::Relaxed)
4472}
4473
4474/// v7.37.15 (Epic W durable-tombstone slice) — read the process-wide
4475/// count of redo tombstones that could not be resolved to a row by
4476/// `RowId` during `apply_redo`. See [`UNRESOLVED_TOMBSTONES`].
4477#[must_use]
4478pub fn unresolved_tombstone_count() -> u64 {
4479    UNRESOLVED_TOMBSTONES.load(core::sync::atomic::Ordering::Relaxed)
4480}
4481// Provably-unambiguous old/new distinction: the pre-Epic-W layout's
4482// first byte is `FILE_VERSION`, which must stay strictly below the
4483// marker forever.
4484const _: () = assert!(FILE_VERSION < REDO_META_MARKER);
4485
4486/// v7.34 (crash-recovery P0 #2), extended v7.37.15 (Epic W slice 1) —
4487/// encode a row-level redo log to bytes for a WAL record.
4488///
4489/// ## Layout (Epic W metadata-carrying form, always emitted now)
4490///
4491/// `[u8 REDO_META_MARKER=0xFF][u8 REDO_META_VERSION][u8 FILE_VERSION]
4492/// [u32 count]` then per change `[u8 op][str table]` and, per op:
4493/// - `Insert [u32 n][value×n][u64 rowid][u64 writer_version]`
4494/// - `Update [u32 pos][u32 n][value×n][u64 rowid][u64 writer_version]`
4495/// - `Delete [u32 n][u32 pos×n][u64 rowid×n][u64 writer_version]`
4496/// - `Tombstone [u32 n][u64 rowid×n][u64 xmax]` (op byte 3; only ever
4497///   emitted under the metadata-carrying layout — the pre-Epic-W layout
4498///   had no in-place tombstone, so a legacy stream can never carry it)
4499///
4500/// Positions are physical (u32 ≤ 4 G rows). The `FILE_VERSION` byte
4501/// still rides along (now the 3rd byte) so the value codec decodes
4502/// string / BYTEA escapes exactly as before.
4503///
4504/// ## Backward compatibility
4505///
4506/// The **pre-Epic-W** layout was `[u8 FILE_VERSION][u32 count]…` with
4507/// no per-change metadata. [`decode_redo_log`] still decodes that form
4508/// (first byte < `0xFF`) byte-for-byte identically — every WAL file
4509/// written by released code replays unchanged.
4510#[must_use]
4511pub fn encode_redo_log(changes: &[RowChange]) -> Vec<u8> {
4512    let mut out = Vec::new();
4513    out.push(REDO_META_MARKER);
4514    out.push(REDO_META_VERSION);
4515    out.push(FILE_VERSION);
4516    codec::write_u32(&mut out, changes.len() as u32);
4517    let write_values = |out: &mut Vec<u8>, vals: &[Value<'static>]| {
4518        codec::write_u32(out, vals.len() as u32);
4519        for v in vals {
4520            codec::write_value(out, v);
4521        }
4522    };
4523    for change in changes {
4524        match change {
4525            RowChange::Insert {
4526                table,
4527                row,
4528                rowid,
4529                writer_version,
4530            } => {
4531                out.push(0);
4532                codec::write_str(&mut out, table);
4533                write_values(&mut out, &row.values);
4534                codec::write_u64(&mut out, rowid.0);
4535                codec::write_u64(&mut out, *writer_version);
4536            }
4537            RowChange::Update {
4538                table,
4539                pos,
4540                new_row,
4541                rowid,
4542                writer_version,
4543            } => {
4544                out.push(1);
4545                codec::write_str(&mut out, table);
4546                codec::write_u32(&mut out, *pos as u32);
4547                write_values(&mut out, new_row);
4548                codec::write_u64(&mut out, rowid.0);
4549                codec::write_u64(&mut out, *writer_version);
4550            }
4551            RowChange::Delete {
4552                table,
4553                positions,
4554                rowids,
4555                writer_version,
4556            } => {
4557                out.push(2);
4558                codec::write_str(&mut out, table);
4559                codec::write_u32(&mut out, positions.len() as u32);
4560                for p in positions {
4561                    codec::write_u32(&mut out, *p as u32);
4562                }
4563                // Epic W: one RowId per position (parallel). Capture
4564                // sites always produce `rowids.len() == positions.len()`;
4565                // this assertion pins that invariant at encode time so a
4566                // mismatch is a loud bug, not a silently short payload.
4567                debug_assert_eq!(
4568                    rowids.len(),
4569                    positions.len(),
4570                    "redo Delete: rowids must be parallel to positions"
4571                );
4572                for rid in rowids {
4573                    codec::write_u64(&mut out, rid.0);
4574                }
4575                codec::write_u64(&mut out, *writer_version);
4576            }
4577            RowChange::Tombstone {
4578                table,
4579                rowids,
4580                xmax,
4581            } => {
4582                out.push(3);
4583                codec::write_str(&mut out, table);
4584                codec::write_u32(&mut out, rowids.len() as u32);
4585                for rid in rowids {
4586                    codec::write_u64(&mut out, rid.0);
4587                }
4588                codec::write_u64(&mut out, *xmax);
4589            }
4590        }
4591    }
4592    out
4593}
4594
4595/// v7.34, extended v7.37.15 (Epic W slice 1) — decode a row-level redo
4596/// log written by [`encode_redo_log`].
4597///
4598/// Decodes **both** the Epic W metadata-carrying layout (first byte
4599/// `REDO_META_MARKER = 0xFF`) and the pre-Epic-W layout (first byte is
4600/// `FILE_VERSION`, always `< 0xFF`). For the old layout the per-change
4601/// metadata is absent, so `rowid`/`rowids` come back
4602/// [`RowId::UNASSIGNED`](row_header::RowId::UNASSIGNED) (empty for
4603/// `Delete`) and `writer_version` comes back `0`.
4604///
4605/// A truncated / corrupt buffer is a hard error — never a panic — the
4606/// embedding layer frames each record with its own length + CRC, so a
4607/// frame that decodes short is corruption, not a torn tail.
4608pub fn decode_redo_log(bytes: &[u8]) -> Result<Vec<RowChange>, StorageError> {
4609    let first = *bytes
4610        .first()
4611        .ok_or_else(|| StorageError::Corrupt("redo log: empty".into()))?;
4612    // Epic W: `0xFF` marker ⇒ metadata-carrying layout; anything else
4613    // is a pre-Epic-W `FILE_VERSION` byte (old layout, no metadata).
4614    let has_meta = first == REDO_META_MARKER;
4615    let (codec_version, header_len) = if has_meta {
4616        let meta_version = *bytes
4617            .get(1)
4618            .ok_or_else(|| StorageError::Corrupt("redo log: short header".into()))?;
4619        if meta_version != REDO_META_VERSION {
4620            return Err(StorageError::Corrupt(alloc::format!(
4621                "redo log: unknown metadata version {meta_version}"
4622            )));
4623        }
4624        let file_version = *bytes
4625            .get(2)
4626            .ok_or_else(|| StorageError::Corrupt("redo log: short header".into()))?;
4627        // header = [marker][meta_version][file_version]
4628        (file_version, 3usize)
4629    } else {
4630        // Old layout: the first byte IS the FILE_VERSION.
4631        (first, 1usize)
4632    };
4633    let mut cur = codec::Cursor::new(bytes).with_codec_version(codec_version);
4634    for _ in 0..header_len {
4635        cur.read_u8()?;
4636    }
4637    let count = cur.read_u32()? as usize;
4638    let mut read_values =
4639        |cur: &mut codec::Cursor<'_>| -> Result<Vec<Value<'static>>, StorageError> {
4640            let n = cur.read_u32()? as usize;
4641            let mut vals = Vec::with_capacity(n);
4642            for _ in 0..n {
4643                vals.push(cur.read_value()?);
4644            }
4645            Ok(vals)
4646        };
4647    let mut changes = Vec::with_capacity(count);
4648    for _ in 0..count {
4649        let op = cur.read_u8()?;
4650        let table = cur.read_str()?;
4651        let change = match op {
4652            0 => {
4653                let row = Row::new(read_values(&mut cur)?);
4654                let (rowid, writer_version) = if has_meta {
4655                    (row_header::RowId(cur.read_u64()?), cur.read_u64()?)
4656                } else {
4657                    (row_header::RowId::UNASSIGNED, 0)
4658                };
4659                RowChange::Insert {
4660                    table,
4661                    row,
4662                    rowid,
4663                    writer_version,
4664                }
4665            }
4666            1 => {
4667                let pos = cur.read_u32()? as usize;
4668                let new_row = read_values(&mut cur)?;
4669                let (rowid, writer_version) = if has_meta {
4670                    (row_header::RowId(cur.read_u64()?), cur.read_u64()?)
4671                } else {
4672                    (row_header::RowId::UNASSIGNED, 0)
4673                };
4674                RowChange::Update {
4675                    table,
4676                    pos,
4677                    new_row,
4678                    rowid,
4679                    writer_version,
4680                }
4681            }
4682            2 => {
4683                let n = cur.read_u32()? as usize;
4684                let mut positions = Vec::with_capacity(n);
4685                for _ in 0..n {
4686                    positions.push(cur.read_u32()? as usize);
4687                }
4688                let (rowids, writer_version) = if has_meta {
4689                    let mut rowids = Vec::with_capacity(n);
4690                    for _ in 0..n {
4691                        rowids.push(row_header::RowId(cur.read_u64()?));
4692                    }
4693                    (rowids, cur.read_u64()?)
4694                } else {
4695                    // Old layout carried no RowId metadata.
4696                    (Vec::new(), 0)
4697                };
4698                RowChange::Delete {
4699                    table,
4700                    positions,
4701                    rowids,
4702                    writer_version,
4703                }
4704            }
4705            // Op 3 is the Epic W in-place tombstone — it only exists in
4706            // the metadata-carrying layout. Guarding on `has_meta` means
4707            // a legacy stream that happens to contain a `3` byte here is
4708            // reported as an unknown op (corruption), never mis-decoded.
4709            3 if has_meta => {
4710                let n = cur.read_u32()? as usize;
4711                let mut rowids = Vec::with_capacity(n);
4712                for _ in 0..n {
4713                    rowids.push(row_header::RowId(cur.read_u64()?));
4714                }
4715                let xmax = cur.read_u64()?;
4716                RowChange::Tombstone {
4717                    table,
4718                    rowids,
4719                    xmax,
4720                }
4721            }
4722            other => {
4723                return Err(StorageError::Corrupt(alloc::format!(
4724                    "redo log: unknown op {other}"
4725                )));
4726            }
4727        };
4728        changes.push(change);
4729    }
4730    Ok(changes)
4731}
4732
4733/// v7.39 (pg_stat knife B) — per-table scan counters, bumped from
4734/// `&self` read paths. Clone (tx shadow catalogs clone tables) copies
4735/// the current values; the counters are volatile like PG's cumulative
4736/// stats.
4737#[derive(Debug, Default)]
4738pub struct ScanStats {
4739    pub seq_scan: core::sync::atomic::AtomicU64,
4740    pub seq_tup_read: core::sync::atomic::AtomicU64,
4741    pub idx_scan: core::sync::atomic::AtomicU64,
4742    pub idx_tup_fetch: core::sync::atomic::AtomicU64,
4743}
4744
4745impl Clone for ScanStats {
4746    fn clone(&self) -> Self {
4747        use core::sync::atomic::{AtomicU64, Ordering};
4748        Self {
4749            seq_scan: AtomicU64::new(self.seq_scan.load(Ordering::Relaxed)),
4750            seq_tup_read: AtomicU64::new(self.seq_tup_read.load(Ordering::Relaxed)),
4751            idx_scan: AtomicU64::new(self.idx_scan.load(Ordering::Relaxed)),
4752            idx_tup_fetch: AtomicU64::new(self.idx_tup_fetch.load(Ordering::Relaxed)),
4753        }
4754    }
4755}
4756
4757/// v7.39 (round 215) — the lower-bound sort key for a range value, used by
4758/// the range-exclusion index. The bound as an `i128` (unbounded lower =
4759/// `i128::MIN`, sorting first) plus an inclusivity rank (inclusive lower
4760/// sorts before exclusive at the same value, `[3` before `(3`). Returns
4761/// `None` for range kinds whose bound isn't an integer scalar (numrange's
4762/// numeric/bignum), for empty ranges, and for non-range values — the caller
4763/// then keeps the O(n) scan rather than risk an unsound order. Int4/Int8/
4764/// Date/Ts/TsTz all reduce here (tstzrange bounds are `Value::Timestamp`).
4765/// Maintenance (index build) and query (overlap probe) MUST agree on this
4766/// key, so both sides call exactly this function.
4767#[must_use]
4768pub fn range_excl_index_key(v: &Value<'_>) -> Option<(i128, u8)> {
4769    let Value::Range {
4770        lower,
4771        lower_inc,
4772        empty,
4773        ..
4774    } = v
4775    else {
4776        return None;
4777    };
4778    if *empty {
4779        return None;
4780    }
4781    let key = match lower {
4782        None => i128::MIN,
4783        Some(b) => match b.as_ref() {
4784            Value::SmallInt(n) => i128::from(*n),
4785            Value::Int(n) => i128::from(*n),
4786            Value::BigInt(n) => i128::from(*n),
4787            Value::Date(n) => i128::from(*n),
4788            Value::Timestamp(n) => i128::from(*n),
4789            _ => return None,
4790        },
4791    };
4792    Some((key, u8::from(!*lower_inc)))
4793}
4794
4795/// v7.39 (round 215) — a per-table range-exclusion index: an incrementally
4796/// maintained map from a range column's lower-bound key
4797/// ([`range_excl_index_key`]) to the physical row locators carrying that
4798/// bound. Lets EXCLUDE enforcement find the few candidate rows a new range
4799/// might overlap in O(log n) instead of scanning every row (measured O(N²),
4800/// r213). Because the stored ranges under a valid `EXCLUDE (col WITH &&)`
4801/// are pairwise disjoint, a candidate overlaps only its predecessor or the
4802/// successors whose lower bound precedes its upper — a handful of probes.
4803///
4804/// NOT persisted: rebuilt from the (persisted) exclusion constraints + rows
4805/// on catalog load, exactly like BRIN re-derives. Backed by a
4806/// `PersistentBTreeMap` so `Table::clone` (the per-write snapshot) stays
4807/// O(1). Locators to tombstoned rows are left in place and filtered by the
4808/// consumer via `is_deleted()` at query time — the established index pattern.
4809#[derive(Debug, Clone)]
4810pub struct ExclRangeIndex {
4811    /// The constrained range column's position in the table.
4812    pub column_position: usize,
4813    /// Lower-bound key → row locators. A key maps to a `Vec` because a
4814    /// tombstoned-then-reinserted bound can transiently collide; live rows
4815    /// under the constraint are disjoint so each key has one live locator.
4816    pub map: PersistentBTreeMap<(i128, u8), crate::posting::PostingList>,
4817}
4818
4819/// v7.38.2 (R2) — see [`Table::tx_write_track`]. Positions are the
4820/// insert-time slots (verified against the header's version at
4821/// extraction, so a shifted slot falls back to the scan); tombstones
4822/// carry the stable RowId, which is what the write-set wants anyway.
4823#[derive(Debug, Clone, Default)]
4824struct TxWriteTrack {
4825    version: u64,
4826    inserted: Vec<(usize, row_header::RowId)>,
4827    tombstoned: Vec<row_header::RowId>,
4828}
4829
4830/// v7.38.11 — hot-tier BRIN granularity: slots per summarised range.
4831///
4832/// 1024 keeps the summary vector three orders of magnitude smaller
4833/// than the table while staying fine enough that a one-day window over
4834/// a 90-day table skips ~99 % of it. A tuning constant, not a format:
4835/// summaries are rebuilt from the rows on load, so changing it costs
4836/// nothing on disk.
4837pub const BRIN_RANGE_ROWS: usize = 1024;
4838
4839/// The comparable scalar a BRIN summary tracks, or `None` for a value
4840/// with no ordering this index can use.
4841///
4842/// Deliberately narrow: only types whose ordering IS the i64 ordering
4843/// of this number. A type added here whose comparison is not that —
4844/// text under a collation, say — would make the summary under-report
4845/// and skip matching rows, which is the one failure this design must
4846/// not have.
4847#[must_use]
4848pub fn brin_scalar(v: &Value<'_>) -> Option<i64> {
4849    match v {
4850        Value::SmallInt(n) => Some(i64::from(*n)),
4851        Value::Int(n) => Some(i64::from(*n)),
4852        Value::BigInt(n) | Value::Timestamp(n) => Some(*n),
4853        Value::Date(d) => Some(i64::from(*d)),
4854        Value::Bool(b) => Some(i64::from(*b)),
4855        _ => None,
4856    }
4857}
4858
4859#[derive(Debug, Clone)]
4860pub struct Table {
4861    schema: TableSchema,
4862    /// v7.38.18 (S2) — the DATABASE's collation, copied in by the
4863    /// catalog that owns this table.
4864    ///
4865    /// A text column that declares no collation inherits it, which is
4866    /// what PostgreSQL does and what `information_schema.columns`
4867    /// reports as NULL. Runtime only, never serialised: it belongs to
4868    /// the catalog, and a table that has been handed around outside one
4869    /// falls back to `C`, which is the answer for every database written
4870    /// before this existed.
4871    db_collation: Option<String>,
4872    /// v7.38.16 — names of the expression indexes whose B-tree currently
4873    /// holds keys derived from the EXPRESSION.
4874    ///
4875    /// Every catalog written before this version stored, under an
4876    /// expression index, the values of its leading column — keys no
4877    /// lookup could ever match, which is why every read path guarded
4878    /// itself with `expression.is_none()` and the index bought nothing
4879    /// while costing 1.9x a plain insert to maintain.
4880    ///
4881    /// Deliberately NOT persisted: a table read off disk starts with the
4882    /// set empty, so those old wrong keys can never answer a query. The
4883    /// engine, which owns the expression evaluator, refills it.
4884    expr_index_complete: alloc::collections::BTreeSet<String>,
4885    /// v7.37.15 (Phase C.1) — stable per-catalog relation identity.
4886    /// [`RelId::UNASSIGNED`](row_header::RelId::UNASSIGNED) until
4887    /// `Catalog::create_table` (or the deserialize dense-assign pass)
4888    /// stamps a real id. Keys the Phase C.4 row-lock table and the
4889    /// Phase C.5 `RelationStore`; survives `DROP TABLE` slot shifts.
4890    rel_id: row_header::RelId,
4891    rows: PersistentVec<Row<'static>>,
4892    /// v7.37.15 (Phase A.2) — per-row MVCC visibility headers
4893    /// parallel to `rows`. `headers.len() == rows.len()` is the
4894    /// load-bearing invariant; debug builds assert it on every
4895    /// scan boundary, release builds rely on it from
4896    /// disciplined insert / delete / update paths.
4897    ///
4898    /// Pre-v7.37.15-loaded tables (every row currently in the
4899    /// fleet) start as `RowHeader::frozen()` — `is_all_visible_fast()`
4900    /// returns `true`, so the per-row visibility gate Phase B
4901    /// adds is a no-op against any snapshot.
4902    ///
4903    /// Headers are NOT yet serialised into the envelope at this
4904    /// commit — on snapshot deserialize every row gets a fresh
4905    /// `RowHeader::frozen()`. Phase D adds the visibility-map
4906    /// + segment-freeze story which makes serialisation
4907    /// meaningful; until then the on-disk story is "the catalog
4908    /// is the set of visible rows."
4909    headers: PersistentVec<row_header::RowHeader>,
4910    /// v7.37.15 (Phase C.1) — stable per-relation row identity
4911    /// parallel to `rows` / `headers`. `rowids[i]` is the never-
4912    /// reused [`RowId`](row_header::RowId) of the row physically at
4913    /// slot `i`; `rowids.len() == rows.len()` joins the same load-
4914    /// bearing lock-step invariant as `headers`. Compaction (delete
4915    /// / vacuum) rebuilds all three vecs together so the id travels
4916    /// with the row while the slot shifts.
4917    ///
4918    /// Introduced additively: allocated + kept lock-step, but index
4919    /// locators still address rows by physical slot at this commit.
4920    /// Later phases migrate the lock table (C.4), HOT chains (D),
4921    /// and the WAL (Epic W) to address by `RowId`.
4922    ///
4923    /// Not yet serialised into the envelope — on load every row is
4924    /// assigned a fresh dense id `1..=len` (see `next_rowid`), which
4925    /// is sufficient while the id is process-local bookkeeping. The
4926    /// V6 envelope (Phase C.6) will persist ids so a WAL redo can
4927    /// name a row across restart.
4928    rowids: PersistentVec<row_header::RowId>,
4929    /// v7.37.15 (Phase C.1) — per-relation monotonic allocator for
4930    /// `rowids`. Starts at 1 (0 is the `RowId::UNASSIGNED` sentinel);
4931    /// every append takes `next_rowid` then increments. Never reused
4932    /// even after the row is deleted / vacuumed, so a stale lock /
4933    /// redo reference can be detected rather than silently aliasing a
4934    /// later row that reused the slot.
4935    ///
4936    /// 7.38.1 (S2.4, MATRIX #20 root cause) — the allocator is SHARED
4937    /// across every `clone()` of the relation (`Arc`), because the
4938    /// monotonic-never-reused promise is a LINEAGE invariant: each
4939    /// open transaction's shadow catalog is a clone, and when clones
4940    /// carried private counters two concurrent shadows minted the
4941    /// same id — duplicate rids in the base after both committed,
4942    /// aliasing every rid-addressed mechanism (locks, tombstones,
4943    /// redo, the rebase unique pre-check).
4944    next_rowid: alloc::sync::Arc<core::sync::atomic::AtomicU64>,
4945    /// v7.37.16 (autovacuum) — live count of tombstoned-but-present hot
4946    /// rows (`headers[i].xmax != XMAX_ALIVE`). Maintained incrementally:
4947    /// `mark_row_deleted` / `mark_rows_deleted` increment (the only
4948    /// tombstone producers), `delete_rows_no_index` recomputes over the
4949    /// survivors (it is the compaction hub every physical removal —
4950    /// including vacuum — flows through), and the v53 snapshot loader
4951    /// recounts verbatim-restored headers. Drives the engine's
4952    /// autovacuum threshold; not persisted (recomputed on load).
4953    dead_rows: u64,
4954    /// v7.39 (pg_stat knife A) — volatile per-table write counters
4955    /// backing `pg_stat_user_tables.n_tup_ins/upd/del`. Not persisted
4956    /// (PG's cumulative stats are shared-memory-volatile too — a
4957    /// restart zeroes them).
4958    stat_tup_ins: u64,
4959    stat_tup_upd: u64,
4960    stat_tup_del: u64,
4961    /// v7.39 (pg_stat knife B) — volatile scan counters
4962    /// (`seq_scan/seq_tup_read/idx_scan/idx_tup_fetch`). Atomics: the
4963    /// read paths that bump them hold only `&Table`.
4964    scan_stats: ScanStats,
4965    /// v7.39 (pg_stat knife C) — wall-clock stamps (unix µs, from the
4966    /// host ClockFn) for pg_stat_user_tables' last_autovacuum /
4967    /// last_analyze. Volatile, like PG's cumulative stats. SPG has no
4968    /// manual-VACUUM statement semantics, so last_vacuum stays NULL.
4969    last_autovacuum_us: Option<i64>,
4970    last_analyze_us: Option<i64>,
4971    indices: Vec<Index>,
4972    hot_bytes: u64,
4973    /// v6.7.0 — cached count of rows currently materialised in the
4974    /// cold tier via `RowLocator::Cold` entries across THIS table's
4975    /// indices. Populated by `ANALYZE` (walks every BTree index and
4976    /// counts Cold locators); the count survives until the next
4977    /// ANALYZE recomputes it. Surfaced via `spg_statistic.cold_row_count`
4978    /// and `spg_stat_segment.table_name`.
4979    ///
4980    /// Honest scope: this is a CACHED count, not a live one.
4981    /// Freezer / promote / DELETE don't currently update the cache
4982    /// incrementally — they invalidate it by setting the
4983    /// `cold_row_count_stale` flag, and the next ANALYZE re-walks.
4984    /// Incremental maintenance is a v6.7.x candidate if observation
4985    /// shows the ANALYZE walk cost dominates.
4986    cold_row_count: u64,
4987    /// v6.7.0 — set when the cached `cold_row_count` may be wrong
4988    /// because rows moved into / out of the cold tier since the last
4989    /// ANALYZE. The virtual-table surface reports the cached value
4990    /// regardless (operators run ANALYZE to refresh).
4991    cold_row_count_stale: bool,
4992    /// v7.34 (crash-recovery P0 #2) — row-level redo capture buffer.
4993    /// `None` (default, in-memory mode) captures nothing — zero overhead.
4994    /// `Some` (set by the engine when persistence is on, before a
4995    /// mutating call) makes `insert` / `update_row` / `delete_rows`
4996    /// record the physical [`RowChange`] they applied, which the engine
4997    /// drains after the statement and writes to the WAL in place of the
4998    /// SQL text. Transient: never serialized; a `Catalog::clone` between
4999    /// enable and drain copies it (cheap — empty in the steady state).
5000    redo_log: Option<Vec<RowChange>>,
5001    /// v7.39 (round 215) — per-`EXCLUDE`-constraint range-overlap indexes,
5002    /// one per single-`&&` constraint on an integer-keyable range column.
5003    /// Maintained incrementally on insert / update / rebuild (mirroring the
5004    /// BTree secondary indexes); NOT serialized — rebuilt from the schema's
5005    /// exclusion constraints on load. Empty for tables with no EXCLUDE
5006    /// constraint (the common case), so `Table::clone` pays nothing.
5007    excl_indexes: Vec<ExclRangeIndex>,
5008    /// v7.38.2 (R2) — incremental write-set track for the RC rebase.
5009    /// `extract_tx_writeset` used to full-scan every header per call —
5010    /// ~200 µs on a 20k-row table, per in-transaction statement, every
5011    /// time a concurrent COMMIT moved the epoch; on tpcb's 100k-row
5012    /// accounts that scan was the c2 concurrency cliff itself. The
5013    /// three version-marking funnels (`insert_with_xmin`,
5014    /// `mark_row_deleted`, `mark_rows_deleted`) record here instead.
5015    ///
5016    /// One track per table, keyed by the LAST writer version: a shadow
5017    /// belongs to one transaction, so a different version claiming the
5018    /// table simply replaces the track (on the committed base that
5019    /// makes memory bounded by the last writer's footprint). Extraction
5020    /// verifies every recorded position still carries the version —
5021    /// any mismatch (compaction, inherited track, pre-track rows)
5022    /// falls back to the full scan, so the fast path can be wrong
5023    /// about NOTHING, only slow.
5024    tx_write_track: Option<TxWriteTrack>,
5025    /// v7.39 (round 493) — the snapshot floor below which a deleted row
5026    /// version is invisible to everyone, as of the statement now running.
5027    ///
5028    /// Runtime only: never serialised, and `0` (the default) prunes
5029    /// nothing, so any path that forgets to set it is merely slower, not
5030    /// wrong. The engine sets it from `vacuum_oldest_active()` — the same
5031    /// floor `vacuum` itself takes — before the statement's inserts.
5032    prune_horizon: u64,
5033}
5034
5035/// Catalog: insertion-ordered `Vec<Table>` for stable iter / serialize,
5036/// plus a `BTreeMap<String, usize>` sidecar index so `get` / `get_mut`
5037/// run in O(log n) instead of the old linear scan with per-element
5038/// string compares.
5039///
5040/// A pure `BTreeMap<String, Table>` was tried in an interim version
5041/// of v3.1.2 and regressed the single-table catalog benches by ~10%
5042/// (the per-element `BTreeMap` overhead outweighs the lookup win
5043/// when n is small). The sidecar shape preserves the insertion-order
5044/// iteration the on-disk encoding relies on and keeps `last_mut`
5045/// (used by the deserialize hot path) cheap.
5046/// v7.39 (pg_stat blks knife) — catalog-wide cold-tier read counter
5047/// backing pg_stat_database.blks_read. Row-granular (SPG has no 8 KB
5048/// page notion): one cold-segment row resolution = one "block read",
5049/// one hot row access = one "block hit" — the hit RATIO monitoring
5050/// dashboards compute keeps its meaning. Volatile like PG's stats.
5051#[derive(Debug, Default)]
5052pub struct ColdReadStats {
5053    pub cold_reads: core::sync::atomic::AtomicU64,
5054}
5055
5056impl Clone for ColdReadStats {
5057    fn clone(&self) -> Self {
5058        Self {
5059            cold_reads: core::sync::atomic::AtomicU64::new(
5060                self.cold_reads.load(core::sync::atomic::Ordering::Relaxed),
5061            ),
5062        }
5063    }
5064}
5065
5066/// 7.38.1 S3.1 (D4) — the non-table catalog families that carry a
5067/// per-transaction dirty window (see `Catalog::dirty_nontable`). One
5068/// entry class per side-map the poisoned-commit merge reconciles.
5069#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
5070pub enum NonTableKind {
5071    Sequence,
5072    View,
5073    MaterializedView,
5074    EnumType,
5075    DomainType,
5076    CompositeType,
5077}
5078
5079#[derive(Debug, Clone, Default)]
5080pub struct Catalog {
5081    /// v7.39 (pg_stat blks knife) — see [`ColdReadStats`].
5082    pub cold_read_stats: ColdReadStats,
5083    tables: Vec<Table>,
5084    /// `name → tables[index]`. Kept in lock-step with `tables`.
5085    /// `create_table` is the only write path.
5086    by_name: BTreeMap<String, usize>,
5087    /// v7.39 (round 436) — the current session's temporary-table namespace.
5088    /// A temp table is stored under `<prefix><name>`, and every lookup tries
5089    /// that first: exactly PG's `pg_temp` search-path rule, and MySQL's
5090    /// "a TEMPORARY table shadows a permanent one of the same name".
5091    ///
5092    /// Process-local, never serialised: the engine sets it per session, and
5093    /// a catalog read back from disk starts with none. Kept here rather than
5094    /// at each of the ~170 engine call sites because `by_name` is private —
5095    /// this is the ONE place a table name becomes an index.
5096    temp_prefix: Option<String>,
5097    /// v7.39.2 — see [`Catalog::set_case_insensitive_names`].
5098    case_insensitive_names: bool,
5099    /// v7.39 (round 496) — the names of tables this catalog handle has had
5100    /// changed since the set was last cleared.
5101    ///
5102    /// Runtime only, never serialised. A transaction's shadow catalog
5103    /// clears it at BEGIN, so at COMMIT the set is exactly the tables the
5104    /// transaction changed — which is what lets a commit that cannot use
5105    /// the row-level merge install only those tables instead of the whole
5106    /// catalog, leaving another session's concurrent work in place.
5107    ///
5108    /// Recorded where the change actually happens (`get_mut`,
5109    /// `create_table`, `drop_table`) rather than from the statement
5110    /// classifier: round 494 tried classification for a correctness gate
5111    /// and it was wrong, because `SELECT lo_write(…)` reads as read-only.
5112    dirty_tables: alloc::collections::BTreeSet<String>,
5113    /// 7.38.1 S3.1 (D4) — the non-table twin of `dirty_tables`: which
5114    /// sequences / views / matviews / enum / domain / composite types
5115    /// THIS window created, altered, renamed or dropped. Counter
5116    /// advances (`nextval`) deliberately do NOT record — counter
5117    /// values merge via `sequence_counters` / `restore_sequence_
5118    /// counters`, and a tx that only consumed ids must not shadow a
5119    /// neighbour's ALTER SEQUENCE. Cleared by `clear_dirty_tables`
5120    /// (one window, both records).
5121    dirty_nontable: alloc::collections::BTreeSet<(NonTableKind, String)>,
5122    /// v7.37.15 (Phase C.1) — monotonic allocator for stable
5123    /// [`RelId`](row_header::RelId)s. Pre-incremented on each
5124    /// `create_table` so real ids start at 1 (0 is `UNASSIGNED`);
5125    /// never reused even after `DROP TABLE`, so a stale lock / redo
5126    /// reference is detectable. Process-local bookkeeping — not yet
5127    /// serialised; `deserialize` re-assigns dense ids on load (the
5128    /// V6 envelope, Phase C.6, will round-trip real ids).
5129    next_rel_id: u64,
5130    /// v5.1: in-memory cold-tier segments. Side-loaded via
5131    /// [`Catalog::load_segment_bytes`] — they live outside the
5132    /// catalog snapshot (caller persists them as separate files
5133    /// and re-loads on boot, until v5.3's `CatalogManifest` makes
5134    /// that wiring automatic). `RowLocator::Cold { segment_id, .. }`
5135    /// indexes this `Vec`. Cleared on `Catalog::new` / fresh
5136    /// `deserialize`.
5137    ///
5138    /// `Arc` wrap keeps `Catalog::clone` at O(N segments) bumps
5139    /// (rather than O(total segment bytes) memcpy) so the v4.42
5140    /// group-commit pre-image rollback invariant — clone is
5141    /// effectively free — survives the cold-tier addition.
5142    ///
5143    /// v6.7.3 — slots became `Option<…>` so cold-segment compaction
5144    /// can tombstone merged sources without breaking the
5145    /// `segment_id = index_into_vec` contract that on-disk
5146    /// `RowLocator::Cold { segment_id }` already serialized.
5147    /// `None` slot = the segment was retired by compaction; the
5148    /// physical file may still be on disk (next CHECKPOINT writes
5149    /// a manifest that no longer lists it, and the file becomes
5150    /// an orphan eligible for offline cleanup).
5151    cold_segments: Vec<Option<Arc<OwnedSegment>>>,
5152    /// v7.12.4 — user-defined functions (PL/pgSQL + SQL).
5153    /// Keyed by function name (PG overloading is out of scope).
5154    /// Bodies are stored as the raw source text the parser saw
5155    /// between `$$ ... $$`; the engine re-parses on each
5156    /// invocation. This keeps `spg-storage` free of `spg-sql`
5157    /// dependency — same pattern as partial-index predicates.
5158    functions: BTreeMap<String, FunctionDef>,
5159    /// v7.12.4 — triggers in insertion order. PG18-measured (round
5160    /// 753): PG fires same-event triggers in NAME order (a_trig
5161    /// before z_trig regardless of creation order); SPG fires in
5162    /// insertion order — a real divergence, ledgered as F31-B2.
5163    triggers: Vec<TriggerDef>,
5164    /// v7.39 (round 139) — query-rewrite RULEs, flat like triggers.
5165    rules: Vec<RuleDef>,
5166    /// v7.39 (round 280) — extended-statistics objects. Recorded so a
5167    /// pg_dump restores them and reflection reports them; the planner
5168    /// does not consult them yet.
5169    statistics_ext: Vec<StatisticsExtDef>,
5170    /// v7.39 (round 287) — server-side large objects, keyed by OID.
5171    /// PG stores them as 2 KB pages in `pg_largeobject`; the page split
5172    /// is a storage detail of ITS heap, so SPG holds the whole byte
5173    /// string and renders the pages on read. What must match is the
5174    /// observable surface: the OIDs, the bytes, and the page rows.
5175    large_objects: alloc::collections::BTreeMap<u32, Vec<u8>>,
5176    /// v7.17.0 — catalogued SEQUENCE objects (Phase 1.1). Each
5177    /// `nextval(name)` reaches in here, atomically increments
5178    /// `last_value` / flips `is_called`, returns the new value.
5179    /// Persisted in catalog FILE_VERSION 26+; older catalogs
5180    /// deserialise with an empty map.
5181    sequences: BTreeMap<String, SequenceDef>,
5182    /// v7.39 (read01 round 60) — the `public` schema's ACL (PG
5183    /// `pg_namespace.nspacl`). EMPTY = PG's default, which is not "nothing":
5184    /// PUBLIC holds USAGE and the owner holds USAGE + CREATE. Materialised on
5185    /// the first GRANT / REVOKE, exactly like a table's relacl.
5186    schema_acl: Vec<AclItem>,
5187    /// v7.39 (read01 round 60) — the database's ACL. EMPTY = PG's default:
5188    /// PUBLIC holds CONNECT + TEMPORARY, the owner holds all three.
5189    database_acl: Vec<AclItem>,
5190    /// v7.17.0 — catalogued VIEW objects (Phase 1.2). Each
5191    /// `SELECT FROM v` at engine exec-time looks up `v` here and
5192    /// prepends the view body as a synthetic CTE. Persisted in
5193    /// catalog FILE_VERSION 27+; older catalogs deserialise with
5194    /// an empty map.
5195    views: BTreeMap<String, ViewDef>,
5196    /// v7.17.0 — catalogued MATERIALIZED VIEW source registry
5197    /// (Phase 1.3). Maps name → SELECT source. The materialised
5198    /// rows themselves live as a regular `Table` with the same
5199    /// name; REFRESH re-parses + re-executes the source against
5200    /// the table. Persisted in catalog FILE_VERSION 28+;
5201    /// older catalogs deserialise with an empty map.
5202    materialized_views: BTreeMap<String, String>,
5203    /// v7.17.0 — catalogued user-defined ENUM types (Phase 1.4).
5204    /// Maps name → label list. Columns reference these by name
5205    /// via `ColumnSchema.user_enum_type`. Persisted in catalog
5206    /// FILE_VERSION 29+; older catalogs deserialise with an empty
5207    /// map.
5208    enum_types: BTreeMap<String, EnumDef>,
5209    /// v7.17.0 — catalogued user-defined DOMAIN types (Phase 1.5).
5210    /// Maps name → base + CHECK constraints. Columns reference
5211    /// these by name via `ColumnSchema.user_domain_type`.
5212    /// Persisted in catalog FILE_VERSION 30+; older catalogs
5213    /// deserialise with an empty map.
5214    domain_types: BTreeMap<String, DomainDef>,
5215    /// v7.39 (read01 round 50) — `COMMENT ON <kind> <obj> IS '…'` store.
5216    /// Keyed by a canonical `"<kind>:<name>"` string (`"table:t"`,
5217    /// `"column:t.c"`, `"index:i"`, `"view:v"`, …) so a new commentable
5218    /// object kind needs no schema change. `COMMENT … IS NULL` removes the
5219    /// entry. Persisted in catalog FILE_VERSION 61+; older catalogs
5220    /// deserialise with an empty map. Read back by obj_description /
5221    /// col_description and the pg_description view.
5222    comments: BTreeMap<String, String>,
5223    /// v7.39 (round 547) — PG's `pg_db_role_setting`: the GUC defaults
5224    /// `ALTER ROLE … SET` / `ALTER DATABASE … SET` record, applied when
5225    /// a session starts.
5226    ///
5227    /// Keyed exactly as PG keys it — `(database, role)` where an empty
5228    /// name is PG's oid 0, meaning "all". So `ALTER ROLE ALL SET` is
5229    /// `("", "")`, `ALTER DATABASE d SET` is `(d, "")`, `ALTER ROLE r
5230    /// SET` is `("", r)` and `ALTER ROLE r IN DATABASE d SET` is
5231    /// `(d, r)`. The value is that scope's parameter list.
5232    db_role_settings: BTreeMap<(String, String), BTreeMap<String, String>>,
5233    /// v7.39 (round 550) — replication slots, by name.
5234    ///
5235    /// A slot in PG is two things: a named record, and a reservation
5236    /// that holds WAL back. SPG keeps the record — which is what every
5237    /// setup script and monitoring query reads — and reports
5238    /// `wal_status = 'unreserved'`, PG's own word for a slot that no
5239    /// longer holds WAL. The whole family used to answer NULL and
5240    /// report success, so `pg_drop_replication_slot('nosuchslot')` said
5241    /// it worked and a setup script created nothing.
5242    ///
5243    /// Value: (plugin, slot_type). `plugin` is empty for a physical slot.
5244    replication_slots: BTreeMap<String, (String, String)>,
5245    /// v7.38.18 (S1) — the collation this database was CREATED with, and
5246    /// the one every text column that declares none is compared under.
5247    ///
5248    /// `None` means `C`, which is what every database written by every
5249    /// earlier version was built with — so an upgrade changes no answer
5250    /// and rebuilds no index. That is the whole migration story, and it
5251    /// is why this is an `Option` rather than a `String` defaulting to
5252    /// `"C"`.
5253    ///
5254    /// Set once, at creation, and never after. PostgreSQL refuses
5255    /// `ALTER DATABASE … LC_COLLATE` and the reason is the one that
5256    /// matters here too: every index key in this database was built
5257    /// under this collation, so it cannot move out from under them.
5258    /// See `docs/DESIGN-2026-08-23-collation.md`.
5259    db_collation: Option<String>,
5260    /// v7.38.19 — every name a `CREATE DATABASE` has asked for.
5261    ///
5262    /// SPG serves one database and answers to any name, so the statement
5263    /// has always been a no-op for naming. `pg_database` then listed one
5264    /// row -- whatever name the current session connected with -- so a
5265    /// database that had just been created, and could be connected to,
5266    /// was absent from the catalogue. `psql \l`, a migration tool asking
5267    /// "does this database exist", and a backup script that enumerates
5268    /// all read that table.
5269    ///
5270    /// Reported by sentori against 7.38.18. Runtime only, like
5271    /// `db_collation`: the statement is audited whenever it records a
5272    /// name, so replay rebuilds the set.
5273    created_databases: alloc::collections::BTreeSet<String>,
5274    /// v7.37.42-T2 ζ-B — catalogued user-defined COMPOSITE types
5275    /// (`CREATE TYPE name AS (field_name field_type, …)`). Columns
5276    /// reference these by name via
5277    /// `ColumnSchema.user_composite_type` (parallel to
5278    /// `user_enum_type` / `user_domain_type`). Persisted in catalog
5279    /// FILE_VERSION 52+; older catalogs deserialise with an empty
5280    /// map.
5281    composite_types: BTreeMap<String, CompositeDef>,
5282    /// v7.17.0 — schema-namespace registry (Phase 1.6). Tracks
5283    /// which schemas exist. `public`, `pg_catalog`, and
5284    /// `information_schema` are built-in and always present.
5285    /// Schema-qualified table references still strip the prefix
5286    /// at lookup time per v7.16-and-earlier — full
5287    /// schema-as-isolation is v7.18+ scope. Persisted in catalog
5288    /// FILE_VERSION 31+; older catalogs deserialise with just
5289    /// the built-ins.
5290    schemas: alloc::collections::BTreeSet<String>,
5291}
5292
5293/// v7.12.4 — catalogued user-defined function. `body` is the raw
5294/// source text between `$$ ... $$`; the engine re-parses it on
5295/// invocation. This keeps the storage codec stable when the
5296/// PL/pgSQL surface grows (no breaking-change risk on the disk
5297/// format).
5298// v7.39 (round 322, V46) — no longer `Eq`: COST / ROWS are f64, as in PG.
5299#[derive(Debug, Clone, PartialEq)]
5300pub struct FunctionDef {
5301    pub name: String,
5302    /// Display form of the argument list, e.g.
5303    /// `"(name TEXT, ts TIMESTAMP)"`. Empty `"()"` for the trigger
5304    /// function shape. Parser-side canonicalised before storage.
5305    pub args_repr: String,
5306    /// Display form of the return type, e.g. `"TRIGGER"` /
5307    /// `"INT"` / `"SETOF text"`. The engine special-cases
5308    /// `"TRIGGER"` (case-insensitive) to gate trigger-only
5309    /// semantics (NEW/OLD).
5310    pub returns: String,
5311    /// `LANGUAGE` clause, lowercased. `"plpgsql"` / `"sql"`.
5312    pub language: String,
5313    /// Source body of the function. PL/pgSQL: includes the
5314    /// surrounding `BEGIN ... END;`. SQL: includes the
5315    /// statement(s). The engine re-parses on invocation; bad
5316    /// bodies surface as a parse error at CALL time, not CREATE.
5317    pub body: String,
5318    /// v7.39 (read01 round 61) — the role that ran CREATE FUNCTION.
5319    pub owner: Option<String>,
5320    /// v7.39 (read01 round 61) — explicit GRANTs (PG `pg_proc.proacl`). EMPTY
5321    /// is NOT "nobody may call it": PG grants EXECUTE to PUBLIC by default, and
5322    /// leaves proacl NULL to say so. The list materialises on the first
5323    /// GRANT / REVOKE.
5324    pub acl: Vec<AclItem>,
5325    /// v7.39 (round 322, V46) — `IMMUTABLE` / `STRICT` / `PARALLEL SAFE` /
5326    /// `SECURITY DEFINER` / `LEAKPROOF` / `COST` / `ROWS`. `strict` is the
5327    /// only one with execution semantics today (a NULL argument yields a
5328    /// NULL result without running the body); the rest are recorded so
5329    /// `pg_get_functiondef` and `pg_proc` report what was declared.
5330    pub volatility: u8,
5331    pub strict: bool,
5332    pub security_definer: bool,
5333    pub leakproof: bool,
5334    pub parallel: u8,
5335    pub cost: Option<f64>,
5336    pub rows: Option<f64>,
5337}
5338
5339/// v7.39 (round 322, V46) — `FunctionDef.volatility` codes: PG's
5340/// `pg_proc.provolatile` letters.
5341pub const FN_VOLATILE: u8 = b'v';
5342pub const FN_IMMUTABLE: u8 = b'i';
5343pub const FN_STABLE: u8 = b's';
5344
5345/// v7.39 (round 322, V46) — `FunctionDef.parallel` codes: PG's
5346/// `pg_proc.proparallel` letters.
5347pub const FN_PARALLEL_UNSAFE: u8 = b'u';
5348pub const FN_PARALLEL_RESTRICTED: u8 = b'r';
5349pub const FN_PARALLEL_SAFE: u8 = b's';
5350
5351/// v7.39 (round 315, V19) — which catalogued function does a persisted
5352/// ACL key refer to?
5353///
5354/// The key was computed by whichever formula was current when the image
5355/// was written, and the multi-word fix changed that formula for bare
5356/// types like `double precision`. A miss therefore does NOT mean "no
5357/// such function": an older image's key would land nowhere and its owner
5358/// and grants would be dropped in silence. Exact match first, then the
5359/// pre-fix formula.
5360#[must_use]
5361pub fn resolve_stored_function_key(
5362    functions: &BTreeMap<String, FunctionDef>,
5363    stored: &str,
5364) -> Option<String> {
5365    if functions.contains_key(stored) {
5366        return Some(stored.to_string());
5367    }
5368    functions
5369        .values()
5370        .find(|f| function_signature_key_legacy(&f.name, &f.args_repr) == stored)
5371        .map(|f| function_signature_key(&f.name, &f.args_repr))
5372}
5373
5374/// v7.39 (round 344, V49) — re-exported from [`spg_sql`], which owns the
5375/// SQL type spellings. This crate carried a byte-identical copy because
5376/// the two were siblings that did not depend on each other; spg-sql is a
5377/// dependency-free leaf, so the dependency is acyclic and the publish
5378/// order already puts it first. One list, one place to keep it right.
5379pub use spg_sql::parser::is_multiword_type_phrase;
5380
5381/// v7.39 (round 315, V19) — the signature key as computed BEFORE the
5382/// multi-word fix, used only to recognise what an older image wrote.
5383///
5384/// The function catalogue recomputes its keys from the stored name and
5385/// argument text on load, so it needs no migration. The ACL block does
5386/// not: it persists the computed key as a string and matches on it. A
5387/// key that changed shape would simply fail to match, and the owner and
5388/// grants would be dropped without a word — so the loader falls back to
5389/// this when the stored key finds nothing.
5390#[must_use]
5391pub fn function_signature_key_legacy(name: &str, args_repr: &str) -> String {
5392    let inner = args_repr
5393        .trim()
5394        .trim_start_matches('(')
5395        .trim_end_matches(')');
5396    let types: Vec<String> = if inner.trim().is_empty() {
5397        Vec::new()
5398    } else {
5399        inner
5400            .split(',')
5401            .map(|part| {
5402                let mut words: Vec<&str> = part.split_whitespace().collect();
5403                if !words.is_empty()
5404                    && (words[0].eq_ignore_ascii_case("OUT")
5405                        || words[0].eq_ignore_ascii_case("INOUT"))
5406                {
5407                    words.remove(0);
5408                }
5409                let ty = if words.len() >= 2 {
5410                    words[1..].join(" ")
5411                } else {
5412                    words.first().map_or(String::new(), |w| (*w).to_string())
5413                };
5414                normalize_type_name(&ty)
5415            })
5416            .collect()
5417    };
5418    format!("{}({})", name.to_ascii_lowercase(), types.join(","))
5419}
5420
5421pub fn function_signature_key(name: &str, args_repr: &str) -> String {
5422    let types = function_arg_types(args_repr);
5423    format!("{}({})", name.to_ascii_lowercase(), types.join(","))
5424}
5425
5426/// The declared argument TYPES of a function, out of its `args_repr`
5427/// (`"(x INT, y DOUBLE PRECISION)"` → `["int", "float"]`). An entry may be a
5428/// bare type with no name (`"(INT)"`).
5429#[must_use]
5430pub fn function_arg_types(args_repr: &str) -> Vec<String> {
5431    let inner = args_repr
5432        .trim()
5433        .trim_start_matches('(')
5434        .trim_end_matches(')');
5435    if inner.trim().is_empty() {
5436        return Vec::new();
5437    }
5438    inner
5439        .split(',')
5440        .map(|part| {
5441            let mut words: Vec<&str> = part.split_whitespace().collect();
5442            // `OUT x INT` / `INOUT x INT` — the mode is not part of the type.
5443            if !words.is_empty()
5444                && (words[0].eq_ignore_ascii_case("OUT") || words[0].eq_ignore_ascii_case("INOUT"))
5445            {
5446                words.remove(0);
5447            }
5448            // v7.39 (round 315, V19) — two or more words is USUALLY
5449            // `name TYPE`, but not when the type itself is spelled in
5450            // several words. `double precision` was read as a parameter
5451            // named "double" of type "precision", so it keyed differently
5452            // from `x double precision` — the same signature written two
5453            // ways did not resolve to the same function. Decide by asking
5454            // whether the whole phrase names a type first; only then is
5455            // the leading word a parameter name.
5456            let whole = words.join(" ");
5457            let ty = if words.len() >= 2 && !is_multiword_type_phrase(&whole) {
5458                words[1..].join(" ")
5459            } else {
5460                whole
5461            };
5462            normalize_type_name(&ty)
5463        })
5464        .collect()
5465}
5466
5467/// v7.39 (read01 round 65) — the declared argument NAMES of a function (`""` for
5468/// a bare type with no name).
5469#[must_use]
5470pub fn function_arg_names(args_repr: &str) -> Vec<String> {
5471    let inner = args_repr
5472        .trim()
5473        .trim_start_matches('(')
5474        .trim_end_matches(')');
5475    if inner.trim().is_empty() {
5476        return Vec::new();
5477    }
5478    inner
5479        .split(',')
5480        .map(|part| {
5481            let mut words: Vec<&str> = part.split_whitespace().collect();
5482            if !words.is_empty()
5483                && (words[0].eq_ignore_ascii_case("OUT") || words[0].eq_ignore_ascii_case("INOUT"))
5484            {
5485                words.remove(0);
5486            }
5487            if words.len() >= 2 {
5488                words[0].to_string()
5489            } else {
5490                String::new()
5491            }
5492        })
5493        .collect()
5494}
5495
5496/// Fold PG's type aliases so a signature key is stable across spellings.
5497/// Unknown names pass through lower-cased — consistency is what the key needs.
5498#[must_use]
5499pub fn normalize_type_name(ty: &str) -> String {
5500    let t = ty.trim().to_ascii_lowercase();
5501    // Peel a precision/length modifier: `numeric(10,2)`, `varchar(64)`.
5502    let base = t.split_once('(').map_or(t.as_str(), |(h, _)| h).trim();
5503    match base {
5504        "int" | "int4" | "integer" => "int",
5505        "bigint" | "int8" => "bigint",
5506        "smallint" | "int2" => "smallint",
5507        "text" | "varchar" | "character varying" | "char" | "character" | "bpchar" => "text",
5508        "bool" | "boolean" => "bool",
5509        "float" | "float8" | "double precision" => "float",
5510        "real" | "float4" => "real",
5511        "numeric" | "decimal" => "numeric",
5512        "timestamptz" | "timestamp with time zone" => "timestamptz",
5513        "timestamp" | "timestamp without time zone" => "timestamp",
5514        other => other,
5515    }
5516    .to_string()
5517}
5518
5519/// v7.12.4 — catalogued trigger. References its function by
5520/// name; the function must exist at TRIGGER creation time
5521/// (forward references are deferred to v7.12.5+).
5522#[derive(Debug, Clone, PartialEq, Eq)]
5523pub struct TriggerDef {
5524    pub name: String,
5525    /// Watched table. Trigger is dropped when the table drops.
5526    pub table: String,
5527    /// `"BEFORE"` / `"AFTER"` / `"INSTEAD OF"`. Stored as the
5528    /// uppercased keyword so deserialised catalogs round-trip
5529    /// without canonicalisation surprises.
5530    pub timing: String,
5531    /// Each entry is one of `"INSERT"` / `"UPDATE"` / `"DELETE"`
5532    /// / `"TRUNCATE"`. `INSERT OR UPDATE` parses to two entries.
5533    pub events: Vec<String>,
5534    /// `"ROW"` / `"STATEMENT"`. v7.12.4 ships `"ROW"` only;
5535    /// `"STATEMENT"` parses and persists but the executor
5536    /// refuses it at trigger fire time.
5537    pub for_each: String,
5538    /// Name of the PL/pgSQL function to invoke.
5539    pub function: String,
5540    /// v7.13.0 — `UPDATE OF col, col, …` column-list filter
5541    /// (mailrs round-5 G7). Non-empty means the trigger fires
5542    /// only when at least one of these columns appears in the
5543    /// UPDATE's SET list. Empty = no column filter. Stored in
5544    /// catalog FILE_VERSION 23+; older catalogs deserialise with
5545    /// an empty vec.
5546    pub update_columns: Vec<String>,
5547    /// v7.16.1 — whether the trigger fires when its watched
5548    /// event occurs. Toggled by `ALTER TABLE … { ENABLE |
5549    /// DISABLE } TRIGGER …`; pg_dump --disable-triggers wraps
5550    /// every data block with a DISABLE/ENABLE pair so the
5551    /// rows already-computed in prod don't get re-rewritten.
5552    /// Defaults to `true` at CREATE TRIGGER time. Stored in
5553    /// catalog FILE_VERSION 25+; older catalogs deserialise
5554    /// with `enabled = true`.
5555    pub enabled: bool,
5556    /// v7.39 (round 138) — the deparsed `WHEN ( condition )` predicate text
5557    /// (re-parsed at fire time to filter row triggers). Empty = no WHEN.
5558    /// Persisted from FILE_VERSION 70; older catalogs read back empty.
5559    pub when_condition: String,
5560}
5561
5562/// v7.39 (round 280) — one `CREATE STATISTICS` object.
5563#[derive(Debug, Clone, PartialEq, Eq)]
5564pub struct StatisticsExtDef {
5565    pub name: String,
5566    pub table: String,
5567    /// PG's single-letter kinds: `d` ndistinct, `f` dependencies,
5568    /// `m` mcv. PG's default set is all three.
5569    pub kinds: Vec<String>,
5570    pub columns: Vec<String>,
5571}
5572
5573/// v7.39 (round 139) — a catalogued query-rewrite RULE. Stored flat like
5574/// `TriggerDef`, keyed by `(name, table)`. Command / WHEN text is deparsed SQL
5575/// re-parsed at rewrite time (the same round-trip trick as
5576/// `TriggerDef.when_condition`). Persisted from FILE_VERSION 71.
5577#[derive(Debug, Clone, PartialEq, Eq)]
5578pub struct RuleDef {
5579    pub name: String,
5580    pub table: String,
5581    /// Event keyword, uppercased: `INSERT` / `UPDATE` / `DELETE` / `SELECT`.
5582    pub event: String,
5583    /// `true` = `DO INSTEAD`, `false` = `DO ALSO`.
5584    pub instead: bool,
5585    /// Deparsed `WHERE` predicate text; empty = unconditional.
5586    pub when_condition: String,
5587    /// Deparsed DO command statements; empty = `NOTHING`.
5588    pub commands: Vec<String>,
5589}
5590
5591/// v7.17.0 — catalogued SEQUENCE. PG semantics: a counter object
5592/// returning monotonically increasing values via `nextval(name)`.
5593/// `last_value` is the most recent value handed out; `is_called`
5594/// is false until the first `nextval`/`setval`. Stored separately
5595/// from tables in the catalog.
5596#[derive(Debug, Clone, PartialEq, Eq)]
5597pub struct SequenceDef {
5598    pub name: String,
5599    /// Data type — narrows the i64 range. PG default BIGINT.
5600    pub data_type: SequenceDataType,
5601    pub start: i64,
5602    pub increment: i64,
5603    pub min_value: i64,
5604    pub max_value: i64,
5605    pub cache: i64,
5606    pub cycle: bool,
5607    /// `OWNED BY` target — `(table, column)` or NONE.
5608    pub owned_by: Option<(String, String)>,
5609    /// Most recently handed-out value. Meaningless when
5610    /// `is_called == false`; in that case the NEXT `nextval`
5611    /// will return `start`.
5612    pub last_value: i64,
5613    pub is_called: bool,
5614    /// v7.39 (read01 round 60) — the role that ran CREATE SEQUENCE. `None` = an
5615    /// image written before FILE_VERSION 66, which predates sequence owners.
5616    pub owner: Option<String>,
5617    /// v7.39 (read01 round 60) — explicit GRANTs on this sequence. A sequence's
5618    /// meaningful privileges are SELECT (`currval`), UPDATE (`setval`) and
5619    /// USAGE (`nextval`).
5620    pub acl: Vec<AclItem>,
5621}
5622
5623/// v7.17.0 — sequence integer width.
5624#[derive(Debug, Clone, Copy, PartialEq, Eq)]
5625pub enum SequenceDataType {
5626    SmallInt,
5627    Int,
5628    BigInt,
5629}
5630
5631/// v7.17.0 Phase 1.6 — built-in schema names that every Catalog
5632/// understands without an explicit CREATE SCHEMA. Used by
5633/// [`Catalog::schema_exists`] and the engine's schema-qualified
5634/// lookup path.
5635#[must_use]
5636pub fn is_builtin_schema(name: &str) -> bool {
5637    name.eq_ignore_ascii_case("public")
5638        || name.eq_ignore_ascii_case("pg_catalog")
5639        || name.eq_ignore_ascii_case("information_schema")
5640}
5641
5642/// v7.17.0 — parse a PG-canonical UUID text representation into the
5643/// 16-byte network-order layout used by `Value::Uuid`. Accepted input
5644/// shapes (all case-insensitive):
5645///   * Canonical hyphenated 8-4-4-4-12 (`550e8400-e29b-41d4-a716-446655440000`)
5646///   * Unhyphenated 32-char hex (`550e8400e29b41d4a716446655440000`)
5647///   * Either form wrapped in `{ ... }`
5648///
5649/// Returns `None` for any malformed input (wrong length, non-hex
5650/// characters, misplaced hyphens). The caller surfaces a SQL error
5651/// at coercion time — silent acceptance of garbage would mask
5652/// application bugs and is exactly the divergence from PG that
5653/// breaks the 0-change cutover promise.
5654#[must_use]
5655pub fn parse_uuid_str(input: &str) -> Option<[u8; 16]> {
5656    let s = input.trim();
5657    // Strip surrounding braces if present.
5658    let s = if let Some(inner) = s.strip_prefix('{').and_then(|x| x.strip_suffix('}')) {
5659        inner
5660    } else {
5661        s
5662    };
5663    // Two valid shapes after braces are stripped: 32 hex chars or
5664    // the canonical 36-char hyphenated form.
5665    let hex: String = match s.len() {
5666        32 => s.to_ascii_lowercase(),
5667        36 => {
5668            // Hyphens must be exactly at positions 8, 13, 18, 23.
5669            let b = s.as_bytes();
5670            if b[8] != b'-' || b[13] != b'-' || b[18] != b'-' || b[23] != b'-' {
5671                return None;
5672            }
5673            let mut out = String::with_capacity(32);
5674            out.push_str(&s[0..8]);
5675            out.push_str(&s[9..13]);
5676            out.push_str(&s[14..18]);
5677            out.push_str(&s[19..23]);
5678            out.push_str(&s[24..36]);
5679            out.make_ascii_lowercase();
5680            out
5681        }
5682        _ => return None,
5683    };
5684    let bytes = hex.as_bytes();
5685    let mut out = [0u8; 16];
5686    for i in 0..16 {
5687        let hi = hex_nibble(bytes[i * 2])?;
5688        let lo = hex_nibble(bytes[i * 2 + 1])?;
5689        out[i] = (hi << 4) | lo;
5690    }
5691    Some(out)
5692}
5693
5694fn hex_nibble(b: u8) -> Option<u8> {
5695    match b {
5696        b'0'..=b'9' => Some(b - b'0'),
5697        b'a'..=b'f' => Some(10 + b - b'a'),
5698        b'A'..=b'F' => Some(10 + b - b'A'),
5699        _ => None,
5700    }
5701}
5702
5703/// v7.17.0 — render a `Value::Uuid` payload as the canonical
5704/// lowercase 8-4-4-4-12 hyphenated form PG `text` cast surfaces.
5705#[must_use]
5706pub fn format_uuid(b: &[u8; 16]) -> String {
5707    const HEX: &[u8; 16] = b"0123456789abcdef";
5708    let mut out = String::with_capacity(36);
5709    for (i, byte) in b.iter().enumerate() {
5710        if matches!(i, 4 | 6 | 8 | 10) {
5711            out.push('-');
5712        }
5713        out.push(HEX[(byte >> 4) as usize] as char);
5714        out.push(HEX[(byte & 0x0f) as usize] as char);
5715    }
5716    out
5717}
5718
5719/// v7.17.0 Phase 1.5 — catalogued user-defined DOMAIN. A domain
5720/// is a named CHECK-constrained alias over a built-in type;
5721/// columns bound to it inherit the base type plus the CHECK
5722/// predicates + NOT NULL + DEFAULT at INSERT/UPDATE time.
5723/// v7.37.17 (Phase E RC rebase) — the write-set one writer version left
5724/// on a table, addressed by stable [`row_header::RowId`]s so it can be
5725/// replayed onto a fresher clone of the relation whose physical slots
5726/// differ. Produced by [`Table::extract_tx_writeset`], consumed by
5727/// [`Table::replay_tx_writeset`].
5728#[derive(Debug, Clone, Default)]
5729pub struct TxWriteSet {
5730    /// INSERTs and UPDATE-new-versions (`header.xmin == v`).
5731    pub inserted: Vec<(row_header::RowId, Row<'static>)>,
5732    /// DELETE / UPDATE-old-version targets (`header.xmax == v`).
5733    pub tombstoned: Vec<row_header::RowId>,
5734}
5735
5736impl TxWriteSet {
5737    #[must_use]
5738    pub fn is_empty(&self) -> bool {
5739        self.inserted.is_empty() && self.tombstoned.is_empty()
5740    }
5741}
5742
5743/// v7.39 (round 260) — one named CHECK on a domain. PG auto-names an
5744/// unnamed one `<domain>_check`, then `_check1`, `_check2`, … (probed).
5745#[derive(Debug, Clone, PartialEq, Eq)]
5746pub struct DomainCheck {
5747    pub name: String,
5748    /// The predicate source, referencing the pseudo-column `VALUE`.
5749    pub expr: String,
5750}
5751
5752/// `default` / `checks` are stored as Display-form source so
5753/// `spg-storage` stays free of `spg-sql` dependency — same
5754/// pattern as FunctionDef / ViewDef.
5755#[derive(Debug, Clone, PartialEq, Eq)]
5756pub struct DomainDef {
5757    pub name: String,
5758    pub base_type: DataType,
5759    pub nullable: bool,
5760    pub default: Option<String>,
5761    /// v7.39 (round 260) — each CHECK carries its constraint NAME, so
5762    /// `ALTER DOMAIN … DROP CONSTRAINT <name>` can find it and the
5763    /// violation message can report the constraint that actually failed.
5764    /// PG's auto-naming for an unnamed check is `<domain>_check`, then
5765    /// `_check1`, `_check2`, … (probed).
5766    pub checks: Vec<DomainCheck>,
5767    /// v7.39 (round 258/259) — when this domain was declared over ANOTHER
5768    /// domain (`CREATE DOMAIN child AS parent CHECK (…)`), the parent's
5769    /// name. `base_type` is the ultimate scalar type either way, so
5770    /// without this the parent's constraints were invisible and a value
5771    /// violating them was silently accepted. PG checks the whole chain,
5772    /// base-first, and an `ALTER DOMAIN` on the parent takes effect for
5773    /// the child immediately (probed) — so the chain is walked at check
5774    /// time rather than copied at CREATE time. Catalog FILE_VERSION 74+.
5775    pub base_domain: Option<String>,
5776}
5777
5778/// v7.17.0 Phase 1.4 — catalogued user-defined ENUM type. The
5779/// label vector is order-preserving (PG enum ordering follows the
5780/// declared order). At INSERT/UPDATE on a column bound to this
5781/// enum, the engine looks up the value against `labels` and
5782/// rejects non-members.
5783#[derive(Debug, Clone, PartialEq, Eq)]
5784pub struct EnumDef {
5785    pub name: String,
5786    pub labels: Vec<String>,
5787}
5788
5789/// v7.37.42-T2 ζ-B — catalogued user-defined COMPOSITE type
5790/// (`CREATE TYPE name AS (field_name field_type, ...)`). Order
5791/// matters: PG composite literals are positional, and SPG mirrors
5792/// that. Stored as ordered `(name, DataType)` pairs to keep the
5793/// codec straightforward and to allow eventual `Value::Composite`
5794/// bodies to encode positionally. Persisted in catalog FILE_VERSION
5795/// 52+; older catalogs deserialise with an empty composite_types
5796/// map. Composite types can be used as a column type by spelling
5797/// the composite's name; the resolution from
5798/// `ColumnSchema.user_composite_type = Some(name)` happens at the
5799/// engine boundary (parallel to `user_enum_type` /
5800/// `user_domain_type`). The dense storage shape — JSON-text body
5801/// keyed by the composite's field list — keeps the codec free of
5802/// recursive `Value` bodies until the full Value::Composite arena
5803/// migration in a later phase.
5804#[derive(Debug, Clone, PartialEq, Eq)]
5805pub struct CompositeDef {
5806    pub name: String,
5807    /// Ordered `(field_name, field_type)` pairs. PG composite
5808    /// literals are positional, so order is part of the type's
5809    /// identity.
5810    pub fields: Vec<(String, DataType)>,
5811    /// v7.39 (round 264) — parallel to `fields`: the USER type name of
5812    /// each field when it is itself a composite (or another named user
5813    /// type). `DataType` has no room for one, so a nested composite
5814    /// field resolved to the parser's Text placeholder and the inner
5815    /// record stayed TEXT — `(x).inner.street` errored, `pg_typeof`
5816    /// said text, and `row_to_json` nested a string instead of an
5817    /// object. Same shape as `ColumnSchema.user_composite_type` and
5818    /// `DomainDef.base_domain`. Catalog FILE_VERSION 76+; an older
5819    /// catalog reads all-None, which is what it meant.
5820    pub field_user_types: Vec<Option<String>>,
5821}
5822
5823/// v7.17.0 Phase 1.2 — catalogued VIEW. The body is stored as the
5824/// raw source text the parser saw between `AS` and the statement
5825/// terminator; the engine re-parses on each invocation. Same
5826/// pattern as `FunctionDef` — keeps `spg-storage` free of
5827/// `spg-sql` dependency.
5828#[derive(Debug, Clone, PartialEq, Eq)]
5829pub struct ViewDef {
5830    pub name: String,
5831    /// Optional `(col, col, …)` rename list. Empty when the body's
5832    /// projected names are used directly.
5833    pub columns: Vec<String>,
5834    /// Raw SELECT source. Display-rendered at storage time so the
5835    /// catalog round-trips a deterministic form regardless of
5836    /// whitespace / comments in the original input. Re-parsed at
5837    /// SELECT-from-view time to materialise as a synthetic CTE.
5838    pub body: String,
5839    /// v7.39 (round 132) — `WITH CHECK OPTION`: 0 = none, 1 = LOCAL,
5840    /// 2 = CASCADED. A storage-local u8 (no dependency on the SQL AST).
5841    /// Persisted from FILE_VERSION 69; older catalogs read back as 0.
5842    pub check_option: u8,
5843}
5844
5845impl SequenceDataType {
5846    /// PG default min/max per AS clause.
5847    pub fn default_bounds(self, increment_positive: bool) -> (i64, i64) {
5848        match self {
5849            Self::SmallInt => {
5850                if increment_positive {
5851                    (1, i64::from(i16::MAX))
5852                } else {
5853                    (i64::from(i16::MIN), -1)
5854                }
5855            }
5856            Self::Int => {
5857                if increment_positive {
5858                    (1, i64::from(i32::MAX))
5859                } else {
5860                    (i64::from(i32::MIN), -1)
5861                }
5862            }
5863            Self::BigInt => {
5864                if increment_positive {
5865                    (1, i64::MAX)
5866                } else {
5867                    (i64::MIN, -1)
5868                }
5869            }
5870        }
5871    }
5872}
5873
5874impl Catalog {
5875    /// v7.37.15 (Phase D) — fleet-wide vacuum pass. Walks every
5876    /// user table and reclaims rows whose delete-commit version is
5877    /// older than `oldest_active_snapshot`. Returns an aggregated
5878    /// report with per-table breakdown so hosts can emit metrics.
5879    ///
5880    /// `dry_run = true` reports the work without doing it. Use it
5881    /// to estimate the cost before scheduling a real pass.
5882    pub fn vacuum_all(
5883        &mut self,
5884        oldest_active_snapshot: u64,
5885        dry_run: bool,
5886    ) -> vacuum::VacuumReport {
5887        let mut total = vacuum::VacuumReport::default();
5888        // Snapshot the table names so we don't hold an immutable
5889        // borrow during the get_mut loop.
5890        let names: Vec<String> = self
5891            .tables
5892            .iter()
5893            .map(|t| t.schema().name.clone())
5894            .collect();
5895        for name in names {
5896            let Some(t) = self.get_mut(&name) else {
5897                continue;
5898            };
5899            let r = t.vacuum(oldest_active_snapshot, dry_run);
5900            if r.rows_reclaimed > 0 {
5901                total.per_table.push((name, r.rows_reclaimed));
5902            }
5903            total.rows_reclaimed += r.rows_reclaimed;
5904            total.rows_examined += r.rows_examined;
5905        }
5906        total
5907    }
5908
5909    pub const fn new() -> Self {
5910        Self {
5911            cold_read_stats: ColdReadStats {
5912                cold_reads: core::sync::atomic::AtomicU64::new(0),
5913            },
5914            tables: Vec::new(),
5915            by_name: BTreeMap::new(),
5916            temp_prefix: None,
5917            case_insensitive_names: false,
5918            dirty_tables: alloc::collections::BTreeSet::new(),
5919            dirty_nontable: alloc::collections::BTreeSet::new(),
5920            next_rel_id: 0,
5921            cold_segments: Vec::new(),
5922            functions: BTreeMap::new(),
5923            triggers: Vec::new(),
5924            rules: Vec::new(),
5925            statistics_ext: Vec::new(),
5926            large_objects: alloc::collections::BTreeMap::new(),
5927            sequences: BTreeMap::new(),
5928            schema_acl: Vec::new(),
5929            database_acl: Vec::new(),
5930            views: BTreeMap::new(),
5931            materialized_views: BTreeMap::new(),
5932            enum_types: BTreeMap::new(),
5933            domain_types: BTreeMap::new(),
5934            comments: BTreeMap::new(),
5935            db_role_settings: BTreeMap::new(),
5936            replication_slots: BTreeMap::new(),
5937            db_collation: None,
5938            created_databases: alloc::collections::BTreeSet::new(),
5939            composite_types: BTreeMap::new(),
5940            schemas: alloc::collections::BTreeSet::new(),
5941        }
5942    }
5943
5944    /// v7.12.4 — read-only view of catalogued user-defined
5945    /// functions. Engine callers go through here to look up the
5946    /// function body before re-parsing it for invocation.
5947    pub const fn functions(&self) -> &BTreeMap<String, FunctionDef> {
5948        &self.functions
5949    }
5950
5951    /// v7.12.4 — register a new user-defined function. With
5952    /// `or_replace = false`, errors if the name is taken. The
5953    /// engine validates the body before passing it here.
5954    pub fn create_function(
5955        &mut self,
5956        def: FunctionDef,
5957        or_replace: bool,
5958    ) -> Result<(), StorageError> {
5959        // v7.39 (read01 round 62) — functions are keyed by SIGNATURE, not by
5960        // name: `f(int)` and `f(text)` are two functions, as in PG. Keying by
5961        // name alone made a second overload an "already exists" error — so a
5962        // pg_dump carrying an overload set could not restore — and, worse, a
5963        // call to one overload silently ran the other.
5964        let key = function_signature_key(&def.name, &def.args_repr);
5965        if !or_replace && self.functions.contains_key(&key) {
5966            return Err(StorageError::Corrupt(format!(
5967                "function {:?} already exists (drop or use CREATE OR REPLACE)",
5968                def.name
5969            )));
5970        }
5971        self.functions.insert(key, def);
5972        Ok(())
5973    }
5974
5975    /// v7.39 (read01 round 62) — every overload of `name`.
5976    #[must_use]
5977    pub fn functions_named(&self, name: &str) -> Vec<&FunctionDef> {
5978        self.functions
5979            .values()
5980            .filter(|f| f.name.eq_ignore_ascii_case(name))
5981            .collect()
5982    }
5983
5984    /// v7.39 (read01 round 62) — one overload, by its signature key.
5985    #[must_use]
5986    pub fn function_by_key(&self, key: &str) -> Option<&FunctionDef> {
5987        self.functions.get(key)
5988    }
5989
5990    /// v7.39 (read01 round 62) — drop ONE overload. `true` if it was there.
5991    pub fn drop_function_by_key(&mut self, key: &str) -> bool {
5992        self.functions.remove(key).is_some()
5993    }
5994
5995    /// v7.12.4 — remove a user-defined function by name. Returns
5996    /// `true` if a function was removed, `false` if none matched.
5997    /// Caller decides whether to surface `if_exists` semantics.
5998    /// v7.39 (read01 round 62) — with no signature, PG drops the function only
5999    /// when the name is unambiguous. SPG mirrors that: this removes EVERY
6000    /// overload of `name`, and the caller (ddl.rs) refuses the ambiguous case
6001    /// before getting here.
6002    pub fn drop_function(&mut self, name: &str) -> bool {
6003        let keys: Vec<String> = self
6004            .functions
6005            .iter()
6006            .filter(|(_, f)| f.name.eq_ignore_ascii_case(name))
6007            .map(|(k, _)| k.clone())
6008            .collect();
6009        let hit = !keys.is_empty();
6010        for k in keys {
6011            self.functions.remove(&k);
6012        }
6013        hit
6014    }
6015
6016    /// v7.17.0 — read-only handle to catalogued sequences.
6017    /// v7.39 (read01 round 60) — the `public` schema's ACL (PG nspacl).
6018    #[must_use]
6019    pub fn schema_acl(&self) -> &[AclItem] {
6020        &self.schema_acl
6021    }
6022
6023    pub fn schema_acl_mut(&mut self) -> &mut Vec<AclItem> {
6024        &mut self.schema_acl
6025    }
6026
6027    /// v7.39 (read01 round 60) — the database's ACL.
6028    #[must_use]
6029    pub fn database_acl(&self) -> &[AclItem] {
6030        &self.database_acl
6031    }
6032
6033    pub fn database_acl_mut(&mut self) -> &mut Vec<AclItem> {
6034        &mut self.database_acl
6035    }
6036
6037    /// v7.39 (read01 round 60) — mutable sequence access, for GRANT.
6038    /// v7.39 (round 469) — resolves the session's temporary sequence
6039    /// first, like its read-only twin. `nextval` and `setval` reach the
6040    /// map through here, so a temporary sequence shadowing a permanent one
6041    /// advances the temporary one — measured against PG18, where the
6042    /// permanent sequence's counter is untouched while the temp exists.
6043    pub fn sequence_mut(&mut self, name: &str) -> Option<&mut SequenceDef> {
6044        let key = self.sequence_key(name);
6045        self.sequences.get_mut(&key)
6046    }
6047
6048    /// v7.39 (read01 round 61) — mutable function access, for GRANT.
6049    pub fn function_mut(&mut self, name: &str) -> Option<&mut FunctionDef> {
6050        self.functions.get_mut(name)
6051    }
6052
6053    /// Every catalogued sequence, temp ones included under their mangled
6054    /// storage names. Listing code filters these through
6055    /// [`Self::listed_name`]; anything resolving ONE name by its logical
6056    /// spelling wants [`Self::sequence`] instead.
6057    pub const fn sequences_all(&self) -> &BTreeMap<String, SequenceDef> {
6058        &self.sequences
6059    }
6060
6061    /// v7.39 (round 469) — resolve one sequence by its logical name, the
6062    /// session's temporary one winning over a permanent one of the same
6063    /// name. The same rule [`Self::resolve_index`] applies to tables.
6064    #[must_use]
6065    pub fn sequence(&self, name: &str) -> Option<&SequenceDef> {
6066        if let Some(mangled) = self.temp_name_for(name)
6067            && let Some(def) = self.sequences.get(&mangled)
6068        {
6069            return Some(def);
6070        }
6071        self.sequences.get(name)
6072    }
6073
6074    /// Does a sequence of this logical name exist for this session?
6075    #[must_use]
6076    pub fn has_sequence(&self, name: &str) -> bool {
6077        self.sequence(name).is_some()
6078    }
6079
6080    /// The storage key a sequence of this logical name resolves to — the
6081    /// session's temp mangling when it has one, else the name itself.
6082    #[must_use]
6083    pub fn sequence_key(&self, name: &str) -> String {
6084        if let Some(mangled) = self.temp_name_for(name)
6085            && self.sequences.contains_key(&mangled)
6086        {
6087            return mangled;
6088        }
6089        name.into()
6090    }
6091
6092    /// v7.17.0 — register a new SEQUENCE. Errors if `name`
6093    /// collides with an existing sequence and `if_not_exists`
6094    /// is false.
6095    pub fn create_sequence(
6096        &mut self,
6097        def: SequenceDef,
6098        if_not_exists: bool,
6099    ) -> Result<(), StorageError> {
6100        if self.sequences.contains_key(&def.name) {
6101            if if_not_exists {
6102                return Ok(());
6103            }
6104            // v7.39 (read01 round 47) — a sequence is a relation to PG (42P07).
6105            return Err(StorageError::Corrupt(format!(
6106                "relation {:?} already exists",
6107                def.name
6108            )));
6109        }
6110        self.mark_nontable_dirty(NonTableKind::Sequence, &def.name);
6111        self.sequences.insert(def.name.clone(), def);
6112        Ok(())
6113    }
6114
6115    /// v7.17.0 — remove a SEQUENCE by name. Returns `true` if a
6116    /// sequence was removed, `false` if none matched. Caller
6117    /// surfaces IF EXISTS semantics.
6118    /// v7.39 (read01 round 49) — `ALTER SEQUENCE old RENAME TO new`.
6119    /// Errors when `old` is missing or `new` is taken; the SequenceDef's own
6120    /// `name` field is rewritten so it stays self-describing.
6121    pub fn rename_sequence(&mut self, old: &str, new: &str) -> Result<(), StorageError> {
6122        if !self.sequences.contains_key(old) {
6123            return Err(StorageError::Corrupt(format!(
6124                "relation {old:?} does not exist"
6125            )));
6126        }
6127        if self.sequences.contains_key(new) {
6128            return Err(StorageError::Corrupt(format!(
6129                "relation {new:?} already exists"
6130            )));
6131        }
6132        self.mark_nontable_dirty(NonTableKind::Sequence, old);
6133        self.mark_nontable_dirty(NonTableKind::Sequence, new);
6134        if let Some(mut def) = self.sequences.remove(old) {
6135            def.name = new.to_string();
6136            self.sequences.insert(new.to_string(), def);
6137        }
6138        Ok(())
6139    }
6140
6141    pub fn drop_sequence(&mut self, name: &str) -> bool {
6142        self.mark_nontable_dirty(NonTableKind::Sequence, name);
6143        self.sequences.remove(name).is_some()
6144    }
6145
6146    /// v7.17.0 — atomic nextval. Increments `last_value` per
6147    /// `increment`, returns the new value, sets `is_called`.
6148    /// Returns an error on CYCLE-less overflow.
6149    /// v7.39 (round 497) — the counter state of every sequence, for
6150    /// carrying across a commit install.
6151    ///
6152    /// A sequence's VALUE is not transactional in PG: `nextval` advances
6153    /// shared state that a rollback does not give back, because two
6154    /// sessions must never receive the same number. SPG keeps sequences in
6155    /// the catalog, and a transaction works on a catalog CLONE, so
6156    /// installing that clone at COMMIT would restore whatever the counter
6157    /// was at BEGIN. These two let the install put the live counters back.
6158    #[must_use]
6159    pub fn sequence_counters(&self) -> Vec<(String, i64, bool)> {
6160        self.sequences
6161            .iter()
6162            .map(|(k, d)| (k.clone(), d.last_value, d.is_called))
6163            .collect()
6164    }
6165
6166    /// Restore counters saved by [`Self::sequence_counters`], for the
6167    /// sequences that still exist. A sequence the transaction CREATED is
6168    /// absent from the saved set and keeps the value it was given.
6169    pub fn restore_sequence_counters(&mut self, saved: &[(String, i64, bool)]) {
6170        for (k, last, called) in saved {
6171            if let Some(d) = self.sequences.get_mut(k) {
6172                d.last_value = *last;
6173                d.is_called = *called;
6174            }
6175        }
6176    }
6177
6178    pub fn sequence_next_value(&mut self, name: &str) -> Result<i64, StorageError> {
6179        let key = self.sequence_key(name);
6180        let Some(seq) = self.sequences.get_mut(&key) else {
6181            return Err(StorageError::TableNotFound { name: name.into() });
6182        };
6183        // PG semantics: when !is_called (fresh sequence or
6184        // setval(_, false)), the next nextval returns the stored
6185        // `last_value`. When is_called, it advances by `increment`
6186        // and CYCLE-wraps on overflow.
6187        let candidate = if seq.is_called {
6188            let next = seq.last_value.checked_add(seq.increment).ok_or_else(|| {
6189                StorageError::Corrupt(format!("sequence {name:?} arithmetic overflow"))
6190            })?;
6191            if seq.increment > 0 {
6192                if next > seq.max_value {
6193                    if seq.cycle {
6194                        seq.min_value
6195                    } else {
6196                        // v7.39 (round 220) — PG's 2200H wording, not a
6197                        // Corrupt-classed error.
6198                        return Err(StorageError::SequenceExhausted {
6199                            name: name.into(),
6200                            limit: seq.max_value,
6201                            is_max: true,
6202                        });
6203                    }
6204                } else {
6205                    next
6206                }
6207            } else if next < seq.min_value {
6208                if seq.cycle {
6209                    seq.max_value
6210                } else {
6211                    return Err(StorageError::SequenceExhausted {
6212                        name: name.into(),
6213                        limit: seq.min_value,
6214                        is_max: false,
6215                    });
6216                }
6217            } else {
6218                next
6219            }
6220        } else {
6221            seq.last_value
6222        };
6223        seq.last_value = candidate;
6224        seq.is_called = true;
6225        Ok(candidate)
6226    }
6227
6228    /// v7.17.0 — currval. Errors if the session has never called
6229    /// nextval on this sequence (PG semantics). At the catalog
6230    /// level we approximate "session" with "is_called persisted";
6231    /// the engine session-tracking layer can wrap this for the
6232    /// strict per-session semantics later.
6233    pub fn sequence_current_value(&self, name: &str) -> Result<i64, StorageError> {
6234        let Some(seq) = self.sequences.get(name) else {
6235            return Err(StorageError::TableNotFound { name: name.into() });
6236        };
6237        if !seq.is_called {
6238            return Err(StorageError::Corrupt(format!(
6239                "currval of sequence {name:?} is not yet defined in this session"
6240            )));
6241        }
6242        Ok(seq.last_value)
6243    }
6244
6245    /// v7.17.0 — setval(name, value [, is_called]). PG returns
6246    /// `value` regardless. `is_called=true` means the NEXT
6247    /// nextval will return `value + increment`; `is_called=false`
6248    /// means the next nextval will return `value`.
6249    pub fn sequence_set_value(
6250        &mut self,
6251        name: &str,
6252        value: i64,
6253        is_called: bool,
6254    ) -> Result<i64, StorageError> {
6255        let key = self.sequence_key(name);
6256        let Some(seq) = self.sequences.get_mut(&key) else {
6257            return Err(StorageError::TableNotFound { name: name.into() });
6258        };
6259        // v7.39 (round 244) — PG refuses a value outside the sequence's
6260        // range (22003); SPG accepted it silently, leaving last_value out
6261        // of bounds.
6262        if value < seq.min_value || value > seq.max_value {
6263            return Err(StorageError::Unsupported(format!(
6264                "setval: value {value} is out of bounds for sequence \"{name}\" ({}..{})",
6265                seq.min_value, seq.max_value
6266            )));
6267        }
6268        seq.last_value = value;
6269        seq.is_called = is_called;
6270        Ok(value)
6271    }
6272
6273    /// v7.17.0 Phase 1.2 — read-only handle to catalogued views. Temp ones
6274    /// are in here under their mangled storage names; listing code filters
6275    /// through [`Self::listed_name`], and anything resolving ONE name by
6276    /// its logical spelling wants [`Self::view`].
6277    pub const fn views_all(&self) -> &BTreeMap<String, ViewDef> {
6278        &self.views
6279    }
6280
6281    /// v7.39 (round 469) — resolve one view by its logical name, the
6282    /// session's temporary one winning over a permanent one of the same
6283    /// name.
6284    #[must_use]
6285    pub fn view(&self, name: &str) -> Option<&ViewDef> {
6286        if let Some(mangled) = self.temp_name_for(name)
6287            && let Some(def) = self.views.get(&mangled)
6288        {
6289            return Some(def);
6290        }
6291        self.views.get(name)
6292    }
6293
6294    /// Does a view of this logical name exist for this session?
6295    #[must_use]
6296    pub fn has_view(&self, name: &str) -> bool {
6297        self.view(name).is_some()
6298    }
6299
6300    /// The storage key a view of this logical name resolves to.
6301    #[must_use]
6302    pub fn view_key(&self, name: &str) -> String {
6303        if let Some(mangled) = self.temp_name_for(name)
6304            && self.views.contains_key(&mangled)
6305        {
6306            return mangled;
6307        }
6308        name.into()
6309    }
6310
6311    /// v7.17.0 Phase 1.2 — install a VIEW. `or_replace=true`
6312    /// overwrites an existing entry; `if_not_exists=true` is a
6313    /// silent no-op when the name is taken. Errors if both flags
6314    /// are off and the name collides.
6315    pub fn create_view(
6316        &mut self,
6317        def: ViewDef,
6318        or_replace: bool,
6319        if_not_exists: bool,
6320    ) -> Result<(), StorageError> {
6321        if self.views.contains_key(&def.name) {
6322            if or_replace {
6323                self.mark_nontable_dirty(NonTableKind::View, &def.name);
6324                self.mark_nontable_dirty(NonTableKind::View, &def.name);
6325                self.views.insert(def.name.clone(), def);
6326                return Ok(());
6327            }
6328            if if_not_exists {
6329                return Ok(());
6330            }
6331            // v7.39 (read01 round 47) — a view is a relation to PG (42P07).
6332            return Err(StorageError::Corrupt(format!(
6333                "relation {:?} already exists",
6334                def.name
6335            )));
6336        }
6337        // Reject name collision with tables / sequences — same
6338        // namespace per PG.
6339        if self.by_name.contains_key(&def.name) {
6340            return Err(StorageError::Corrupt(format!(
6341                "view {:?} would shadow an existing table",
6342                def.name
6343            )));
6344        }
6345        if self.sequences.contains_key(&def.name) {
6346            return Err(StorageError::Corrupt(format!(
6347                "view {:?} would shadow an existing sequence",
6348                def.name
6349            )));
6350        }
6351        self.views.insert(def.name.clone(), def);
6352        Ok(())
6353    }
6354
6355    /// v7.17.0 Phase 1.2 — remove a view by name. Returns true if
6356    /// a view was removed.
6357    pub fn drop_view(&mut self, name: &str) -> bool {
6358        self.mark_nontable_dirty(NonTableKind::View, name);
6359        self.views.remove(name).is_some()
6360    }
6361
6362    /// v7.17.0 Phase 1.3 — read-only handle to the materialised-
6363    /// view source registry. Each entry pairs with a regular
6364    /// table of the same name that holds the cached rows.
6365    pub const fn materialized_views(&self) -> &BTreeMap<String, String> {
6366        &self.materialized_views
6367    }
6368
6369    /// v7.17.0 Phase 1.3 — register a source for a materialised
6370    /// view. Caller has already created the backing table.
6371    pub fn register_materialized_view(&mut self, name: String, body: String) {
6372        self.mark_nontable_dirty(NonTableKind::MaterializedView, &name);
6373        self.materialized_views.insert(name, body);
6374    }
6375
6376    /// v7.17.0 Phase 1.3 — drop the source registry entry. Returns
6377    /// true if a source was unregistered. Caller separately drops
6378    /// the backing table.
6379    pub fn drop_materialized_view_source(&mut self, name: &str) -> bool {
6380        self.mark_nontable_dirty(NonTableKind::MaterializedView, name);
6381        self.materialized_views.remove(name).is_some()
6382    }
6383
6384    /// v7.17.0 Phase 1.4 — read-only handle to user-defined ENUM
6385    /// catalog.
6386    pub const fn enum_types(&self) -> &BTreeMap<String, EnumDef> {
6387        &self.enum_types
6388    }
6389
6390    /// v7.17.0 Phase 1.4 — install a new ENUM type. Errors if
6391    /// `name` collides with an existing enum (no IF NOT EXISTS
6392    /// per PG semantics for CREATE TYPE).
6393    pub fn create_enum_type(&mut self, def: EnumDef) -> Result<(), StorageError> {
6394        if self.enum_types.contains_key(&def.name) {
6395            return Err(StorageError::Corrupt(format!(
6396                "type {:?} already exists",
6397                def.name
6398            )));
6399        }
6400        self.mark_nontable_dirty(NonTableKind::EnumType, &def.name);
6401        self.enum_types.insert(def.name.clone(), def);
6402        Ok(())
6403    }
6404
6405    /// v7.17.0 Phase 1.4 — drop an ENUM type by name. Returns
6406    /// true if a type was removed.
6407    /// v7.37 D.55 — `ALTER TYPE … ADD VALUE`. Appends `label` to an existing
6408    /// enum's ordered label list, or inserts it before/after an existing label.
6409    /// `if_not_exists` makes a duplicate a no-op; otherwise a duplicate errors.
6410    /// Returns `Ok(true)` if a label was added, `Ok(false)` if it already existed
6411    /// (only possible under `if_not_exists`).
6412    /// v7.39 (read01 round 49) — `ALTER TYPE t RENAME VALUE 'old' TO 'new'`.
6413    /// The parser used to swallow this form as a no-op, so the rename was
6414    /// accepted and silently ignored. Renaming in place keeps the label's
6415    /// sort position, which is what PG does (enumsortorder is untouched).
6416    pub fn rename_enum_value(
6417        &mut self,
6418        type_name: &str,
6419        old: &str,
6420        new: &str,
6421    ) -> Result<(), StorageError> {
6422        let def = self
6423            .enum_types
6424            .get_mut(type_name)
6425            .ok_or_else(|| StorageError::Corrupt(format!("type {type_name:?} does not exist")))?;
6426        if def.labels.iter().any(|l| l == new) {
6427            return Err(StorageError::Corrupt(format!(
6428                "enum label {new:?} already exists"
6429            )));
6430        }
6431        let at = def.labels.iter().position(|l| l == old).ok_or_else(|| {
6432            StorageError::Corrupt(format!("{old:?} is not an existing enum label"))
6433        })?;
6434        def.labels[at] = new.to_string();
6435        Ok(())
6436    }
6437
6438    /// v7.39 (read01 round 50) — set (or, with `None`, remove) the comment on
6439    /// an object. `key` is the canonical `"<kind>:<name>"` form.
6440    pub fn set_comment(&mut self, key: &str, text: Option<&str>) {
6441        match text {
6442            Some(t) => {
6443                self.comments.insert(key.to_string(), t.to_string());
6444            }
6445            None => {
6446                self.comments.remove(key);
6447            }
6448        }
6449    }
6450
6451    /// v7.39 (read01 round 50) — the comment on an object, if any.
6452    #[must_use]
6453    pub fn comment(&self, key: &str) -> Option<&str> {
6454        self.comments.get(key).map(String::as_str)
6455    }
6456
6457    /// v7.39 (round 547) — record a GUC default for a scope. An empty
6458    /// database or role name is PG's oid 0 ("all"). `None` value
6459    /// removes just that parameter, as PG's RESET does.
6460    pub fn set_db_role_setting(
6461        &mut self,
6462        database: &str,
6463        role: &str,
6464        param: &str,
6465        value: Option<&str>,
6466    ) {
6467        let key = (database.to_string(), role.to_string());
6468        match value {
6469            Some(v) => {
6470                self.db_role_settings
6471                    .entry(key)
6472                    .or_default()
6473                    .insert(param.to_ascii_lowercase(), v.to_string());
6474            }
6475            None => {
6476                if let Some(m) = self.db_role_settings.get_mut(&key) {
6477                    m.remove(&param.to_ascii_lowercase());
6478                    if m.is_empty() {
6479                        self.db_role_settings.remove(&key);
6480                    }
6481                }
6482            }
6483        }
6484    }
6485
6486    /// v7.39 (round 550) — create a replication slot. `Err` carries
6487    /// PG's own message for a duplicate.
6488    ///
6489    /// # Errors
6490    /// When a slot of that name already exists.
6491    pub fn create_replication_slot(
6492        &mut self,
6493        name: &str,
6494        plugin: &str,
6495        slot_type: &str,
6496    ) -> Result<(), String> {
6497        if self.replication_slots.contains_key(name) {
6498            return Err(alloc::format!("replication slot \"{name}\" already exists"));
6499        }
6500        self.replication_slots.insert(
6501            name.to_string(),
6502            (plugin.to_string(), slot_type.to_string()),
6503        );
6504        Ok(())
6505    }
6506
6507    /// # Errors
6508    /// When no slot of that name exists — PG's message, and the case
6509    /// that used to report success.
6510    pub fn drop_replication_slot(&mut self, name: &str) -> Result<(), String> {
6511        if self.replication_slots.remove(name).is_none() {
6512            return Err(alloc::format!("replication slot \"{name}\" does not exist"));
6513        }
6514        Ok(())
6515    }
6516
6517    #[must_use]
6518    /// v7.38.18 (S1) — the collation this database was created with.
6519    /// `"C"` when nothing was recorded, which is what an older catalog
6520    /// and a default `initdb`-less start both mean.
6521    pub fn db_collation(&self) -> &str {
6522        self.db_collation.as_deref().unwrap_or("C")
6523    }
6524
6525    /// Record the creation collation. Refused once one is set, because
6526    /// every index key already in this database was built under it —
6527    /// the same refusal PostgreSQL gives `ALTER DATABASE … LC_COLLATE`,
6528    /// and for the same reason.
6529    ///
6530    /// `Ok(false)` when the value asked for is the one already in force,
6531    /// so a host that passes its environment on every start is not an
6532    /// error.
6533    pub fn set_db_collation(&mut self, name: &str) -> Result<bool, StorageError> {
6534        if self.db_collation.as_deref() == Some(name) {
6535            return Ok(false);
6536        }
6537        if self.db_collation.is_none() && name.eq_ignore_ascii_case("C") {
6538            return Ok(false);
6539        }
6540        if self.db_collation.is_some() || !self.tables.is_empty() {
6541            return Err(StorageError::Corrupt(format!(
6542                "database collation is already {:?} and cannot be changed; \
6543                 PostgreSQL refuses this too, because every index key here \
6544                 was built under it",
6545                self.db_collation()
6546            )));
6547        }
6548        self.db_collation = Some(name.into());
6549        Ok(true)
6550    }
6551
6552    /// The user said so, in SQL: `CREATE DATABASE … LC_COLLATE 'x'`.
6553    ///
6554    /// Differs from [`Self::set_db_collation`] in one way, and the
6555    /// difference is the whole point: this REPLACES a collation the
6556    /// database already has, as long as no table has been created yet.
6557    /// The refusal in `set_db_collation` exists because index keys were
6558    /// built under the old collation — with no tables, none were.
6559    ///
6560    /// The case it is for: a server stamps the container's `LANG` on a
6561    /// fresh database at startup, and the customer's bootstrap script
6562    /// then says `CREATE DATABASE app LC_COLLATE 'de_DE.utf8'`. What the
6563    /// script asked for beats what the container happened to export.
6564    ///
6565    /// `Ok(false)` when a table already exists — the caller warns rather
6566    /// than failing, because PostgreSQL would have made a SEPARATE
6567    /// database here and returned success, and failing a bootstrap
6568    /// script is a customer change.
6569    pub fn declare_db_collation(&mut self, name: &str) -> bool {
6570        if self.db_collation.as_deref() == Some(name) {
6571            return true;
6572        }
6573        if !self.tables.is_empty() {
6574            return false;
6575        }
6576        self.db_collation = Some(name.into());
6577        true
6578    }
6579
6580    /// Record a name a `CREATE DATABASE` asked for; `true` when new.
6581    pub fn record_created_database(&mut self, name: &str) -> bool {
6582        self.created_databases.insert(name.to_string())
6583    }
6584
6585    /// The names `CREATE DATABASE` has been asked for.
6586    pub const fn created_databases(&self) -> &alloc::collections::BTreeSet<String> {
6587        &self.created_databases
6588    }
6589
6590    pub const fn replication_slots(&self) -> &BTreeMap<String, (String, String)> {
6591        &self.replication_slots
6592    }
6593
6594    /// PG's RESET ALL: drops this scope's whole entry, leaving the
6595    /// other scopes alone — measured on PG18, where `ALTER ROLE r RESET
6596    /// ALL` left the ALL, the database and the role-in-database rows.
6597    pub fn reset_db_role_settings(&mut self, database: &str, role: &str) {
6598        self.db_role_settings
6599            .remove(&(database.to_string(), role.to_string()));
6600    }
6601
6602    #[must_use]
6603    pub const fn db_role_settings(&self) -> &BTreeMap<(String, String), BTreeMap<String, String>> {
6604        &self.db_role_settings
6605    }
6606
6607    /// v7.39 (read01 round 50) — every `(key, text)` pair, for the
6608    /// pg_description view.
6609    #[must_use]
6610    pub const fn comments(&self) -> &BTreeMap<String, String> {
6611        &self.comments
6612    }
6613
6614    /// v7.39 (read01 round 50) — drop every comment whose key names `obj`
6615    /// (the object itself and, for a table, its columns). Called when the
6616    /// object is dropped so a later object of the same name doesn't inherit
6617    /// a stale comment.
6618    pub fn drop_comments_for(&mut self, kind: &str, name: &str) {
6619        let exact = alloc::format!("{kind}:{name}");
6620        let col_prefix = alloc::format!("column:{name}.");
6621        self.comments
6622            .retain(|k, _| *k != exact && !k.starts_with(&col_prefix));
6623    }
6624
6625    pub fn add_enum_value(
6626        &mut self,
6627        type_name: &str,
6628        label: &str,
6629        if_not_exists: bool,
6630        position: Option<(bool, String)>,
6631    ) -> Result<bool, StorageError> {
6632        self.mark_nontable_dirty(NonTableKind::EnumType, type_name);
6633        let def = self
6634            .enum_types
6635            .get_mut(type_name)
6636            .ok_or_else(|| StorageError::Corrupt(format!("type {type_name:?} does not exist")))?;
6637        if def.labels.iter().any(|l| l == label) {
6638            if if_not_exists {
6639                return Ok(false);
6640            }
6641            // v7.39 (read01 round 49) — PG wording (42710 at the wire).
6642            return Err(StorageError::Corrupt(format!(
6643                "enum label {label:?} already exists"
6644            )));
6645        }
6646        match position {
6647            None => def.labels.push(label.to_string()),
6648            Some((is_before, anchor)) => {
6649                let at = def
6650                    .labels
6651                    .iter()
6652                    .position(|l| l == &anchor)
6653                    .ok_or_else(|| {
6654                        StorageError::Corrupt(format!(
6655                            "enum label {anchor:?} does not exist in type {type_name:?}"
6656                        ))
6657                    })?;
6658                let idx = if is_before { at } else { at + 1 };
6659                def.labels.insert(idx, label.to_string());
6660            }
6661        }
6662        Ok(true)
6663    }
6664
6665    pub fn drop_enum_type(&mut self, name: &str) -> bool {
6666        self.mark_nontable_dirty(NonTableKind::EnumType, name);
6667        self.enum_types.remove(name).is_some()
6668    }
6669
6670    /// v7.17.0 Phase 1.5 — read-only handle to DOMAIN catalog.
6671    pub const fn domain_types(&self) -> &BTreeMap<String, DomainDef> {
6672        &self.domain_types
6673    }
6674
6675    /// v7.17.0 Phase 1.5 — install a DOMAIN. Errors on collision
6676    /// with an existing domain.
6677    pub fn create_domain_type(&mut self, def: DomainDef) -> Result<(), StorageError> {
6678        if self.domain_types.contains_key(&def.name) {
6679            return Err(StorageError::Corrupt(format!(
6680                "domain {:?} already exists",
6681                def.name
6682            )));
6683        }
6684        self.mark_nontable_dirty(NonTableKind::DomainType, &def.name);
6685        self.domain_types.insert(def.name.clone(), def);
6686        Ok(())
6687    }
6688
6689    /// v7.17.0 Phase 1.5 — drop a DOMAIN by name.
6690    pub fn drop_domain_type(&mut self, name: &str) -> bool {
6691        self.mark_nontable_dirty(NonTableKind::DomainType, name);
6692        self.domain_types.remove(name).is_some()
6693    }
6694
6695    /// v7.37.42-T2 ζ-B — read-only handle to user-defined COMPOSITE
6696    /// catalog. Used by the engine to resolve
6697    /// `ColumnSchema.user_composite_type` lookups + by
6698    /// information_schema-style introspection.
6699    pub const fn composite_types(&self) -> &BTreeMap<String, CompositeDef> {
6700        &self.composite_types
6701    }
6702
6703    /// v7.37.42-T2 ζ-B — install a new COMPOSITE type. Errors if
6704    /// `name` already exists in the composite registry (PG forbids
6705    /// IF NOT EXISTS on CREATE TYPE composite; the engine surfaces
6706    /// the collision with the existing name).
6707    pub fn create_composite_type(&mut self, def: CompositeDef) -> Result<(), StorageError> {
6708        if self.composite_types.contains_key(&def.name) {
6709            return Err(StorageError::Corrupt(format!(
6710                "type {:?} already exists",
6711                def.name
6712            )));
6713        }
6714        self.mark_nontable_dirty(NonTableKind::CompositeType, &def.name);
6715        self.composite_types.insert(def.name.clone(), def);
6716        Ok(())
6717    }
6718
6719    /// v7.37.42-T2 ζ-B — drop a COMPOSITE type by name. Returns
6720    /// true if a type was removed.
6721    pub fn drop_composite_type(&mut self, name: &str) -> bool {
6722        self.mark_nontable_dirty(NonTableKind::CompositeType, name);
6723        self.composite_types.remove(name).is_some()
6724    }
6725
6726    /// v7.17.0 Phase 1.6 — read-only handle to the user-created
6727    /// schema registry. Built-in schemas (`public`, `pg_catalog`,
6728    /// `information_schema`) are NOT included here; use
6729    /// [`schema_exists`](Self::schema_exists) for the full
6730    /// check.
6731    pub const fn user_schemas(&self) -> &alloc::collections::BTreeSet<String> {
6732        &self.schemas
6733    }
6734
6735    /// v7.17.0 Phase 1.6 — schema-name resolver. Returns true
6736    /// for built-in schemas + every user-CREATEd one. Used by
6737    /// CREATE SCHEMA collision checks and (future) by
6738    /// information_schema.schemata.
6739    pub fn schema_exists(&self, name: &str) -> bool {
6740        is_builtin_schema(name) || self.schemas.contains(name)
6741    }
6742
6743    /// v7.17.0 Phase 1.6 — register a new schema. Errors if the
6744    /// name already exists and `if_not_exists=false`. Built-in
6745    /// names cannot be redeclared.
6746    pub fn create_schema(&mut self, name: String, if_not_exists: bool) -> Result<(), StorageError> {
6747        if is_builtin_schema(&name) {
6748            if if_not_exists {
6749                return Ok(());
6750            }
6751            return Err(StorageError::Corrupt(format!(
6752                "schema {name:?} is built-in and cannot be redeclared"
6753            )));
6754        }
6755        if self.schemas.contains(&name) {
6756            if if_not_exists {
6757                return Ok(());
6758            }
6759            return Err(StorageError::Corrupt(format!(
6760                "schema {name:?} already exists"
6761            )));
6762        }
6763        self.schemas.insert(name);
6764        Ok(())
6765    }
6766
6767    /// v7.17.0 Phase 1.6 — drop a user-created schema. Returns
6768    /// true if a schema was removed. Built-in names always
6769    /// return false (cannot be dropped). Tables that previously
6770    /// used the schema as a prefix keep their bare name and stay
6771    /// queryable — this is the "prefix routing, not isolation"
6772    /// posture documented in v7.17 Phase 1.6.
6773    pub fn drop_schema(&mut self, name: &str) -> Result<bool, StorageError> {
6774        if is_builtin_schema(name) {
6775            return Err(StorageError::Corrupt(format!(
6776                "schema {name:?} is built-in and cannot be dropped"
6777            )));
6778        }
6779        Ok(self.schemas.remove(name))
6780    }
6781
6782    /// v7.17.0 — ALTER SEQUENCE option merge. Caller-provided
6783    /// updates overwrite the matching fields; unset fields keep
6784    /// their stored values. RESTART variants update last_value
6785    /// directly per PG: `RESTART` resets to current `start`;
6786    /// `RESTART WITH n` resets to `n`.
6787    #[allow(clippy::too_many_arguments)]
6788    pub fn alter_sequence(
6789        &mut self,
6790        name: &str,
6791        increment: Option<i64>,
6792        min_value: Option<i64>,
6793        max_value: Option<i64>,
6794        start: Option<i64>,
6795        restart: Option<Option<i64>>,
6796        cache: Option<i64>,
6797        cycle: Option<bool>,
6798        owned_by: Option<Option<(String, String)>>,
6799    ) -> Result<(), StorageError> {
6800        self.mark_nontable_dirty(NonTableKind::Sequence, name);
6801        let Some(seq) = self.sequences.get_mut(name) else {
6802            return Err(StorageError::TableNotFound { name: name.into() });
6803        };
6804        if let Some(v) = increment {
6805            seq.increment = v;
6806        }
6807        if let Some(v) = min_value {
6808            seq.min_value = v;
6809        }
6810        if let Some(v) = max_value {
6811            seq.max_value = v;
6812        }
6813        if let Some(v) = start {
6814            seq.start = v;
6815        }
6816        if let Some(restart_value) = restart {
6817            seq.last_value = restart_value.unwrap_or(seq.start);
6818            seq.is_called = false;
6819        }
6820        if let Some(v) = cache {
6821            seq.cache = v;
6822        }
6823        if let Some(v) = cycle {
6824            seq.cycle = v;
6825        }
6826        if let Some(v) = owned_by {
6827            seq.owned_by = v;
6828        }
6829        Ok(())
6830    }
6831
6832    /// v7.12.4 — read-only slice of all catalogued triggers.
6833    /// Engine row-write paths filter this by (table, event,
6834    /// timing) and fire matches in slice order.
6835    pub fn triggers(&self) -> &[TriggerDef] {
6836        &self.triggers
6837    }
6838
6839    /// v7.15.0 — mutable handle to the trigger slice for
6840    /// `ALTER TABLE … RENAME COLUMN`, which rewrites every
6841    /// `update_columns` entry that referenced the renamed
6842    /// column.
6843    pub fn triggers_mut(&mut self) -> &mut Vec<TriggerDef> {
6844        &mut self.triggers
6845    }
6846
6847    /// v7.12.4 — register a new trigger. With `or_replace = false`,
6848    /// errors when a trigger with the same name already exists on
6849    /// the same table (PG scoping rule — trigger names are
6850    /// per-table, not global). Trigger function must already
6851    /// exist in the catalog at registration time.
6852    pub fn create_trigger(
6853        &mut self,
6854        def: TriggerDef,
6855        or_replace: bool,
6856    ) -> Result<(), StorageError> {
6857        // v7.39 (round 137) — a trigger may target a base table (BEFORE / AFTER)
6858        // or a view (INSTEAD OF). The engine enforces the timing↔target rule;
6859        // storage only requires the relation to exist as one or the other.
6860        if !self.by_name.contains_key(&def.table) && !self.views.contains_key(&def.table) {
6861            return Err(StorageError::TableNotFound {
6862                name: def.table.clone(),
6863            });
6864        }
6865        // v7.39 (read01 round 62) — functions are keyed by SIGNATURE now. A
6866        // trigger names its function by NAME (a trigger function takes no
6867        // arguments), so the existence check goes through the name index.
6868        if self.functions_named(&def.function).is_empty() {
6869            // v7.39 (round 710) — PG's wording: the FUNCTION is what does
6870            // not exist (`function nosuch_fn() does not exist`), and the
6871            // old message rode `Corrupt`'s on-disk banner besides.
6872            return Err(StorageError::Corrupt(format!(
6873                "function {}() does not exist",
6874                def.function
6875            )));
6876        }
6877        let dup = self
6878            .triggers
6879            .iter()
6880            .position(|t| t.name == def.name && t.table == def.table);
6881        match (dup, or_replace) {
6882            (Some(_), false) => Err(StorageError::Corrupt(format!(
6883                "trigger {:?} already exists on table {:?}",
6884                def.name, def.table
6885            ))),
6886            (Some(i), true) => {
6887                self.triggers[i] = def;
6888                Ok(())
6889            }
6890            (None, _) => {
6891                self.triggers.push(def);
6892                Ok(())
6893            }
6894        }
6895    }
6896
6897    /// v7.12.4 — remove a trigger by `(name, table)`. Returns
6898    /// `true` if one was removed.
6899    pub fn drop_trigger(&mut self, name: &str, table: &str) -> bool {
6900        let before = self.triggers.len();
6901        self.triggers
6902            .retain(|t| !(t.name == name && t.table == table));
6903        before != self.triggers.len()
6904    }
6905
6906    /// v7.39 (round 139) — the catalogued query-rewrite RULEs.
6907    pub fn rules(&self) -> &[RuleDef] {
6908        &self.rules
6909    }
6910
6911    /// v7.39 (round 280) — the catalogued extended-statistics objects.
6912    #[must_use]
6913    pub fn statistics_ext(&self) -> &[StatisticsExtDef] {
6914        &self.statistics_ext
6915    }
6916
6917    /// v7.39 (round 287) — every large object, ascending by OID.
6918    #[must_use]
6919    pub fn large_objects(&self) -> &alloc::collections::BTreeMap<u32, Vec<u8>> {
6920        &self.large_objects
6921    }
6922
6923    /// The bytes of one large object, or `None` when no such OID exists.
6924    #[must_use]
6925    pub fn large_object(&self, oid: u32) -> Option<&[u8]> {
6926        self.large_objects.get(&oid).map(Vec::as_slice)
6927    }
6928
6929    /// Create a large object. `oid` of 0 means "pick one" — PG's
6930    /// `lo_create(0)` / `lo_creat(-1)` spelling. Errors when the
6931    /// requested OID is taken.
6932    pub fn create_large_object(&mut self, oid: u32, bytes: Vec<u8>) -> Result<u32, String> {
6933        let id = if oid == 0 {
6934            self.next_large_object_oid()
6935        } else {
6936            oid
6937        };
6938        if self.large_objects.contains_key(&id) {
6939            return Err(format!("large object {id} already exists"));
6940        }
6941        self.large_objects.insert(id, bytes);
6942        Ok(id)
6943    }
6944
6945    /// Overwrite `len` bytes at `offset` (0-based), growing the object
6946    /// with zero bytes if the write starts past the end — PG's
6947    /// `lo_put` semantics.
6948    pub fn put_large_object(&mut self, oid: u32, offset: usize, data: &[u8]) -> Result<(), String> {
6949        let Some(buf) = self.large_objects.get_mut(&oid) else {
6950            return Err(format!("large object {oid} does not exist"));
6951        };
6952        let end = offset.saturating_add(data.len());
6953        if buf.len() < end {
6954            buf.resize(end, 0);
6955        }
6956        buf[offset..end].copy_from_slice(data);
6957        Ok(())
6958    }
6959
6960    /// v7.39 (round 306) — `lo_truncate`. PG's truncate sets the object
6961    /// to exactly `len` bytes in BOTH directions: it shortens, and it
6962    /// GROWS with zero fill when `len` exceeds the current size
6963    /// (measured — `lo_truncate(fd, 8)` over a 4-byte object leaves
6964    /// eight bytes, the last four zero).
6965    pub fn truncate_large_object(&mut self, oid: u32, len: usize) -> Result<(), String> {
6966        let Some(buf) = self.large_objects.get_mut(&oid) else {
6967            return Err(format!("large object {oid} does not exist"));
6968        };
6969        buf.resize(len, 0);
6970        Ok(())
6971    }
6972
6973    /// Remove a large object. `false` when the OID was not there.
6974    pub fn unlink_large_object(&mut self, oid: u32) -> bool {
6975        self.large_objects.remove(&oid).is_some()
6976    }
6977
6978    /// The next free OID in PG's user band.
6979    /// v7.39 (round 343, V40) — large objects have their own oid band.
6980    /// It used to start at 16_384, which is where user TABLES start, so
6981    /// the first large object and the first table shared an oid — and
6982    /// `pg_largeobject_metadata.oid` is joinable against `pg_class.oid`,
6983    /// so a join across them matched a row that has nothing to do with
6984    /// it. (PG cannot collide: every oid there comes off one counter.)
6985    /// An object already stored keeps the oid it was given; only new
6986    /// ones land in the band.
6987    fn next_large_object_oid(&self) -> u32 {
6988        self.large_objects
6989            .keys()
6990            .next_back()
6991            .map_or(500_000, |m| m.saturating_add(1))
6992    }
6993
6994    /// Register one. `Err(name)` when the name is taken.
6995    pub fn create_statistics_ext(&mut self, def: StatisticsExtDef) -> Result<(), String> {
6996        if self.statistics_ext.iter().any(|s| s.name == def.name) {
6997            return Err(def.name);
6998        }
6999        self.statistics_ext.push(def);
7000        Ok(())
7001    }
7002
7003    /// Drop one by name; false when absent.
7004    pub fn drop_statistics_ext(&mut self, name: &str) -> bool {
7005        let before = self.statistics_ext.len();
7006        self.statistics_ext.retain(|s| s.name != name);
7007        before != self.statistics_ext.len()
7008    }
7009
7010    /// v7.39 (round 139) — register a RULE. Its target relation (table or view)
7011    /// must exist; `or_replace` overwrites a same-(name,table) rule.
7012    pub fn create_rule(&mut self, def: RuleDef, or_replace: bool) -> Result<(), StorageError> {
7013        if !self.by_name.contains_key(&def.table) && !self.views.contains_key(&def.table) {
7014            return Err(StorageError::TableNotFound {
7015                name: def.table.clone(),
7016            });
7017        }
7018        let dup = self
7019            .rules
7020            .iter()
7021            .position(|r| r.name == def.name && r.table == def.table);
7022        match (dup, or_replace) {
7023            (Some(_), false) => Err(StorageError::Corrupt(format!(
7024                "rule {:?} for relation {:?} already exists",
7025                def.name, def.table
7026            ))),
7027            (Some(i), true) => {
7028                self.rules[i] = def;
7029                Ok(())
7030            }
7031            (None, _) => {
7032                self.rules.push(def);
7033                Ok(())
7034            }
7035        }
7036    }
7037
7038    /// v7.39 (round 139) — drop a RULE by `(name, table)`.
7039    pub fn drop_rule(&mut self, name: &str, table: &str) -> bool {
7040        let before = self.rules.len();
7041        self.rules.retain(|r| !(r.name == name && r.table == table));
7042        before != self.rules.len()
7043    }
7044
7045    pub fn create_table(&mut self, schema: TableSchema) -> Result<(), StorageError> {
7046        if self.by_name.contains_key(&schema.name) {
7047            return Err(StorageError::DuplicateTable {
7048                name: schema.name.clone(),
7049            });
7050        }
7051        let idx = self.tables.len();
7052        let name = schema.name.clone();
7053        let mut t = Table::new(schema);
7054        // v7.38.18 (S2) — the table inherits the database's collation,
7055        // which is what its undeclared text columns compare under.
7056        t.set_db_collation(self.db_collation());
7057        self.tables.push(t);
7058        self.by_name.insert(name.clone(), idx);
7059        // v7.39 (round 496) — see `dirty_tables`.
7060        self.dirty_tables.insert(name);
7061        // v7.37.15 (Phase C.1) — stamp the new relation with a stable,
7062        // monotonic, never-reused RelId. Pre-increment so ids start at
7063        // 1 (0 = UNASSIGNED); a later DROP TABLE frees the slot but not
7064        // the id.
7065        self.next_rel_id += 1;
7066        let rid = row_header::RelId(self.next_rel_id);
7067        self.tables[idx].set_rel_id(rid);
7068        Ok(())
7069    }
7070
7071    /// v7.39 (round 436) — the session's temporary table of this name wins
7072    /// over a permanent one, as `pg_temp` does in PG's search path and as
7073    /// MySQL's TEMPORARY shadowing does. Every name → index resolution in
7074    /// this catalog goes through here.
7075    fn resolve_index(&self, name: &str) -> Option<usize> {
7076        if let Some(prefix) = &self.temp_prefix {
7077            let mut mangled = String::with_capacity(prefix.len() + name.len());
7078            mangled.push_str(prefix);
7079            mangled.push_str(name);
7080            if let Some(idx) = self.by_name.get(&mangled) {
7081                return Some(*idx);
7082            }
7083            if self.case_insensitive_names
7084                && let Some(idx) = self.index_ignoring_case(&mangled)
7085            {
7086                return Some(idx);
7087            }
7088        }
7089        if let Some(idx) = self.by_name.get(name) {
7090            return Some(*idx);
7091        }
7092        // v7.39.2 — a MySQL session finds the relation under any
7093        // spelling of its name.
7094        //
7095        // The lexer folds an unquoted identifier and leaves a backticked
7096        // one alone, so `CREATE TABLE MyTable` stored `mytable` while
7097        // ``SELECT 1 FROM `MyTable` `` looked for `MyTable` and found
7098        // nothing: the two spellings of one name were two tables.
7099        // `mysqldump` backticks every identifier, so a dump restored
7100        // here and an application that writes the name unquoted were
7101        // looking at different relations.
7102        //
7103        // This is MySQL's `lower_case_table_names = 1` — names compare
7104        // without case — which is what SPG has always half-done, and
7105        // what it now reports. Exact match first, so a catalog that
7106        // already holds two names differing only in case keeps
7107        // answering the way it did.
7108        //
7109        // PostgreSQL sessions never set this: `"MyTable"` and `mytable`
7110        // are two relations there, and the flag is off.
7111        if self.case_insensitive_names {
7112            return self.index_ignoring_case(name);
7113        }
7114        None
7115    }
7116
7117    /// The single relation whose name matches `name` without regard to
7118    /// case, or `None` when there is none — or more than one, which the
7119    /// exact lookup above has already failed to settle.
7120    fn index_ignoring_case(&self, name: &str) -> Option<usize> {
7121        let mut found = None;
7122        for (k, idx) in &self.by_name {
7123            if k.len() == name.len() && k.eq_ignore_ascii_case(name) {
7124                if found.is_some() {
7125                    return None;
7126                }
7127                found = Some(*idx);
7128            }
7129        }
7130        found
7131    }
7132
7133    /// v7.39.2 — does this session compare relation names without case?
7134    ///
7135    /// Per SESSION, and the catalog is shared, so the engine installs it
7136    /// the way it installs `temp_prefix`: on every session switch, into
7137    /// the main catalog and into every open transaction's shadow.
7138    pub fn set_case_insensitive_names(&mut self, on: bool) {
7139        self.case_insensitive_names = on;
7140    }
7141
7142    /// v7.39 (round 436) — install the calling session's temp namespace.
7143    /// `None` disables temp resolution entirely (a session that never made
7144    /// one pays a single `Option` check per lookup).
7145    pub fn set_temp_prefix(&mut self, prefix: Option<String>) {
7146        self.temp_prefix = prefix;
7147    }
7148
7149    /// The mangled storage name a temp table of `name` takes in this
7150    /// session, or `None` when the session has no temp namespace.
7151    #[must_use]
7152    pub fn temp_name_for(&self, name: &str) -> Option<String> {
7153        self.temp_prefix
7154            .as_ref()
7155            .map(|p| alloc::format!("{p}{name}"))
7156    }
7157
7158    pub fn get(&self, name: &str) -> Option<&Table> {
7159        let idx = self.resolve_index(name)?;
7160        self.tables.get(idx)
7161    }
7162
7163    pub fn get_mut(&mut self, name: &str) -> Option<&mut Table> {
7164        let idx = self.resolve_index(name)?;
7165        // v7.39 (round 496) — the choke point for changing a table, so the
7166        // record is taken here. Over-approximate on purpose: a caller that
7167        // takes the handle and writes nothing merely carries that table
7168        // through a commit, which is the old behaviour.
7169        let recorded = self.tables.get(idx).map(|t| t.schema().name.clone());
7170        if let Some(n) = recorded {
7171            self.dirty_tables.insert(n);
7172        }
7173        self.tables.get_mut(idx)
7174    }
7175
7176    /// v7.39 (round 496) — the tables changed through this handle since
7177    /// [`Self::clear_dirty_tables`]. See `dirty_tables`.
7178    #[must_use]
7179    pub fn dirty_tables(&self) -> &alloc::collections::BTreeSet<String> {
7180        &self.dirty_tables
7181    }
7182
7183    /// r1059 — mark one table dirty without taking its handle. The
7184    /// rebase/merge paths replace a tx's shadow with a fresh base
7185    /// clone and must carry the tx's OWN dirty window across (the
7186    /// base's set is an ever-growing history, never cleared).
7187    pub fn mark_table_dirty(&mut self, name: &str) {
7188        self.dirty_tables.insert(name.into());
7189    }
7190
7191    /// v7.39 (round 496) — start a fresh recording window. A transaction's
7192    /// shadow calls this at BEGIN so the set means "changed by this tx".
7193    /// 7.38.1 S3.1 — one window covers both records (tables and the
7194    /// non-table families).
7195    pub fn clear_dirty_tables(&mut self) {
7196        self.dirty_tables.clear();
7197        self.dirty_nontable.clear();
7198    }
7199
7200    /// 7.38.1 S3.1 (D4) — record a non-table object as changed by this
7201    /// window. Called from every create/alter/rename/drop of the six
7202    /// [`NonTableKind`] families; a rename records BOTH names.
7203    fn mark_nontable_dirty(&mut self, kind: NonTableKind, name: &str) {
7204        self.dirty_nontable.insert((kind, name.into()));
7205    }
7206
7207    /// 7.38.1 S3.1 (D4) — reconcile the six non-table families with
7208    /// `base` (the latest committed catalog): every entry this window
7209    /// did NOT touch is taken from base — existence, definition and
7210    /// absence alike — so a neighbour's CREATE / ALTER / DROP of a
7211    /// sequence, view, matview, enum, domain or composite type
7212    /// survives a poisoned transaction's COMMIT. Entries this window
7213    /// DID touch keep the shadow's version (the tx's own DDL wins its
7214    /// own objects, exactly like the dirty-table merge above it).
7215    pub fn merge_nontable_objects_from(&mut self, base: &Catalog) {
7216        use NonTableKind as K;
7217        fn merge_map<V: Clone>(
7218            kind: NonTableKind,
7219            dirty: &alloc::collections::BTreeSet<(NonTableKind, String)>,
7220            mine: &mut BTreeMap<String, V>,
7221            theirs: &BTreeMap<String, V>,
7222        ) {
7223            let names: alloc::vec::Vec<String> =
7224                mine.keys().chain(theirs.keys()).cloned().collect();
7225            for n in names {
7226                if dirty.contains(&(kind, n.clone())) {
7227                    continue;
7228                }
7229                match theirs.get(&n) {
7230                    Some(v) => {
7231                        mine.insert(n, v.clone());
7232                    }
7233                    None => {
7234                        mine.remove(&n);
7235                    }
7236                }
7237            }
7238        }
7239        let dirty = self.dirty_nontable.clone();
7240        merge_map(K::Sequence, &dirty, &mut self.sequences, &base.sequences);
7241        merge_map(K::View, &dirty, &mut self.views, &base.views);
7242        merge_map(
7243            K::MaterializedView,
7244            &dirty,
7245            &mut self.materialized_views,
7246            &base.materialized_views,
7247        );
7248        merge_map(K::EnumType, &dirty, &mut self.enum_types, &base.enum_types);
7249        merge_map(
7250            K::DomainType,
7251            &dirty,
7252            &mut self.domain_types,
7253            &base.domain_types,
7254        );
7255        merge_map(
7256            K::CompositeType,
7257            &dirty,
7258            &mut self.composite_types,
7259            &base.composite_types,
7260        );
7261    }
7262
7263    /// v7.39 (round 496) — put `table` in at `name`, replacing any table
7264    /// already there and keeping the rest of the catalog untouched.
7265    ///
7266    /// The commit-time table-granularity merge needs exactly this: take
7267    /// the latest committed catalog, then overwrite only the tables the
7268    /// transaction changed.
7269    pub fn install_table(&mut self, name: &str, table: Table) {
7270        match self.by_name.get(name).copied() {
7271            Some(idx) => self.tables[idx] = table,
7272            None => {
7273                let idx = self.tables.len();
7274                self.tables.push(table);
7275                self.by_name.insert(name.into(), idx);
7276            }
7277        }
7278        self.dirty_tables.insert(name.into());
7279    }
7280
7281    /// v7.37.42 (docker-fair SCALARSQ attack) — resolve a table name to
7282    /// its insertion-order index ONCE, so callers that need to fetch the
7283    /// same table many times (per-row PK probes in correlated scalar
7284    /// subqueries) can avoid the per-call `BTreeMap<String, usize>` string
7285    /// descent. The returned index is stable for the lifetime of the
7286    /// catalog snapshot the caller holds (same engine read guard).
7287    pub fn tables_position_of(&self, name: &str) -> Option<usize> {
7288        self.resolve_index(name)
7289    }
7290
7291    /// Direct positional fetch counterpart to [`tables_position_of`].
7292    /// `idx` must come from `tables_position_of` against the same catalog
7293    /// snapshot — out-of-range returns `None`.
7294    pub fn tables_at(&self, idx: usize) -> Option<&Table> {
7295        self.tables.get(idx)
7296    }
7297
7298    /// v7.34 (crash-recovery P0 #2) — replay a row-level redo log onto
7299    /// this catalog (the [`RowChange`] physical-redo apply primitive that
7300    /// row-level WAL recovery will use in place of statement re-execution).
7301    /// Applies each change in order via the same `Table` mutators the
7302    /// engine used — no uniqueness/FK/parse/plan: the original execution
7303    /// already validated, replay trusts and applies. Positions are
7304    /// physical and only valid when replayed from the matching checkpoint
7305    /// baseline in original order (see [`RowChange`] docs).
7306    ///
7307    /// A change naming an absent table, or whose position is out of range,
7308    /// is a corrupt/misaligned log and surfaces as an error rather than a
7309    /// silent skip.
7310    pub fn apply_redo(&mut self, changes: &[RowChange]) -> Result<(), StorageError> {
7311        // v7.37.5 (mailrs crash-recovery Ask 3) — true batched replay.
7312        // Pre-v7.37.5 each `RowChange::Delete` record ran a fresh
7313        // O(N) PersistentVec rebuild + O(N × indices × log N)
7314        // `rebuild_indices()` — 5000 records × 100k rows × 13 indices
7315        // ≈ 27 min on the mailrs prod-shape WAL.
7316        //
7317        // The strategy: group consecutive changes by table, and for
7318        // each run, compose all the row-level mutations through a
7319        // single "live" tracking vector + a per-table operation log,
7320        // then apply rows + indices ONCE at the end. The result:
7321        //  - DELETE blow-up: O(records × rows × indices × log rows)
7322        //    → O(rows × indices × log rows) — one rebuild per run.
7323        //  - Row-position semantics preserved: positions in a later
7324        //    `Delete` / `Update` record reference the layout produced
7325        //    by every earlier change; we walk the live-vector
7326        //    forward as each change is processed so positions
7327        //    translate correctly to the ORIGINAL row index space.
7328        //
7329        // For correctness, even with this batching `apply_redo`
7330        // remains in-order: a single per-table run only batches
7331        // a contiguous slice of changes targeting that table; a
7332        // mid-run change targeting a DIFFERENT table forces a
7333        // flush of the current run.
7334        let mut runs: alloc::vec::Vec<(String, alloc::vec::Vec<&RowChange>)> =
7335            alloc::vec::Vec::new();
7336        for change in changes {
7337            // v7.39 (flip crash-replay P0) — a replayed tombstone carries
7338            // the xmax the CRASHED process allocated, but this process's
7339            // version cursor restarted; without advancing it past every
7340            // replayed version, `Snapshot::visible`'s "deletion is in the
7341            // future" branch (xmax > snapshot.version) resurrects every
7342            // replayed delete. Same recovery contract as the snapshot
7343            // loader (`observe_persisted_version`, the pg_control-style
7344            // nextXid recovery).
7345            if let RowChange::Tombstone { xmax, .. } = change {
7346                row_header::observe_persisted_version(*xmax);
7347            }
7348            let table = match change {
7349                RowChange::Insert { table, .. }
7350                | RowChange::Update { table, .. }
7351                | RowChange::Delete { table, .. }
7352                | RowChange::Tombstone { table, .. } => table.clone(),
7353            };
7354            if runs.last().map(|(t, _)| t.as_str()) != Some(table.as_str()) {
7355                runs.push((table, alloc::vec::Vec::new()));
7356            }
7357            runs.last_mut().unwrap().1.push(change);
7358        }
7359        for (table_name, run) in runs {
7360            self.apply_redo_run_on_table(&table_name, &run)?;
7361        }
7362        Ok(())
7363    }
7364
7365    /// v7.37.5 — apply a contiguous slice of `RowChange`s all
7366    /// targeting the same `table_name`. Composes row mutations
7367    /// through a single live-tracking vector + a single tail
7368    /// for appended `Insert`s + a single in-place edit set for
7369    /// `Update`s, then writes the final row layout to
7370    /// `self.rows` and rebuilds indices ONCE.
7371    fn apply_redo_run_on_table(
7372        &mut self,
7373        table_name: &str,
7374        run: &[&RowChange],
7375    ) -> Result<(), StorageError> {
7376        // Look up the table once; the unchecked unwrap is safe
7377        // because the caller just resolved `table_name` for each
7378        // change.
7379        let table = self.get_mut(table_name).ok_or_else(|| {
7380            StorageError::Corrupt(alloc::format!("redo: unknown table {table_name:?}"))
7381        })?;
7382        // Live-tracking over both pre-existing rows and tail-
7383        // appended Insert rows. `live[i] = true` initially for
7384        // every existing row. Appended Inserts extend with `true`.
7385        // A `Delete` flips entries to `false` (using the position
7386        // mapping that walks live indices in order). An `Update`
7387        // edits in place — collected into an overlay map keyed by
7388        // ORIGINAL row position so later Updates win.
7389        let original_rows: alloc::vec::Vec<Row<'static>> = table.rows().iter().cloned().collect();
7390        let mut live: alloc::vec::Vec<bool> = alloc::vec![true; original_rows.len()];
7391        let mut tail: alloc::vec::Vec<Row<'static>> = alloc::vec::Vec::new();
7392        // Overlay: index into ORIGINAL row space (existing rows
7393        // 0..original_rows.len()) or into tail (offset
7394        // original_rows.len()). Map -> new values.
7395        let mut overlay: alloc::collections::BTreeMap<usize, alloc::vec::Vec<Value<'static>>> =
7396            alloc::collections::BTreeMap::new();
7397        // v7.37.15 (Epic W durable-tombstone slice) — extra bookkeeping
7398        // ONLY when this run actually carries an in-place `Tombstone`.
7399        // A tombstone keeps its row physically present but stamps `xmax`
7400        // on the header; the run finalizer `set_rows_and_rebuild_indices`
7401        // freezes every header (and reassigns ids), so we must re-stamp
7402        // in a post-pass keyed by RowId. When the run has no tombstone
7403        // (every default gate-off replay) this is all skipped and the
7404        // path below stays byte-for-byte the legacy one.
7405        let has_tomb = run.iter().any(|c| matches!(c, RowChange::Tombstone { .. }));
7406        // Ids of the pre-existing rows, snapshotted parallel to
7407        // `original_rows`, and ids of the tail rows filled from each
7408        // `Insert`'s carried `rowid`. Together they let a tombstone name
7409        // the exact row the writer stamped, independent of the ids the
7410        // finalizer will hand out. (When `!has_tomb`, both stay empty.)
7411        // v7.39 (flip crash-replay P0) — ids are tracked UNCONDITIONALLY
7412        // now: the finalizer preserves them so a later WAL record's
7413        // tombstone can still name rows this record produced.
7414        let orig_rowids: alloc::vec::Vec<row_header::RowId> =
7415            table.rowids().iter().copied().collect();
7416        // Headers snapshotted in lock-step: the finalizer preserves
7417        // them so earlier records' tombstone stamps survive.
7418        let orig_headers: alloc::vec::Vec<row_header::RowHeader> =
7419            table.headers().iter().copied().collect();
7420        let mut tail_rowids: alloc::vec::Vec<row_header::RowId> = alloc::vec::Vec::new();
7421        // (RowId, xmax) of every row this run tombstones.
7422        let mut tomb_targets: alloc::vec::Vec<(row_header::RowId, u64)> = alloc::vec::Vec::new();
7423        // Helper: given a "current" position (i.e. position in
7424        // the post-prior-deletes layout), translate to the
7425        // ABSOLUTE position in the unified live + tail space
7426        // by walking the live vector + tail. Returns None when
7427        // the position is out of range.
7428        fn translate(live: &[bool], tail_len: usize, current_pos: usize) -> Option<usize> {
7429            // Walk live[..] counting live entries until we hit
7430            // current_pos. Then if not yet matched, dip into tail.
7431            let mut seen = 0usize;
7432            for (i, &alive) in live.iter().enumerate() {
7433                if alive {
7434                    if seen == current_pos {
7435                        return Some(i);
7436                    }
7437                    seen += 1;
7438                }
7439            }
7440            // Position lives in tail. tail_len rows in the tail
7441            // are all live (we haven't deleted any tail rows in
7442            // this simplification; if we did, we'd extend `live`).
7443            let off = current_pos - seen;
7444            if off < tail_len {
7445                Some(live.len() + off)
7446            } else {
7447                None
7448            }
7449        }
7450        for change in run {
7451            match *change {
7452                RowChange::Insert { row, rowid, .. } => {
7453                    // Validate against schema before recording the
7454                    // change so a corrupt log surfaces as an error
7455                    // rather than silently mis-applying.
7456                    if row.len() != table.schema().columns.len() {
7457                        return Err(StorageError::ArityMismatch {
7458                            expected: table.schema().columns.len(),
7459                            actual: row.len(),
7460                        });
7461                    }
7462                    tail.push(row.clone());
7463                    // Keep the id lock-step with `tail` so a later
7464                    // tombstone (this run or a later WAL record) can
7465                    // find the row by the id the writer captured.
7466                    tail_rowids.push(*rowid);
7467                }
7468                RowChange::Update { pos, new_row, .. } => {
7469                    if new_row.len() != table.schema().columns.len() {
7470                        return Err(StorageError::ArityMismatch {
7471                            expected: table.schema().columns.len(),
7472                            actual: new_row.len(),
7473                        });
7474                    }
7475                    let abs = translate(&live, tail.len(), *pos).ok_or_else(|| {
7476                        StorageError::Corrupt(alloc::format!(
7477                            "redo: update_row position {pos} out of bounds in table {table_name:?}",
7478                        ))
7479                    })?;
7480                    // Tail edits are applied directly to `tail`
7481                    // (we own it); existing-row edits land in
7482                    // the overlay map keyed by original index.
7483                    if abs < live.len() {
7484                        overlay.insert(abs, new_row.clone());
7485                    } else {
7486                        tail[abs - live.len()] = Row::new(new_row.clone());
7487                    }
7488                }
7489                RowChange::Delete { positions, .. } => {
7490                    // De-dup + sort so the translate walk stays
7491                    // monotone (the second translate doesn't have
7492                    // to redo work the first one did, in principle;
7493                    // we keep it simple here and re-walk per
7494                    // position). Bounds-filter silently mirrors
7495                    // `Table::delete_rows`.
7496                    let mut sorted: alloc::vec::Vec<usize> = positions.clone();
7497                    sorted.sort_unstable();
7498                    sorted.dedup();
7499                    // Walk live[] once per Delete record to
7500                    // translate all positions in this record's
7501                    // post-prior-deletes layout to absolute
7502                    // indices. We MUST defer the live[] flip
7503                    // until after all positions are translated
7504                    // so two positions in the same record
7505                    // (e.g. [3, 7]) reference the same layout.
7506                    let mut to_flip_live: alloc::vec::Vec<usize> = alloc::vec::Vec::new();
7507                    let mut to_flip_tail: alloc::vec::Vec<usize> = alloc::vec::Vec::new();
7508                    // Two-pointer walk: live[i] scanned monotonically,
7509                    // sorted positions consumed in order.
7510                    let mut seen = 0usize;
7511                    let mut sp = sorted.iter().peekable();
7512                    for (i, &alive) in live.iter().enumerate() {
7513                        if !alive {
7514                            continue;
7515                        }
7516                        while let Some(&&p) = sp.peek() {
7517                            if seen == p {
7518                                to_flip_live.push(i);
7519                                sp.next();
7520                            } else {
7521                                break;
7522                            }
7523                        }
7524                        if sp.peek().is_none() {
7525                            break;
7526                        }
7527                        seen += 1;
7528                    }
7529                    // Remaining positions fall into the tail.
7530                    for &p in sp {
7531                        // p >= seen and refers to the (p - seen)-th
7532                        // entry in tail. Filter out-of-bounds.
7533                        let off = p - seen;
7534                        if off < tail.len() {
7535                            to_flip_tail.push(off);
7536                        }
7537                    }
7538                    for i in to_flip_live {
7539                        live[i] = false;
7540                        // Any pending overlay edit for this
7541                        // index is moot — the row is gone.
7542                        overlay.remove(&i);
7543                    }
7544                    // Tail deletes: remove in REVERSE order so
7545                    // shifting indices stay valid.
7546                    to_flip_tail.sort_unstable();
7547                    to_flip_tail.dedup();
7548                    for off in to_flip_tail.into_iter().rev() {
7549                        tail.remove(off);
7550                        {
7551                            // Keep the id vector lock-step with `tail`.
7552                            tail_rowids.remove(off);
7553                        }
7554                        // Re-key tail-relative overlay entries that
7555                        // were past `off` — in practice tail edits
7556                        // are applied directly so the overlay map
7557                        // only holds existing-row keys; nothing to
7558                        // do here.
7559                    }
7560                }
7561                RowChange::Tombstone { rowids, xmax, .. } => {
7562                    // An in-place tombstone leaves the row physically
7563                    // present — it does not touch `live` / `tail` /
7564                    // `overlay`. Record the (id, xmax) targets; the
7565                    // post-finalizer pass re-stamps `xmax` onto the
7566                    // matching row's (otherwise-frozen) header.
7567                    for rid in rowids {
7568                        tomb_targets.push((*rid, *xmax));
7569                    }
7570                }
7571            }
7572        }
7573        // Compose the final row layout: keep existing rows where
7574        // live[i] = true, applying overlay edits in place; then
7575        // append the surviving tail.
7576        let mut new_rows: PersistentVec<Row> = PersistentVec::new();
7577        let mut new_hot_bytes: u64 = 0;
7578        let schema_snapshot = table.schema().clone();
7579        // Parallel to `new_rows` (only built when `has_tomb`): the RowId
7580        // of each row in its FINAL slot, so the post-pass can map a
7581        // tombstone target id → the slot to re-stamp `xmax` on.
7582        let mut final_rowids: alloc::vec::Vec<row_header::RowId> = alloc::vec::Vec::new();
7583        let mut final_headers: alloc::vec::Vec<row_header::RowHeader> = alloc::vec::Vec::new();
7584        for (i, row) in original_rows.into_iter().enumerate() {
7585            if !live[i] {
7586                continue;
7587            }
7588            let final_row = if let Some(new_values) = overlay.remove(&i) {
7589                Row::new(new_values)
7590            } else {
7591                row
7592            };
7593            new_hot_bytes = new_hot_bytes
7594                .saturating_add(row_body_encoded_len(&final_row, &schema_snapshot) as u64);
7595            new_rows.push_mut(final_row);
7596            final_rowids.push(
7597                orig_rowids
7598                    .get(i)
7599                    .copied()
7600                    .unwrap_or(row_header::RowId::UNASSIGNED),
7601            );
7602            final_headers.push(
7603                orig_headers
7604                    .get(i)
7605                    .copied()
7606                    .unwrap_or_else(row_header::RowHeader::frozen),
7607            );
7608        }
7609        for (off, row) in tail.into_iter().enumerate() {
7610            new_hot_bytes =
7611                new_hot_bytes.saturating_add(row_body_encoded_len(&row, &schema_snapshot) as u64);
7612            new_rows.push_mut(row);
7613            final_rowids.push(
7614                tail_rowids
7615                    .get(off)
7616                    .copied()
7617                    .unwrap_or(row_header::RowId::UNASSIGNED),
7618            );
7619            final_headers.push(row_header::RowHeader::frozen());
7620        }
7621        // v7.39 (flip crash-replay P0) — id-preserving finalizer, so a
7622        // LATER WAL record's tombstone still resolves rows this record
7623        // produced (per-statement replay used to reassign ids between
7624        // records, orphaning every cross-record tombstone target).
7625        table.set_rows_and_rebuild_indices_with_rowids(
7626            new_rows,
7627            new_hot_bytes,
7628            &final_rowids,
7629            &final_headers,
7630        );
7631        // v7.37.15 (Epic W durable-tombstone slice) — header-preserving
7632        // re-stamp. `set_rows_and_rebuild_indices` above froze every
7633        // header, so any row this run tombstoned is currently all-
7634        // visible again. Re-apply the `xmax` stamp by matching the
7635        // tombstone's target RowId against the final-slot id map. This
7636        // is what makes a gate-on DELETE durable across replay without
7637        // changing the on-disk snapshot format (headers/ids are still
7638        // NOT serialised — that is the deferred V6 coupling; see below).
7639        if has_tomb && !tomb_targets.is_empty() {
7640            let mut id_to_slot: alloc::collections::BTreeMap<row_header::RowId, usize> =
7641                alloc::collections::BTreeMap::new();
7642            for (slot, rid) in final_rowids.iter().enumerate() {
7643                if *rid != row_header::RowId::UNASSIGNED {
7644                    id_to_slot.insert(*rid, slot);
7645                }
7646            }
7647            let table = self.get_mut(table_name).ok_or_else(|| {
7648                StorageError::Corrupt(alloc::format!("redo: unknown table {table_name:?}"))
7649            })?;
7650            for (rid, xmax) in &tomb_targets {
7651                match id_to_slot.get(rid) {
7652                    Some(&slot) => {
7653                        // First-deleter-wins + bounds handled inside.
7654                        let _ = table.mark_row_deleted(slot, *xmax);
7655                    }
7656                    None => {
7657                        // The target row was not produced by THIS redo
7658                        // run and its id was not in the run-start
7659                        // snapshot — the documented cross-checkpoint
7660                        // limitation: after a checkpoint restore the
7661                        // table's ids are reassigned (not yet persisted
7662                        // in the envelope), so a tombstone naming a
7663                        // pre-checkpoint row cannot be resolved by id.
7664                        // Skipping leaves the row visible (identical to
7665                        // the pre-Epic-W non-durable behaviour); it is
7666                        // never a correctness regression, only an
7667                        // unclosed durability gap the V6 envelope slice
7668                        // closes. Counted for observability.
7669                        UNRESOLVED_TOMBSTONES.fetch_add(1, core::sync::atomic::Ordering::Relaxed);
7670                    }
7671                }
7672            }
7673        }
7674        Ok(())
7675    }
7676
7677    fn table_for_redo(&mut self, name: &str) -> Result<&mut Table, StorageError> {
7678        self.get_mut(name)
7679            .ok_or_else(|| StorageError::Corrupt(alloc::format!("redo: unknown table {name:?}")))
7680    }
7681
7682    /// v7.34 (crash-recovery P0 #2) — enable row-level redo capture on
7683    /// every table (the engine calls this before a mutating statement
7684    /// when persistence is on; idempotent, keeps any in-flight capture).
7685    pub fn enable_redo_all(&mut self) {
7686        for t in &mut self.tables {
7687            t.enable_redo();
7688        }
7689    }
7690
7691    /// v7.34 — drain the row-level redo captured across all tables, in
7692    /// table order then per-table apply order, and stop capturing. The
7693    /// engine calls this after a successful mutating statement and writes
7694    /// the returned [`RowChange`]s to the WAL in place of the SQL text.
7695    pub fn drain_redo(&mut self) -> Vec<RowChange> {
7696        let mut all = Vec::new();
7697        for t in &mut self.tables {
7698            all.extend(t.take_redo());
7699        }
7700        all
7701    }
7702
7703    pub fn table_count(&self) -> usize {
7704        self.tables.len()
7705    }
7706
7707    /// v7.14.0 — remove a table by name. Returns `true` when the
7708    /// table existed (and is now gone), `false` when it didn't.
7709    /// Used by `DROP TABLE` from pg_dump / mysqldump preambles
7710    /// where the dump re-creates schema and starts with
7711    /// `DROP TABLE IF EXISTS`.
7712    pub fn drop_table(&mut self, name: &str) -> bool {
7713        // v7.39 (round 436) — resolve through the session's temp namespace
7714        // first, exactly as a read would: MariaDB's plain `DROP TABLE tmp`
7715        // drops the TEMPORARY one and leaves a permanent namesake standing
7716        // (measured). Removing by the raw name would have dropped the
7717        // permanent table out from under every other session.
7718        let key = match self.temp_prefix.as_ref() {
7719            Some(p) => {
7720                let mangled = alloc::format!("{p}{name}");
7721                if self.by_name.contains_key(&mangled) {
7722                    mangled
7723                } else {
7724                    name.into()
7725                }
7726            }
7727            None => name.into(),
7728        };
7729        let Some(idx) = self.by_name.remove(&key) else {
7730            return false;
7731        };
7732        // v7.39 (round 496) — see `dirty_tables`. Recorded under the
7733        // RESOLVED key, which is what a commit-time merge looks up.
7734        self.dirty_tables.insert(key.clone());
7735        // swap_remove invalidates the trailing index → rebuild
7736        // by_name for affected entries.
7737        self.tables.swap_remove(idx);
7738        // Re-stamp moved table's index slot in by_name.
7739        if idx < self.tables.len() {
7740            let moved_name = self.tables[idx].schema.name.clone();
7741            self.by_name.insert(moved_name, idx);
7742        }
7743        true
7744    }
7745
7746    /// v7.16.2 — rename a table (mailrs round-10 A.5). Updates
7747    /// the schema name, the catalog name → index map, and
7748    /// rewrites every reference dangling at the table name:
7749    ///   * every FK on every OTHER table whose `parent_table`
7750    ///     pointed at the old name now points at the new
7751    ///     name, so FK enforcement keeps working
7752    ///   * every trigger watching the table updates its `table`
7753    ///     field
7754    /// Returns `Ok` on success; `Err(StorageError::TableNotFound)`
7755    /// when the old name isn't in the catalog and
7756    /// `Err(StorageError::DuplicateTable)` when the new name is
7757    /// already taken.
7758    pub fn rename_table(&mut self, old: &str, new: &str) -> Result<(), StorageError> {
7759        if old == new {
7760            return Ok(());
7761        }
7762        if self.by_name.contains_key(new) {
7763            return Err(StorageError::Corrupt(format!(
7764                "rename_table: target name {new:?} already exists"
7765            )));
7766        }
7767        let idx = self
7768            .by_name
7769            .remove(old)
7770            .ok_or_else(|| StorageError::TableNotFound { name: old.into() })?;
7771        self.tables[idx].schema.name = new.to_string();
7772        self.by_name.insert(new.to_string(), idx);
7773        for t in &mut self.tables {
7774            for fk in &mut t.schema.foreign_keys {
7775                if fk.parent_table == old {
7776                    fk.parent_table = new.to_string();
7777                }
7778            }
7779        }
7780        for trig in &mut self.triggers {
7781            if trig.table == old {
7782                trig.table = new.to_string();
7783            }
7784        }
7785        Ok(())
7786    }
7787
7788    /// v7.16.2 — rename an index by name. Walks every table
7789    /// since the index lives on its owning table; updates the
7790    /// name in place. Errors with `IndexNotFound` when no
7791    /// index matches. mailrs round-10 A.5.
7792    pub fn rename_index(&mut self, old: &str, new: &str) -> Result<(), StorageError> {
7793        if old == new {
7794            return Ok(());
7795        }
7796        // Reject the new name if it already exists anywhere.
7797        for t in &self.tables {
7798            if t.indices.iter().any(|i| i.name == new) {
7799                return Err(StorageError::Corrupt(format!(
7800                    "rename_index: target name {new:?} already exists"
7801                )));
7802            }
7803        }
7804        for t in &mut self.tables {
7805            for i in &mut t.indices {
7806                if i.name == old {
7807                    i.name = new.to_string();
7808                    return Ok(());
7809                }
7810            }
7811        }
7812        Err(StorageError::IndexNotFound { name: old.into() })
7813    }
7814
7815    /// v7.14.0 — remove a named index across the catalog.
7816    /// Returns `true` when found + dropped.
7817    pub fn drop_named_index(&mut self, name: &str) -> bool {
7818        for t in &mut self.tables {
7819            let before = t.indices.len();
7820            t.indices.retain(|i| i.name != name);
7821            if t.indices.len() != before {
7822                return true;
7823            }
7824        }
7825        false
7826    }
7827
7828    /// v7.39.7 — the same drop, scoped to ONE table.
7829    ///
7830    /// MySQL keys an index name inside its table, and `DROP INDEX i ON t`
7831    /// says which. `None` means the table itself is missing, which is a
7832    /// different error from the index being missing — MySQL answers 1146
7833    /// for the first and 1091 for the second.
7834    pub fn drop_named_index_on(&mut self, table: &str, name: &str) -> Option<bool> {
7835        let t = self
7836            .tables
7837            .iter_mut()
7838            .find(|t| t.schema.name.eq_ignore_ascii_case(table))?;
7839        let before = t.indices.len();
7840        t.indices.retain(|i| i.name != name);
7841        Some(t.indices.len() != before)
7842    }
7843
7844    /// Borrow-free copy of every table's name in catalog order
7845    /// (= insertion order, matching the on-disk encoding).
7846    pub fn table_names(&self) -> Vec<String> {
7847        self.tables.iter().map(|t| t.schema.name.clone()).collect()
7848    }
7849
7850    /// v7.39 (round 436) — the marker every session's temporary-table
7851    /// namespace starts with. Public so the catalog synths can tell a
7852    /// temp table from an ordinary one without knowing the session id.
7853    pub const TEMP_NAME_MARKER: &'static str = "__spg_temp_";
7854
7855    /// v7.39 (round 437) — how a stored table name should appear to the
7856    /// CALLING session in a catalog listing (SHOW TABLES, pg_class,
7857    /// information_schema, …):
7858    ///   * an ordinary table → its own name
7859    ///   * this session's temporary table → its logical name, prefix stripped
7860    ///   * another session's temporary table → `None`, i.e. not listed
7861    ///
7862    /// Measured on both oracles: MariaDB 11 and PG 18 each list the calling
7863    /// session's own temporary tables and neither lists anybody else's.
7864    /// Round 436 stored temp tables under a prefix without teaching the
7865    /// listings about it, so the mangled names leaked to every client.
7866    #[must_use]
7867    pub fn listed_name<'a>(&self, stored: &'a str) -> Option<&'a str> {
7868        if !stored.starts_with(Self::TEMP_NAME_MARKER) {
7869            return Some(stored);
7870        }
7871        let prefix = self.temp_prefix.as_ref()?;
7872        stored.strip_prefix(prefix.as_str())
7873    }
7874
7875    /// The listing names of every table this session may see, in catalog
7876    /// order. See [`Catalog::listed_name`].
7877    #[must_use]
7878    pub fn visible_table_names(&self) -> Vec<String> {
7879        self.tables
7880            .iter()
7881            .filter_map(|t| self.listed_name(&t.schema.name).map(String::from))
7882            .collect()
7883    }
7884
7885    /// v5.1: register a cold-tier segment that already lives in
7886    /// memory (caller did the file read). Returns the
7887    /// `segment_id` that `RowLocator::Cold { segment_id, .. }`
7888    /// will reference — currently this is just the index into
7889    /// `cold_segments`, but treat it as an opaque token.
7890    ///
7891    /// Storage is `no_std`, so file I/O is the caller's
7892    /// responsibility — `spg-server` reads the file and forwards
7893    /// the bytes here. The bytes stay resident in the catalog
7894    /// for the life of the `Catalog`, parsed only once.
7895    pub fn load_segment_bytes(&mut self, bytes: Vec<u8>) -> Result<u32, StorageError> {
7896        let id = u32::try_from(self.cold_segments.len()).map_err(|_| {
7897            StorageError::Corrupt("cold segment count would exceed u32::MAX".into())
7898        })?;
7899        let seg = OwnedSegment::from_bytes(bytes)
7900            .map_err(|e| StorageError::Corrupt(format!("cold segment parse failed: {e}")))?;
7901        self.cold_segments.push(Some(Arc::new(seg)));
7902        Ok(id)
7903    }
7904
7905    /// v6.7.3 — register a cold-tier segment at a specific id. Used
7906    /// by the spg-server manifest-boot path so segments whose
7907    /// neighbouring ids were retired by compaction still get back
7908    /// the same `segment_id` they had pre-restart (the
7909    /// `RowLocator::Cold { segment_id }` baked into the BTree-index
7910    /// snapshot persists across restart and must continue to
7911    /// resolve).
7912    ///
7913    /// Pads the Vec with `None` slots up to `target_id` if needed.
7914    /// Errors when the target slot is already occupied (would
7915    /// stomp another segment), the parse fails, or `target_id`
7916    /// exceeds `u32::MAX`.
7917    pub fn load_segment_bytes_at(
7918        &mut self,
7919        target_id: u32,
7920        bytes: Vec<u8>,
7921    ) -> Result<(), StorageError> {
7922        let seg = OwnedSegment::from_bytes(bytes)
7923            .map_err(|e| StorageError::Corrupt(format!("cold segment parse failed: {e}")))?;
7924        let idx = target_id as usize;
7925        while self.cold_segments.len() <= idx {
7926            self.cold_segments.push(None);
7927        }
7928        if self.cold_segments[idx].is_some() {
7929            return Err(StorageError::Corrupt(format!(
7930                "load_segment_bytes_at: segment_id {target_id} already occupied"
7931            )));
7932        }
7933        self.cold_segments[idx] = Some(Arc::new(seg));
7934        Ok(())
7935    }
7936
7937    /// v6.7.3 — retire a cold-tier segment slot (compaction-driven).
7938    /// The physical file is the caller's concern (typically kept
7939    /// on disk until the next CHECKPOINT writes a manifest that
7940    /// no longer lists it); this just flips the in-memory slot
7941    /// to `None` so later cold lookups for `segment_id` resolve
7942    /// as "unknown" instead of returning a stale row.
7943    ///
7944    /// No-op when the slot is already `None`. Errors only when
7945    /// `segment_id` is out of bounds.
7946    pub fn tombstone_segment(&mut self, segment_id: u32) -> Result<(), StorageError> {
7947        let idx = segment_id as usize;
7948        if idx >= self.cold_segments.len() {
7949            return Err(StorageError::Corrupt(format!(
7950                "tombstone_segment: segment_id {segment_id} out of bounds (len={})",
7951                self.cold_segments.len()
7952            )));
7953        }
7954        self.cold_segments[idx] = None;
7955        Ok(())
7956    }
7957
7958    /// Number of *active* (non-tombstoned) cold segments.
7959    #[must_use]
7960    pub fn cold_segment_count(&self) -> usize {
7961        self.cold_segments.iter().filter(|s| s.is_some()).count()
7962    }
7963
7964    /// v7.37.42 (docker-fair SCALARSQ attack 3) — short-circuit guard
7965    /// for scan loops that conditionally walk the cold tier. Returns
7966    /// `false` when the catalog has never loaded a cold segment (or all
7967    /// segments are tombstoned), so callers can skip the per-table cold
7968    /// PK-index walk entirely on hot-only databases. O(N segments);
7969    /// typical N is small (single-digit) so the check is sub-µs.
7970    #[must_use]
7971    pub fn has_any_cold_segments(&self) -> bool {
7972        self.cold_segments.iter().any(Option::is_some)
7973    }
7974
7975    /// Slot count including tombstones (= the next id the
7976    /// no-arg `load_segment_bytes` would allocate).
7977    #[must_use]
7978    pub fn cold_segment_slot_count(&self) -> usize {
7979        self.cold_segments.len()
7980    }
7981
7982    /// v6.2.7 — list every *active* cold-tier segment id known to
7983    /// this catalog (skips compaction tombstones since v6.7.3).
7984    /// Used by EXPLAIN ANALYZE to annotate scan nodes with the
7985    /// segments they could have walked.
7986    #[must_use]
7987    pub fn cold_segment_ids_global(&self) -> Vec<u32> {
7988        self.cold_segments
7989            .iter()
7990            .enumerate()
7991            .filter_map(|(i, s)| s.as_ref().map(|_| i as u32))
7992            .collect()
7993    }
7994
7995    /// v5.2.1: sum of `Table::hot_bytes` across every table. The v5.2
7996    /// freezer compares this against `SPG_HOT_TIER_BYTES` (parsed at
7997    /// server startup; default 4 GiB) and wakes when the budget is
7998    /// crossed. Pre-freezer (v5.2.1) this is measurement-only — the
7999    /// counter exposes whether the budget is being approached without
8000    /// triggering any demotion.
8001    #[must_use]
8002    pub fn hot_tier_bytes(&self) -> u64 {
8003        self.tables
8004            .iter()
8005            .map(Table::hot_bytes)
8006            .fold(0u64, u64::saturating_add)
8007    }
8008
8009    /// v5.2.2: freeze the **first** `max_rows` rows of `table_name`'s
8010    /// hot tier into a brand-new cold-tier segment. The named `BTree`
8011    /// index supplies the per-row PK (its column must be an integer
8012    /// type — v5.2.2 only supports `IndexKey::Int` PKs, matching the
8013    /// `index_key_as_u64` constraint used by the cold-tier lookup
8014    /// path). On success returns a [`FreezeReport`] with the
8015    /// freshly-allocated segment id, the count of rows that moved,
8016    /// the encoded segment bytes (so the caller can persist them to
8017    /// disk for later reload via `SPG_PRELOAD_COLD_SEGMENT`), and the
8018    /// hot-tier byte delta that was reclaimed.
8019    ///
8020    /// **Semantics**:
8021    /// 1. The first `max_rows` rows (by hot-tier position — same as
8022    ///    insertion order under v4.39 `PersistentVec`) are read.
8023    /// 2. Rows are sorted ascending by PK and serialised into a new
8024    ///    segment via [`encode_segment`].
8025    /// 3. The hot rows are dropped via [`Table::delete_rows`]; the
8026    ///    `rebuild_indices` it triggers regenerates `Hot` locators
8027    ///    for every remaining row (their positions shift down by
8028    ///    `max_rows`). Existing `Cold` locators in this index — from
8029    ///    a previous freeze — are also rebuilt **but with empty
8030    ///    payload** since rebuild reads only `self.rows`; this
8031    ///    routine re-registers them at the end of the call so the
8032    ///    user-visible state preserves all prior cold locators.
8033    /// 4. The new segment is loaded into `self.cold_segments` via
8034    ///    [`Catalog::load_segment_bytes`] (allocating a fresh
8035    ///    `segment_id`). New `Cold` locators are registered on the
8036    ///    named index — one per frozen row.
8037    ///
8038    /// **v5.2.2 limits** (relaxed in later sub-versions):
8039    /// - INSERT-only flow: subsequent UPDATE/DELETE on a frozen row
8040    ///   returns a stale-locator error (no promote-on-write until
8041    ///   v5.2.3).
8042    /// - Single-table scope: callers iterate tables themselves.
8043    /// - All-or-nothing: returns `Err` and leaves catalog unchanged
8044    ///   if any step fails before the atomic swap point.
8045    ///
8046    /// Errors:
8047    /// - [`StorageError::Corrupt`] for missing table/index, non-`BTree`
8048    ///   index, non-integer PK column, `max_rows == 0`, or
8049    ///   `max_rows > row_count`.
8050    /// - The encoder's [`SegmentError`] surfaces as `Corrupt` (the
8051    ///   only realistic source is "a single row is larger than the
8052    ///   page size"; SPG schemas don't hit it in practice).
8053    pub fn freeze_oldest_to_cold(
8054        &mut self,
8055        table_name: &str,
8056        index_name: &str,
8057        max_rows: usize,
8058    ) -> Result<FreezeReport, StorageError> {
8059        // --- validation phase: never mutates ---------------------
8060        if max_rows == 0 {
8061            return Err(StorageError::Corrupt(
8062                "freeze_oldest_to_cold: max_rows must be > 0".into(),
8063            ));
8064        }
8065        let table = self.get(table_name).ok_or_else(|| {
8066            StorageError::Corrupt(format!(
8067                "freeze_oldest_to_cold: table {table_name:?} not found"
8068            ))
8069        })?;
8070        if max_rows > table.rows.len() {
8071            return Err(StorageError::Corrupt(format!(
8072                "freeze_oldest_to_cold: max_rows {max_rows} > row_count {}",
8073                table.rows.len()
8074            )));
8075        }
8076        let idx = table
8077            .indices
8078            .iter()
8079            .find(|i| i.name == index_name)
8080            .ok_or_else(|| {
8081                StorageError::Corrupt(format!(
8082                    "freeze_oldest_to_cold: index {index_name:?} not found on {table_name:?}"
8083                ))
8084            })?;
8085        if !matches!(idx.kind, IndexKind::BTree(_)) {
8086            return Err(StorageError::Corrupt(format!(
8087                "freeze_oldest_to_cold: index {index_name:?} is NSW; only BTree indices may freeze"
8088            )));
8089        }
8090        let column_position = idx.column_position;
8091
8092        // --- segment build phase: reads only --------------------
8093        let schema = table.schema.clone();
8094        let mut to_freeze: Vec<(u64, Vec<u8>, IndexKey)> = Vec::with_capacity(max_rows);
8095        for row_idx in 0..max_rows {
8096            let row = table.rows.get(row_idx).expect("bounds-checked above");
8097            let key = IndexKey::from_value(&row.values[column_position]).ok_or_else(|| {
8098                StorageError::Corrupt(format!(
8099                    "freeze_oldest_to_cold: row {row_idx} has NULL / non-key value in index column"
8100                ))
8101            })?;
8102            let pk_u64 = index_key_as_u64(&key).ok_or_else(|| {
8103                StorageError::Corrupt(format!(
8104                    "freeze_oldest_to_cold: index {index_name:?} column type is non-integer; \
8105                     v5.2.2 cold tier requires IndexKey::Int (Text PK lands in v5.5+)"
8106                ))
8107            })?;
8108            to_freeze.push((pk_u64, encode_row_body_dense(row, &schema), key));
8109        }
8110        // encode_segment requires ascending u64 keys. Sort by PK
8111        // before encoding; the caller's row-position order is not
8112        // necessarily PK order (e.g. workloads that insert random
8113        // PKs).
8114        to_freeze.sort_by_key(|(k, _, _)| *k);
8115        // Reject duplicate PKs — encode_segment also rejects them
8116        // (`SegmentError::UnsortedKey`), but the resulting error
8117        // message there is misleading. Surface a clearer one.
8118        for w in to_freeze.windows(2) {
8119            if w[0].0 == w[1].0 {
8120                return Err(StorageError::Corrupt(format!(
8121                    "freeze_oldest_to_cold: duplicate PK {} in freeze batch",
8122                    w[0].0
8123                )));
8124            }
8125        }
8126        // Snapshot the (key, locator) pairs that will be registered
8127        // post-swap. Cloning the IndexKey out before the move makes
8128        // the registration loop borrow-free.
8129        let post_swap_keys: Vec<IndexKey> = to_freeze.iter().map(|(_, _, k)| k.clone()).collect();
8130        // Segment encode is now infallible w.r.t. ordering. Map the
8131        // `SegmentError` into a `StorageError::Corrupt` so the
8132        // public surface stays one error type.
8133        let seg_rows: Vec<(u64, Vec<u8>)> = to_freeze
8134            .into_iter()
8135            .map(|(k, body, _)| (k, body))
8136            .collect();
8137        let frozen_rows = seg_rows.len();
8138        let (seg_bytes, _meta) = encode_segment(seg_rows.into_iter(), 0.01, SEGMENT_PAGE_BYTES)
8139            .map_err(|e| StorageError::Corrupt(format!("freeze_oldest_to_cold: encode: {e}")))?;
8140
8141        // --- atomic swap phase: mutations only past this point ---
8142        // v5.2.3 made `Table::rebuild_indices` preserve every Cold
8143        // locator across the per-table rebuild, so `delete_rows`
8144        // below no longer wipes prior-freeze cold entries. The pre-
8145        // v5.2.3 capture-then-re-register that used to live here
8146        // was removed in v5.3.1 — keeping it would double-count
8147        // every prior-frozen key's Cold locator on each subsequent
8148        // freeze.
8149        let bytes_before = self.get(table_name).expect("just validated").hot_bytes();
8150        let positions: Vec<usize> = (0..max_rows).collect();
8151        let t_mut = self
8152            .get_mut(table_name)
8153            .expect("just validated; still present");
8154        let removed = t_mut.delete_rows(&positions);
8155        debug_assert_eq!(removed, max_rows, "delete_rows count matches request");
8156        let bytes_after = t_mut.hot_bytes();
8157        let bytes_freed = bytes_before.saturating_sub(bytes_after);
8158
8159        let segment_id = self
8160            .load_segment_bytes(seg_bytes.clone())
8161            .map_err(|e| StorageError::Corrupt(format!("freeze_oldest_to_cold: load: {e}")))?;
8162        let new_cold = post_swap_keys.into_iter().map(|k| {
8163            (
8164                k,
8165                RowLocator::Cold {
8166                    segment_id,
8167                    page_offset: 0,
8168                },
8169            )
8170        });
8171        let t_mut = self.get_mut(table_name).expect("still present");
8172        t_mut.register_cold_locators(index_name, new_cold)?;
8173        // r944 — a freeze has to say that it froze something.
8174        //
8175        // `has_cold_rows_fast()` reads the cached count, and neither
8176        // freeze path touched it, so afterwards it answered "no cold
8177        // rows" while cold rows existed. That predicate gates four join
8178        // paths, and a gate that wrongly declines the cold-aware path
8179        // drops the frozen rows from the answer.
8180        //
8181        // Marking it stale rather than adding to it: stale reads as
8182        // true, which is the safe direction, and this function cannot
8183        // know the exact total (rows may already have been cold). ANALYZE
8184        // recomputes the number.
8185        t_mut.mark_cold_row_count_stale();
8186
8187        Ok(FreezeReport {
8188            segment_id,
8189            frozen_rows,
8190            bytes_freed,
8191            segment_bytes: seg_bytes,
8192        })
8193    }
8194
8195    /// v5.1: borrow the cold segment at `segment_id`. Used by the
8196    /// spg-server preload path to enumerate (key, locator) pairs
8197    /// after loading a segment, so it can call
8198    /// [`Table::register_cold_locators`] without re-parsing the
8199    /// bytes.
8200    #[must_use]
8201    pub fn cold_segment(&self, segment_id: u32) -> Option<&OwnedSegment> {
8202        self.cold_segments
8203            .get(segment_id as usize)
8204            .and_then(|s| s.as_deref())
8205    }
8206
8207    /// v5.1: resolve a single `RowLocator::Cold` to its underlying
8208    /// `Row`. Decoupled from [`Catalog::lookup_by_pk`] so callers
8209    /// iterating a multi-locator slice (e.g. the engine's index
8210    /// seek path) can dispatch per locator instead of getting back
8211    /// only the first row for a key. Returns `None` when the
8212    /// segment isn't registered, the key isn't `u64`-coercible, or
8213    /// the segment doesn't actually carry the key (bloom or page-
8214    /// index reject).
8215    pub fn resolve_cold_locator(
8216        &self,
8217        table_name: &str,
8218        segment_id: u32,
8219        key: &IndexKey,
8220    ) -> Option<Row<'static>> {
8221        let t = self.get(table_name)?;
8222        let u64_key = index_key_as_u64(key)?;
8223        let seg = self.cold_segments.get(segment_id as usize)?.as_ref()?;
8224        let payload = seg.lookup(u64_key)?;
8225        let (row, _) = decode_row_body_dense(&payload, &t.schema, seg.codec_version()).ok()?;
8226        // v7.39 (pg_stat blks knife) — one cold-tier "block read".
8227        self.cold_read_stats
8228            .cold_reads
8229            .fetch_add(1, core::sync::atomic::Ordering::Relaxed);
8230        Some(row)
8231    }
8232
8233    /// v5.1: indexed PK lookup that dispatches per locator,
8234    /// returning the first matching row from either the hot tier
8235    /// (`Table::rows`) or a registered cold segment.
8236    ///
8237    /// The cold path requires the index column to be coercible to
8238    /// a `u64` (the segment's PK type) and the segment payload to
8239    /// be a [`encode_row_body_dense`]-encoded row body for the
8240    /// same schema. v5.1 ships this for BIGINT / INT / SMALLINT
8241    /// PKs; other types fall through to hot-only behavior.
8242    ///
8243    /// Returns `None` if (a) the table or index doesn't exist,
8244    /// (b) the key isn't in the index at all, or (c) the key was
8245    /// resolved to a stale locator (Hot index out of range, Cold
8246    /// segment id unknown, segment lookup miss). Does not surface
8247    /// segment-decode errors — those would indicate corrupted
8248    /// cold-tier files and should be caught at
8249    /// [`Catalog::load_segment_bytes`] time.
8250    pub fn lookup_by_pk(&self, table: &str, index_name: &str, key: &IndexKey) -> Option<Row<'_>> {
8251        let t = self.get(table)?;
8252        let idx = t.indices.iter().find(|i| i.name == index_name)?;
8253        let locators = idx.lookup_eq(key);
8254        let cold_u64_key = index_key_as_u64(key);
8255        for loc in locators {
8256            match *loc {
8257                RowLocator::Hot(i) => {
8258                    if let Some(row) = t.rows.get(i) {
8259                        return Some(row.clone());
8260                    }
8261                }
8262                RowLocator::Cold {
8263                    segment_id,
8264                    page_offset: _,
8265                } => {
8266                    let Some(u64_key) = cold_u64_key else {
8267                        // Key type not coercible to u64 — cold tier
8268                        // only handles BIGINT/INT/SMALLINT in v5.1.
8269                        continue;
8270                    };
8271                    let Some(seg) = self
8272                        .cold_segments
8273                        .get(segment_id as usize)
8274                        .and_then(|s| s.as_deref())
8275                    else {
8276                        // v6.7.3 — `None` slot = compaction
8277                        // retired this segment; the live locator
8278                        // on a freshly-compacted index points to
8279                        // the merged segment_id, so a Cold hit
8280                        // here against a tombstone means the BTree
8281                        // entry hasn't been swapped yet (mid-
8282                        // compaction reader race) or the caller is
8283                        // looking up a stale snapshot. Skip — the
8284                        // next locator in the list, if any, is
8285                        // typically the merged segment.
8286                        continue;
8287                    };
8288                    let Some(payload) = seg.lookup(u64_key) else {
8289                        continue;
8290                    };
8291                    let (row, _) =
8292                        decode_row_body_dense(&payload, &t.schema, seg.codec_version()).ok()?;
8293                    return Some(row);
8294                }
8295            }
8296        }
8297        None
8298    }
8299
8300    /// v5.2.3: promote a frozen row back to the hot tier so an
8301    /// UPDATE / DELETE can mutate it. Reads the cold-tier row body
8302    /// (decoded from its registered segment), pushes it into
8303    /// `table.rows` via [`Table::insert`] (which also adds a fresh
8304    /// `Hot(new_idx)` locator on `index_name`), then retires the
8305    /// shadowed `Cold` locator via
8306    /// [`Table::remove_cold_locators_for_key`]. The cold-tier row
8307    /// in the segment file becomes garbage — recoverable when a
8308    /// future cold-segment compaction job lands.
8309    ///
8310    /// Returns:
8311    /// - `Ok(Some(new_hot_idx))` when the key resolved through a
8312    ///   cold locator and the promote completed. `new_hot_idx` is
8313    ///   the position the row now occupies in `table.rows`.
8314    /// - `Ok(None)` when the key has no Cold locator on the index
8315    ///   (already hot, or wasn't present at all). Callers treat this
8316    ///   as "nothing to do here, fall back to the hot-only path".
8317    ///
8318    /// Errors when the table / index doesn't exist, the index isn't
8319    /// `BTree`, the cold segment is missing / can't decode the row,
8320    /// or the inferred row body fails `Table::insert` validation.
8321    pub fn promote_cold_row(
8322        &mut self,
8323        table_name: &str,
8324        index_name: &str,
8325        key: &IndexKey,
8326    ) -> Result<Option<usize>, StorageError> {
8327        let cold_loc = self.find_cold_locator(table_name, index_name, key)?;
8328        let Some((segment_id, _page_offset)) = cold_loc else {
8329            return Ok(None);
8330        };
8331        let u64_key = index_key_as_u64(key).ok_or_else(|| {
8332            StorageError::Corrupt(
8333                "promote_cold_row: key type not coercible to u64 (cold tier requires integer PK)"
8334                    .into(),
8335            )
8336        })?;
8337        // Read the row body from the segment. Borrow the segment +
8338        // schema short-term so we can then take `&mut self` for the
8339        // hot-side insert.
8340        let schema = self
8341            .get(table_name)
8342            .ok_or_else(|| {
8343                StorageError::Corrupt(format!("promote_cold_row: table {table_name:?} not found"))
8344            })?
8345            .schema
8346            .clone();
8347        let seg = self
8348            .cold_segments
8349            .get(segment_id as usize)
8350            .and_then(|s| s.as_ref())
8351            .ok_or_else(|| {
8352                StorageError::Corrupt(format!(
8353                    "promote_cold_row: segment {segment_id} not registered on catalog"
8354                ))
8355            })?;
8356        let payload = seg.lookup(u64_key).ok_or_else(|| {
8357            StorageError::Corrupt(format!(
8358                "promote_cold_row: key {u64_key} resolves to segment {segment_id} \
8359                 but the segment's bloom/page lookup didn't return a row"
8360            ))
8361        })?;
8362        let (row, _consumed) = decode_row_body_dense(&payload, &schema, seg.codec_version())?;
8363        // Insert the promoted row into the hot tier. `Table::insert`
8364        // appends to `self.rows`, adds a `Hot(new_idx)` locator to
8365        // every BTree index covering the row's keyed columns, and
8366        // increments `hot_bytes`.
8367        let t = self
8368            .get_mut(table_name)
8369            .expect("table existed at lookup time");
8370        t.insert(row)?;
8371        let new_hot_idx =
8372            t.rows.len().checked_sub(1).ok_or_else(|| {
8373                StorageError::Corrupt("promote_cold_row: empty after insert".into())
8374            })?;
8375        // The hot insert added Hot(new_idx) alongside the still-
8376        // present Cold locator. Drop the Cold entry so future
8377        // lookups return only the fresh hot row.
8378        t.remove_cold_locators_for_key(index_name, key)?;
8379        Ok(Some(new_hot_idx))
8380    }
8381
8382    /// v5.2.3: shadow a frozen row's index entry. Used by DELETE
8383    /// when the row to remove lives in a cold-tier segment — the
8384    /// row body stays in the segment file (becoming garbage) but
8385    /// every `Cold` locator for `key` on `index_name` is removed
8386    /// so PK lookups stop returning it.
8387    ///
8388    /// Returns the number of cold locators retired (0 when the key
8389    /// has no cold entries — the DELETE fell on a hot row or a
8390    /// key that was already absent). Errors when the table /
8391    /// index doesn't exist or the index isn't `BTree`.
8392    ///
8393    /// Cold-segment compaction (which merges shadowed-heavy
8394    /// segments and reclaims their disk footprint) lands in a
8395    /// later v5.x sub-version; until then, repeated UPDATE/DELETE
8396    /// of cold rows can amplify cold-segment disk usage by up to
8397    /// 1-2× — still well under typical LSM-tree shadowing because
8398    /// SPG segments are bulk-baked, not write-merged.
8399    pub fn shadow_cold_row(
8400        &mut self,
8401        table_name: &str,
8402        index_name: &str,
8403        key: &IndexKey,
8404    ) -> Result<usize, StorageError> {
8405        let t = self.get_mut(table_name).ok_or_else(|| {
8406            StorageError::Corrupt(format!("shadow_cold_row: table {table_name:?} not found"))
8407        })?;
8408        t.remove_cold_locators_for_key(index_name, key)
8409    }
8410
8411    /// v6.7.4 — read-only slice preparation for the parallel
8412    /// freezer. Walks rows in `row_range`, builds the
8413    /// `(pk_u64, encoded_body, IndexKey)` triples that the
8414    /// coordinator's k-way merge consumes, sorts the slice by
8415    /// `pk_u64`, and returns a [`FreezeSlice`].
8416    ///
8417    /// Caller invariants:
8418    /// - `row_range.end <= table.rows.len()` (caller's job to
8419    ///   compute the partition).
8420    /// - All slices passed to `commit_freeze_slices` must cover a
8421    ///   contiguous half-open range `[0, total_max_rows)` with no
8422    ///   gaps and no overlaps. The coordinator validates this
8423    ///   invariant before committing.
8424    ///
8425    /// `&self`-only — multiple workers can run this concurrently
8426    /// against the same `Catalog` reference under the engine's
8427    /// write lock (workers don't mutate; the coordinator does).
8428    pub fn prepare_freeze_slice(
8429        &self,
8430        table_name: &str,
8431        index_name: &str,
8432        row_range: core::ops::Range<usize>,
8433    ) -> Result<FreezeSlice, StorageError> {
8434        let table = self.get(table_name).ok_or_else(|| {
8435            StorageError::Corrupt(format!(
8436                "prepare_freeze_slice: table {table_name:?} not found"
8437            ))
8438        })?;
8439        let idx = table
8440            .indices
8441            .iter()
8442            .find(|i| i.name == index_name)
8443            .ok_or_else(|| {
8444                StorageError::Corrupt(format!(
8445                    "prepare_freeze_slice: index {index_name:?} not found on {table_name:?}"
8446                ))
8447            })?;
8448        if !matches!(idx.kind, IndexKind::BTree(_)) {
8449            return Err(StorageError::Corrupt(format!(
8450                "prepare_freeze_slice: index {index_name:?} is NSW; only BTree indices may freeze"
8451            )));
8452        }
8453        if row_range.end > table.rows.len() {
8454            return Err(StorageError::Corrupt(format!(
8455                "prepare_freeze_slice: row_range end {} > row_count {}",
8456                row_range.end,
8457                table.rows.len()
8458            )));
8459        }
8460        let column_position = idx.column_position;
8461        let schema = table.schema.clone();
8462        let mut rows: Vec<(u64, Vec<u8>, IndexKey)> = Vec::with_capacity(row_range.len());
8463        for row_idx in row_range.clone() {
8464            let row = table.rows.get(row_idx).expect("bounds-checked above");
8465            let key = IndexKey::from_value(&row.values[column_position]).ok_or_else(|| {
8466                StorageError::Corrupt(format!(
8467                    "prepare_freeze_slice: row {row_idx} has NULL / non-key value in index column"
8468                ))
8469            })?;
8470            let pk_u64 = index_key_as_u64(&key).ok_or_else(|| {
8471                StorageError::Corrupt(format!(
8472                    "prepare_freeze_slice: index {index_name:?} column type is non-integer; \
8473                     v5.2.2 cold tier requires IndexKey::Int (Text PK lands in v5.5+)"
8474                ))
8475            })?;
8476            rows.push((pk_u64, encode_row_body_dense(row, &schema), key));
8477        }
8478        rows.sort_by_key(|(k, _, _)| *k);
8479        Ok(FreezeSlice { row_range, rows })
8480    }
8481
8482    /// v6.7.4 — coordinator commit step. Merges N
8483    /// [`FreezeSlice`]s into one segment via the standard
8484    /// [`encode_segment`] path, atomically swaps the catalog
8485    /// state (delete the union row range + register Cold
8486    /// locators + load the segment).
8487    ///
8488    /// Validates that the slices cover a contiguous, gap-free,
8489    /// overlap-free half-open range starting at index 0 (the
8490    /// freezer always freezes "oldest first" — same semantics as
8491    /// the single-threaded [`Catalog::freeze_oldest_to_cold`]).
8492    ///
8493    /// Empty `slices` → no-op success (returns a zero-row report
8494    /// without mutating). Total row count = `Σ slice.rows.len()`.
8495    pub fn commit_freeze_slices(
8496        &mut self,
8497        table_name: &str,
8498        index_name: &str,
8499        slices: Vec<FreezeSlice>,
8500    ) -> Result<FreezeReport, StorageError> {
8501        // --- validation phase: never mutates ---------------------
8502        let table = self.get(table_name).ok_or_else(|| {
8503            StorageError::Corrupt(format!(
8504                "commit_freeze_slices: table {table_name:?} not found"
8505            ))
8506        })?;
8507        let idx = table
8508            .indices
8509            .iter()
8510            .find(|i| i.name == index_name)
8511            .ok_or_else(|| {
8512                StorageError::Corrupt(format!(
8513                    "commit_freeze_slices: index {index_name:?} not found on {table_name:?}"
8514                ))
8515            })?;
8516        if !matches!(idx.kind, IndexKind::BTree(_)) {
8517            return Err(StorageError::Corrupt(format!(
8518                "commit_freeze_slices: index {index_name:?} is NSW; only BTree indices may freeze"
8519            )));
8520        }
8521        // Validate slice coverage: contiguous from 0, no gaps, no
8522        // overlaps. Allow the caller to pass slices in any order —
8523        // sort by row_range.start first.
8524        let mut ordered = slices;
8525        ordered.sort_by_key(|s| s.row_range.start);
8526        // Drop fully-empty slices that fell out of an uneven
8527        // partition; they carry no data but contribute to the
8528        // contiguity check, so keep them in line.
8529        let mut expected_start = 0usize;
8530        for s in &ordered {
8531            if s.row_range.start != expected_start {
8532                return Err(StorageError::Corrupt(format!(
8533                    "commit_freeze_slices: gap/overlap at row {}; expected start {}",
8534                    s.row_range.start, expected_start
8535                )));
8536            }
8537            expected_start = s.row_range.end;
8538        }
8539        let max_rows = expected_start;
8540        if max_rows > table.rows.len() {
8541            return Err(StorageError::Corrupt(format!(
8542                "commit_freeze_slices: total row range {} exceeds row_count {}",
8543                max_rows,
8544                table.rows.len()
8545            )));
8546        }
8547        if max_rows == 0 {
8548            return Ok(FreezeReport {
8549                segment_id: u32::MAX,
8550                frozen_rows: 0,
8551                bytes_freed: 0,
8552                segment_bytes: Vec::new(),
8553            });
8554        }
8555
8556        // --- segment build phase: reads only --------------------
8557        // K-way merge of already-sorted slices. Each slice's rows
8558        // are ascending by pk_u64; we keep a per-slice cursor and
8559        // pull the next-smallest head until every cursor drains.
8560        let total_rows: usize = ordered.iter().map(|s| s.rows.len()).sum();
8561        if total_rows != max_rows {
8562            return Err(StorageError::Corrupt(format!(
8563                "commit_freeze_slices: total slice rows {total_rows} ≠ row_range coverage {max_rows}"
8564            )));
8565        }
8566        let mut cursors: Vec<usize> = alloc::vec![0; ordered.len()];
8567        let mut merged: Vec<(u64, Vec<u8>, IndexKey)> = Vec::with_capacity(total_rows);
8568        loop {
8569            // Pick the slice whose head row has the smallest key
8570            // and isn't yet exhausted.
8571            let mut pick: Option<usize> = None;
8572            for (i, c) in cursors.iter().enumerate() {
8573                let slice = &ordered[i];
8574                if *c >= slice.rows.len() {
8575                    continue;
8576                }
8577                match pick {
8578                    None => pick = Some(i),
8579                    Some(j) => {
8580                        if slice.rows[*c].0 < ordered[j].rows[cursors[j]].0 {
8581                            pick = Some(i);
8582                        }
8583                    }
8584                }
8585            }
8586            let Some(i) = pick else { break };
8587            let row = ordered[i].rows[cursors[i]].clone();
8588            cursors[i] += 1;
8589            merged.push(row);
8590        }
8591        // Reject duplicate PKs — same error as the single-threaded
8592        // path so callers get a uniform surface.
8593        for w in merged.windows(2) {
8594            if w[0].0 == w[1].0 {
8595                return Err(StorageError::Corrupt(format!(
8596                    "commit_freeze_slices: duplicate PK {} across slices",
8597                    w[0].0
8598                )));
8599            }
8600        }
8601        let post_swap_keys: Vec<IndexKey> = merged.iter().map(|(_, _, k)| k.clone()).collect();
8602        let seg_rows: Vec<(u64, Vec<u8>)> =
8603            merged.into_iter().map(|(k, body, _)| (k, body)).collect();
8604        let frozen_rows = seg_rows.len();
8605        let (seg_bytes, _meta) = encode_segment(seg_rows.into_iter(), 0.01, SEGMENT_PAGE_BYTES)
8606            .map_err(|e| StorageError::Corrupt(format!("commit_freeze_slices: encode: {e}")))?;
8607
8608        // --- atomic swap phase: mutations only past this point ---
8609        let bytes_before = self.get(table_name).expect("just validated").hot_bytes();
8610        let positions: Vec<usize> = (0..max_rows).collect();
8611        let t_mut = self
8612            .get_mut(table_name)
8613            .expect("just validated; still present");
8614        let removed = t_mut.delete_rows(&positions);
8615        debug_assert_eq!(removed, max_rows, "delete_rows count matches request");
8616        let bytes_after = t_mut.hot_bytes();
8617        let bytes_freed = bytes_before.saturating_sub(bytes_after);
8618
8619        let segment_id = self
8620            .load_segment_bytes(seg_bytes.clone())
8621            .map_err(|e| StorageError::Corrupt(format!("commit_freeze_slices: load: {e}")))?;
8622        let new_cold = post_swap_keys.into_iter().map(|k| {
8623            (
8624                k,
8625                RowLocator::Cold {
8626                    segment_id,
8627                    page_offset: 0,
8628                },
8629            )
8630        });
8631        let t_mut = self.get_mut(table_name).expect("still present");
8632        t_mut.register_cold_locators(index_name, new_cold)?;
8633        // r944 — a freeze has to say that it froze something.
8634        //
8635        // `has_cold_rows_fast()` reads the cached count, and neither
8636        // freeze path touched it, so afterwards it answered "no cold
8637        // rows" while cold rows existed. That predicate gates four join
8638        // paths, and a gate that wrongly declines the cold-aware path
8639        // drops the frozen rows from the answer.
8640        //
8641        // Marking it stale rather than adding to it: stale reads as
8642        // true, which is the safe direction, and this function cannot
8643        // know the exact total (rows may already have been cold). ANALYZE
8644        // recomputes the number.
8645        t_mut.mark_cold_row_count_stale();
8646
8647        Ok(FreezeReport {
8648            segment_id,
8649            frozen_rows,
8650            bytes_freed,
8651            segment_bytes: seg_bytes,
8652        })
8653    }
8654
8655    /// v6.7.3 — compact every cold segment on `(table, index)` whose
8656    /// `OwnedSegment::bytes().len()` is below `target_segment_bytes`
8657    /// into a single larger merged segment. Rows present in source
8658    /// segment payloads but no longer referenced by any
8659    /// `RowLocator::Cold` on the index (DELETE'd + frozen rows
8660    /// retired via [`Catalog::shadow_cold_row`]) are GC'd in the
8661    /// merge.
8662    ///
8663    /// **Semantics**:
8664    /// 1. Walk the BTree index to collect every Cold locator that
8665    ///    targets a small (< threshold) segment. Each such
8666    ///    `(key, segment_id)` becomes a row in the merged segment;
8667    ///    payload is looked up from the source segment in-place.
8668    /// 2. Encode the collected rows into one new segment via
8669    ///    [`encode_segment`]; register it via
8670    ///    [`Catalog::load_segment_bytes`] (allocating a fresh
8671    ///    `merged_segment_id` at the end of `cold_segments`).
8672    /// 3. Rewrite the BTree index in one pass: every
8673    ///    `RowLocator::Cold { segment_id ∈ sources }` becomes
8674    ///    `RowLocator::Cold { segment_id = merged_id, page_offset = 0 }`.
8675    ///    Hot locators are untouched.
8676    /// 4. Tombstone every source slot via
8677    ///    [`Catalog::tombstone_segment`]. Source segment payloads
8678    ///    are no longer reachable through the catalog; the on-disk
8679    ///    files are the caller's concern.
8680    ///
8681    /// On fewer than 2 candidate segments the catalog is **not**
8682    /// mutated and a no-op report (`merged_segment_id: None`,
8683    /// `sources: []`) is returned. This is the routine case — a
8684    /// freshly-frozen table has at most 1 small segment, no merge
8685    /// possible.
8686    ///
8687    /// Atomicity: every mutating step runs after the read-only
8688    /// gather phase, so a panic before the merge encode leaves the
8689    /// catalog unchanged. The mutation block itself (load + rewrite +
8690    /// tombstone) takes only `&mut self` — callers serialise the
8691    /// engine write lock outside this function.
8692    ///
8693    /// Errors when the table / index doesn't exist, the index isn't
8694    /// `BTree`, the index column type isn't u64-coercible (cold-tier
8695    /// pre-condition), or a source segment fails its in-place
8696    /// row-body lookup (would indicate prior catalog corruption).
8697    pub fn compact_cold_segments(
8698        &mut self,
8699        table_name: &str,
8700        index_name: &str,
8701        target_segment_bytes: u64,
8702    ) -> Result<CompactReport, StorageError> {
8703        // --- validation phase ----------------------------------
8704        let t = self.get(table_name).ok_or_else(|| {
8705            StorageError::Corrupt(format!(
8706                "compact_cold_segments: table {table_name:?} not found"
8707            ))
8708        })?;
8709        let idx = t
8710            .indices
8711            .iter()
8712            .find(|i| i.name == index_name)
8713            .ok_or_else(|| {
8714                StorageError::Corrupt(format!(
8715                    "compact_cold_segments: index {index_name:?} not found on {table_name:?}"
8716                ))
8717            })?;
8718        let map = match &idx.kind {
8719            IndexKind::BTree(m) => m,
8720            IndexKind::Nsw(_)
8721            | IndexKind::Brin { .. }
8722            | IndexKind::Gin(_)
8723            | IndexKind::GinTrgm(_)
8724            | IndexKind::GinFulltext(_)
8725            | IndexKind::GinJsonb(_)
8726            | IndexKind::BTreeMulti(_) => {
8727                return Err(StorageError::Corrupt(format!(
8728                    "compact_cold_segments: index {index_name:?} is not BTree; \
8729                     compaction applies only to BTree cold-tier indices"
8730                )));
8731            }
8732        };
8733
8734        // --- gather phase --------------------------------------
8735        // Step A: every segment_id this BTree index Cold-references.
8736        let mut referenced_ids: BTreeSet<u32> = BTreeSet::new();
8737        for (_key, locators) in map.iter() {
8738            for loc in locators {
8739                if let RowLocator::Cold { segment_id, .. } = loc {
8740                    referenced_ids.insert(*segment_id);
8741                }
8742            }
8743        }
8744        // Step B: keep only the small + still-active ones.
8745        let candidate_set: BTreeSet<u32> = referenced_ids
8746            .into_iter()
8747            .filter(|id| {
8748                self.cold_segments
8749                    .get(*id as usize)
8750                    .and_then(|s| s.as_deref())
8751                    .is_some_and(|s| (s.bytes().len() as u64) < target_segment_bytes)
8752            })
8753            .collect();
8754        if candidate_set.len() < 2 {
8755            return Ok(CompactReport {
8756                sources: Vec::new(),
8757                merged_segment_id: None,
8758                merged_segment_bytes: Vec::new(),
8759                merged_rows: 0,
8760                deleted_rows_pruned: 0,
8761                bytes_reclaimed_estimate: 0,
8762            });
8763        }
8764        // Step C: pre-count source rows for the deleted-pruned metric.
8765        let mut source_row_count: usize = 0;
8766        let mut source_byte_total: u64 = 0;
8767        for &id in &candidate_set {
8768            let seg = self.cold_segments[id as usize]
8769                .as_ref()
8770                .expect("candidate selected only when slot is Some");
8771            source_row_count = source_row_count.saturating_add(seg.meta().num_rows as usize);
8772            source_byte_total = source_byte_total.saturating_add(seg.bytes().len() as u64);
8773        }
8774        // Step D: collect (key, body) pairs from every live Cold
8775        // locator pointing at a candidate. dedupe by key — one
8776        // BTree key resolves to at most one cold payload (the
8777        // freezer + promote/shadow flow keeps Cold locators
8778        // unique per key).
8779        let mut collected: BTreeMap<u64, (Vec<u8>, IndexKey)> = BTreeMap::new();
8780        for (key, locators) in map.iter() {
8781            for loc in locators {
8782                let RowLocator::Cold { segment_id, .. } = loc else {
8783                    continue;
8784                };
8785                if !candidate_set.contains(segment_id) {
8786                    continue;
8787                }
8788                let u64_key = index_key_as_u64(key).ok_or_else(|| {
8789                    StorageError::Corrupt(format!(
8790                        "compact_cold_segments: index {index_name:?} has non-integer Cold key; \
8791                         cold tier requires IndexKey::Int (Text PK lands in v5.5+)"
8792                    ))
8793                })?;
8794                let seg = self.cold_segments[*segment_id as usize]
8795                    .as_ref()
8796                    .expect("candidate slot guaranteed Some above");
8797                let payload = seg.lookup(u64_key).ok_or_else(|| {
8798                    StorageError::Corrupt(format!(
8799                        "compact_cold_segments: BTree {index_name:?} points key={u64_key} \
8800                         at segment {segment_id} but the segment lookup missed"
8801                    ))
8802                })?;
8803                collected.insert(u64_key, (payload, key.clone()));
8804                break;
8805            }
8806        }
8807        let merged_rows = collected.len();
8808        let deleted_rows_pruned = source_row_count.saturating_sub(merged_rows);
8809
8810        // Step E: encode the merged segment. `BTreeMap<u64, _>`
8811        // iteration is ascending by key, which is what
8812        // `encode_segment` requires.
8813        let seg_rows: Vec<(u64, Vec<u8>)> = collected
8814            .iter()
8815            .map(|(k, (body, _))| (*k, body.clone()))
8816            .collect();
8817        let (seg_bytes, _meta) = encode_segment(seg_rows.into_iter(), 0.01, SEGMENT_PAGE_BYTES)
8818            .map_err(|e| StorageError::Corrupt(format!("compact_cold_segments: encode: {e}")))?;
8819        let merged_bytes_len = seg_bytes.len() as u64;
8820
8821        // --- atomic mutation phase ------------------------------
8822        let merged_segment_id = self
8823            .load_segment_bytes(seg_bytes.clone())
8824            .map_err(|e| StorageError::Corrupt(format!("compact_cold_segments: load: {e}")))?;
8825
8826        // Rewrite the BTree index: every Cold locator pointing at
8827        // a candidate source becomes a Cold locator pointing at
8828        // the merged segment. Use a flat collect-then-replace
8829        // pattern so we never hold a `&self` borrow across the
8830        // `&mut self` write.
8831        let entries: Vec<(IndexKey, crate::posting::PostingList)> = {
8832            let t = self
8833                .get(table_name)
8834                .expect("table existed at the start of this fn");
8835            let idx = t
8836                .indices
8837                .iter()
8838                .find(|i| i.name == index_name)
8839                .expect("index existed at the start of this fn");
8840            let IndexKind::BTree(map) = &idx.kind else {
8841                unreachable!("validated above");
8842            };
8843            map.iter().map(|(k, v)| (k.clone(), v.clone())).collect()
8844        };
8845        let t_mut = self
8846            .get_mut(table_name)
8847            .expect("table existed at the start of this fn");
8848        let idx_mut = t_mut
8849            .indices
8850            .iter_mut()
8851            .find(|i| i.name == index_name)
8852            .expect("index existed at the start of this fn");
8853        let IndexKind::BTree(map_mut) = &mut idx_mut.kind else {
8854            unreachable!("validated above");
8855        };
8856        for (key, locators) in entries {
8857            let mut new_locs = crate::posting::PostingList::new();
8858            let mut changed = false;
8859            for loc in &locators {
8860                match *loc {
8861                    RowLocator::Cold {
8862                        segment_id,
8863                        page_offset: _,
8864                    } if candidate_set.contains(&segment_id) => {
8865                        let replacement = RowLocator::Cold {
8866                            segment_id: merged_segment_id,
8867                            page_offset: 0,
8868                        };
8869                        if !new_locs.contains(replacement) {
8870                            new_locs.push(replacement);
8871                        }
8872                        changed = true;
8873                    }
8874                    other => new_locs.push(other),
8875                }
8876            }
8877            if changed {
8878                map_mut.insert_mut(key, new_locs);
8879            }
8880        }
8881
8882        // Tombstone every source slot. Last step — failures here
8883        // would leave the segment double-referenced in both
8884        // memory + manifest, but `tombstone_segment` only errors
8885        // on out-of-bounds, which we've already validated.
8886        for &id in &candidate_set {
8887            self.tombstone_segment(id)?;
8888        }
8889
8890        let bytes_reclaimed_estimate = source_byte_total.saturating_sub(merged_bytes_len);
8891        Ok(CompactReport {
8892            sources: candidate_set.into_iter().collect(),
8893            merged_segment_id: Some(merged_segment_id),
8894            merged_segment_bytes: seg_bytes,
8895            merged_rows,
8896            deleted_rows_pruned,
8897            bytes_reclaimed_estimate,
8898        })
8899    }
8900
8901    /// Internal helper: scan `(table, index)` for a `Cold` locator
8902    /// keyed by `key`. Returns `Ok(Some((segment_id, page_offset)))`
8903    /// when found, `Ok(None)` when the key has only hot entries
8904    /// or no entries at all, `Err` on the same input-validation
8905    /// errors as the public `promote_cold_row` / `shadow_cold_row`.
8906    fn find_cold_locator(
8907        &self,
8908        table_name: &str,
8909        index_name: &str,
8910        key: &IndexKey,
8911    ) -> Result<Option<(u32, u32)>, StorageError> {
8912        let t = self.get(table_name).ok_or_else(|| {
8913            StorageError::Corrupt(format!("find_cold_locator: table {table_name:?} not found"))
8914        })?;
8915        let idx = t
8916            .indices
8917            .iter()
8918            .find(|i| i.name == index_name)
8919            .ok_or_else(|| {
8920                StorageError::Corrupt(format!(
8921                    "find_cold_locator: index {index_name:?} not found on {table_name:?}"
8922                ))
8923            })?;
8924        if !matches!(idx.kind, IndexKind::BTree(_)) {
8925            return Err(StorageError::Corrupt(format!(
8926                "find_cold_locator: index {index_name:?} is NSW; promote-on-write only applies to BTree indices"
8927            )));
8928        }
8929        for loc in idx.lookup_eq(key) {
8930            if let RowLocator::Cold {
8931                segment_id,
8932                page_offset,
8933            } = *loc
8934            {
8935                return Ok(Some((segment_id, page_offset)));
8936            }
8937        }
8938        Ok(None)
8939    }
8940}
8941
8942/// Coerce an [`IndexKey`] to the `u64` that v5.1 cold-tier
8943/// segments use as their on-disk PK. Returns `None` for keys that
8944/// aren't representable as `u64` — Text PKs need a hash mapping
8945/// the segment writer baked in (deferred to v5.2+), Bool PKs are
8946/// almost never wide enough to be sharded into a cold tier.
8947fn index_key_as_u64(key: &IndexKey) -> Option<u64> {
8948    match key {
8949        // Reinterpret the i64 bit pattern as u64. Cold-tier segments
8950        // are sorted by this u64 view, so the chosen interpretation
8951        // only has to match between insert (bake_segment / freezer)
8952        // and lookup — using cast_unsigned keeps both sides honest
8953        // and silences clippy::cast_sign_loss.
8954        IndexKey::Int(n) => Some(n.cast_unsigned()),
8955        // Text / Bool / Uuid / Bytes / Numeric PKs aren't representable
8956        // as u64 and so can't participate in the u64-sorted cold-tier
8957        // segment PK layout. Same deferral story as Text — lookup falls
8958        // through the in-memory btree.
8959        IndexKey::Text(_)
8960        | IndexKey::Bool(_)
8961        | IndexKey::Uuid(_)
8962        | IndexKey::Bytes(_)
8963        | IndexKey::Numeric(_)
8964        | IndexKey::Null => None,
8965    }
8966}
8967
8968#[derive(Debug, Clone, PartialEq, Eq)]
8969#[non_exhaustive]
8970pub enum StorageError {
8971    DuplicateTable {
8972        name: String,
8973    },
8974    TableNotFound {
8975        name: String,
8976    },
8977    ArityMismatch {
8978        expected: usize,
8979        actual: usize,
8980    },
8981    TypeMismatch {
8982        column: String,
8983        expected: DataType,
8984        actual: DataType,
8985        position: usize,
8986    },
8987    NullInNotNull {
8988        column: String,
8989    },
8990    /// Index with this name already exists on the table.
8991    DuplicateIndex {
8992        name: String,
8993    },
8994    /// Column referenced by an index doesn't exist on the table.
8995    ColumnNotFound {
8996        column: String,
8997    },
8998    /// On-disk format failed to parse — corrupted file, wrong magic, truncated
8999    /// payload, or unknown tag bytes.
9000    Corrupt(String),
9001    /// v6.0.4 — ALTER INDEX targeted an index name that doesn't
9002    /// exist on any table in this catalog.
9003    IndexNotFound {
9004        name: String,
9005    },
9006    /// v6.0.4 — operation requested isn't supported on this index
9007    /// kind / column type (e.g. ALTER INDEX REBUILD on a `BTree`
9008    /// index, or REBUILD WITH (encoding=…) on a non-vector column).
9009    Unsupported(String),
9010    /// v7.39 (round 220) — a CYCLE-less sequence ran past its bound.
9011    /// PG's 2200H phrasing: `nextval: reached maximum value of
9012    /// sequence "s" (n)` (`is_max: false` = the MINVALUE direction).
9013    SequenceExhausted {
9014        name: String,
9015        limit: i64,
9016        is_max: bool,
9017    },
9018}
9019
9020impl fmt::Display for StorageError {
9021    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
9022        match self {
9023            // v7.39 (read01 round 47) — PG's 42P07 wording.
9024            Self::DuplicateTable { name } => write!(f, "relation \"{name}\" already exists"),
9025            // v7.39 (read01 round 47) — PG's wording for a missing relation
9026            // (42P01). DROP TABLE says "table" and raises its own error at
9027            // the engine; every other path (SELECT / ALTER / …) says
9028            // "relation", which is what this carries.
9029            Self::TableNotFound { name } => write!(f, "relation \"{name}\" does not exist"),
9030            Self::ArityMismatch { expected, actual } => write!(
9031                f,
9032                "row arity mismatch: expected {expected} columns, got {actual}"
9033            ),
9034            Self::TypeMismatch {
9035                column,
9036                expected,
9037                actual,
9038                position,
9039            } => write!(
9040                f,
9041                "type mismatch in column {column:?} (position {position}): expected {expected}, got {actual}"
9042            ),
9043            Self::NullInNotNull { column } => {
9044                // v7.39 (SQLSTATE fidelity) — PG's 23502 phrasing (the
9045                // relation-qualified long form is added by engine call
9046                // sites that know the table name).
9047                write!(
9048                    f,
9049                    "null value in column \"{column}\" violates not-null constraint"
9050                )
9051            }
9052            // v7.39 (read01 round 47) — an index is a relation to PG (42P07).
9053            Self::DuplicateIndex { name } => write!(f, "relation \"{name}\" already exists"),
9054            // v7.39 (round 701) — PG's wording, and the same fix `EvalError::
9055            // ColumnNotFound` took in read01 round 81 with the same reason:
9056            // "column not found: x" matches none of the wire layer's `does
9057            // not exist` patterns, so a missing column reached the client as
9058            // the generic error class. The eval-side variant was changed and
9059            // the storage-side one was not, so which sentence you got
9060            // depended on which layer noticed — `CREATE INDEX ix ON t(nope)`
9061            // came out of storage and kept the old spelling.
9062            Self::ColumnNotFound { column } => write!(f, "column \"{column}\" does not exist"),
9063            Self::Corrupt(detail) => write!(f, "corrupt on-disk format: {detail}"),
9064            Self::IndexNotFound { name } => write!(f, "index \"{name}\" does not exist"),
9065            Self::Unsupported(detail) => write!(f, "unsupported: {detail}"),
9066            // v7.39 (round 220) — PG's exact 2200H wording.
9067            Self::SequenceExhausted {
9068                name,
9069                limit,
9070                is_max,
9071            } => write!(
9072                f,
9073                "nextval: reached {} value of sequence \"{name}\" ({limit})",
9074                if *is_max { "maximum" } else { "minimum" }
9075            ),
9076        }
9077    }
9078}
9079
9080impl ColumnSchema {
9081    pub fn new(name: impl Into<String>, ty: DataType, nullable: bool) -> Self {
9082        Self {
9083            name: name.into(),
9084            ty,
9085            nullable,
9086            collation_name: None,
9087            default: None,
9088            runtime_default: None,
9089            auto_increment: false,
9090            user_enum_type: None,
9091            user_domain_type: None,
9092            user_composite_type: None,
9093            acl: Vec::new(),
9094            on_update_runtime: None,
9095            collation: Collation::Binary,
9096            is_unsigned: false,
9097            inline_enum_variants: None,
9098            inline_set_variants: None,
9099            generated_stored_expr: None,
9100            identity_always: false,
9101            default_text: None,
9102            auto_restart: None,
9103            scalar_row_source: false,
9104            mysql_int_width: None,
9105            mysql_fsp: None,
9106            mysql_declared_timestamp: false,
9107            mysql_float_md: None,
9108        }
9109    }
9110
9111    /// v7.38.14 — the SAME column, re-described.
9112    ///
9113    /// `ColumnSchema::new` is for SYNTHESISING a column: a catalog row, an
9114    /// admin view, a computed output. It sets twenty-two fields to their
9115    /// defaults, which is right when there is no source column to speak of.
9116    ///
9117    /// It is wrong, and quietly so, when there IS one -- a join's combined
9118    /// schema, an aggregate's synthetic keys, a derived table's output. Those
9119    /// sites re-describe an existing column under a new name or type, and
9120    /// have each been written as `new(..)` followed by hand-picking a few
9121    /// attributes to copy across. They all pick differently and none picks
9122    /// them all.
9123    ///
9124    /// Five fields have been lost through that shape so far -- enum identity,
9125    /// MySQL fsp, the PG collation name, `ProjectedItem::fold_exempt`, and
9126    /// the `collation` enum -- and v7.38.14 alone found four sites dropping
9127    /// the last of those. The failure is never loud: `collation` defaults to
9128    /// `Binary`, which downstream reads as "byte-wise ON PURPOSE" rather than
9129    /// as "unknown", so a dropped declaration presents as a deliberate one.
9130    ///
9131    /// This constructor copies everything by construction. A field added to
9132    /// `ColumnSchema` therefore reaches every re-describe site without anyone
9133    /// having to remember, which is the property the hand-written copy lists
9134    /// never had.
9135    ///
9136    /// The two fields a re-describe legitimately changes -- name and
9137    /// nullability -- are parameters. Callers that also retype the column
9138    /// assign `ty` afterwards.
9139    #[must_use]
9140    pub fn rederive(source: &Self, name: impl Into<String>, nullable: bool) -> Self {
9141        Self {
9142            name: name.into(),
9143            nullable,
9144            ..source.clone()
9145        }
9146    }
9147
9148    /// Builder-style helper to attach a default value to an otherwise
9149    /// plain column schema. Used by the engine when CREATE TABLE
9150    /// specifies `column TYPE DEFAULT <expr>`.
9151    #[must_use]
9152    pub fn with_default(mut self, default: Value<'static>) -> Self {
9153        self.default = Some(default);
9154        self
9155    }
9156
9157    /// v7.9.21 — builder for runtime-evaluated defaults
9158    /// (`DEFAULT now()`, `DEFAULT CURRENT_TIMESTAMP`, …).
9159    /// `expr` is the Expr's `Display` form, re-parsed by the
9160    /// engine at each INSERT.
9161    #[must_use]
9162    pub fn with_runtime_default(mut self, expr: impl Into<String>) -> Self {
9163        self.runtime_default = Some(expr.into());
9164        self
9165    }
9166
9167    /// Builder-style helper to mark a column as `AUTO_INCREMENT`.
9168    #[must_use]
9169    pub const fn with_auto_increment(mut self) -> Self {
9170        self.auto_increment = true;
9171        self
9172    }
9173}
9174
9175impl TableSchema {
9176    pub fn new(name: impl Into<String>, columns: Vec<ColumnSchema>) -> Self {
9177        Self {
9178            name: name.into(),
9179            columns,
9180            hot_tier_bytes: None,
9181            foreign_keys: Vec::new(),
9182            uniqueness_constraints: Vec::new(),
9183            exclusion_constraints: Vec::new(),
9184            checks: Vec::new(),
9185            partition_role: None,
9186            policies: Vec::new(),
9187            row_security: false,
9188            force_row_security: false,
9189            owner: None,
9190            acl: Vec::new(),
9191        }
9192    }
9193}
9194
9195// =========================================================================
9196// Persistent binary format for the catalog.
9197//
9198// Layout (little-endian throughout):
9199//
9200//   [magic "SPGDB001" 8 bytes][version u8]
9201//   [table_count u32]
9202//   for each table:
9203//       [name_len u16][name bytes]
9204//       [col_count u16]
9205//       for each col:
9206//           [name_len u16][name bytes]
9207//           [type_tag u8 + optional payload]
9208//               1=Int 2=BigInt 3=Float 4=Text 5=Bool
9209//               6=Vector(u32 dim)
9210//               7=SmallInt
9211//               8=Varchar(u32 max)
9212//               9=Char(u32 size)
9213//               10=Numeric(u8 precision, u8 scale)
9214//               11=Date
9215//               12=Timestamp
9216//           [nullable u8]   0/1
9217//           [default_tag u8] 0=none 1=value (followed by [value_tag u8] + bytes)
9218//       [row_count u32]
9219//       for each row, for each col, one [value_tag u8] + value bytes:
9220//           tag 0 (Null)     → no body
9221//           tag 1 (Int)      → i32 LE
9222//           tag 2 (BigInt)   → i64 LE
9223//           tag 3 (Float)    → f64 LE
9224//           tag 4 (Text)     → u16 LE len + UTF-8 bytes
9225//           tag 5 (Bool)     → u8 0/1
9226//           tag 6 (Vector)   → u32 LE dim + dim×f32 LE
9227//           tag 7 (SmallInt) → i16 LE
9228//           tag 8 (Numeric)  → i128 LE (16 bytes) + u8 scale
9229//           tag 9 (Date)     → i32 LE (days since Unix epoch)
9230//           tag 10 (Timestamp) → i64 LE (microseconds since Unix epoch)
9231//
9232// Bumped to version 3 when NUMERIC was added; to version 4 when
9233// AUTO_INCREMENT (per-column flag) + NSW index `kind` byte landed;
9234// to version 5 when DATE / TIMESTAMP were added; to version 6 when
9235// NSW graph topology started travelling on disk (v2.7); to version 7
9236// when the NSW topology became multi-layer HNSW (v2.13); to version 8
9237// when row encoding switched to schema-driven dense layout (v3.0.2 —
9238// per-row NULL bitmap + per-column fixed-width body, no per-cell type
9239// tag).
9240// =========================================================================
9241
9242const FILE_MAGIC: &[u8; 8] = b"SPGDB001";
9243/// Current catalog snapshot format version emitted by [`Catalog::serialize`].
9244///
9245/// v9 (v5.2) extends v8 by serialising `BTree` index entries directly — every
9246/// `(IndexKey, Vec<RowLocator>)` pair travels on disk with the v5.1
9247/// `RowLocator::write_le` tag-prefixed codec. v8 `BTree` indices stored no
9248/// entries at all (the map was rebuilt from `Table::rows` on load); v9
9249/// preserves on-disk Cold locators so freezer-produced cold-tier index
9250/// entries survive a catalog snapshot round-trip. v8 readers are accepted
9251/// by version dispatch in [`Catalog::deserialize`] — every entry decodes
9252/// as `RowLocator::Hot(_)` via `add_index` rebuild, identical to v5.1
9253/// behaviour.
9254/// v6.7.2 — bumped from 10 to 11 to append per-table
9255/// `hot_tier_bytes: Option<u64>` after the per-table indices
9256/// section. v10 catalogs (v6.7.1) load with `hot_tier_bytes =
9257/// None` for every table (the deserialiser short-circuits when
9258/// version < 11). v11 snapshots written by a pre-v6.7.2 binary
9259/// fail loudly at the version check, matching the v6.1.2 /
9260/// v6.1.4 / v6.2.0 / v6.7.1 envelope-bump upgrade fences.
9261///
9262/// v6.8.0 — bumped from 11 to 12: per-index
9263/// `included_columns: Vec<u16>` appended at the tail of each
9264/// index payload. v11 (= v6.7.2) catalogs load with
9265/// `included_columns = Vec::new()` for every index — same
9266/// "older readers, append-only extension" pattern as the v6.7.2
9267/// hot_tier_bytes byte.
9268/// v7.13.0 — bumped from 22 to 23. mailrs round-5 G3 / G10.
9269/// Per-table appendix gains two new sections:
9270///   * `checks: Vec<String>` — CHECK predicate sources (Display
9271///     form of the AST Expr); re-parsed on INSERT/UPDATE to
9272///     enforce against candidate rows. Same persistence pattern
9273///     as `Index::partial_predicate`.
9274///   * Per `UniquenessConstraint`: trailing `nulls_not_distinct:
9275///     u8` flag for PG 15+ `UNIQUE NULLS NOT DISTINCT (cols)`
9276///     semantics.
9277/// v22 catalogs deserialise with empty `checks` and every UC
9278/// at `nulls_not_distinct = false`.
9279/// v24 introduces:
9280///   * Index kind tag 4 = trigram-GIN (`gin_trgm_ops`-flavoured
9281///     `USING gin` over a TEXT/VARCHAR column). Payload shape is
9282///     identical to tag-3 GIN (String → Vec<RowLocator>); the
9283///     keys are PG-compatible 3-byte trigram shingles instead of
9284///     tsvector lexemes. v23 catalogs deserialise unchanged — no
9285///     v23 writer ever emitted tag 4.
9286/// v25 introduces:
9287///   * Per `TriggerDef`: trailing `enabled: u8` flag (mailrs
9288///     round-9 A.2.b — `ALTER TABLE … { ENABLE | DISABLE }
9289///     TRIGGER …`). v24 catalogs deserialise with every trigger
9290///     `enabled = true`, matching pre-v7.16.1 behaviour.
9291/// v26 introduces (v7.17.0 Phase 1.1):
9292///   * Trailing SEQUENCE catalog block after triggers. Encoded
9293///     as `u32 count` followed by per-sequence:
9294///     `name`, `data_type: u8` (0=SmallInt,1=Int,2=BigInt),
9295///     `start i64`, `increment i64`, `min_value i64`,
9296///     `max_value i64`, `cache i64`, `cycle u8`,
9297///     `owned_by_tag u8` (0=NONE, 1=Column → `table`,`column`),
9298///     `last_value i64`, `is_called u8`. v25-and-below catalogs
9299///     deserialise with an empty sequences map.
9300/// v27 introduces (v7.17.0 Phase 1.2):
9301///   * Trailing VIEW catalog block after sequences. Encoded as
9302///     `u32 count` followed by per-view:
9303///     `name`, `column_count u16`, then column names, then
9304///     `body` long-string. v26-and-below catalogs deserialise
9305///     with an empty views map.
9306/// v28 introduces (v7.17.0 Phase 1.3):
9307///   * Trailing MATERIALIZED VIEW source registry block after
9308///     views. Encoded as `u32 count` followed by per-entry:
9309///     `name`, `body` long-string. The materialised rows live
9310///     as a regular Table of the same name (already covered by
9311///     the pre-existing tables block). v27-and-below catalogs
9312///     deserialise with an empty map.
9313/// v29 introduces (v7.17.0 Phase 1.4):
9314///   * Per-table user_enum_type appendix (after the CHECK
9315///     appendix). Layout: `u16 count` followed by per-binding
9316///     `[u16 col_pos][str enum_name]`. Only columns whose
9317///     `user_enum_type` is Some land here; the catalog stays
9318///     compact for the common no-enum case.
9319///   * Trailing ENUM types catalog block after materialized
9320///     views. Encoded as `u32 count` followed by per-entry:
9321///     `name`, `u16 label_count`, then `label_count` short
9322///     strings. v28-and-below catalogs deserialise with an
9323///     empty enum_types map and every column's
9324///     `user_enum_type = None`.
9325/// v30 introduces (v7.17.0 Phase 1.5):
9326///   * Per-table user_domain_type appendix (after the
9327///     user_enum_type appendix). Same shape as the enum one.
9328///   * Trailing DOMAIN types catalog block after the enum
9329///     block. Encoded as `u32 count` followed by per-entry:
9330///     `name`, `data_type` byte, `nullable u8`,
9331///     `default_present u8` + optional default string,
9332///     `u16 check_count` then `check_count` Display-form
9333///     CHECK strings. v29-and-below catalogs deserialise with
9334///     an empty domain_types map and `user_domain_type = None`.
9335/// v31 introduces (v7.17.0 Phase 1.6):
9336///   * Trailing user-schemas block after the DOMAIN block.
9337///     Encoded as `u32 count` followed by `count` schema-name
9338///     short strings. Built-in schemas (`public`, `pg_catalog`,
9339///     `information_schema`) are NOT serialised — they're
9340///     hardcoded in `is_builtin_schema`. v30-and-below catalogs
9341///     deserialise with an empty user-schemas set.
9342/// v32 introduces (v7.17.0 Phase 2.1):
9343///   * Per-table on_update_runtime appendix (after the
9344///     user_domain_type appendix). Layout: `u16 count` followed
9345///     by per-binding `[u16 col_pos][str expr_src]`. Only
9346///     columns whose `on_update_runtime` is Some land here;
9347///     the catalog stays compact when no MySQL-shaped table
9348///     uses the attribute. v31-and-below catalogs deserialise
9349///     with every column's `on_update_runtime = None`.
9350/// v33 introduces (v7.17.0 Phase 2.2):
9351///   * Index kind tag 5 = fulltext-GIN (MySQL `FULLTEXT KEY`
9352///     surface over a TEXT / VARCHAR column). Payload shape is
9353///     identical to tag-3 / tag-4 GIN (`String → Vec<RowLocator>`);
9354///     the keys are lower-cased word lexemes (same rule as
9355///     `to_tsvector('simple', text)`). v32 catalogs deserialise
9356///     unchanged — no v32 writer ever emitted tag 5, and FULLTEXT
9357///     KEY was silently dropped pre-v7.17 so no rebuild shim is
9358///     needed for round-tripped catalogs.
9359/// v34 introduces (v7.17.0 Phase 2.5):
9360///   * Per-table collation appendix (after the on_update_runtime
9361///     appendix). Sparse layout: only columns whose `collation`
9362///     is non-Binary land here. `u16 count` then per-binding
9363///     `[u16 col_pos][u8 collation_tag]` where the tag matches
9364///     `Collation::TAG_*`. Snapshots written by v33-and-below
9365///     readers deserialise every column with `collation =
9366///     Binary`, preserving the prior byte-wise compare
9367///     semantics. Unknown tags read back as Binary too — keeps
9368///     a forward-compat path if a future v35 adds variants
9369///     and someone rolls back to a v34 reader.
9370/// v35 introduces (v7.17.0 Phase 4.4):
9371///   * Per-table is_unsigned appendix (after the collation
9372///     appendix). Sparse layout: only `is_unsigned = true`
9373///     columns land. `u16 count` then per-binding `[u16 col_pos]`.
9374///     v34-and-below catalogs deserialise every column as
9375///     `is_unsigned = false`, preserving the prior silent-
9376///     accept behaviour for negative inserts on UNSIGNED columns.
9377/// v46 introduces (v7.23, mailrs round-14):
9378///   * Escaped short-string codec — `write_str` lengths >= 0xFFFF
9379///     emit `[u16 0xFFFF][u32 real_len]` so TEXT cells (mail bodies,
9380///     document text) above 64 KiB encode instead of panicking.
9381///     One-way upgrade: v45-and-below readers reject v46 catalogs
9382///     loudly via the version gate; v46 readers decode v45 catalogs
9383///     with the plain-u16 rules (0xFFFF is a legitimate length
9384///     there).
9385/// v47 introduces (v7.27, mailrs round-21):
9386///   * Escaped lengths for the REMAINING u16-length cell payloads —
9387///     BYTEA cells, TEXT[] elements, tsvector lexemes and tsquery
9388///     terms — the same `[u16 0xFFFF][u32 real_len]` escape v46
9389///     gave short strings. Round-14 fixed TEXT and missed these;
9390///     round-21 fired the BYTEA twin during a production migration.
9391///     One-way upgrade, same posture as v46.
9392/// v48 introduces (v7.37.5 β-P2, sentori cutover window):
9393///   * `INTERVAL` becomes a real column type. Catalog tag 34 in
9394///     `write_data_type`; per-row body is a fixed 16 bytes
9395///     (i64 micros + i32 days + i32 months, LE, PG-byte-equal
9396///     field order). The runtime-only days collapse is gone —
9397///     `'1 day'` and `'24 hours'` are stored distinctly. One-way
9398///     upgrade: v47 catalogs without INTERVAL columns deserialise
9399///     identically; v47 readers fed a v48 catalog that contains
9400///     INTERVAL hit the explicit "unknown data type tag: 34"
9401///     fence in `read_data_type`.
9402/// v49 introduces (v7.37.6-B, sentori Epic 2 P0):
9403///   * Per-table partition role appendix(declarative
9404///     `PARTITION BY RANGE` parent / range child / DEFAULT
9405///     child)。Layout, written **after** the inline_set_variants
9406///     appendix and **before** the per-table block close:
9407///       `[u8 role_tag]`
9408///         0 = `None`(普通表,后向兼容默认)
9409///         1 = `Parent`:  `[u8 kind_tag (0=Range)]`
9410///                        `[u16 key_col_count]` `(× u16 col_pos)`
9411///                        `[u16 tmpl_count]` `(× str source)`
9412///         2 = `Range`:   `[str parent_name]` `[Bound]` `[Bound]`
9413///         3 = `Default`: `[str parent_name]`
9414///     `PartitionBound` codec:
9415///       `[u8 bound_tag]` 0=MinValue 1=MaxValue 2=TimestampTz(`[i64 LE micros]`)
9416///     v48-and-below readers stop after the inline_set_variants
9417///     block — they don't see this appendix and deserialise every
9418///     table with `partition_role = None`. v49 writers always emit
9419///     `[0]` for plain tables, so the encoding stays one-byte-cheap.
9420/// v50 introduces (v7.37.7, sentori Epic 3 P1):
9421///   * Per-table `generated_stored_expr` appendix(stored generated
9422///     columns — `GENERATED ALWAYS AS (<expr>) STORED`)。Layout,
9423///     written **after** the partition_role appendix and before
9424///     the per-table block close:
9425///       `[u16 binding_count]`
9426///       `binding_count × { [u16 col_pos][str expr_source] }`
9427///     Sparse — only generated columns land here, so plain-shape
9428///     catalogs stay byte-for-byte identical save for the new
9429///     u16 zero count. v49-and-below readers stop after the
9430///     partition_role appendix; v50 readers default every column
9431///     to `generated_stored_expr = None` when this block is absent.
9432/// v51 introduces (v7.37.8, sentori Epic 5 P2):
9433///   * Per-index tag byte 6 = `GinJsonb`(real posting-list GIN
9434///     over a JSONB column). Payload shape mirrors tag-3 / 4 / 5:
9435///     `[u32 posting_list_count]` then `(str token, u32 locator_count,
9436///     locators …)` per posting list. Same `write_str` /
9437///     `RowLocator::write_le` codec as the rest of the GIN family.
9438///     v50 catalogs never wrote tag 6(the same DDL loaded as a
9439///     BTree fallback); v51 readers see tag 6 explicitly and dispatch
9440///     into `IndexKind::GinJsonb`.
9441/// v52 introduces (v7.37.42-T2 ζ-B composite + domain metasystem):
9442///   * Trailing COMPOSITE-types catalog block after the
9443///     user-schemas block. Encoded as `u32 count` followed by
9444///     per-entry: `name`, `u16 field_count`, then `field_count`
9445///     `[str field_name][data_type]` pairs (`write_data_type` is
9446///     reused). v51-and-below catalogs deserialise with an empty
9447///     composite_types map; v52 readers tolerate v51 catalogs by
9448///     stopping at the schema block (no composite block present
9449///     ⇒ empty map). Composite types are referenced by columns
9450///     via `ColumnSchema.user_composite_type`, mirroring the
9451///     `user_enum_type` / `user_domain_type` pattern. The block
9452///     lands here (not as a per-table appendix) so dropping the
9453///     composite type registers globally and DROP TYPE can find it
9454///     without a table scan.
9455/// v53 introduces (v7.37.16 Epic W — cross-checkpoint tombstone
9456///   durability):
9457///   * Trailing per-table MVCC appendix carrying, for every row,
9458///     its `RowHeader` (`xmin:u64`, `xmax:u64`, `flags:u8`) and its
9459///     stable `RowId` (`u64`), followed by the relation's
9460///     `next_rowid:u64`. Layout per table (after the v50
9461///     generated_stored_expr block, before the table loop closes):
9462///       `[u32 row_count]` (== `Table::rows().len()`, cross-check)
9463///       per row in physical order:
9464///         `[u64 xmin][u64 xmax][u8 flags][u64 rowid]`
9465///       `[u64 next_rowid]`
9466///     v52-and-below catalogs never wrote this block; their reader
9467///     stops after the last per-table appendix and
9468///     `deserialize_rows` leaves every row `RowHeader::frozen()`
9469///     with dense 1..=N ids — the exact pre-v53 contract. A v53
9470///     reader instead reconstructs headers + ids VERBATIM, so a
9471///     tombstone-redo naming a row inserted before the last
9472///     checkpoint resolves by `RowId` across the base-snapshot
9473///     boundary (closing the coupling the Epic W WAL slices deferred
9474///     to this format bump). Because the reader routes on `version`,
9475///     the block is strictly backward-compatible: old images load
9476///     byte-for-byte as before. `SPG_MVCC_INPLACE` is unaffected —
9477///     a gate-off database's rows are all frozen/alive, so
9478///     persisting + restoring their headers is observationally a
9479///     no-op.
9480/// v7.38 (read01 P5.05) — v54 appends a CRC32C over the whole preceding
9481/// image so a corrupted `base.spg` is caught on load instead of silently
9482/// deserialising garbage. Older images (v8..=53) carry no trailer and load
9483/// unchanged.
9484/// v7.39 (round 210) — v72 appends a per-table EXCLUDE-constraint appendix
9485/// (sparse: only tables carrying an EXCLUDE write it) at the very end of the
9486/// per-table block, after the column-ACL appendix. A v71 reader stops before
9487/// it and its tables read back with no exclusion constraints, which is what
9488/// they were.
9489/// v7.39 (round 220) — v73 appends a per-table identity-RESTART appendix
9490/// (sparse: [u16 count] then per entry [u16 col_pos][i64 LE floor]) after
9491/// the EXCLUDE appendix. A v72 reader stops before it; its columns read
9492/// back with no RESTART floor, losing only an un-consumed
9493/// `ALTER … RESTART WITH` across a restart.
9494/// r1039 — v90 adds index-key tags 4 (bytea) and 5 (the canonical
9495/// numeric key), so BYTEA and NUMERIC columns carry a real B-tree
9496/// instead of falling back to a scan. A v89 reader meeting either tag
9497/// reports a corrupt catalog rather than mis-reading it, which is the
9498/// same forward-compatibility story tag 3 (uuid) had at v36.
9499const FILE_VERSION: u8 = 95;
9500
9501/// v7.37 (round 833) — the codec version to decode a row that
9502/// [`encode_row_body_dense`] has just produced.
9503///
9504/// That encoder always writes the newest form, and every decoder gate is
9505/// a `codec_version >= N` feature test, so a freshly encoded row must be
9506/// read at the current version. Cold segments carry their own version in
9507/// their header and keep passing that; this is for in-process round
9508/// trips — sort runs on temp storage — where the bytes never outlive the
9509/// build that wrote them.
9510pub const CURRENT_ROW_CODEC_VERSION: u8 = FILE_VERSION;
9511/// First version that appends the trailing CRC32C integrity trailer.
9512const FILE_VERSION_CRC_TRAILER: u8 = 54;
9513/// Oldest format version [`Catalog::deserialize`] still accepts. v8 is the
9514/// v3.0.2 dense-row layout; pre-v8 catalogs require an offline migration.
9515const MIN_SUPPORTED_FILE_VERSION: u8 = 8;
9516
9517// IndexKey wire format (v9):
9518//   tag 0 = Int  → [i64 LE]
9519//   tag 1 = Text → [u16 LE len + UTF-8 bytes] (via write_str / read_str)
9520//   tag 2 = Bool → [u8 0/1]
9521const INDEX_KEY_TAG_INT: u8 = 0;
9522const INDEX_KEY_TAG_TEXT: u8 = 1;
9523const INDEX_KEY_TAG_BOOL: u8 = 2;
9524/// v7.17.0 — `IndexKey::Uuid([u8; 16])`. Body = raw 16 bytes
9525/// (RFC 4122 byte order). Persisted only in FILE_VERSION 36+
9526/// catalogs.
9527const INDEX_KEY_TAG_UUID: u8 = 3;
9528/// r1039 — `IndexKey::Bytes`. Body = [u32 LE len][raw bytes].
9529/// Persisted only in FILE_VERSION 90+ catalogs.
9530const INDEX_KEY_TAG_BYTES: u8 = 4;
9531/// r1039 — `IndexKey::Numeric`. Body = [u8 class][u8 neg][i32 LE exp]
9532/// [u32 LE digit count][one byte per decimal digit, 0..=9, MSD first].
9533/// Persisted only in FILE_VERSION 90+ catalogs.
9534const INDEX_KEY_TAG_NUMERIC: u8 = 5;
9535/// v7.38.1 (L12) — `IndexKey::Null`, a NULL component inside a
9536/// composite key. No body. Persisted only inside tag-7 multi-index
9537/// payloads, FILE_VERSION 91+.
9538const INDEX_KEY_TAG_NULL: u8 = 6;
9539
9540impl Catalog {
9541    /// Serialize the whole catalog (schema + every row) into a self-contained
9542    /// byte buffer. Format is documented above the impl block.
9543    pub fn serialize(&self) -> Vec<u8> {
9544        let mut out = Vec::with_capacity(64);
9545        out.extend_from_slice(FILE_MAGIC);
9546        out.push(FILE_VERSION);
9547        write_u32(
9548            &mut out,
9549            u32::try_from(self.tables.len()).expect("≤ 4G tables"),
9550        );
9551        for t in &self.tables {
9552            write_str(&mut out, &t.schema.name);
9553            write_u16(
9554                &mut out,
9555                u16::try_from(t.schema.columns.len()).expect("≤ 65k columns/table"),
9556            );
9557            for c in &t.schema.columns {
9558                write_str(&mut out, &c.name);
9559                write_data_type(&mut out, c.ty);
9560                out.push(u8::from(c.nullable));
9561                match &c.default {
9562                    None => out.push(0),
9563                    Some(v) => {
9564                        out.push(1);
9565                        write_value(&mut out, v);
9566                    }
9567                }
9568                out.push(u8::from(c.auto_increment));
9569            }
9570            write_u32(
9571                &mut out,
9572                u32::try_from(t.rows.len()).expect("≤ 4G rows/table"),
9573            );
9574            // v3.0.2 dense row encoding (FILE_VERSION 8): per-row NULL
9575            // bitmap, then tightly-packed bodies. Identical wire format
9576            // as before — extracted into `encode_row_body_dense` so cold-
9577            // tier segments (v5.1+) can share the encoding.
9578            for row in &t.rows {
9579                out.extend_from_slice(&encode_row_body_dense(row, &t.schema));
9580            }
9581            // Index definitions. Per-index payload:
9582            //   [name][col_pos u16][kind u8]
9583            //     kind 0 = B-tree           (no params — rebuilt on load)
9584            //     kind 1 = NSW graph        (u16 M + serialized graph)
9585            // For NSW the graph topology travels on disk so startup
9586            // doesn't re-run the O(n²M) rebuild — see v2.7 notes.
9587            write_u16(
9588                &mut out,
9589                u16::try_from(t.indices.len()).expect("≤ 65k indices/table"),
9590            );
9591            for idx in &t.indices {
9592                write_str(&mut out, &idx.name);
9593                write_u16(
9594                    &mut out,
9595                    u16::try_from(idx.column_position).expect("≤ 65k columns/table"),
9596                );
9597                match &idx.kind {
9598                    IndexKind::BTree(map) => {
9599                        out.push(0);
9600                        // v9: serialise the full PB map. Each entry's
9601                        // RowLocator list travels with the tag-prefixed
9602                        // codec from `row_locator::write_le`, so freezer-
9603                        // produced Cold locators survive a snapshot
9604                        // round-trip. v8 BTree wrote nothing here and
9605                        // rebuilt from rows — v9 readers tolerate v8 by
9606                        // version dispatch in `Catalog::deserialize`.
9607                        write_u32(
9608                            &mut out,
9609                            u32::try_from(map.len()).expect("≤ 4G index entries/index"),
9610                        );
9611                        for (key, locators) in map {
9612                            write_index_key(&mut out, key);
9613                            write_u32(
9614                                &mut out,
9615                                u32::try_from(locators.len()).expect("≤ 4G locators/key"),
9616                            );
9617                            for loc in locators {
9618                                loc.write_le(&mut out);
9619                            }
9620                        }
9621                    }
9622                    // v7.38.1 (L12) — tag byte 7 = BTreeMulti. Payload
9623                    // mirrors the tag-0 BTree encoding, with each key
9624                    // written as `[u16 arity]` followed by that many
9625                    // `write_index_key` components. FILE_VERSION 91+;
9626                    // older catalogs never carried a multi index, so no
9627                    // migration shim is needed.
9628                    IndexKind::BTreeMulti(map) => {
9629                        out.push(7);
9630                        write_u32(
9631                            &mut out,
9632                            u32::try_from(map.len()).expect("≤ 4G index entries/index"),
9633                        );
9634                        for (key, locators) in map {
9635                            write_u16(
9636                                &mut out,
9637                                u16::try_from(key.len()).expect("≤ 65k key components"),
9638                            );
9639                            for component in key.iter() {
9640                                write_index_key(&mut out, component);
9641                            }
9642                            write_u32(
9643                                &mut out,
9644                                u32::try_from(locators.len()).expect("≤ 4G locators/key"),
9645                            );
9646                            for loc in locators {
9647                                loc.write_le(&mut out);
9648                            }
9649                        }
9650                    }
9651                    IndexKind::Nsw(g) => {
9652                        out.push(1);
9653                        write_u16(&mut out, u16::try_from(g.m).expect("≤ 65k NSW neighbours"));
9654                        write_nsw_graph(&mut out, g);
9655                    }
9656                    IndexKind::Brin { column_type, .. } => {
9657                        // v6.7.1 — tag byte 2 = BRIN. Payload is the
9658                        // column type code (1 byte mapping to the
9659                        // shared DataType numeric encoding); no
9660                        // further data — BRIN summaries live in
9661                        // cold segments, not the catalog.
9662                        out.push(2);
9663                        write_data_type(&mut out, *column_type);
9664                    }
9665                    IndexKind::Gin(map) => {
9666                        // v7.12.3 — tag byte 3 = GIN. Payload mirrors
9667                        // the BTree encoding but with String (lexeme
9668                        // word) keys instead of IndexKey. Tag-prefixed
9669                        // RowLocator codec so freezer-produced Cold
9670                        // locators survive snapshot round-trip.
9671                        // FILE_VERSION 21+; v20 catalogs never wrote a
9672                        // GIN index (the AM degraded to BTree fallback
9673                        // pre-v7.12.3), so no migration shim is needed.
9674                        out.push(3);
9675                        write_u32(
9676                            &mut out,
9677                            u32::try_from(map.len()).expect("≤ 4G GIN posting lists"),
9678                        );
9679                        for (word, locators) in map {
9680                            write_str(&mut out, word);
9681                            write_u32(
9682                                &mut out,
9683                                u32::try_from(locators.len()).expect("≤ 4G locators/posting list"),
9684                            );
9685                            for loc in locators {
9686                                loc.write_le(&mut out);
9687                            }
9688                        }
9689                    }
9690                    IndexKind::GinTrgm(map) => {
9691                        // v7.15.0 — tag byte 4 = GinTrgm
9692                        // (`gin_trgm_ops` GIN over a TEXT column).
9693                        // Payload shape is identical to tag-3 GIN —
9694                        // `String → Vec<RowLocator>` posting lists.
9695                        // The String keys are 3-byte trigrams instead
9696                        // of tsvector lexemes; the deserializer
9697                        // dispatches on the tag, not the key shape.
9698                        // FILE_VERSION 24+; v23 catalogs never wrote
9699                        // a trigram-GIN.
9700                        out.push(4);
9701                        write_u32(
9702                            &mut out,
9703                            u32::try_from(map.len()).expect("≤ 4G trigram-GIN posting lists"),
9704                        );
9705                        for (tri, locators) in map {
9706                            write_str(&mut out, tri);
9707                            write_u32(
9708                                &mut out,
9709                                u32::try_from(locators.len()).expect("≤ 4G locators/posting list"),
9710                            );
9711                            for loc in locators {
9712                                loc.write_le(&mut out);
9713                            }
9714                        }
9715                    }
9716                    IndexKind::GinFulltext(map) => {
9717                        // v7.17.0 Phase 2.2 — tag byte 5 =
9718                        // GinFulltext (MySQL `FULLTEXT KEY` GIN
9719                        // over a TEXT/VARCHAR column). Payload
9720                        // shape mirrors tag-3 / tag-4 GIN —
9721                        // `String → Vec<RowLocator>` posting
9722                        // lists keyed by lower-cased word
9723                        // lexemes. FILE_VERSION 33+; v32 catalogs
9724                        // never wrote a fulltext-GIN (FULLTEXT
9725                        // KEY was silently dropped pre-v7.17).
9726                        out.push(5);
9727                        write_u32(
9728                            &mut out,
9729                            u32::try_from(map.len()).expect("≤ 4G fulltext-GIN posting lists"),
9730                        );
9731                        for (lex, locators) in map {
9732                            write_str(&mut out, lex);
9733                            write_u32(
9734                                &mut out,
9735                                u32::try_from(locators.len()).expect("≤ 4G locators/posting list"),
9736                            );
9737                            for loc in locators {
9738                                loc.write_le(&mut out);
9739                            }
9740                        }
9741                    }
9742                    IndexKind::GinJsonb(map) => {
9743                        // v7.37.8 — tag byte 6 = GinJsonb
9744                        // (real posting-list GIN over a JSONB
9745                        // column; sentori Epic 5 P2). Payload
9746                        // shape mirrors tag-3 / 4 / 5 — keys are
9747                        // the canonical `(path, leaf)` tokens
9748                        // from `jsonb_gin::extract_tokens`.
9749                        // FILE_VERSION 51+; v50 catalogs never
9750                        // wrote a JSONB-GIN (the same DDL loaded
9751                        // as a BTree fallback).
9752                        out.push(6);
9753                        write_u32(
9754                            &mut out,
9755                            u32::try_from(map.len()).expect("≤ 4G JSONB-GIN posting lists"),
9756                        );
9757                        for (token, locators) in map {
9758                            write_str(&mut out, token);
9759                            write_u32(
9760                                &mut out,
9761                                u32::try_from(locators.len()).expect("≤ 4G locators/posting list"),
9762                            );
9763                            for loc in locators {
9764                                loc.write_le(&mut out);
9765                            }
9766                        }
9767                    }
9768                }
9769                // v6.8.0 — included_columns appendix per index.
9770                // Layout: [u16 num_included][num × u16 column_position].
9771                // v11 readers stop before this u16 (deserialise loop
9772                // gated on version >= 12); v12+ readers always
9773                // consume it. Empty Vec serialises as a bare 0u16.
9774                write_u16(
9775                    &mut out,
9776                    u16::try_from(idx.included_columns.len()).expect("≤ 65k INCLUDE columns/index"),
9777                );
9778                for col_pos in &idx.included_columns {
9779                    write_u16(
9780                        &mut out,
9781                        u16::try_from(*col_pos).expect("≤ 65k columns/table"),
9782                    );
9783                }
9784                // v6.8.1 — partial_predicate appendix per index.
9785                // Layout: [u8 has_pred][u16 LE len][bytes (if has_pred)].
9786                // Same v12 gate as included_columns.
9787                match &idx.partial_predicate {
9788                    None => out.push(0),
9789                    Some(pred) => {
9790                        out.push(1);
9791                        write_str(&mut out, pred);
9792                    }
9793                }
9794                // v6.8.2 — expression appendix. Same shape as
9795                // partial_predicate.
9796                match &idx.expression {
9797                    None => out.push(0),
9798                    Some(expr) => {
9799                        out.push(1);
9800                        write_str(&mut out, expr);
9801                    }
9802                }
9803                // v7.9.29 — is_unique appendix (FILE_VERSION 16+).
9804                // Single byte 0/1. v15-and-below readers stop before
9805                // this byte; v16 readers always consume it. mailrs K1.
9806                out.push(u8::from(idx.is_unique));
9807                // v7.9.29 — extra_column_positions appendix.
9808                // Layout: [u16 count][count × u16 column_position].
9809                write_u16(
9810                    &mut out,
9811                    u16::try_from(idx.extra_column_positions.len())
9812                        .expect("≤ 65k extra cols / index"),
9813                );
9814                for cp in &idx.extra_column_positions {
9815                    write_u16(&mut out, u16::try_from(*cp).expect("≤ 65k columns/table"));
9816                }
9817                // v7.39 (read01 round 52) — nulls_not_distinct (FILE_VERSION
9818                // 62+). Appended at the end of the per-index block so the v16
9819                // layout above is untouched; v61-and-below readers stop before
9820                // this byte and default the flag to false (NULLS DISTINCT).
9821                out.push(u8::from(idx.nulls_not_distinct));
9822                // v7.39 (round 537) — the key column's ordering clause
9823                // (FILE_VERSION 83+).
9824                out.push(u8::from(idx.descending));
9825                out.push(match idx.nulls_first {
9826                    None => 0,
9827                    Some(true) => 1,
9828                    Some(false) => 2,
9829                });
9830                // v7.39 (round 538) — the key's explicit collation
9831                // (FILE_VERSION 84+).
9832                match &idx.collation {
9833                    Some(c) => {
9834                        out.push(1);
9835                        write_str(&mut out, c);
9836                    }
9837                    None => out.push(0),
9838                }
9839                // v7.39.11 — the EXTRA key columns' ordering clauses
9840                // (FILE_VERSION 95+). Appended after the collation so a
9841                // v94 reader stops before it and defaults every extra
9842                // to ascending / nulls last, which is what those
9843                // snapshots recorded.
9844                write_u16(
9845                    &mut out,
9846                    u16::try_from(idx.extra_orders.len()).expect("\u{2264} 65k extra cols / index"),
9847                );
9848                for o in &idx.extra_orders {
9849                    out.push(u8::from(o.descending));
9850                    out.push(match o.nulls_first {
9851                        None => 0,
9852                        Some(true) => 1,
9853                        Some(false) => 2,
9854                    });
9855                }
9856            }
9857            // v6.7.2 — per-table hot_tier_bytes Option<u64>.
9858            // Layout: [u8 has_value][u64 LE value (if has_value)].
9859            // v10 readers stop before this byte (deserialise loop
9860            // gated on version >= 11); v11+ readers always
9861            // consume it.
9862            match t.schema.hot_tier_bytes {
9863                None => out.push(0),
9864                Some(n) => {
9865                    out.push(1);
9866                    out.extend_from_slice(&n.to_le_bytes());
9867                }
9868            }
9869            // v7.6.1 — FOREIGN KEY appendix (catalog FILE_VERSION 13+).
9870            // Layout: [u16 LE fk_count]
9871            //   per fk:
9872            //     [u8 has_name] [str name (if has_name)]
9873            //     [u16 LE local_arity] [u16 LE local_pos]*arity
9874            //     [str parent_table]
9875            //     [u16 LE parent_arity] [u16 LE parent_pos]*arity
9876            //     [u8 on_delete_tag] [u8 on_update_tag]
9877            // Older catalogs (v12 and below) skip this block entirely;
9878            // their reader stops before this byte.
9879            write_u16(
9880                &mut out,
9881                u16::try_from(t.schema.foreign_keys.len()).expect("≤ 65k FKs/table"),
9882            );
9883            for fk in &t.schema.foreign_keys {
9884                match &fk.name {
9885                    None => out.push(0),
9886                    Some(n) => {
9887                        out.push(1);
9888                        write_str(&mut out, n);
9889                    }
9890                }
9891                write_u16(
9892                    &mut out,
9893                    u16::try_from(fk.local_columns.len()).expect("≤ 65k FK columns"),
9894                );
9895                for &p in &fk.local_columns {
9896                    write_u16(&mut out, u16::try_from(p).expect("≤ 65k columns/table"));
9897                }
9898                write_str(&mut out, &fk.parent_table);
9899                write_u16(
9900                    &mut out,
9901                    u16::try_from(fk.parent_columns.len()).expect("≤ 65k FK parent columns"),
9902                );
9903                for &p in &fk.parent_columns {
9904                    write_u16(&mut out, u16::try_from(p).expect("≤ 65k columns/table"));
9905                }
9906                out.push(fk.on_delete.tag());
9907                out.push(fk.on_update.tag());
9908                // v7.38 (read01, T29) — MATCH type tag (FILE_VERSION 55+).
9909                out.push(fk.match_type.tag());
9910                // v7.39 (round 288) — constraint timing (FILE_VERSION 79+).
9911                // One byte, bit 0 = DEFERRABLE, bit 1 = INITIALLY DEFERRED.
9912                out.push(u8::from(fk.deferrable) | (u8::from(fk.initially_deferred) << 1));
9913            }
9914            // v7.9.19 — UniquenessConstraint appendix (catalog
9915            // FILE_VERSION 15+). Layout per table after the FK
9916            // block:
9917            //   [u16 count]
9918            //     per constraint:
9919            //       [u8 is_primary_key]
9920            //       [u16 arity][u16 col_pos]*arity
9921            // Older catalogs (v14 and below) skip this block.
9922            write_u16(
9923                &mut out,
9924                u16::try_from(t.schema.uniqueness_constraints.len())
9925                    .expect("≤ 65k uniqueness constraints/table"),
9926            );
9927            for uc in &t.schema.uniqueness_constraints {
9928                out.push(u8::from(uc.is_primary_key));
9929                write_u16(
9930                    &mut out,
9931                    u16::try_from(uc.columns.len()).expect("≤ 65k cols in uniqueness constraint"),
9932                );
9933                for &p in &uc.columns {
9934                    write_u16(&mut out, u16::try_from(p).expect("≤ 65k columns/table"));
9935                }
9936                // v7.13.0 — `nulls_not_distinct` flag
9937                // (FILE_VERSION 23+). Always written by writers at
9938                // version 23+; deserialise gates on `version >= 23`
9939                // so v22-and-below catalogs round-trip cleanly.
9940                out.push(u8::from(uc.nulls_not_distinct));
9941            }
9942            // v7.9.21 — runtime_default appendix per table.
9943            // Layout: [u16 count] then for each:
9944            //   [u16 col_pos][str expr]
9945            // Only columns whose runtime_default is Some land here;
9946            // catalog stays compact for the common literal-default
9947            // case.
9948            let mut rt_defaults: Vec<(usize, &str)> = Vec::new();
9949            for (i, c) in t.schema.columns.iter().enumerate() {
9950                if let Some(e) = &c.runtime_default {
9951                    rt_defaults.push((i, e.as_str()));
9952                }
9953            }
9954            write_u16(
9955                &mut out,
9956                u16::try_from(rt_defaults.len()).expect("≤ 65k runtime defaults/table"),
9957            );
9958            for (pos, expr) in rt_defaults {
9959                write_u16(&mut out, u16::try_from(pos).expect("≤ 65k columns/table"));
9960                write_str(&mut out, expr);
9961            }
9962            // v7.13.0 — CHECK constraint appendix per table.
9963            // Layout: [u16 count] then `count` Display-form
9964            // expression strings. Re-parsed on every INSERT/UPDATE
9965            // by the engine. FILE_VERSION 23+ only; v22 readers
9966            // never reach this block because the writer also moves
9967            // to v23 in lock-step.
9968            write_u16(
9969                &mut out,
9970                u16::try_from(t.schema.checks.len()).expect("≤ 65k CHECK constraints/table"),
9971            );
9972            for c in &t.schema.checks {
9973                // v7.39 (read01 round 48) — the expr stays in this v23
9974                // appendix (byte layout unchanged for old readers); the
9975                // name rides the v60 constraint-name appendix at the tail.
9976                write_str(&mut out, c.expr.as_str());
9977            }
9978            // v7.17.0 Phase 1.4 — per-table user_enum_type
9979            // appendix. Layout: [u16 count] then
9980            // [u16 col_pos][str enum_name] per binding. Only
9981            // columns whose user_enum_type is Some land here.
9982            let mut enum_bindings: Vec<(usize, &str)> = Vec::new();
9983            for (i, c) in t.schema.columns.iter().enumerate() {
9984                if let Some(e) = &c.user_enum_type {
9985                    enum_bindings.push((i, e.as_str()));
9986                }
9987            }
9988            write_u16(
9989                &mut out,
9990                u16::try_from(enum_bindings.len()).expect("≤ 65k enum-typed columns/table"),
9991            );
9992            for (pos, ename) in enum_bindings {
9993                write_u16(&mut out, u16::try_from(pos).expect("≤ 65k columns/table"));
9994                write_str(&mut out, ename);
9995            }
9996            // v7.17.0 Phase 1.5 — per-table user_domain_type
9997            // appendix. Same layout as the enum one. v29-and-
9998            // below readers stop after the enum appendix.
9999            let mut domain_bindings: Vec<(usize, &str)> = Vec::new();
10000            for (i, c) in t.schema.columns.iter().enumerate() {
10001                if let Some(d) = &c.user_domain_type {
10002                    domain_bindings.push((i, d.as_str()));
10003                }
10004            }
10005            write_u16(
10006                &mut out,
10007                u16::try_from(domain_bindings.len()).expect("≤ 65k domain-typed columns/table"),
10008            );
10009            for (pos, dname) in domain_bindings {
10010                write_u16(&mut out, u16::try_from(pos).expect("≤ 65k columns/table"));
10011                write_str(&mut out, dname);
10012            }
10013            // v7.17.0 Phase 2.1 — per-table on_update_runtime
10014            // appendix. Sparse: only ON UPDATE-bound columns.
10015            let mut on_update_bindings: Vec<(usize, &str)> = Vec::new();
10016            for (i, c) in t.schema.columns.iter().enumerate() {
10017                if let Some(e) = &c.on_update_runtime {
10018                    on_update_bindings.push((i, e.as_str()));
10019                }
10020            }
10021            write_u16(
10022                &mut out,
10023                u16::try_from(on_update_bindings.len()).expect("≤ 65k ON UPDATE columns/table"),
10024            );
10025            for (pos, expr_src) in on_update_bindings {
10026                write_u16(&mut out, u16::try_from(pos).expect("≤ 65k columns/table"));
10027                write_str(&mut out, expr_src);
10028            }
10029            // v7.17.0 Phase 2.5 — per-table collation appendix.
10030            // Sparse: only non-Binary columns land. Layout:
10031            // `[u16 count][u16 col_pos][u8 tag] × count`.
10032            let mut coll_bindings: Vec<(usize, u8)> = Vec::new();
10033            for (i, c) in t.schema.columns.iter().enumerate() {
10034                let tag = match c.collation {
10035                    Collation::Binary => continue,
10036                    Collation::CaseInsensitive => Collation::TAG_CASE_INSENSITIVE,
10037                };
10038                coll_bindings.push((i, tag));
10039            }
10040            write_u16(
10041                &mut out,
10042                u16::try_from(coll_bindings.len()).expect("≤ 65k collation bindings/table"),
10043            );
10044            for (pos, tag) in coll_bindings {
10045                write_u16(&mut out, u16::try_from(pos).expect("≤ 65k columns/table"));
10046                out.push(tag);
10047            }
10048            // v7.17.0 Phase 4.4 — per-table is_unsigned appendix.
10049            // Sparse: only UNSIGNED columns land. Layout:
10050            // `[u16 count][u16 col_pos] × count`.
10051            let mut unsigned_bindings: Vec<usize> = Vec::new();
10052            for (i, c) in t.schema.columns.iter().enumerate() {
10053                if c.is_unsigned {
10054                    unsigned_bindings.push(i);
10055                }
10056            }
10057            write_u16(
10058                &mut out,
10059                u16::try_from(unsigned_bindings.len()).expect("≤ 65k UNSIGNED columns/table"),
10060            );
10061            for pos in unsigned_bindings {
10062                write_u16(&mut out, u16::try_from(pos).expect("≤ 65k columns/table"));
10063            }
10064            // v7.17.0 Phase 3.P0-36 — per-table inline_enum_variants
10065            // appendix. Sparse: only ENUM columns land. Layout:
10066            // `[u16 count] then per binding [u16 col_pos]
10067            // [u16 variant_count] then variant strings`.
10068            // FILE_VERSION 41+; v40 readers never reach this block.
10069            let mut enum_inline_bindings: Vec<(usize, &[String])> = Vec::new();
10070            for (i, c) in t.schema.columns.iter().enumerate() {
10071                if let Some(vs) = &c.inline_enum_variants {
10072                    enum_inline_bindings.push((i, vs.as_slice()));
10073                }
10074            }
10075            write_u16(
10076                &mut out,
10077                u16::try_from(enum_inline_bindings.len()).expect("≤ 65k inline-ENUM columns/table"),
10078            );
10079            for (pos, variants) in enum_inline_bindings {
10080                write_u16(&mut out, u16::try_from(pos).expect("≤ 65k columns/table"));
10081                write_u16(
10082                    &mut out,
10083                    u16::try_from(variants.len()).expect("≤ 65k variants/ENUM"),
10084                );
10085                for v in variants {
10086                    write_str(&mut out, v.as_str());
10087                }
10088            }
10089            // v7.17.0 Phase 3.P0-37 — per-table inline_set_variants
10090            // appendix. Same layout as the inline ENUM block.
10091            // FILE_VERSION 42+; v41 readers never reach this block.
10092            let mut set_inline_bindings: Vec<(usize, &[String])> = Vec::new();
10093            for (i, c) in t.schema.columns.iter().enumerate() {
10094                if let Some(vs) = &c.inline_set_variants {
10095                    set_inline_bindings.push((i, vs.as_slice()));
10096                }
10097            }
10098            write_u16(
10099                &mut out,
10100                u16::try_from(set_inline_bindings.len()).expect("≤ 65k inline-SET columns/table"),
10101            );
10102            for (pos, variants) in set_inline_bindings {
10103                write_u16(&mut out, u16::try_from(pos).expect("≤ 65k columns/table"));
10104                write_u16(
10105                    &mut out,
10106                    u16::try_from(variants.len()).expect("≤ 65k variants/SET"),
10107                );
10108                for v in variants {
10109                    write_str(&mut out, v.as_str());
10110                }
10111            }
10112            // v7.37.6-B — partition role appendix(FILE_VERSION 49+)。
10113            // Layout 详见 FILE_VERSION 49 docstring。普通表 = 单字节 0。
10114            write_partition_role(&mut out, t.schema.partition_role.as_ref());
10115            // v7.37.7 — per-table generated_stored_expr appendix
10116            // (FILE_VERSION 50+). Sparse: only columns whose
10117            // generated_stored_expr is Some land here.
10118            let mut gen_bindings: Vec<(usize, &str)> = Vec::new();
10119            for (i, c) in t.schema.columns.iter().enumerate() {
10120                if let Some(src) = &c.generated_stored_expr {
10121                    gen_bindings.push((i, src.as_str()));
10122                }
10123            }
10124            write_u16(
10125                &mut out,
10126                u16::try_from(gen_bindings.len()).expect("≤ 65k GENERATED STORED columns/table"),
10127            );
10128            for (pos, src) in gen_bindings {
10129                write_u16(&mut out, u16::try_from(pos).expect("≤ 65k columns/table"));
10130                write_str(&mut out, src);
10131            }
10132            // v7.38 (read01) — per-table default_text appendix
10133            // (FILE_VERSION 58+). Sparse: only columns whose default_text
10134            // is Some land here. Mirrors the generated_stored_expr shape.
10135            let mut default_texts: Vec<(usize, &str)> = Vec::new();
10136            for (i, c) in t.schema.columns.iter().enumerate() {
10137                if let Some(src) = &c.default_text {
10138                    default_texts.push((i, src.as_str()));
10139                }
10140            }
10141            write_u16(
10142                &mut out,
10143                u16::try_from(default_texts.len()).expect("≤ 65k defaulted columns/table"),
10144            );
10145            for (pos, src) in default_texts {
10146                write_u16(&mut out, u16::try_from(pos).expect("≤ 65k columns/table"));
10147                write_str(&mut out, src);
10148            }
10149            // v7.39 (RLS) — per-table policy appendix + the two RLS flags
10150            // (FILE_VERSION 59+). Written after the default_text block and
10151            // before the MVCC row appendix, so a v58 reader stops before it.
10152            // Layout: [u8 row_security][u8 force] [u16 policy_count] then per
10153            // policy: [str name][u8 cmd][u8 permissive][u16 role_count]
10154            // (role_count × str) [u8 has_using](+str)[u8 has_check](+str).
10155            out.push(u8::from(t.schema.row_security));
10156            out.push(u8::from(t.schema.force_row_security));
10157            write_u16(
10158                &mut out,
10159                u16::try_from(t.schema.policies.len()).expect("≤ 65k policies/table"),
10160            );
10161            for p in &t.schema.policies {
10162                write_str(&mut out, &p.name);
10163                out.push(p.cmd.to_wire_byte());
10164                out.push(u8::from(p.permissive));
10165                write_u16(
10166                    &mut out,
10167                    u16::try_from(p.roles.len()).expect("≤ 65k roles/policy"),
10168                );
10169                for r in &p.roles {
10170                    write_str(&mut out, r);
10171                }
10172                match &p.using_expr {
10173                    Some(s) => {
10174                        out.push(1);
10175                        write_str(&mut out, s);
10176                    }
10177                    None => out.push(0),
10178                }
10179                match &p.with_check_expr {
10180                    Some(s) => {
10181                        out.push(1);
10182                        write_str(&mut out, s);
10183                    }
10184                    None => out.push(0),
10185                }
10186            }
10187            // v7.37.16 (Epic W) — per-row MVCC header + stable RowId
10188            // appendix (FILE_VERSION 53+). Persists xmin/xmax/flags +
10189            // RowId for every row so a tombstone naming a pre-checkpoint
10190            // row survives a serialize→deserialize base restore
10191            // (cross-checkpoint tombstone durability). `headers` /
10192            // `rowids` are lock-step parallel to `rows` (invariant held
10193            // at every mutation boundary), so the count is `rows.len()`
10194            // and the zipped walk visits them in physical row order —
10195            // the same order the rows block above was written in. v52
10196            // readers never reach this block (the writer also moves to
10197            // v53 in lock-step); a v53 reader restores headers + ids
10198            // verbatim instead of freezing + dense-assigning.
10199            debug_assert_eq!(
10200                t.rows.len(),
10201                t.headers.len(),
10202                "headers must be lock-step with rows at serialize"
10203            );
10204            debug_assert_eq!(
10205                t.rows.len(),
10206                t.rowids.len(),
10207                "rowids must be lock-step with rows at serialize"
10208            );
10209            write_u32(
10210                &mut out,
10211                u32::try_from(t.rows.len()).expect("≤ 4G rows/table"),
10212            );
10213            for (h, rid) in t.headers.iter().zip(t.rowids.iter()) {
10214                out.extend_from_slice(&h.xmin.to_le_bytes());
10215                out.extend_from_slice(&h.xmax.to_le_bytes());
10216                out.push(h.flags);
10217                out.extend_from_slice(&rid.0.to_le_bytes());
10218            }
10219            out.extend_from_slice(
10220                &t.next_rowid
10221                    .load(core::sync::atomic::Ordering::Relaxed)
10222                    .to_le_bytes(),
10223            );
10224            // v7.39 (read01 round 48) — constraint-name appendix
10225            // (FILE_VERSION 60+). Index-aligned to the CHECK and
10226            // uniqueness-constraint appendices written above, so the
10227            // existing byte layouts stay untouched and a v59 catalog still
10228            // decodes (its constraints just come back unnamed).
10229            // Layout: [u16 check_count] then per check
10230            //         [u8 has_name] ([str name] when has_name)
10231            //         [u16 uc_count] then per uc the same pair.
10232            write_u16(
10233                &mut out,
10234                u16::try_from(t.schema.checks.len()).expect("≤ 65k CHECK constraints/table"),
10235            );
10236            for c in &t.schema.checks {
10237                match &c.name {
10238                    Some(n) => {
10239                        out.push(1);
10240                        write_str(&mut out, n);
10241                    }
10242                    None => out.push(0),
10243                }
10244            }
10245            write_u16(
10246                &mut out,
10247                u16::try_from(t.schema.uniqueness_constraints.len())
10248                    .expect("≤ 65k uniqueness constraints/table"),
10249            );
10250            for uc in &t.schema.uniqueness_constraints {
10251                match &uc.name {
10252                    Some(n) => {
10253                        out.push(1);
10254                        write_str(&mut out, n);
10255                    }
10256                    None => out.push(0),
10257                }
10258            }
10259            // v7.39 (read01 round 56) — user_composite_type appendix
10260            // (FILE_VERSION 63+). Sparse, at the very end of the per-table
10261            // block: only composite-typed columns land here, so a v62 reader
10262            // stops before it and its composite columns stay plain JSON.
10263            let mut comp_bindings: Vec<(usize, &str)> = Vec::new();
10264            for (i, c) in t.schema.columns.iter().enumerate() {
10265                if let Some(n) = &c.user_composite_type {
10266                    comp_bindings.push((i, n.as_str()));
10267                }
10268            }
10269            write_u16(
10270                &mut out,
10271                u16::try_from(comp_bindings.len()).expect("≤ 65k composite-typed columns/table"),
10272            );
10273            for (pos, n) in comp_bindings {
10274                write_u16(&mut out, u16::try_from(pos).expect("≤ 65k columns/table"));
10275                write_str(&mut out, n);
10276            }
10277            // v7.39 (read01 round 57) — owner + ACL appendix (FILE_VERSION
10278            // 64+), at the very end of the per-table block so a v63 reader
10279            // stops before it (its tables then read back owner-less, i.e.
10280            // owned by the login role, with no grants — which is exactly what
10281            // they were).
10282            match &t.schema.owner {
10283                Some(o) => {
10284                    out.push(1);
10285                    write_str(&mut out, o);
10286                }
10287                None => out.push(0),
10288            }
10289            write_u16(
10290                &mut out,
10291                u16::try_from(t.schema.acl.len()).expect("≤ 65k aclitems/table"),
10292            );
10293            for a in &t.schema.acl {
10294                write_str(&mut out, &a.grantee);
10295                write_u16(&mut out, a.privs);
10296                write_u16(&mut out, a.grantable);
10297                write_str(&mut out, &a.grantor);
10298            }
10299            // v7.39 (read01 round 59) — COLUMN acl appendix (FILE_VERSION 65+),
10300            // sparse: only columns that carry a grant land here, so a v64 reader
10301            // stops before it and its columns read back un-granted, which is
10302            // what they were.
10303            let granted: Vec<(usize, &ColumnSchema)> = t
10304                .schema
10305                .columns
10306                .iter()
10307                .enumerate()
10308                .filter(|(_, c)| !c.acl.is_empty())
10309                .collect();
10310            write_u16(
10311                &mut out,
10312                u16::try_from(granted.len()).expect("≤ 65k granted columns/table"),
10313            );
10314            for (pos, c) in granted {
10315                write_u16(&mut out, u16::try_from(pos).expect("≤ 65k columns/table"));
10316                write_u16(
10317                    &mut out,
10318                    u16::try_from(c.acl.len()).expect("≤ 65k aclitems/column"),
10319                );
10320                for a in &c.acl {
10321                    write_str(&mut out, &a.grantee);
10322                    write_u16(&mut out, a.privs);
10323                    write_u16(&mut out, a.grantable);
10324                    write_str(&mut out, &a.grantor);
10325                }
10326            }
10327            // v7.39 (round 210) — EXCLUDE-constraint appendix (FILE_VERSION
10328            // 72+), at the very end of the per-table block so a v71 reader
10329            // stops before it and its tables read back with no exclusion
10330            // constraints. Layout: [u16 excl_count] then per constraint
10331            // [str name] [u8 has_method](+str) [u16 elem_count] then per
10332            // element [u16 col_pos][str op].
10333            write_u16(
10334                &mut out,
10335                u16::try_from(t.schema.exclusion_constraints.len())
10336                    .expect("≤ 65k exclusion constraints/table"),
10337            );
10338            for ex in &t.schema.exclusion_constraints {
10339                write_str(&mut out, &ex.name);
10340                match &ex.method {
10341                    Some(m) => {
10342                        out.push(1);
10343                        write_str(&mut out, m);
10344                    }
10345                    None => out.push(0),
10346                }
10347                write_u16(
10348                    &mut out,
10349                    u16::try_from(ex.elements.len()).expect("≤ 65k elements/exclusion"),
10350                );
10351                for (pos, op) in &ex.elements {
10352                    write_u16(&mut out, u16::try_from(*pos).expect("≤ 65k columns/table"));
10353                    write_str(&mut out, op);
10354                }
10355            }
10356            // v7.39 (round 220) — identity-RESTART appendix (FILE_VERSION
10357            // 73+), sparse: only columns carrying a RESTART floor land here.
10358            let restarts: Vec<(usize, i64)> = t
10359                .schema
10360                .columns
10361                .iter()
10362                .enumerate()
10363                .filter_map(|(i, c)| c.auto_restart.map(|n| (i, n)))
10364                .collect();
10365            write_u16(
10366                &mut out,
10367                u16::try_from(restarts.len()).expect("≤ 65k restart columns/table"),
10368            );
10369            for (pos, n) in restarts {
10370                write_u16(&mut out, u16::try_from(pos).expect("≤ 65k columns/table"));
10371                out.extend_from_slice(&n.to_le_bytes());
10372            }
10373            // v7.39 (round 386, type-fidelity epic P1) — per-table
10374            // mysql_int_width appendix (FILE_VERSION 81+). Sparse: only
10375            // TINYINT / MEDIUMINT columns land. Layout:
10376            // `[u16 count]([u16 col_pos][u8 width_tag]) × count`
10377            // (tag 0 = Tiny, 1 = Medium). v80-and-below readers stop after
10378            // the identity-RESTART appendix, leaving every column at None.
10379            let int_widths: Vec<(usize, u8)> = t
10380                .schema
10381                .columns
10382                .iter()
10383                .enumerate()
10384                .filter_map(|(i, c)| {
10385                    c.mysql_int_width.map(|w| {
10386                        let tag = match w {
10387                            MysqlIntWidth::Tiny => 0u8,
10388                            MysqlIntWidth::Medium => 1u8,
10389                            MysqlIntWidth::Small => 2u8,
10390                            MysqlIntWidth::Int => 3u8,
10391                            MysqlIntWidth::Big => 4u8,
10392                        };
10393                        (i, tag)
10394                    })
10395                })
10396                .collect();
10397            write_u16(
10398                &mut out,
10399                u16::try_from(int_widths.len()).expect("≤ 65k narrow-int columns/table"),
10400            );
10401            for (pos, tag) in int_widths {
10402                write_u16(&mut out, u16::try_from(pos).expect("≤ 65k columns/table"));
10403                out.push(tag);
10404            }
10405            // v7.39 (round 424, type-fidelity epic) — per-table mysql_fsp
10406            // appendix (FILE_VERSION 82+). Sparse: only MySQL-declared
10407            // temporal columns land. Layout:
10408            // `[u16 count]([u16 col_pos][u8 fsp]) × count`, fsp in 0..=6.
10409            // v81-and-below readers stop after the int-width appendix,
10410            // leaving every column at None (PG microsecond behaviour).
10411            let fsps: Vec<(usize, u8)> = t
10412                .schema
10413                .columns
10414                .iter()
10415                .enumerate()
10416                .filter_map(|(i, c)| c.mysql_fsp.map(|p| (i, p)))
10417                .collect();
10418            write_u16(
10419                &mut out,
10420                u16::try_from(fsps.len()).expect("≤ 65k temporal columns/table"),
10421            );
10422            for (pos, fsp) in fsps {
10423                write_u16(&mut out, u16::try_from(pos).expect("≤ 65k columns/table"));
10424                out.push(fsp);
10425            }
10426            // v7.39.2 — the declared-TIMESTAMP appendix (FILE_VERSION
10427            // 93+). Sparse: only the columns written as `TIMESTAMP` in a
10428            // MySQL session. Layout: `[u16 count]([u16 col_pos]) × count`.
10429            // v92-and-below readers stop after the CHECK appendix below,
10430            // leaving every column at `false` — which is what they meant.
10431            let declared_ts: Vec<usize> = t
10432                .schema
10433                .columns
10434                .iter()
10435                .enumerate()
10436                .filter_map(|(i, c)| c.mysql_declared_timestamp.then_some(i))
10437                .collect();
10438            write_u16(
10439                &mut out,
10440                u16::try_from(declared_ts.len()).expect("≤ 65k timestamp columns/table"),
10441            );
10442            for pos in declared_ts {
10443                write_u16(&mut out, u16::try_from(pos).expect("≤ 65k columns/table"));
10444            }
10445            // v7.39.3 — the FLOAT/DOUBLE (m,d) appendix (FILE_VERSION
10446            // 94+). Sparse: only columns declared with the pair.
10447            // Layout: `[u16 count]([u16 col_pos][u8 m][u8 d]) × count`.
10448            let float_mds: Vec<(usize, u8, u8)> = t
10449                .schema
10450                .columns
10451                .iter()
10452                .enumerate()
10453                .filter_map(|(i, c)| c.mysql_float_md.map(|(m, d)| (i, m, d)))
10454                .collect();
10455            write_u16(
10456                &mut out,
10457                u16::try_from(float_mds.len()).expect("≤ 65k (m,d) columns/table"),
10458            );
10459            for (pos, m, d) in float_mds {
10460                write_u16(&mut out, u16::try_from(pos).expect("≤ 65k columns/table"));
10461                out.push(m);
10462                out.push(d);
10463            }
10464            // v7.39 (round 652) — CHECK-validated appendix (FILE_VERSION
10465            // 87+). Sparse the other way round from the ones above: the
10466            // common case is every constraint validated, so only the
10467            // NOT VALID ones are written, by their index into the CHECK
10468            // appendix. Layout: `[u16 count]([u16 check_idx]) × count`.
10469            let unvalidated: Vec<usize> = t
10470                .schema
10471                .checks
10472                .iter()
10473                .enumerate()
10474                .filter_map(|(i, c)| (!c.validated).then_some(i))
10475                .collect();
10476            write_u16(
10477                &mut out,
10478                u16::try_from(unvalidated.len()).expect("≤ 65k CHECK constraints/table"),
10479            );
10480            for idx in unvalidated {
10481                write_u16(&mut out, u16::try_from(idx).expect("≤ 65k CHECK/table"));
10482            }
10483            // v7.39 (round 677) — per-column collation names (FILE_VERSION
10484            // 88+). Sparse: only the columns that were written with an
10485            // explicit `COLLATE` appear, so a table that declares none pays
10486            // two bytes. Layout: `[u16 count]([u16 col_idx][str]) × count`.
10487            //
10488            // Without this the declaration survives CREATE TABLE and dies
10489            // at the next restart — measured: a column declared
10490            // `COLLATE "C"` reported attcollation 950 in the session that
10491            // created it and 100 after a reload.
10492            let collated: Vec<(usize, &str)> = t
10493                .schema
10494                .columns
10495                .iter()
10496                .enumerate()
10497                .filter_map(|(i, c)| c.collation_name.as_deref().map(|n| (i, n)))
10498                .collect();
10499            write_u16(
10500                &mut out,
10501                u16::try_from(collated.len()).expect("≤ 65k columns/table"),
10502            );
10503            for (idx, name) in collated {
10504                write_u16(&mut out, u16::try_from(idx).expect("≤ 65k columns/table"));
10505                write_str(&mut out, name);
10506            }
10507            // v7.39 (round 711) — PK/UNIQUE constraint timing (FILE_VERSION
10508            // 89+). Dense, one byte per uniqueness constraint in
10509            // declaration order, the same bit layout the FK block has
10510            // carried since round 288: bit 0 = DEFERRABLE, bit 1 =
10511            // INITIALLY DEFERRED. A v88 reader stops before it.
10512            write_u16(
10513                &mut out,
10514                u16::try_from(t.schema.uniqueness_constraints.len())
10515                    .expect("≤ 65k uniqueness constraints/table"),
10516            );
10517            for uc in &t.schema.uniqueness_constraints {
10518                out.push(u8::from(uc.deferrable) | (u8::from(uc.initially_deferred) << 1));
10519            }
10520        }
10521        // v7.12.4 — catalog-wide appendix: user-defined functions
10522        // then triggers. FILE_VERSION 22+ only. v21 and earlier
10523        // readers stop after the last table; v22 readers always
10524        // consume two `u32` counts (possibly zero).
10525        //
10526        // Function entry layout:
10527        //   [str name] [str args_repr] [str returns]
10528        //   [str language] [str body]
10529        // Trigger entry layout:
10530        //   [str name] [str table] [str timing]
10531        //   [u16 event_count] (event_count × str)
10532        //   [str for_each] [str function]
10533        write_u32(
10534            &mut out,
10535            u32::try_from(self.functions.len()).expect("≤ 4G functions"),
10536        );
10537        for fd in self.functions.values() {
10538            write_str(&mut out, &fd.name);
10539            write_str(&mut out, &fd.args_repr);
10540            write_str(&mut out, &fd.returns);
10541            write_str(&mut out, &fd.language);
10542            write_str_long(&mut out, &fd.body);
10543        }
10544        write_u32(
10545            &mut out,
10546            u32::try_from(self.triggers.len()).expect("≤ 4G triggers"),
10547        );
10548        for td in &self.triggers {
10549            write_str(&mut out, &td.name);
10550            write_str(&mut out, &td.table);
10551            write_str(&mut out, &td.timing);
10552            write_u16(
10553                &mut out,
10554                u16::try_from(td.events.len()).expect("≤ 65k events / trigger"),
10555            );
10556            for ev in &td.events {
10557                write_str(&mut out, ev);
10558            }
10559            write_str(&mut out, &td.for_each);
10560            write_str(&mut out, &td.function);
10561            // v7.13.0 — `UPDATE OF cols` filter
10562            // (FILE_VERSION 23+). v22 readers omit; v23 writers
10563            // always emit (possibly zero).
10564            write_u16(
10565                &mut out,
10566                u16::try_from(td.update_columns.len()).expect("≤ 65k cols / trigger"),
10567            );
10568            for c in &td.update_columns {
10569                write_str(&mut out, c);
10570            }
10571            // v7.16.1 — TriggerDef.enabled (FILE_VERSION 25+).
10572            out.push(u8::from(td.enabled));
10573            // v7.39 (round 138) — WHEN condition text (FILE_VERSION 70+).
10574            write_str(&mut out, &td.when_condition);
10575        }
10576        // v7.17.0 Phase 1.1 — SEQUENCE catalog block (FILE_VERSION 26+).
10577        write_u32(
10578            &mut out,
10579            u32::try_from(self.sequences.len()).expect("≤ 4G sequences"),
10580        );
10581        for seq in self.sequences.values() {
10582            write_str(&mut out, &seq.name);
10583            out.push(match seq.data_type {
10584                SequenceDataType::SmallInt => 0,
10585                SequenceDataType::Int => 1,
10586                SequenceDataType::BigInt => 2,
10587            });
10588            out.extend_from_slice(&seq.start.to_le_bytes());
10589            out.extend_from_slice(&seq.increment.to_le_bytes());
10590            out.extend_from_slice(&seq.min_value.to_le_bytes());
10591            out.extend_from_slice(&seq.max_value.to_le_bytes());
10592            out.extend_from_slice(&seq.cache.to_le_bytes());
10593            out.push(u8::from(seq.cycle));
10594            match &seq.owned_by {
10595                None => out.push(0),
10596                Some((table, column)) => {
10597                    out.push(1);
10598                    write_str(&mut out, table);
10599                    write_str(&mut out, column);
10600                }
10601            }
10602            out.extend_from_slice(&seq.last_value.to_le_bytes());
10603            out.push(u8::from(seq.is_called));
10604        }
10605        // v7.17.0 Phase 1.2 — VIEW catalog block (FILE_VERSION 27+).
10606        write_u32(
10607            &mut out,
10608            u32::try_from(self.views.len()).expect("≤ 4G views"),
10609        );
10610        for view in self.views.values() {
10611            write_str(&mut out, &view.name);
10612            write_u16(
10613                &mut out,
10614                u16::try_from(view.columns.len()).expect("≤ 65k cols / view"),
10615            );
10616            for c in &view.columns {
10617                write_str(&mut out, c);
10618            }
10619            write_str_long(&mut out, &view.body);
10620            // v7.39 (round 132, FILE_VERSION 69+) — WITH CHECK OPTION marker.
10621            out.push(view.check_option);
10622        }
10623        // v7.17.0 Phase 1.3 — MATERIALIZED VIEW source registry
10624        // (FILE_VERSION 28+). The backing rows live as a regular
10625        // table of the same name already in the tables block.
10626        write_u32(
10627            &mut out,
10628            u32::try_from(self.materialized_views.len()).expect("≤ 4G materialized views"),
10629        );
10630        for (name, body) in &self.materialized_views {
10631            write_str(&mut out, name);
10632            write_str_long(&mut out, body);
10633        }
10634        // v7.17.0 Phase 1.4 — ENUM types catalog block
10635        // (FILE_VERSION 29+).
10636        write_u32(
10637            &mut out,
10638            u32::try_from(self.enum_types.len()).expect("≤ 4G enum types"),
10639        );
10640        for e in self.enum_types.values() {
10641            write_str(&mut out, &e.name);
10642            write_u16(
10643                &mut out,
10644                u16::try_from(e.labels.len()).expect("≤ 65k labels / enum"),
10645            );
10646            for l in &e.labels {
10647                write_str(&mut out, l);
10648            }
10649        }
10650        // v7.17.0 Phase 1.5 — DOMAIN types catalog block
10651        // (FILE_VERSION 30+).
10652        write_u32(
10653            &mut out,
10654            u32::try_from(self.domain_types.len()).expect("≤ 4G domain types"),
10655        );
10656        for d in self.domain_types.values() {
10657            write_str(&mut out, &d.name);
10658            write_data_type(&mut out, d.base_type);
10659            out.push(u8::from(d.nullable));
10660            match &d.default {
10661                None => out.push(0),
10662                Some(s) => {
10663                    out.push(1);
10664                    write_str(&mut out, s);
10665                }
10666            }
10667            write_u16(
10668                &mut out,
10669                u16::try_from(d.checks.len()).expect("≤ 65k CHECKs / domain"),
10670            );
10671            for c in &d.checks {
10672                write_str(&mut out, &c.expr);
10673                // v7.39 (round 260) — the constraint name (FILE_VERSION 75+).
10674                write_str(&mut out, &c.name);
10675            }
10676            // v7.39 (round 259) — the parent domain (FILE_VERSION 74+).
10677            match &d.base_domain {
10678                None => out.push(0),
10679                Some(s) => {
10680                    out.push(1);
10681                    write_str(&mut out, s);
10682                }
10683            }
10684        }
10685        // v7.17.0 Phase 1.6 — user-schemas registry
10686        // (FILE_VERSION 31+). Built-ins are hardcoded in
10687        // `is_builtin_schema` and not persisted.
10688        write_u32(
10689            &mut out,
10690            u32::try_from(self.schemas.len()).expect("≤ 4G schemas"),
10691        );
10692        for name in &self.schemas {
10693            write_str(&mut out, name);
10694        }
10695        // v7.37.42-T2 ζ-B — COMPOSITE types catalog block
10696        // (FILE_VERSION 52+). Each entry: name, u16 field_count,
10697        // then field_count `[str field_name][data_type]` pairs.
10698        write_u32(
10699            &mut out,
10700            u32::try_from(self.composite_types.len()).expect("≤ 4G composite types"),
10701        );
10702        for c in self.composite_types.values() {
10703            write_str(&mut out, &c.name);
10704            write_u16(
10705                &mut out,
10706                u16::try_from(c.fields.len()).expect("≤ 65k fields / composite"),
10707            );
10708            for (i, (fname, fty)) in c.fields.iter().enumerate() {
10709                write_str(&mut out, fname);
10710                write_data_type(&mut out, *fty);
10711                // v7.39 (round 264) — the field's user type (v76+).
10712                match c.field_user_types.get(i).and_then(Option::as_ref) {
10713                    None => out.push(0),
10714                    Some(n) => {
10715                        out.push(1);
10716                        write_str(&mut out, n);
10717                    }
10718                }
10719            }
10720        }
10721        // v7.39 (read01 round 50) — COMMENT store (FILE_VERSION 61+).
10722        // Catalog-wide, written last (before the CRC trailer) so every older
10723        // reader stops before it. Layout: [u32 count] then [str key][str text].
10724        write_u32(
10725            &mut out,
10726            u32::try_from(self.comments.len()).expect("≤ 4G comments"),
10727        );
10728        for (k, v) in &self.comments {
10729            write_str(&mut out, k);
10730            write_str_long(&mut out, v);
10731        }
10732        // v7.39 (read01 round 60) — non-table ACLs (FILE_VERSION 66+), catalog-
10733        // wide and written last so a v65 reader stops before them. The sequence
10734        // block itself sits mid-image and cannot grow without breaking older
10735        // readers, so a sequence's owner + ACL rides here, keyed by name.
10736        let acl_out = |out: &mut Vec<u8>, acl: &[AclItem]| {
10737            write_u16(out, u16::try_from(acl.len()).expect("≤ 65k aclitems"));
10738            for a in acl {
10739                write_str(out, &a.grantee);
10740                write_u16(out, a.privs);
10741                write_u16(out, a.grantable);
10742                write_str(out, &a.grantor);
10743            }
10744        };
10745        let owned: Vec<&SequenceDef> = self
10746            .sequences
10747            .values()
10748            .filter(|s| s.owner.is_some() || !s.acl.is_empty())
10749            .collect();
10750        write_u32(
10751            &mut out,
10752            u32::try_from(owned.len()).expect("≤ 4G sequences"),
10753        );
10754        for seq in owned {
10755            write_str(&mut out, &seq.name);
10756            match &seq.owner {
10757                Some(o) => {
10758                    out.push(1);
10759                    write_str(&mut out, o);
10760                }
10761                None => out.push(0),
10762            }
10763            acl_out(&mut out, &seq.acl);
10764        }
10765        acl_out(&mut out, &self.schema_acl);
10766        acl_out(&mut out, &self.database_acl);
10767        // v7.39 (read01 round 61) — FUNCTION owner + ACL (FILE_VERSION 67+).
10768        // The function block sits mid-image like the sequence one, so this
10769        // rides the catalog-wide tail too, keyed by name.
10770        let fns: Vec<&FunctionDef> = self
10771            .functions
10772            .values()
10773            .filter(|f| f.owner.is_some() || !f.acl.is_empty())
10774            .collect();
10775        write_u32(&mut out, u32::try_from(fns.len()).expect("≤ 4G functions"));
10776        for f in fns {
10777            // v7.39 (read01 round 62) — keyed by SIGNATURE now: two overloads
10778            // have two ACLs.
10779            write_str(&mut out, &function_signature_key(&f.name, &f.args_repr));
10780            match &f.owner {
10781                Some(o) => {
10782                    out.push(1);
10783                    write_str(&mut out, o);
10784                }
10785                None => out.push(0),
10786            }
10787            acl_out(&mut out, &f.acl);
10788        }
10789        // v7.39 (round 139) — RULE catalog block (FILE_VERSION 71+), catalog-
10790        // wide and written last (right before the CRC trailer) so every older
10791        // reader stops cleanly before it. Layout: [u32 count] then per rule
10792        // [str name][str table][str event][u8 instead][str when]
10793        // [u16 cmd_count]([str cmd] × cmd_count).
10794        write_u32(
10795            &mut out,
10796            u32::try_from(self.rules.len()).expect("≤ 4G rules"),
10797        );
10798        for r in &self.rules {
10799            write_str(&mut out, &r.name);
10800            write_str(&mut out, &r.table);
10801            write_str(&mut out, &r.event);
10802            out.push(u8::from(r.instead));
10803            write_str(&mut out, &r.when_condition);
10804            write_u16(
10805                &mut out,
10806                u16::try_from(r.commands.len()).expect("≤ 65k commands / rule"),
10807            );
10808            for c in &r.commands {
10809                write_str(&mut out, c);
10810            }
10811        }
10812        // v7.39 (round 280) — extended-statistics block (FILE_VERSION
10813        // 77+), appended after the RULE block for the same reason: an
10814        // older reader stops cleanly before it. Layout: [u32 count]
10815        // then per object [str name][str table][u16 n]([str kind] × n)
10816        // [u16 m]([str column] × m).
10817        write_u32(
10818            &mut out,
10819            u32::try_from(self.statistics_ext.len()).expect("≤ 4G statistics objects"),
10820        );
10821        for st in &self.statistics_ext {
10822            write_str(&mut out, &st.name);
10823            write_str(&mut out, &st.table);
10824            write_u16(
10825                &mut out,
10826                u16::try_from(st.kinds.len()).expect("≤ 65k kinds"),
10827            );
10828            for k in &st.kinds {
10829                write_str(&mut out, k);
10830            }
10831            write_u16(
10832                &mut out,
10833                u16::try_from(st.columns.len()).expect("≤ 65k columns"),
10834            );
10835            for c in &st.columns {
10836                write_str(&mut out, c);
10837            }
10838        }
10839        // v7.39 (round 287) — large-object block (FILE_VERSION 78+),
10840        // appended after the statistics block for the same reason: an
10841        // older reader stops cleanly before it. Layout: [u32 count]
10842        // then per object [u32 oid][u32 len][len bytes].
10843        write_u32(
10844            &mut out,
10845            u32::try_from(self.large_objects.len()).expect("≤ 4G large objects"),
10846        );
10847        for (oid, bytes) in &self.large_objects {
10848            write_u32(&mut out, *oid);
10849            write_u32(
10850                &mut out,
10851                u32::try_from(bytes.len()).expect("≤ 4G per object"),
10852            );
10853            out.extend_from_slice(bytes);
10854        }
10855        // v7.39 (round 322, V46) — function-attribute block (FILE_VERSION
10856        // 80+), appended last for the same reason as every block before
10857        // it: an older reader stops cleanly ahead of it and simply sees
10858        // functions with PG's default attributes. Only functions that
10859        // declared something non-default are written. Layout: [u32 count]
10860        // then per function [str signature_key][u8 volatility][u8 flags]
10861        // [u8 parallel][f64 cost or NaN][f64 rows or NaN], where flags bit
10862        // 0 = strict, 1 = security definer, 2 = leakproof.
10863        let attr_fns: Vec<(&String, &FunctionDef)> = self
10864            .functions
10865            .iter()
10866            .filter(|(_, f)| {
10867                f.volatility != FN_VOLATILE
10868                    || f.strict
10869                    || f.security_definer
10870                    || f.leakproof
10871                    || f.parallel != FN_PARALLEL_UNSAFE
10872                    || f.cost.is_some()
10873                    || f.rows.is_some()
10874            })
10875            .collect();
10876        write_u32(
10877            &mut out,
10878            u32::try_from(attr_fns.len()).expect("≤ 4G functions"),
10879        );
10880        for (key, f) in attr_fns {
10881            write_str(&mut out, key);
10882            out.push(f.volatility);
10883            let flags = u8::from(f.strict)
10884                | (u8::from(f.security_definer) << 1)
10885                | (u8::from(f.leakproof) << 2);
10886            out.push(flags);
10887            out.push(f.parallel);
10888            out.extend_from_slice(&f.cost.unwrap_or(f64::NAN).to_le_bytes());
10889            out.extend_from_slice(&f.rows.unwrap_or(f64::NAN).to_le_bytes());
10890        }
10891        // v7.38 (read01 P5.05) — CRC32C trailer over the whole image so a
10892        // corrupted snapshot is rejected on load. FILE_VERSION is >= the
10893        // trailer version, so this always runs for freshly-written images.
10894        // v7.39 (round 547) — pg_db_role_setting (FILE_VERSION 85+),
10895        // catalog-wide and written LAST so a v84 reader stops before it.
10896        // Layout: [u32 scopes] then [str database][str role][u32 params]
10897        // then [str name][str value] per param.
10898        write_u32(
10899            &mut out,
10900            u32::try_from(self.db_role_settings.len()).expect("≤ 4G scopes"),
10901        );
10902        for ((db, role), params) in &self.db_role_settings {
10903            write_str(&mut out, db);
10904            write_str(&mut out, role);
10905            write_u32(&mut out, u32::try_from(params.len()).expect("≤ 4G params"));
10906            for (name, value) in params {
10907                write_str(&mut out, name);
10908                write_str(&mut out, value);
10909            }
10910        }
10911        // v7.39 (round 550) — replication slots (FILE_VERSION 86+),
10912        // written LAST so a v85 reader stops before them.
10913        write_u32(
10914            &mut out,
10915            u32::try_from(self.replication_slots.len()).expect("≤ 4G slots"),
10916        );
10917        for (name, (plugin, slot_type)) in &self.replication_slots {
10918            write_str(&mut out, name);
10919            write_str(&mut out, plugin);
10920            write_str(&mut out, slot_type);
10921        }
10922        // v7.38.18 (S1) — the database collation (FILE_VERSION 92+).
10923        // Absent on an older image, which reads back as `C`.
10924        match &self.db_collation {
10925            None => out.push(0),
10926            Some(c) => {
10927                out.push(1);
10928                write_str(&mut out, c);
10929            }
10930        }
10931        let crc = spg_crypto::crc32c::crc32c(&out);
10932        write_u32(&mut out, crc);
10933        out
10934    }
10935
10936    /// Deserialize a previously-serialized catalog. Rejects bad magic, version
10937    /// mismatch, unknown tags, truncation, and trailing bytes.
10938    pub fn deserialize(buf: &[u8]) -> Result<Self, StorageError> {
10939        let mut cur = Cursor::new(buf);
10940        let magic = cur.take(8)?;
10941        if magic != FILE_MAGIC {
10942            return Err(StorageError::Corrupt(format!(
10943                "bad magic: expected SPGDB001, got {magic:?}"
10944            )));
10945        }
10946        let version = cur.read_u8()?;
10947        if !(MIN_SUPPORTED_FILE_VERSION..=FILE_VERSION).contains(&version) {
10948            return Err(StorageError::Corrupt(format!(
10949                "unsupported file version: {version} (supported: {MIN_SUPPORTED_FILE_VERSION}..={FILE_VERSION})"
10950            )));
10951        }
10952        // v7.23/v7.27 — escape decoding is version-gated (see
10953        // STR_LEN_ESCAPE / Cursor::codec_version).
10954        cur.codec_version = version;
10955        let table_count = cur.read_u32()? as usize;
10956        let mut cat = Self::new();
10957        for _ in 0..table_count {
10958            deserialize_table(&mut cur, &mut cat, version)?;
10959        }
10960        // v7.37.15 (Phase C.1) — stamp dense stable RelIds on load.
10961        // Pre-V6 envelopes carry no ids; a dense 1..=N assignment is
10962        // sufficient while RelId is process-local bookkeeping (the V6
10963        // envelope, Phase C.6, will round-trip real ids). Sets the
10964        // allocator above the loaded ids so a post-load CREATE TABLE
10965        // never collides.
10966        for (i, t) in cat.tables.iter_mut().enumerate() {
10967            t.set_rel_id(row_header::RelId((i as u64) + 1));
10968        }
10969        cat.next_rel_id = cat.tables.len() as u64;
10970        // v7.12.4 — catalog-wide function + trigger appendix.
10971        // FILE_VERSION 22+ only; v21 and earlier catalogs stop
10972        // after the last table.
10973        if version >= 22 {
10974            let fn_count = cur.read_u32()? as usize;
10975            for _ in 0..fn_count {
10976                let name = cur.read_str()?;
10977                let args_repr = cur.read_str()?;
10978                let returns = cur.read_str()?;
10979                let language = cur.read_str()?;
10980                let body = cur.read_str_long()?;
10981                let key = function_signature_key(&name, &args_repr);
10982                cat.functions.insert(
10983                    key,
10984                    FunctionDef {
10985                        name,
10986                        args_repr,
10987                        returns,
10988                        language,
10989                        body,
10990                        owner: None,
10991                        acl: Vec::new(),
10992                        volatility: FN_VOLATILE,
10993                        strict: false,
10994                        security_definer: false,
10995                        leakproof: false,
10996                        parallel: FN_PARALLEL_UNSAFE,
10997                        cost: None,
10998                        rows: None,
10999                    },
11000                );
11001            }
11002            let trg_count = cur.read_u32()? as usize;
11003            for _ in 0..trg_count {
11004                let name = cur.read_str()?;
11005                let table = cur.read_str()?;
11006                let timing = cur.read_str()?;
11007                let ev_count = cur.read_u16()? as usize;
11008                let mut events = Vec::with_capacity(ev_count);
11009                for _ in 0..ev_count {
11010                    events.push(cur.read_str()?);
11011                }
11012                let for_each = cur.read_str()?;
11013                let function = cur.read_str()?;
11014                // v7.13.0 — trailing `UPDATE OF cols` filter
11015                // (FILE_VERSION 23+ only; v22 catalogs omit and
11016                // deserialise with an empty vec).
11017                let update_columns = if version >= 23 {
11018                    let n = cur.read_u16()? as usize;
11019                    let mut cols = Vec::with_capacity(n);
11020                    for _ in 0..n {
11021                        cols.push(cur.read_str()?);
11022                    }
11023                    cols
11024                } else {
11025                    Vec::new()
11026                };
11027                // v7.16.1 — TriggerDef.enabled (FILE_VERSION 25+).
11028                // v24-and-below catalogs deserialise with `true`
11029                // — pre-v7.16.1 every trigger always fired.
11030                let enabled = if version >= 25 {
11031                    cur.read_u8()? != 0
11032                } else {
11033                    true
11034                };
11035                // v7.39 (round 138) — WHEN condition text added at FILE_VERSION
11036                // 70; older catalogs read back empty (no WHEN filter).
11037                let when_condition = if version >= 70 {
11038                    cur.read_str()?
11039                } else {
11040                    String::new()
11041                };
11042                cat.triggers.push(TriggerDef {
11043                    name,
11044                    table,
11045                    timing,
11046                    events,
11047                    for_each,
11048                    function,
11049                    update_columns,
11050                    enabled,
11051                    when_condition,
11052                });
11053            }
11054        }
11055        // v7.17.0 Phase 1.1 — SEQUENCE block (FILE_VERSION 26+).
11056        // v25-and-below catalogs omit; we leave the map empty.
11057        if version >= 26 {
11058            let seq_count = cur.read_u32()? as usize;
11059            for _ in 0..seq_count {
11060                let name = cur.read_str()?;
11061                let data_type = match cur.read_u8()? {
11062                    0 => SequenceDataType::SmallInt,
11063                    1 => SequenceDataType::Int,
11064                    2 => SequenceDataType::BigInt,
11065                    other => {
11066                        return Err(StorageError::Corrupt(format!(
11067                            "unknown SEQUENCE data-type tag {other}"
11068                        )));
11069                    }
11070                };
11071                let start = cur.read_i64()?;
11072                let increment = cur.read_i64()?;
11073                let min_value = cur.read_i64()?;
11074                let max_value = cur.read_i64()?;
11075                let cache = cur.read_i64()?;
11076                let cycle = cur.read_u8()? != 0;
11077                let owned_by = match cur.read_u8()? {
11078                    0 => None,
11079                    1 => {
11080                        let t = cur.read_str()?;
11081                        let c = cur.read_str()?;
11082                        Some((t, c))
11083                    }
11084                    other => {
11085                        return Err(StorageError::Corrupt(format!(
11086                            "unknown SEQUENCE owned-by tag {other}"
11087                        )));
11088                    }
11089                };
11090                let last_value = cur.read_i64()?;
11091                let is_called = cur.read_u8()? != 0;
11092                cat.sequences.insert(
11093                    name.clone(),
11094                    SequenceDef {
11095                        name,
11096                        data_type,
11097                        start,
11098                        increment,
11099                        min_value,
11100                        max_value,
11101                        cache,
11102                        cycle,
11103                        owned_by,
11104                        last_value,
11105                        is_called,
11106                        owner: None,
11107                        acl: Vec::new(),
11108                    },
11109                );
11110            }
11111        }
11112        // v7.17.0 Phase 1.2 — VIEW block (FILE_VERSION 27+).
11113        // v26-and-below catalogs omit; we leave the map empty.
11114        if version >= 27 {
11115            let view_count = cur.read_u32()? as usize;
11116            for _ in 0..view_count {
11117                let name = cur.read_str()?;
11118                let col_count = cur.read_u16()? as usize;
11119                let mut columns = Vec::with_capacity(col_count);
11120                for _ in 0..col_count {
11121                    columns.push(cur.read_str()?);
11122                }
11123                let body = cur.read_str_long()?;
11124                // v7.39 (round 132) — check-option marker added at FILE_VERSION
11125                // 69; older catalogs default to 0 (no check option).
11126                let check_option = if version >= 69 { cur.read_u8()? } else { 0 };
11127                cat.views.insert(
11128                    name.clone(),
11129                    ViewDef {
11130                        name,
11131                        columns,
11132                        body,
11133                        check_option,
11134                    },
11135                );
11136            }
11137        }
11138        // v7.17.0 Phase 1.3 — MATERIALIZED VIEW source registry
11139        // (FILE_VERSION 28+). v27-and-below catalogs omit.
11140        if version >= 28 {
11141            let mv_count = cur.read_u32()? as usize;
11142            for _ in 0..mv_count {
11143                let name = cur.read_str()?;
11144                let body = cur.read_str_long()?;
11145                cat.materialized_views.insert(name, body);
11146            }
11147        }
11148        // v7.17.0 Phase 1.4 — ENUM types catalog block
11149        // (FILE_VERSION 29+).
11150        if version >= 29 {
11151            let etype_count = cur.read_u32()? as usize;
11152            for _ in 0..etype_count {
11153                let name = cur.read_str()?;
11154                let label_count = cur.read_u16()? as usize;
11155                let mut labels = Vec::with_capacity(label_count);
11156                for _ in 0..label_count {
11157                    labels.push(cur.read_str()?);
11158                }
11159                cat.enum_types
11160                    .insert(name.clone(), EnumDef { name, labels });
11161            }
11162        }
11163        // v7.17.0 Phase 1.5 — DOMAIN types catalog block
11164        // (FILE_VERSION 30+).
11165        if version >= 30 {
11166            let dtype_count = cur.read_u32()? as usize;
11167            for _ in 0..dtype_count {
11168                let name = cur.read_str()?;
11169                let base_type = cur.read_data_type()?;
11170                let nullable = cur.read_u8()? != 0;
11171                let default = match cur.read_u8()? {
11172                    0 => None,
11173                    1 => Some(cur.read_str()?),
11174                    other => {
11175                        return Err(StorageError::Corrupt(format!(
11176                            "unknown DOMAIN default tag {other}"
11177                        )));
11178                    }
11179                };
11180                let check_count = cur.read_u16()? as usize;
11181                let mut checks: Vec<DomainCheck> = Vec::with_capacity(check_count);
11182                for i in 0..check_count {
11183                    let expr = cur.read_str()?;
11184                    // v7.39 (round 260) — names arrived in FILE_VERSION 75.
11185                    // An older catalog gets PG's auto-naming applied to the
11186                    // checks it stored, which is what they would have been.
11187                    let cname = if version >= 75 {
11188                        cur.read_str()?
11189                    } else if i == 0 {
11190                        alloc::format!("{name}_check")
11191                    } else {
11192                        alloc::format!("{name}_check{i}")
11193                    };
11194                    checks.push(DomainCheck { name: cname, expr });
11195                }
11196                // v7.39 (round 259) — the parent domain. Absent before
11197                // FILE_VERSION 74; an older catalog reads as a domain over
11198                // a scalar, which is what it was.
11199                let base_domain = if version >= 74 {
11200                    match cur.read_u8()? {
11201                        0 => None,
11202                        1 => Some(cur.read_str()?),
11203                        other => {
11204                            return Err(StorageError::Corrupt(alloc::format!(
11205                                "domain base_domain tag {other}"
11206                            )));
11207                        }
11208                    }
11209                } else {
11210                    None
11211                };
11212                cat.domain_types.insert(
11213                    name.clone(),
11214                    DomainDef {
11215                        name,
11216                        base_type,
11217                        nullable,
11218                        default,
11219                        checks,
11220                        base_domain,
11221                    },
11222                );
11223            }
11224        }
11225        // v7.17.0 Phase 1.6 — user-schemas registry
11226        // (FILE_VERSION 31+).
11227        if version >= 31 {
11228            let sch_count = cur.read_u32()? as usize;
11229            for _ in 0..sch_count {
11230                let name = cur.read_str()?;
11231                cat.schemas.insert(name);
11232            }
11233        }
11234        // v7.37.42-T2 ζ-B — COMPOSITE types catalog block
11235        // (FILE_VERSION 52+). v51-and-below readers stop at the
11236        // user-schemas block; v52 readers fed a v51 catalog see no
11237        // composite block and default to an empty map.
11238        if version >= 52 {
11239            let ctype_count = cur.read_u32()? as usize;
11240            for _ in 0..ctype_count {
11241                let name = cur.read_str()?;
11242                let field_count = cur.read_u16()? as usize;
11243                let mut fields = Vec::with_capacity(field_count);
11244                let mut field_user_types: Vec<Option<String>> = Vec::with_capacity(field_count);
11245                for _ in 0..field_count {
11246                    let fname = cur.read_str()?;
11247                    let fty = cur.read_data_type()?;
11248                    // v7.39 (round 264) — present from FILE_VERSION 76.
11249                    let ut = if version >= 76 {
11250                        match cur.read_u8()? {
11251                            0 => None,
11252                            1 => Some(cur.read_str()?),
11253                            other => {
11254                                return Err(StorageError::Corrupt(alloc::format!(
11255                                    "composite field user-type tag {other}"
11256                                )));
11257                            }
11258                        }
11259                    } else {
11260                        None
11261                    };
11262                    fields.push((fname, fty));
11263                    field_user_types.push(ut);
11264                }
11265                cat.composite_types.insert(
11266                    name.clone(),
11267                    CompositeDef {
11268                        name,
11269                        fields,
11270                        field_user_types,
11271                    },
11272                );
11273            }
11274        }
11275        // v7.39 (read01 round 50) — COMMENT store (FILE_VERSION 61+).
11276        if version >= 61 {
11277            let comment_count = cur.read_u32()? as usize;
11278            for _ in 0..comment_count {
11279                let key = cur.read_str()?;
11280                let text = cur.read_str_long()?;
11281                cat.comments.insert(key, text);
11282            }
11283        }
11284        // v7.39 (read01 round 60) — non-table ACLs (FILE_VERSION 66+).
11285        if version >= 66 {
11286            let read_acl = |cur: &mut Cursor| -> Result<Vec<AclItem>, StorageError> {
11287                let n = cur.read_u16()? as usize;
11288                let mut acl = Vec::with_capacity(n);
11289                for _ in 0..n {
11290                    let grantee = cur.read_str()?;
11291                    let privs = cur.read_u16()?;
11292                    let grantable = cur.read_u16()?;
11293                    let grantor = cur.read_str()?;
11294                    acl.push(AclItem {
11295                        grantee,
11296                        privs,
11297                        grantable,
11298                        grantor,
11299                    });
11300                }
11301                Ok(acl)
11302            };
11303            let seq_count = cur.read_u32()? as usize;
11304            for _ in 0..seq_count {
11305                let name = cur.read_str()?;
11306                let owner = if cur.read_u8()? == 1 {
11307                    Some(cur.read_str()?)
11308                } else {
11309                    None
11310                };
11311                let acl = read_acl(&mut cur)?;
11312                if let Some(seq) = cat.sequences.get_mut(&name) {
11313                    seq.owner = owner;
11314                    seq.acl = acl;
11315                }
11316            }
11317            cat.schema_acl = read_acl(&mut cur)?;
11318            cat.database_acl = read_acl(&mut cur)?;
11319            // v7.39 (read01 round 61) — FUNCTION owner + ACL (v67+; keyed by
11320            // signature from v68, when overloads became possible).
11321            if version >= 67 {
11322                let fn_count = cur.read_u32()? as usize;
11323                for _ in 0..fn_count {
11324                    let name = cur.read_str()?;
11325                    let owner = if cur.read_u8()? == 1 {
11326                        Some(cur.read_str()?)
11327                    } else {
11328                        None
11329                    };
11330                    let acl = read_acl(&mut cur)?;
11331                    // v7.39 (round 315, V19) — the stored key was computed
11332                    // by whichever formula was current when the image was
11333                    // written. A miss is not "no such function": before the
11334                    // multi-word fix, `f(double precision)` keyed as
11335                    // `f(precision)`, so an older image's grants would land
11336                    // nowhere and vanish silently. Fall back to matching by
11337                    // the old formula, which re-attaches them.
11338                    let target = resolve_stored_function_key(&cat.functions, &name);
11339                    if let Some(k) = target
11340                        && let Some(f) = cat.functions.get_mut(&k)
11341                    {
11342                        f.owner = owner;
11343                        f.acl = acl;
11344                    }
11345                }
11346            }
11347        }
11348        // v7.39 (round 139) — RULE catalog block (FILE_VERSION 71+), read from
11349        // the tail right before the CRC trailer. Pre-71 images stop before it.
11350        if version >= 71 {
11351            let rule_count = cur.read_u32()? as usize;
11352            for _ in 0..rule_count {
11353                let name = cur.read_str()?;
11354                let table = cur.read_str()?;
11355                let event = cur.read_str()?;
11356                let instead = cur.read_u8()? != 0;
11357                let when_condition = cur.read_str()?;
11358                let cmd_count = cur.read_u16()? as usize;
11359                let mut commands = Vec::with_capacity(cmd_count);
11360                for _ in 0..cmd_count {
11361                    commands.push(cur.read_str()?);
11362                }
11363                cat.rules.push(RuleDef {
11364                    name,
11365                    table,
11366                    event,
11367                    instead,
11368                    when_condition,
11369                    commands,
11370                });
11371            }
11372        }
11373        // v7.39 (round 280) — extended-statistics block (FILE_VERSION
11374        // 77+). Pre-77 images stop before it.
11375        if version >= 77 {
11376            let count = cur.read_u32()? as usize;
11377            for _ in 0..count {
11378                let name = cur.read_str()?;
11379                let table = cur.read_str()?;
11380                let nk = cur.read_u16()? as usize;
11381                let mut kinds = Vec::with_capacity(nk);
11382                for _ in 0..nk {
11383                    kinds.push(cur.read_str()?);
11384                }
11385                let nc = cur.read_u16()? as usize;
11386                let mut columns = Vec::with_capacity(nc);
11387                for _ in 0..nc {
11388                    columns.push(cur.read_str()?);
11389                }
11390                cat.statistics_ext.push(StatisticsExtDef {
11391                    name,
11392                    table,
11393                    kinds,
11394                    columns,
11395                });
11396            }
11397        }
11398        // v7.39 (round 287) — large-object block (FILE_VERSION 78+).
11399        // Pre-78 images stop before it.
11400        if version >= 78 {
11401            let count = cur.read_u32()? as usize;
11402            for _ in 0..count {
11403                let oid = cur.read_u32()?;
11404                let len = cur.read_u32()? as usize;
11405                let bytes = cur.read_bytes(len)?;
11406                cat.large_objects.insert(oid, bytes);
11407            }
11408        }
11409        // v7.39 (round 322, V46) — function-attribute block (FILE_VERSION
11410        // 80+). Pre-80 images stop before it and keep PG's defaults.
11411        if version >= 80 {
11412            let count = cur.read_u32()? as usize;
11413            for _ in 0..count {
11414                let key = cur.read_str()?;
11415                let volatility = cur.read_u8()?;
11416                let flags = cur.read_u8()?;
11417                let parallel = cur.read_u8()?;
11418                let cost = f64::from_le_bytes(cur.read_bytes(8)?.try_into().unwrap_or([0; 8]));
11419                let rows = f64::from_le_bytes(cur.read_bytes(8)?.try_into().unwrap_or([0; 8]));
11420                if let Some(f) = cat.functions.get_mut(&key) {
11421                    f.volatility = volatility;
11422                    f.strict = flags & 1 != 0;
11423                    f.security_definer = flags & 2 != 0;
11424                    f.leakproof = flags & 4 != 0;
11425                    f.parallel = parallel;
11426                    f.cost = (!cost.is_nan()).then_some(cost);
11427                    f.rows = (!rows.is_nan()).then_some(rows);
11428                }
11429            }
11430        }
11431        // v7.39 (round 547) — pg_db_role_setting (FILE_VERSION 85+).
11432        // Pre-85 images stop before it and carry no GUC defaults.
11433        if version >= 85 {
11434            let scopes = cur.read_u32()? as usize;
11435            for _ in 0..scopes {
11436                let db = cur.read_str()?;
11437                let role = cur.read_str()?;
11438                let params = cur.read_u32()? as usize;
11439                let mut m: BTreeMap<String, String> = BTreeMap::new();
11440                for _ in 0..params {
11441                    let name = cur.read_str()?;
11442                    let value = cur.read_str()?;
11443                    m.insert(name, value);
11444                }
11445                if !m.is_empty() {
11446                    cat.db_role_settings.insert((db, role), m);
11447                }
11448            }
11449        }
11450        // v7.39 (round 550) — replication slots (FILE_VERSION 86+).
11451        if version >= 86 {
11452            let count = cur.read_u32()? as usize;
11453            for _ in 0..count {
11454                let name = cur.read_str()?;
11455                let plugin = cur.read_str()?;
11456                let slot_type = cur.read_str()?;
11457                cat.replication_slots.insert(name, (plugin, slot_type));
11458            }
11459        }
11460        // v7.38.18 (S1) — the database collation (FILE_VERSION 92+).
11461        if version >= 92 {
11462            match cur.read_u8()? {
11463                0 => {}
11464                1 => cat.db_collation = Some(cur.read_str()?),
11465                other => {
11466                    return Err(StorageError::Corrupt(format!(
11467                        "db_collation tag: unknown byte {other}"
11468                    )));
11469                }
11470            }
11471        }
11472        // v7.38.18 (S3) — a database created under a collation this
11473        // build cannot perform does not open.
11474        //
11475        // Falling back to bytes would answer with a different comparator
11476        // than every index key in it was built under, which is the one
11477        // failure this whole layer exists to prevent — and it would do
11478        // it silently, since a byte-ordered answer looks exactly like a
11479        // correct one. The check is a NAME classification here; the
11480        // engine, which owns the collator, verifies it can actually
11481        // perform the name before recording it.
11482        if let Some(c) = &cat.db_collation
11483            && c.trim().is_empty()
11484        {
11485            return Err(StorageError::Corrupt(format!(
11486                "database collation is recorded as {c:?}, which names nothing"
11487            )));
11488        }
11489        // v7.38.18 (S2) — and every table read back learns it, because a
11490        // table decides for itself which of its indexes key under a
11491        // collation. Done here rather than per-table in the loop above
11492        // because the byte that says so is written after the tables.
11493        let db_coll = cat.db_collation().to_string();
11494        for t in &mut cat.tables {
11495            t.set_db_collation(&db_coll);
11496        }
11497        // v7.38 (read01 P5.05) — v54+ images end with a CRC32C over every
11498        // preceding byte; verify it before accepting the snapshot. Older
11499        // images have no trailer and fall through to the trailing-byte check.
11500        if version >= FILE_VERSION_CRC_TRAILER {
11501            let crc_start = cur.pos;
11502            let stored = cur.read_u32()?;
11503            let computed = spg_crypto::crc32c::crc32c(&buf[..crc_start]);
11504            if computed != stored {
11505                return Err(StorageError::Corrupt(format!(
11506                    "base snapshot CRC mismatch: computed {computed:#010x}, stored {stored:#010x}"
11507                )));
11508            }
11509        }
11510        if cur.pos < buf.len() {
11511            return Err(StorageError::Corrupt(format!(
11512                "trailing bytes: {} unread",
11513                buf.len() - cur.pos
11514            )));
11515        }
11516        Ok(cat)
11517    }
11518}
11519
11520#[cfg(test)]
11521mod tests;