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 bloom;
15mod codec;
16pub mod fts_simple;
17pub mod halfvec;
18mod nsw;
19pub mod persistent;
20pub mod persistent_btree;
21pub mod quantize;
22pub mod row_locator;
23pub mod segment;
24mod table;
25pub mod trgm;
26
27pub use self::bloom::{BloomError, BloomFilter};
28// v7.31 monster tier-3 cut 3 — on-disk codec moved to `codec`; the
29// public dense-row surface keeps its `spg_storage::*` paths, and the
30// low-level write/read primitives stay crate-visible for the
31// `Catalog::serialize`/`deserialize` methods that remain in this file.
32pub(crate) use self::codec::*;
33pub use self::codec::{decode_row_body_dense, encode_row_body_dense, row_body_encoded_len};
34// v7.31 monster tier-3 cut 2 — HNSW algorithms moved to `nsw`; the
35// public vector-search surface keeps its `spg_storage::*` paths via
36// these re-exports, and `nsw_insert_at` stays crate-visible for the
37// `Table` insert paths in the `table` module.
38pub(crate) use self::nsw::nsw_insert_at;
39pub use self::nsw::{NswMetric, cosine_dot_norms_f32, inner_product_f32, nsw_index_on, nsw_query};
40pub use self::row_locator::{RowLocator, RowLocatorError};
41pub use self::segment::{
42 BRIN_SIDECAR_MAGIC, BrinSummary, OwnedSegment, SEGMENT_COMPRESS_ALGO_LZSS,
43 SEGMENT_COMPRESS_ALGO_NONE, SEGMENT_MAGIC, SEGMENT_MAGIC_V2, SEGMENT_PAGE_BYTES, SegmentError,
44 SegmentMeta, SegmentReader, derive_brin_summaries, encode_segment, wrap_v2_envelope,
45 wrap_v2_envelope_with_brin,
46};
47
48use alloc::boxed::Box;
49use alloc::collections::{BTreeMap, BTreeSet};
50use alloc::format;
51use alloc::string::{String, ToString};
52use alloc::sync::Arc;
53use alloc::vec::Vec;
54use core::fmt;
55
56use self::persistent::PersistentVec;
57use self::persistent_btree::PersistentBTreeMap;
58
59/// In-cell encoding for `DataType::Vector`. Mirrors
60/// `spg_sql::ast::VecEncoding` — kept here so storage stays
61/// dep-free of `spg-sql`. The engine bridges between the two
62/// at DDL-execution time.
63///
64/// `F32` is the pre-v6 default: each cell holds a raw `Vec<f32>`.
65/// `Sq8` (v6.0.1) stores `Sq8Vector { min, max, bytes: Vec<u8> }`
66/// per cell; 4× compression vs `F32` with recall@10 ≥ 0.95 on
67/// natural embeddings (Gaussian / unit-sphere corpora).
68/// `F16` (v6.0.3, DDL keyword `HALF`) stores each element as
69/// IEEE-754 binary16; 2× compression and bit-exact dequantise.
70#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
71pub enum VecEncoding {
72 #[default]
73 F32,
74 Sq8,
75 F16,
76}
77
78impl fmt::Display for VecEncoding {
79 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
80 match self {
81 Self::F32 => f.write_str("F32"),
82 Self::Sq8 => f.write_str("SQ8"),
83 Self::F16 => f.write_str("HALF"),
84 }
85 }
86}
87
88/// Runtime type tags. `Vector { dim, encoding }` / `Varchar(max)` /
89/// `Char(size)` are parameterised; the parameter travels with both
90/// the column schema and the on-wire serialised representation.
91#[derive(Debug, Clone, Copy, PartialEq, Eq)]
92pub enum DataType {
93 /// 16-bit signed. Backed by `Value::SmallInt(i16)`; arithmetic that
94 /// would overflow surfaces as a type error at INSERT time.
95 SmallInt,
96 Int, // 32-bit signed
97 BigInt, // 64-bit signed
98 Float, // f64 (PG double precision)
99 Text,
100 /// `VARCHAR(n)` — same byte representation as `Text`, but INSERT
101 /// rejects values longer than `n` Unicode characters.
102 Varchar(u32),
103 /// `CHAR(n)` — same representation as `Text`, but INSERT right-pads
104 /// with U+0020 to exactly `n` Unicode characters (or rejects when
105 /// the input is already longer).
106 Char(u32),
107 Bool,
108 /// pgvector-style fixed-dimension vector. `encoding` selects
109 /// the in-cell representation (`F32` = pre-v6 raw f32 buffer;
110 /// `Sq8` = v6.0.1 8-bit scalar-quantised). The DDL grammar
111 /// surfaces encoding via the optional `USING <encoding>`
112 /// clause: `VECTOR(128) USING SQ8`.
113 Vector {
114 dim: u32,
115 encoding: VecEncoding,
116 },
117 /// `NUMERIC(precision, scale)` — exact fixed-point decimal stored as
118 /// a scaled `i128`. `precision` caps total decimal digits, `scale`
119 /// fixes digits after the decimal point. v1.12 supports up to
120 /// precision 38 (the i128-safe ceiling). `NUMERIC` and `NUMERIC(p)`
121 /// surface as `Numeric { precision: p, scale: 0 }`.
122 Numeric {
123 precision: u8,
124 scale: u8,
125 },
126 /// `DATE` — calendar date with day precision, stored as `i32` days
127 /// since the Unix epoch (1970-01-01).
128 Date,
129 /// `TIMESTAMP` (a.k.a. `MySQL` `DATETIME`) — instant with microsecond
130 /// precision, stored as `i64` microseconds since the Unix epoch.
131 Timestamp,
132 /// v7.9.2 `TIMESTAMPTZ` — bit-identical to `Timestamp` on disk
133 /// (i64 microseconds, UTC by convention). Carried as a distinct
134 /// type tag so the PG-wire layer can advertise OID 1184 (PG's
135 /// `timestamp with time zone`) and `sqlx`/`pgx`/JDBC clients
136 /// decode into their TZ-aware datetime types. The internal
137 /// semantics are unchanged: SPG never stored per-row offsets,
138 /// and neither did PG — `TIMESTAMPTZ` in PG is also UTC i64.
139 Timestamptz,
140 /// `INTERVAL` — calendar-aware span (months + microseconds). v2.11
141 /// supports INTERVAL only as a runtime intermediate (literals,
142 /// arithmetic results); on-disk encoding is rejected so this branch
143 /// can't appear in a `ColumnSchema`.
144 Interval,
145 /// v4.9: `JSON` — text-backed JSON document. We don't parse
146 /// the content (no path operators or jsonb functions yet) —
147 /// the column accepts any TEXT-compatible value and round-trips
148 /// it verbatim. PG OID 114 on the wire.
149 Json,
150 /// v7.9.0: `JSONB` — semantically identical to `Json` on
151 /// the storage side (same `Value::Json` cells, same
152 /// row codec), but advertised as PG OID 3802 on the wire
153 /// so `sqlx`-style clients that bind `jsonb` columns
154 /// decode correctly. mailrs migration blocker #3.
155 Jsonb,
156 /// v7.10.4: `BYTES` / `BYTEA` — variable-length raw binary.
157 /// Backed by `Value::Bytes(Vec<u8>)`. PG wire OID 17. Literal
158 /// forms accepted by parser/engine: PG hex form `'\xDEADBEEF'`
159 /// (case-insensitive hex pairs) and escape form
160 /// `'foo\\000bar'` (the latter decoded at coercion time when
161 /// the target column is BYTEA — TEXT columns leave the
162 /// backslash sequence verbatim).
163 Bytes,
164 /// v7.10.9: `TEXT[]` — single-dimension TEXT array. Elements
165 /// may be NULL (PG semantics). PG wire OID 1009. Literal
166 /// forms: `ARRAY['a', 'b', NULL]` and the PG external form
167 /// `'{a,b,NULL}'::TEXT[]`. Engine implements `= ANY(arr)`,
168 /// `<> ALL(arr)`, and 1-based indexing `arr[i]`. Catalog
169 /// FILE_VERSION 18+; older snapshots reject this DataType
170 /// (forward-only by design — TEXT[] columns aren't readable
171 /// on a pre-v7.10 binary).
172 TextArray,
173 /// v7.11.12: `INT[]` — single-dimension i32 array. PG wire
174 /// OID 1007 (_int4). Same `ARRAY[...]` / `'{1,2,3}'::INT[]`
175 /// literal surface as TEXT[]. Catalog FILE_VERSION 19+.
176 IntArray,
177 /// v7.11.12: `BIGINT[]` — single-dimension i64 array. PG
178 /// wire OID 1016 (_int8). Catalog FILE_VERSION 19+.
179 BigIntArray,
180 /// v7.12.0: PG `tsvector` — ordered, deduplicated set of
181 /// `(lexeme, positions, weight)` tuples. PG wire OID 3614.
182 /// Catalog FILE_VERSION 20+. Storage shape is row-codec
183 /// tag 22; the schema-agnostic `write_value` path emits tag
184 /// 18. Literal: `'foo:1 bar:2,3'::tsvector` (PG external
185 /// form). G-CRIT-3 entry — v7.12.0 only ships the type +
186 /// codec; matching `@@` lands in v7.12.2.
187 TsVector,
188 /// v7.12.0: PG `tsquery` — parse tree of lexemes joined by
189 /// `&` `|` `!` and phrase operators. PG wire OID 3615.
190 /// Catalog FILE_VERSION 20+.
191 TsQuery,
192 /// v7.17.0: PG `uuid` — 128-bit identifier stored as
193 /// `Value::Uuid([u8; 16])`. PG wire OID 2950. Canonical
194 /// text form is lowercase 8-4-4-4-12 hyphenated; input
195 /// also accepts uppercase, unhyphenated, and brace-wrapped
196 /// forms (`{xxxx…}`). Catalog FILE_VERSION 36+; tag 24 on
197 /// the dense type-tag side, tag 20 on the schema-agnostic
198 /// value side. The drop-in PG/MySQL surface for Django /
199 /// Rails / Hibernate "id UUID PRIMARY KEY DEFAULT
200 /// gen_random_uuid()" default-PK pattern.
201 Uuid,
202 /// v7.17.0 Phase 3.P0-32: PG `time` (without time zone) — i64
203 /// microseconds since 00:00:00. PG wire OID 1083. Display:
204 /// canonical zero-padded `HH:MM:SS` when fractional is zero,
205 /// `HH:MM:SS.ffffff` otherwise. Catalog FILE_VERSION 37+;
206 /// tag 25 on the dense type-tag side, tag 21 on the schema-
207 /// agnostic value side. The wall-clock-of-day half of PG's
208 /// date/time triplet (date / time / timestamp).
209 Time,
210 /// v7.17.0 Phase 3.P0-33: MySQL `YEAR` — u16 in range
211 /// 1901..=2155 plus the special zero-year sentinel 0. No
212 /// dedicated PG OID (advertised as INT4 / OID 23 on the wire
213 /// — psql renders integers, MySQL CLI renders 4-digit
214 /// zero-padded text). Display always 4 digits: `0000` for the
215 /// zero-year, `1985` / `2007` / etc otherwise. Catalog
216 /// FILE_VERSION 38+; tag 26 on the dense type-tag side, tag
217 /// 22 on the schema-agnostic value side.
218 Year,
219 /// v7.17.0 Phase 3.P0-34: PG `time with time zone` (TIMETZ) —
220 /// i64 microseconds since 00:00:00 in the local wall clock
221 /// PLUS i32 offset-from-UTC in seconds. PG wire OID 1266.
222 /// Display: `HH:MM:SS[.ffffff]±HH[:MM]` (PG `timetz_out`).
223 /// Range: offset in ±50400 seconds (±14 hours). Catalog
224 /// FILE_VERSION 39+; tag 27 on the dense type-tag side, tag
225 /// 23 on the schema-agnostic value side.
226 TimeTz,
227 /// v7.17.0 Phase 3.P0-35: PG `money` — i64 cents (locale-
228 /// independent storage). PG wire OID 790. Display: en_US
229 /// locale (`$N,NNN.CC`, negative → `-$1.23`). Input accepts
230 /// `$N.NN`, `$N,NNN.NN`, bare integer (treated as major
231 /// units), optional leading `-`. Range: full i64. Catalog
232 /// FILE_VERSION 40+; tag 28 on the dense type-tag side, tag
233 /// 24 on the schema-agnostic value side.
234 Money,
235 /// v7.17.0 Phase 3.P0-38: PG range type. The same DataType
236 /// variant covers all six builtin ranges (int4range,
237 /// int8range, numrange, tsrange, tstzrange, daterange) —
238 /// `RangeKind` pins the element type so encode / decode /
239 /// display can route off one switch. Catalog FILE_VERSION
240 /// 43+; tag 29 + a 1-byte RangeKind on the dense type-tag
241 /// side, tag 25 on the schema-agnostic value side.
242 Range(RangeKind),
243 /// v7.17.0 Phase 3.P0-39: PG `hstore` extension type — flat
244 /// `text => text` map with NULL value support. Catalog
245 /// FILE_VERSION 44+; tag 30 on the dense type-tag side, tag
246 /// 26 on the schema-agnostic value side. The contrib OID is
247 /// installation-dependent in real PG; SPG advertises it via
248 /// dynamic lookup, falling back to TEXT (OID 25) on the wire
249 /// when the installed `hstore` extension hasn't claimed an
250 /// OID yet.
251 Hstore,
252 /// v7.17.0 Phase 3.P0-40: PG `int[][]` — 2-dimensional INT
253 /// matrix. Storage: row-major Vec<Vec<Option<i32>>>. All
254 /// rows must share the same column count. Wire OID 1007
255 /// (same as INT[]; the dimension count travels in the data
256 /// header, not the OID). Catalog FILE_VERSION 45+; tag 31
257 /// on the dense type-tag side, tag 27 on the schema-agnostic
258 /// value side.
259 IntArray2D,
260 /// v7.17.0 Phase 3.P0-40: PG `bigint[][]` — 2-dimensional
261 /// BIGINT matrix. Storage / OID / tags mirror IntArray2D.
262 /// Tag 32 dense, tag 28 schema-agnostic.
263 BigIntArray2D,
264 /// v7.17.0 Phase 3.P0-40: PG `text[][]` — 2-dimensional TEXT
265 /// matrix. Storage: row-major Vec<Vec<Option<String>>>.
266 /// Tag 33 dense, tag 29 schema-agnostic.
267 TextArray2D,
268}
269
270/// v7.17.0 Phase 3.P0-38 — pins the element type of a range value
271/// or column. Wire OIDs: Int4=3904, Int8=3926, Num=3906,
272/// Ts=3908, TsTz=3910, Date=3912.
273#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
274pub enum RangeKind {
275 Int4,
276 Int8,
277 Num,
278 Ts,
279 TsTz,
280 Date,
281}
282
283impl RangeKind {
284 pub const fn tag(self) -> u8 {
285 match self {
286 Self::Int4 => 0,
287 Self::Int8 => 1,
288 Self::Num => 2,
289 Self::Ts => 3,
290 Self::TsTz => 4,
291 Self::Date => 5,
292 }
293 }
294 pub const fn from_tag(t: u8) -> Option<Self> {
295 Some(match t {
296 0 => Self::Int4,
297 1 => Self::Int8,
298 2 => Self::Num,
299 3 => Self::Ts,
300 4 => Self::TsTz,
301 5 => Self::Date,
302 _ => return None,
303 })
304 }
305 pub const fn keyword(self) -> &'static str {
306 match self {
307 Self::Int4 => "INT4RANGE",
308 Self::Int8 => "INT8RANGE",
309 Self::Num => "NUMRANGE",
310 Self::Ts => "TSRANGE",
311 Self::TsTz => "TSTZRANGE",
312 Self::Date => "DATERANGE",
313 }
314 }
315}
316
317impl fmt::Display for DataType {
318 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
319 match self {
320 Self::SmallInt => f.write_str("SMALLINT"),
321 Self::Int => f.write_str("INT"),
322 Self::BigInt => f.write_str("BIGINT"),
323 Self::Float => f.write_str("FLOAT"),
324 Self::Text => f.write_str("TEXT"),
325 Self::Varchar(n) => write!(f, "VARCHAR({n})"),
326 Self::Char(n) => write!(f, "CHAR({n})"),
327 Self::Bool => f.write_str("BOOL"),
328 Self::Vector { dim, encoding } => match encoding {
329 VecEncoding::F32 => write!(f, "VECTOR({dim})"),
330 VecEncoding::Sq8 => write!(f, "VECTOR({dim}) USING SQ8"),
331 VecEncoding::F16 => write!(f, "VECTOR({dim}) USING HALF"),
332 },
333 Self::Numeric { precision, scale } => {
334 if *scale == 0 {
335 write!(f, "NUMERIC({precision})")
336 } else {
337 write!(f, "NUMERIC({precision}, {scale})")
338 }
339 }
340 Self::Date => f.write_str("DATE"),
341 Self::Timestamp => f.write_str("TIMESTAMP"),
342 Self::Timestamptz => f.write_str("TIMESTAMPTZ"),
343 Self::Interval => f.write_str("INTERVAL"),
344 Self::Json => f.write_str("JSON"),
345 Self::Jsonb => f.write_str("JSONB"),
346 Self::Bytes => f.write_str("BYTEA"),
347 Self::TextArray => f.write_str("TEXT[]"),
348 Self::IntArray => f.write_str("INT[]"),
349 Self::BigIntArray => f.write_str("BIGINT[]"),
350 Self::TsVector => f.write_str("TSVECTOR"),
351 Self::TsQuery => f.write_str("TSQUERY"),
352 Self::Uuid => f.write_str("UUID"),
353 Self::Time => f.write_str("TIME"),
354 Self::Year => f.write_str("YEAR"),
355 Self::TimeTz => f.write_str("TIMETZ"),
356 Self::Money => f.write_str("MONEY"),
357 Self::Range(k) => f.write_str(k.keyword()),
358 Self::Hstore => f.write_str("HSTORE"),
359 Self::IntArray2D => f.write_str("INT[][]"),
360 Self::BigIntArray2D => f.write_str("BIGINT[][]"),
361 Self::TextArray2D => f.write_str("TEXT[][]"),
362 }
363 }
364}
365
366/// v7.12.0 — one entry in a `Value::TsVector`. The lexeme is the
367/// (already-tokenised + stemmed in v7.12.1+) word; `positions` is
368/// a strictly-ascending list of 1-based positions; `weight` is the
369/// PG weight letter (A=3, B=2, C=1, D=0) — v7.12.0 defaults every
370/// lexeme to D, the v7.12.2 ranking path consumes the weight.
371#[derive(Debug, Clone, PartialEq, Eq)]
372pub struct TsLexeme {
373 pub word: String,
374 pub positions: Vec<u16>,
375 pub weight: u8,
376}
377
378/// v7.12.0 — parse tree for a PG `tsquery`. v7.12.0 ships the
379/// type + codec only; the `to_tsquery` / `plainto_tsquery` lexer
380/// lands in v7.12.1 and the `@@` evaluator in v7.12.2.
381#[derive(Debug, Clone, PartialEq, Eq)]
382pub enum TsQueryAst {
383 /// Single lexeme term. The `weight_mask` is the PG-style
384 /// bitmask of accepted weights (`A=1<<3`, `B=1<<2`, `C=1<<1`,
385 /// `D=1<<0`); `0` = any weight. v7.12.0 always sets it to 0.
386 Term {
387 word: String,
388 weight_mask: u8,
389 },
390 And(Box<TsQueryAst>, Box<TsQueryAst>),
391 Or(Box<TsQueryAst>, Box<TsQueryAst>),
392 Not(Box<TsQueryAst>),
393 /// `phrase <distance> phrase`. v7.12.0 only persists this; the
394 /// match semantics arrive in v7.12.2 alongside `@@`.
395 Phrase {
396 left: Box<TsQueryAst>,
397 right: Box<TsQueryAst>,
398 distance: u16,
399 },
400}
401
402/// A row-cell value, including SQL `NULL`. `Float` uses `f64`; NaN compares
403/// non-equal to itself (PG behaviour) — `PartialEq` is derived so callers
404/// must opt into NaN-aware comparison if they need stronger guarantees.
405#[derive(Debug, Clone, PartialEq)]
406#[non_exhaustive]
407pub enum Value {
408 SmallInt(i16),
409 Int(i32),
410 BigInt(i64),
411 Float(f64),
412 Text(String),
413 Bool(bool),
414 Vector(Vec<f32>),
415 /// v6.0.1: 8-bit scalar-quantised vector cell. Lives in
416 /// columns declared `VECTOR(N) USING SQ8`. Layout per cell:
417 /// `Sq8Vector { min: f32, max: f32, bytes: Vec<u8> }` —
418 /// 4× compression vs `Vector(Vec<f32>)`. The wire layer
419 /// dequantises to `f32` on SELECT; INSERT path quantises
420 /// incoming `Vector(Vec<f32>)` cells into this variant.
421 Sq8Vector(crate::quantize::Sq8Vector),
422 /// v6.0.3: IEEE-754 binary16 vector cell. Lives in columns
423 /// declared `VECTOR(N) USING HALF`. Stores raw u16 LE bits
424 /// (2× compression vs `Vector(Vec<f32>)`). Wire / display
425 /// paths dequantise to f32 bit-exactly; INSERT path converts
426 /// incoming f32 vectors at the engine boundary.
427 HalfVector(crate::halfvec::HalfVector),
428 /// Exact fixed-point decimal. `scaled` holds the value as
429 /// `actual * 10^scale` so the storage type is always integral —
430 /// arithmetic never falls back to floating-point.
431 Numeric {
432 scaled: i128,
433 scale: u8,
434 },
435 /// Days since the Unix epoch (1970-01-01). Negative for earlier dates.
436 Date(i32),
437 /// Microseconds since the Unix epoch (1970-01-01T00:00:00Z).
438 Timestamp(i64),
439 /// Calendar span: `months` (variable-length) + `micros` (fixed-length).
440 /// Runtime-only — cannot appear in a stored row in v2.11.
441 Interval {
442 months: i32,
443 micros: i64,
444 },
445 /// v4.9 `JSON` — raw JSON text. No structural validation
446 /// happens at the storage layer; whatever the parser hands us
447 /// round-trips verbatim. Equality is byte-wise.
448 Json(String),
449 /// v7.10.4 `BYTEA` — raw binary blob. Equality is byte-wise.
450 /// Layout matches `Text`'s length-prefixed shape (`[u32 LE
451 /// len][bytes]`) under tag 18; the engine accepts PG hex
452 /// literals (`'\xDEADBEEF'`) and escape literals at the
453 /// coercion boundary.
454 Bytes(Vec<u8>),
455 /// v7.10.9 `TEXT[]` — single-dimension TEXT array with
456 /// optional NULL elements. Equality is element-wise. PG's
457 /// NULL-element comparison semantics: NULL ≠ NULL inside
458 /// arrays under `=`, so `[NULL] != [NULL]` (the engine
459 /// honours this).
460 TextArray(Vec<Option<String>>),
461 /// v7.11.12 `INT[]` — single-dimension i32 array with optional
462 /// NULL elements. Codec mirrors TextArray with i32 LE per
463 /// element instead of length-prefixed UTF-8.
464 IntArray(Vec<Option<i32>>),
465 /// v7.11.12 `BIGINT[]` — single-dimension i64 array with optional
466 /// NULL elements.
467 BigIntArray(Vec<Option<i64>>),
468 /// v7.12.0 `tsvector` — sorted-by-word, deduped lexeme set with
469 /// positions + weights. The engine enforces sort/dedup on
470 /// construction; consumers can rely on `lexemes.windows(2)`
471 /// being strictly ascending by `word`.
472 TsVector(Vec<TsLexeme>),
473 /// v7.12.0 `tsquery` — boolean / phrase parse tree over
474 /// lexemes. Engine builds via `to_tsquery` family.
475 TsQuery(TsQueryAst),
476 /// v7.17.0 `uuid` — 128-bit identifier. Stored as 16 bytes
477 /// (big-endian / network-byte order, same as RFC 4122).
478 /// Display normalises to canonical lowercase 8-4-4-4-12
479 /// hyphenated form. Equality is byte-wise.
480 Uuid([u8; 16]),
481 /// v7.17.0 Phase 3.P0-32 — PG `time` (without time zone) —
482 /// i64 microseconds since 00:00:00. Range 0..86_400_000_000.
483 /// Display: `HH:MM:SS` zero-padded, with optional `.ffffff`
484 /// suffix when fractional is non-zero.
485 Time(i64),
486 /// v7.17.0 Phase 3.P0-33 — MySQL `YEAR` — u16 in range
487 /// 1901..=2155 plus the special zero-year sentinel 0.
488 /// Display always 4 digits zero-padded (`0000` for the
489 /// sentinel; `1985`/`2007` otherwise).
490 Year(u16),
491 /// v7.17.0 Phase 3.P0-34 — PG `time with time zone` — i64
492 /// microseconds since 00:00:00 in the LOCAL wall clock PLUS
493 /// an i32 offset-from-UTC in seconds. PG preserves the
494 /// offset on output, so the wall-clock value is NOT shifted
495 /// to UTC at storage time. Offset range: ±50400 seconds
496 /// (±14 hours).
497 TimeTz {
498 us: i64,
499 offset_secs: i32,
500 },
501 /// v7.17.0 Phase 3.P0-35 — PG `money` — i64 cents
502 /// (locale-independent storage; the en_US locale renders on
503 /// display via `$N,NNN.CC`).
504 Money(i64),
505 /// v7.17.0 Phase 3.P0-39 — PG `hstore` value: flat
506 /// `text => text` map with NULL value support. Insertion
507 /// order preserved on input; duplicate keys take last-write-
508 /// wins at parse time.
509 Hstore(Vec<(String, Option<String>)>),
510 /// v7.17.0 Phase 3.P0-40 — 2D INT matrix (row-major).
511 IntArray2D(Vec<Vec<Option<i32>>>),
512 /// v7.17.0 Phase 3.P0-40 — 2D BIGINT matrix (row-major).
513 BigIntArray2D(Vec<Vec<Option<i64>>>),
514 /// v7.17.0 Phase 3.P0-40 — 2D TEXT matrix (row-major).
515 TextArray2D(Vec<Vec<Option<String>>>),
516 /// v7.17.0 Phase 3.P0-38 — PG range value. One shape covers
517 /// all six builtin range types; `kind` pins the element type
518 /// (must match the column's `DataType::Range(kind)`).
519 /// `lower` / `upper` are `None` for the unbounded sides;
520 /// `lower_inc` / `upper_inc` mirror the canonical PG
521 /// `[` / `(` / `]` / `)` bracket inclusivity. `empty=true`
522 /// supersedes all other fields (the empty range has no
523 /// bounds).
524 Range {
525 kind: RangeKind,
526 lower: Option<alloc::boxed::Box<Value>>,
527 upper: Option<alloc::boxed::Box<Value>>,
528 lower_inc: bool,
529 upper_inc: bool,
530 empty: bool,
531 },
532 Null,
533}
534
535impl Value {
536 /// Type tag, or `None` for `NULL` (unknown at value level).
537 pub fn data_type(&self) -> Option<DataType> {
538 match self {
539 Self::SmallInt(_) => Some(DataType::SmallInt),
540 Self::Int(_) => Some(DataType::Int),
541 Self::BigInt(_) => Some(DataType::BigInt),
542 Self::Float(_) => Some(DataType::Float),
543 // `Text` covers both unbounded TEXT and bounded VARCHAR/CHAR
544 // — the constraint lives on the column schema, not the value.
545 Self::Text(_) => Some(DataType::Text),
546 Self::Bool(_) => Some(DataType::Bool),
547 Self::Vector(v) => Some(DataType::Vector {
548 dim: u32::try_from(v.len()).expect("vector dim ≤ u32"),
549 encoding: VecEncoding::F32,
550 }),
551 Self::Sq8Vector(q) => Some(DataType::Vector {
552 dim: u32::try_from(q.bytes.len()).expect("vector dim ≤ u32"),
553 encoding: VecEncoding::Sq8,
554 }),
555 Self::HalfVector(h) => Some(DataType::Vector {
556 dim: u32::try_from(h.dim()).expect("vector dim ≤ u32"),
557 encoding: VecEncoding::F16,
558 }),
559 // `Value::Numeric` doesn't carry its precision (the column
560 // schema does); we surface precision=0 as "unknown" and let
561 // the engine reconcile against the column type at coercion
562 // time.
563 Self::Numeric { scale, .. } => Some(DataType::Numeric {
564 precision: 0,
565 scale: *scale,
566 }),
567 Self::Date(_) => Some(DataType::Date),
568 Self::Timestamp(_) => Some(DataType::Timestamp),
569 Self::Interval { .. } => Some(DataType::Interval),
570 Self::Json(_) => Some(DataType::Json),
571 Self::Bytes(_) => Some(DataType::Bytes),
572 Self::TextArray(_) => Some(DataType::TextArray),
573 Self::IntArray(_) => Some(DataType::IntArray),
574 Self::BigIntArray(_) => Some(DataType::BigIntArray),
575 Self::TsVector(_) => Some(DataType::TsVector),
576 Self::TsQuery(_) => Some(DataType::TsQuery),
577 Self::Uuid(_) => Some(DataType::Uuid),
578 Self::Time(_) => Some(DataType::Time),
579 Self::Year(_) => Some(DataType::Year),
580 Self::TimeTz { .. } => Some(DataType::TimeTz),
581 Self::Money(_) => Some(DataType::Money),
582 Self::Range { kind, .. } => Some(DataType::Range(*kind)),
583 Self::Hstore(_) => Some(DataType::Hstore),
584 Self::IntArray2D(_) => Some(DataType::IntArray2D),
585 Self::BigIntArray2D(_) => Some(DataType::BigIntArray2D),
586 Self::TextArray2D(_) => Some(DataType::TextArray2D),
587 Self::Null => None,
588 }
589 }
590
591 pub const fn is_null(&self) -> bool {
592 matches!(self, Self::Null)
593 }
594}
595
596/// One table row — values are positional and must match
597/// `TableSchema.columns` in length and (modulo NULL) in `DataType`.
598#[derive(Debug, Clone, PartialEq)]
599pub struct Row {
600 pub values: Vec<Value>,
601}
602
603impl Row {
604 pub const fn new(values: Vec<Value>) -> Self {
605 Self { values }
606 }
607
608 pub fn len(&self) -> usize {
609 self.values.len()
610 }
611
612 pub fn is_empty(&self) -> bool {
613 self.values.is_empty()
614 }
615}
616
617#[derive(Debug, Clone, PartialEq)]
618pub struct ColumnSchema {
619 pub name: String,
620 pub ty: DataType,
621 pub nullable: bool,
622 /// Optional `DEFAULT` value, frozen at CREATE TABLE time. `None`
623 /// means "no default" (so omitted columns become NULL, or error
624 /// out when the column is NOT NULL). Literal defaults take this
625 /// path.
626 pub default: Option<Value>,
627 /// v7.9.21 — for DEFAULT expressions that need INSERT-time
628 /// evaluation (e.g. `DEFAULT now()`, `DEFAULT CURRENT_TIMESTAMP`),
629 /// the Display form of the expression. The engine re-parses
630 /// it on each INSERT default-fill, evaluates against an empty
631 /// row context, and coerces to the column type. mailrs G4.
632 /// Persisted in catalog FILE_VERSION 15+; older catalogs
633 /// deserialise with None.
634 pub runtime_default: Option<String>,
635 /// MySQL-style `AUTO_INCREMENT`. When set, an INSERT that leaves
636 /// this column unbound (or sets it to NULL) gets the next integer
637 /// computed from the column's current max + 1.
638 pub auto_increment: bool,
639 /// v7.17.0 Phase 1.4 — when the column is bound to a user-
640 /// defined ENUM type (the parser saw an unknown type ident
641 /// and the engine resolved it against `catalog.enum_types`),
642 /// this carries the enum name so INSERT/UPDATE can validate
643 /// the cell value against the enum's labels. `ty` is
644 /// `DataType::Text` in that case. Persisted in catalog
645 /// FILE_VERSION 29+; older catalogs deserialise with None.
646 pub user_enum_type: Option<String>,
647 /// v7.17.0 Phase 1.5 — when the column is bound to a user-
648 /// defined DOMAIN (the parser saw an unknown type ident and
649 /// the engine resolved it against `catalog.domain_types`),
650 /// this carries the domain name. `ty` is the domain's base
651 /// type; INSERT/UPDATE re-evaluates the domain's CHECK list
652 /// + NOT NULL against the cell value. Persisted in catalog
653 /// FILE_VERSION 30+; older catalogs deserialise with None.
654 pub user_domain_type: Option<String>,
655 /// v7.17.0 Phase 2.1 — MySQL `ON UPDATE CURRENT_TIMESTAMP`
656 /// column attribute. When `Some(expr_src)`, an UPDATE that
657 /// does NOT bind this column overrides the new value with
658 /// the engine-evaluated expression (always `now()` in
659 /// v7.17.0). Stored as Display-form source so storage
660 /// stays free of spg-sql; the engine re-parses at UPDATE
661 /// time. Persisted in catalog FILE_VERSION 32+; older
662 /// catalogs deserialise with None — preserves the existing
663 /// "silent ignore" behaviour for snapshots written before
664 /// the upgrade.
665 pub on_update_runtime: Option<String>,
666 /// v7.17.0 Phase 2.5 — text collation. Pre-2.5 SPG accepted
667 /// `COLLATE <name>` clauses but discarded the name, so a
668 /// column declared `COLLATE "case_insensitive"` (or any
669 /// MySQL `_ci` collation) still compared byte-wise — a
670 /// Tier-S silent failure where `WHERE name = 'foo'` never
671 /// matched stored `'Foo'`. This carries the parser-derived
672 /// classification so the engine's WHERE evaluator can route
673 /// text equality through a case-aware compare. `Binary` (the
674 /// default) preserves the prior byte-wise behaviour. Only
675 /// CaseInsensitive lands in the catalog appendix — Binary
676 /// columns stay implicit, keeping snapshots compact.
677 /// Persisted in catalog FILE_VERSION 34+; older catalogs
678 /// deserialise every column as `Binary`.
679 pub collation: Collation,
680 /// v7.17.0 Phase 4.4 — MySQL `UNSIGNED` modifier flag. Drives
681 /// engine-side INSERT / UPDATE range enforcement (rejects
682 /// negative values on UNSIGNED int columns). Pre-4.4 the
683 /// parser consumed and discarded the keyword silently, so
684 /// every UNSIGNED column quietly accepted negatives — a
685 /// Tier-A correctness drift. Sparse: only UNSIGNED columns
686 /// land in the catalog appendix; the default `false` keeps
687 /// snapshots compact for the common signed-int path.
688 /// Persisted in catalog FILE_VERSION 35+; older catalogs
689 /// deserialise every column as `is_unsigned = false`.
690 pub is_unsigned: bool,
691 /// v7.17.0 Phase 3.P0-36 — MySQL inline `ENUM('a','b','c')`
692 /// value list. Distinct from `user_enum_type` (which points
693 /// to a separately CREATE TYPE'd PG enum); this carries the
694 /// column-local list MySQL DDL declares inline. When `Some`,
695 /// `ty` is `DataType::Text` and INSERT/UPDATE validates the
696 /// cell value against this list. Variant ORDER is preserved
697 /// (MySQL uses it for `ORDER BY col`). Sparse: only ENUM
698 /// columns land in the catalog appendix.
699 /// Persisted in catalog FILE_VERSION 41+; older catalogs
700 /// deserialise with None — preserves silent-drop behaviour
701 /// for snapshots written before P0-36.
702 pub inline_enum_variants: Option<Vec<String>>,
703 /// v7.17.0 Phase 3.P0-37 — MySQL inline `SET('a','b','c')`
704 /// variant list. Storage is TEXT (canonical comma-joined in
705 /// definition order, de-duplicated). INSERT/UPDATE validates
706 /// every comma-separated token against this list. Sparse:
707 /// only SET columns land in the catalog appendix.
708 /// Persisted in catalog FILE_VERSION 42+; older catalogs
709 /// deserialise with None.
710 pub inline_set_variants: Option<Vec<String>>,
711}
712
713/// v7.17.0 Phase 2.5 — column-level text collation. Drives the
714/// engine's WHERE / GROUP BY equality routing for `Value::Text`.
715/// Only two variants are modelled in v7.17:
716/// * `Binary` — byte-wise comparison (the SPG default;
717/// matches PG `COLLATE "C"` / `pg_catalog.default`
718/// and MySQL `*_bin`).
719/// * `CaseInsensitive` — ASCII case-folded comparison
720/// (matches PG `COLLATE "case_insensitive"` and
721/// MySQL `*_ci` collations). Non-ASCII bytes
722/// still compare byte-wise; full ICU folding is
723/// out of v7.17 scope.
724/// New variants append at the end — older catalogs read missing
725/// columns as `Binary`.
726#[derive(Debug, Clone, Copy, PartialEq, Eq)]
727pub enum Collation {
728 Binary,
729 CaseInsensitive,
730}
731
732#[allow(clippy::derivable_impls)]
733impl Default for Collation {
734 fn default() -> Self {
735 Self::Binary
736 }
737}
738
739impl Collation {
740 /// Wire tag persisted in the FILE_VERSION 34+ catalog appendix.
741 /// Stable: future variants append above the recognised range
742 /// and unknown tags read back as `Binary` for forward-compat
743 /// on rollback.
744 pub const TAG_BINARY: u8 = 0;
745 pub const TAG_CASE_INSENSITIVE: u8 = 1;
746}
747
748#[derive(Debug, Clone, PartialEq)]
749pub struct TableSchema {
750 pub name: String,
751 pub columns: Vec<ColumnSchema>,
752 /// v6.7.2 — per-table hot-tier byte budget override. `None`
753 /// falls through to the global `SPG_HOT_TIER_BYTES` setting;
754 /// `Some(n)` overrides it for this specific table. Set via
755 /// `ALTER TABLE t SET hot_tier_bytes = X`. Persisted in
756 /// catalog FILE_VERSION 11+.
757 pub hot_tier_bytes: Option<u64>,
758 /// v7.6.1 — FOREIGN KEY constraints declared on this table.
759 /// Engine maintains this in lock-step with `spg-sql`'s parser
760 /// AST; the storage layer carries the on-disk shape so a
761 /// catalog snapshot round-trips without external mapping.
762 /// Persisted in catalog FILE_VERSION 13+. Older catalogs
763 /// deserialise with an empty vec.
764 pub foreign_keys: Vec<ForeignKeyConstraint>,
765 /// v7.9.19 — composite UNIQUE / PRIMARY KEY constraints
766 /// declared at the table level. Each entry's leading column
767 /// has a BTree index (created via the constraint), and INSERT
768 /// path enforces the full-tuple uniqueness via a scan keyed
769 /// by the leading column. Persisted in catalog FILE_VERSION
770 /// 15+. Older catalogs (≤ 14) deserialise with an empty vec.
771 pub uniqueness_constraints: Vec<UniquenessConstraint>,
772 /// v7.13.0 — `CHECK (<expr>)` predicates declared on this
773 /// table. Both column-level inline `CHECK (…)` and
774 /// table-level `CHECK (…)` fold into this list. Each entry
775 /// is the AST Expr's `Display` form, re-parsed on every
776 /// INSERT/UPDATE and evaluated against the candidate row.
777 /// A false / NULL result rejects the mutation (PG semantics).
778 /// Persisted in catalog FILE_VERSION 23+. Older catalogs
779 /// deserialise with an empty vec.
780 pub checks: Vec<String>,
781}
782
783/// v7.9.19 — composite UNIQUE / PRIMARY KEY constraint persisted
784/// on the table schema. The leading column always has a BTree
785/// index (created at CREATE TABLE time); INSERT enforcement
786/// scans that index for collisions on the full column tuple.
787#[derive(Debug, Clone, PartialEq, Eq)]
788pub struct UniquenessConstraint {
789 /// `true` when this constraint was declared as `PRIMARY KEY`
790 /// (vs `UNIQUE`). Semantically PK implies NOT NULL on all
791 /// referenced columns; the engine enforces that at CREATE
792 /// TABLE time.
793 pub is_primary_key: bool,
794 /// Column positions on the parent table. ≥ 1 element. For
795 /// single-column UNIQUE this is exactly one position; the
796 /// BTree index alone enforces it.
797 pub columns: Vec<usize>,
798 /// v7.13.0 — `UNIQUE NULLS NOT DISTINCT` modifier
799 /// (mailrs round-5 G10; PG 15+ surface). When `true`, two
800 /// rows whose constrained columns are all NULL collide on
801 /// the constraint. Default (`false`) is the SQL-standard
802 /// `NULLS DISTINCT` behaviour where any NULL passes.
803 /// Persisted in catalog FILE_VERSION 23+.
804 pub nulls_not_distinct: bool,
805}
806
807/// v7.6.1 — Storage-layer mirror of `spg_sql::ast::ForeignKeyConstraint`.
808/// The engine's CREATE TABLE path translates between the two; keeping
809/// them separate preserves the no-deps boundary between
810/// `spg-storage` and `spg-sql`.
811#[derive(Debug, Clone, PartialEq, Eq)]
812pub struct ForeignKeyConstraint {
813 /// Optional user-supplied constraint name (`CONSTRAINT <name>`
814 /// prefix). Used by `ALTER TABLE DROP CONSTRAINT <name>` in
815 /// v7.6.8; ignored by enforcement.
816 pub name: Option<String>,
817 /// Positions of local columns in this table's column list.
818 /// Same arity as `parent_columns`.
819 pub local_columns: Vec<usize>,
820 /// Referenced parent table name.
821 pub parent_table: String,
822 /// Positions of parent columns in the parent's column list.
823 /// Engine resolves these at CREATE TABLE time (after the parent
824 /// schema is known) so enforcement paths can skip the name
825 /// lookup on every row.
826 pub parent_columns: Vec<usize>,
827 /// Referential action when a parent row is deleted.
828 pub on_delete: FkAction,
829 /// Referential action when a parent row's referenced columns
830 /// are updated.
831 pub on_update: FkAction,
832}
833
834/// v7.6.1 — referential action tag. Mirrors `spg_sql::ast::FkAction`.
835#[derive(Debug, Clone, Copy, PartialEq, Eq)]
836pub enum FkAction {
837 Restrict,
838 Cascade,
839 SetNull,
840 SetDefault,
841 NoAction,
842}
843
844impl FkAction {
845 /// On-disk tag byte (v13 catalog appendix).
846 pub const fn tag(self) -> u8 {
847 match self {
848 Self::Restrict => 0,
849 Self::Cascade => 1,
850 Self::SetNull => 2,
851 Self::SetDefault => 3,
852 Self::NoAction => 4,
853 }
854 }
855 pub const fn from_tag(b: u8) -> Option<Self> {
856 Some(match b {
857 0 => Self::Restrict,
858 1 => Self::Cascade,
859 2 => Self::SetNull,
860 3 => Self::SetDefault,
861 4 => Self::NoAction,
862 _ => return None,
863 })
864 }
865}
866
867impl TableSchema {
868 pub fn column_position(&self, name: &str) -> Option<usize> {
869 self.columns.iter().position(|c| c.name == name)
870 }
871}
872
873/// Key type accepted by secondary indices. Float / NULL / Vector values
874/// can't participate in a B-tree index — `f64` is only `PartialOrd`, NULL
875/// has SQL-three-valued semantics, and Vector belongs to the (future) HNSW
876/// path. Index lookups on those columns fall back to full scan.
877#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
878pub enum IndexKey {
879 Int(i64),
880 Text(String),
881 Bool(bool),
882 /// v7.17.0 — `Value::Uuid` index key. Comparison is byte-wise
883 /// (RFC 4122 byte order) so PRIMARY KEY UUID lookups land on
884 /// the same fast-path as Int / Text.
885 Uuid([u8; 16]),
886}
887
888impl IndexKey {
889 pub fn from_value(v: &Value) -> Option<Self> {
890 match v {
891 Value::SmallInt(n) => Some(Self::Int(i64::from(*n))),
892 Value::Int(n) => Some(Self::Int(i64::from(*n))),
893 Value::BigInt(n) => Some(Self::Int(*n)),
894 Value::Text(s) => Some(Self::Text(s.clone())),
895 Value::Bool(b) => Some(Self::Bool(*b)),
896 // Date/Timestamp use their integer storage repr as the
897 // index key — same order semantics, same comparison.
898 Value::Date(d) => Some(Self::Int(i64::from(*d))),
899 Value::Timestamp(t) => Some(Self::Int(*t)),
900 // v7.17.0: UUID indexable via byte-wise ordering. Lookup
901 // on `id = '...'::uuid` resolves through the secondary
902 // index rather than full-scan.
903 Value::Uuid(b) => Some(Self::Uuid(*b)),
904 // v7.17.0 Phase 3.P0-32: TIME indexable via i64 — same
905 // order semantics as Date/Timestamp.
906 Value::Time(us) => Some(Self::Int(*us)),
907 // v7.17.0 Phase 3.P0-33: YEAR indexable as i64 — u16
908 // widens losslessly and gives the natural calendar
909 // ordering.
910 Value::Year(y) => Some(Self::Int(i64::from(*y))),
911 // v7.17.0 Phase 3.P0-34: TIMETZ indexable by its
912 // UTC-equivalent microseconds (local wall - offset).
913 // Without normalising, two values for the same
914 // physical instant in different zones would sort
915 // wrong. Matches PG's TIMETZ index behaviour.
916 Value::TimeTz { us, offset_secs } => {
917 Some(Self::Int(us - i64::from(*offset_secs) * 1_000_000))
918 }
919 // v7.17.0 Phase 3.P0-35: MONEY indexable as i64 cents
920 // (no scaling needed — natural numeric ordering).
921 Value::Money(c) => Some(Self::Int(*c)),
922 // v7.17.0 Phase 3.P0-38: ranges are NOT indexable in
923 // v7.17.0 — they'd need a custom comparator (PG uses
924 // SP-GiST for this). Skip.
925 Value::Range { .. } => None,
926 // v7.17.0 Phase 3.P0-39: hstore is NOT indexable in
927 // v7.17.0 — map columns need GIN with bespoke ops.
928 Value::Hstore(_) => None,
929 // v7.17.0 Phase 3.P0-40: 2D arrays aren't indexable.
930 Value::IntArray2D(_) | Value::BigIntArray2D(_) | Value::TextArray2D(_) => None,
931 // Numeric isn't (yet) indexable — exact-decimal index keys
932 // would need a stable scale-normalised representation.
933 // Interval isn't index-eligible either (and can't reach this
934 // path through column storage anyway).
935 Value::Null
936 | Value::Float(_)
937 | Value::Vector(_)
938 | Value::Sq8Vector(_)
939 | Value::HalfVector(_)
940 | Value::Numeric { .. }
941 | Value::Interval { .. }
942 | Value::Json(_)
943 | Value::Bytes(_)
944 | Value::TextArray(_)
945 | Value::IntArray(_)
946 | Value::BigIntArray(_)
947 | Value::TsVector(_)
948 | Value::TsQuery(_) => None,
949 }
950 }
951}
952
953/// A single-column secondary index. v2.0 carries either a B-tree map
954/// (the default — used for equality / range lookups on scalar columns)
955/// or a navigable-small-world graph (used for kNN over vector
956/// columns).
957#[derive(Debug, Clone)]
958pub struct Index {
959 pub name: String,
960 pub column_position: usize,
961 pub kind: IndexKind,
962 /// v6.8.0 — column positions of `INCLUDE (col1, col2, …)`
963 /// non-key columns. Carries the planner's "this query is
964 /// covered by the index" signal; lookup paths still resolve
965 /// via the `RowLocator` to fetch the row body, but EXPLAIN
966 /// surfaces the covered-scan annotation so operators can
967 /// confirm the planner sees the coverage.
968 ///
969 /// Empty `Vec` = no `INCLUDE` clause (the legacy shape). v12
970 /// catalog snapshots deserialise with an empty vec.
971 pub included_columns: Vec<usize>,
972 /// v6.8.1 — partial-index predicate stored as its canonical
973 /// Display form (the engine re-parses it on the maintenance
974 /// path). `None` = unconditional index (the legacy shape).
975 /// Persisted as `[u8 has_pred][u16 LE len][bytes]` on the
976 /// catalog snapshot (FILE_VERSION 12, appended after
977 /// `included_columns`).
978 pub partial_predicate: Option<String>,
979 /// v6.8.2 — expression-index key, stored as the expression's
980 /// canonical Display form. `None` = bare column-reference
981 /// index (the legacy shape). Persisted alongside
982 /// `partial_predicate` on the v12 catalog snapshot.
983 pub expression: Option<String>,
984 /// v7.9.29 — `CREATE UNIQUE INDEX …`. When true the engine
985 /// rejects INSERTs whose key already appears in this index
986 /// (combined with `partial_predicate` when present — only
987 /// rows matching the predicate enter the uniqueness check).
988 /// Catalog FILE_VERSION 16+; older snapshots deserialise
989 /// with `false`. mailrs K1.
990 pub is_unique: bool,
991 /// v7.9.29 — extra (non-leading) column positions for
992 /// multi-column indexes (`CREATE INDEX … (a, b, c)`). The
993 /// planner today still only uses the leading
994 /// `column_position` for index seeks, but UNIQUE INDEX
995 /// enforcement walks the full tuple so partial-unique
996 /// invariants like CalDAV `(calendar_id, uid,
997 /// recurrence_id)` are enforced correctly. Catalog
998 /// FILE_VERSION 16+; older snapshots deserialise empty.
999 pub extra_column_positions: Vec<usize>,
1000}
1001
1002/// Default neighbor degree (M) for the NSW graph. Picked at construction
1003/// time and persisted with the index.
1004pub const NSW_DEFAULT_M: usize = 16;
1005
1006/// v5.2.2: outcome of a successful [`Catalog::freeze_oldest_to_cold`]
1007/// call. The catalog state has already been mutated by the time this
1008/// is returned (hot rows dropped + segment registered + Cold locators
1009/// flipped). The caller's only remaining concern is `segment_bytes` —
1010/// persist them to disk under `<db>.spg/segments/seg_<id>.spg` so a
1011/// future restart can reload via the v5.1 `SPG_PRELOAD_COLD_SEGMENT`
1012/// path. (v5.3's manifest will subsume this manual step.)
1013#[derive(Debug, Clone)]
1014pub struct FreezeReport {
1015 /// Id allocated by [`Catalog::load_segment_bytes`] for the new
1016 /// cold-tier segment. Stable across the call's success path.
1017 pub segment_id: u32,
1018 /// Number of rows that moved hot → cold. Equals the `max_rows`
1019 /// the caller asked for (the API is strict on the count).
1020 pub frozen_rows: usize,
1021 /// Hot-tier bytes reclaimed by the freeze — the
1022 /// [`Table::hot_bytes`] delta before vs after. Useful to feed
1023 /// back into the freezer's budget check on the next tick.
1024 pub bytes_freed: u64,
1025 /// Encoded segment bytes, byte-identical to what
1026 /// [`encode_segment`] produced. The catalog already owns a
1027 /// copy inside `cold_segments`; this hand-off lets the caller
1028 /// persist them without re-encoding.
1029 pub segment_bytes: Vec<u8>,
1030}
1031
1032/// v6.7.4 — read-only output of [`Catalog::prepare_freeze_slice`].
1033/// Carries every row body + key in a contiguous hot-row range,
1034/// already encoded and sorted by PK so the coordinator's merge
1035/// step is a k-way merge over already-sorted streams.
1036///
1037/// `Vec<FreezeSlice>` from N independent workers feeds
1038/// [`Catalog::commit_freeze_slices`], which concats + encodes the
1039/// merged segment + atomically swaps the catalog state.
1040#[derive(Debug, Clone)]
1041pub struct FreezeSlice {
1042 /// Hot-row index range this slice covered (half-open, in the
1043 /// table's `rows: PersistentVec` ordering at call time). The
1044 /// commit step uses this to compute the union range that
1045 /// gets passed to [`Table::delete_rows`].
1046 pub row_range: core::ops::Range<usize>,
1047 /// `(pk_u64, encoded_row_body, IndexKey)` triples, sorted
1048 /// ascending by `pk_u64`. Per-slice sort happens inside
1049 /// `prepare_freeze_slice`; the coordinator does only a
1050 /// k-way merge to reach the global PK ordering
1051 /// [`encode_segment`] requires.
1052 pub rows: Vec<(u64, Vec<u8>, IndexKey)>,
1053}
1054
1055/// v6.7.3 — outcome of a [`Catalog::compact_cold_segments`] call.
1056/// The catalog state has already been mutated when this is returned:
1057/// the merged segment is loaded into `cold_segments`, the source
1058/// segment slots are tombstoned (`None`), and every BTree-index
1059/// `RowLocator::Cold` that previously pointed at a source now
1060/// points at the merged segment. The caller's remaining job is to
1061/// persist `merged_segment_bytes` under
1062/// `<db>.spg/segments/seg_<merged_segment_id>.spg` and update the
1063/// in-memory `segment_id → path` map (remove the source ids, add
1064/// the merged id) so the next CHECKPOINT writes a manifest that
1065/// no longer lists the retired sources.
1066///
1067/// On a no-op (fewer than 2 candidate segments under the threshold),
1068/// `merged_segment_id` is `None` and `sources` is empty; the
1069/// catalog was not mutated.
1070#[derive(Debug, Clone)]
1071pub struct CompactReport {
1072 /// Source segment ids that were merged + tombstoned.
1073 pub sources: Vec<u32>,
1074 /// Id allocated for the merged segment. `None` on no-op.
1075 pub merged_segment_id: Option<u32>,
1076 /// Encoded merged-segment bytes (empty on no-op).
1077 pub merged_segment_bytes: Vec<u8>,
1078 /// Number of rows that landed in the merged segment.
1079 pub merged_rows: usize,
1080 /// `Σ source.num_rows − merged_rows`. Rows present in source
1081 /// segment payloads but unreferenced by any live BTree
1082 /// `Cold` locator — DELETE'd-but-still-frozen rows that
1083 /// compaction GC'd during the merge.
1084 pub deleted_rows_pruned: usize,
1085 /// `Σ source.bytes() − merged.bytes()`. Estimate of on-disk
1086 /// space the merge will reclaim once the source segment files
1087 /// are GC'd. Saturating subtract — never negative.
1088 pub bytes_reclaimed_estimate: u64,
1089}
1090
1091#[derive(Debug, Clone)]
1092pub enum IndexKind {
1093 /// v4.40: structural-sharing B-tree over `IndexKey`. Replaces the v0.8
1094 /// `BTreeMap<IndexKey, Vec<usize>>` — `Index::clone` is now an `Arc`
1095 /// bump regardless of index size, so `Catalog::clone` inside the
1096 /// v4.34 auto-commit wrap stays O(1) even for tables with secondary
1097 /// indices (the case that bottlenecked v4.39 at 1M rows in the
1098 /// sweep).
1099 ///
1100 /// v5.1: value type widened from `Vec<usize>` to `Vec<RowLocator>` so
1101 /// a single key can point to a mix of hot-tier rows (`RowLocator::Hot`,
1102 /// equivalent to the pre-v5 `usize` row index) and cold-tier rows
1103 /// (`RowLocator::Cold { segment_id, page_offset }`) once the v5.2
1104 /// freezer starts producing them. Pre-v5.2 only `Hot` entries appear
1105 /// — the on-disk encoding stays at `FILE_VERSION` 8 (raw u64 row index)
1106 /// because every locator round-trips through `RowLocator::from_legacy_v8_u64`
1107 /// without information loss. `FILE_VERSION` 9 with tagged encoding lands
1108 /// alongside the first freezer commit (v5.1 step 2b / v5.2).
1109 BTree(PersistentBTreeMap<IndexKey, Vec<RowLocator>>),
1110 /// Navigable-small-world graph for vector kNN search.
1111 Nsw(NswGraph),
1112 /// v6.7.1 — BRIN (Block Range INdex). Pure metadata: BRIN
1113 /// indexes carry NO in-memory key→locator map. The (min,
1114 /// max) summaries live in each cold-tier segment's v2
1115 /// envelope sidecar; the BRIN entry in `Table.indices` only
1116 /// records THAT a BRIN index exists on this column so the
1117 /// segment encoder + planner can opt into the summary path.
1118 Brin {
1119 /// The cell type at `column_position` at CREATE INDEX time.
1120 /// Used by the planner to type-check WHERE-clause range
1121 /// predicates against the BRIN-indexed column.
1122 column_type: DataType,
1123 },
1124 /// v7.12.3 — GIN inverted index over a `tsvector` column.
1125 ///
1126 /// Storage shape: `lexeme word → Vec<RowLocator>`. The posting
1127 /// list per word is appended in row-order, so range scans are
1128 /// O(matching rows) once the per-word lookup is done. Multi-
1129 /// term queries intersect / union posting lists.
1130 ///
1131 /// `IndexKey::from_value(TsVector)` returns `None` — GIN doesn't
1132 /// participate in `try_index_seek` (which is BTree-equality-keyed).
1133 /// The engine consults this index through `try_gin_lookup` on
1134 /// `WHERE col @@ tsquery` predicates instead.
1135 ///
1136 /// Backed by a `PersistentBTreeMap` so `Catalog::clone` (the
1137 /// per-write snapshot) stays O(1) — same structural-sharing
1138 /// invariant as BTree.
1139 Gin(PersistentBTreeMap<alloc::string::String, Vec<RowLocator>>),
1140 /// v7.15.0 — `USING gin (col gin_trgm_ops)` over a `TEXT`
1141 /// column. Posting lists map `trigram` (PG-compatible 3-byte
1142 /// shingle on the lower-cased + space-padded input) to row
1143 /// locators. The planner uses this index to accelerate
1144 /// `WHERE col LIKE '…'` / `ILIKE '…'` / `similarity(col, q) >
1145 /// t` — every literal run of length ≥ 1 in the pattern
1146 /// produces a trigram set, the engine intersects the posting
1147 /// lists, and the LIKE / similarity predicate is re-evaluated
1148 /// per candidate row to filter the over-approximation.
1149 /// Persisted via tag-4 index payload in `FILE_VERSION` 24+.
1150 GinTrgm(PersistentBTreeMap<alloc::string::String, Vec<RowLocator>>),
1151 /// v7.17.0 Phase 2.2 — MySQL `FULLTEXT KEY (col)` over a
1152 /// `TEXT` / `VARCHAR` column. Posting lists map
1153 /// `tsvector('simple') lexeme` to row locators. At insert /
1154 /// build time the engine derives the lexemes from the cell
1155 /// via the same lower-case tokenisation rule as
1156 /// `to_tsvector('simple', ...)` — the column itself stays a
1157 /// plain text type on disk (mysqldump round-trips would be
1158 /// broken otherwise). The planner uses this index to
1159 /// accelerate MySQL-shape `MATCH(col) AGAINST('term')`
1160 /// queries by mapping them onto the existing tsquery `@@`
1161 /// walker. Persisted via tag-5 index payload in
1162 /// `FILE_VERSION` 33+.
1163 GinFulltext(PersistentBTreeMap<alloc::string::String, Vec<RowLocator>>),
1164}
1165
1166impl IndexKind {
1167 /// v7.31 (memory campaign, C2) — bytes this index variant holds
1168 /// resident in RAM, computed by walking its OWN structure rather
1169 /// than a parametric guess made by the engine. Replaces the old
1170 /// `spg_admin::memory_stats` inline match, which charged NSW with
1171 /// a stale `m_max_0 * 8` per node (neighbour slots are `u32` = 4 B
1172 /// since v6.1.x, and most nodes never fill `m_max_0`) and lumped
1173 /// every GIN family index into a flat 1 KiB token — a gross
1174 /// undercount for the text-heavy posting lists that dominate
1175 /// mailrs' footprint. Per-entry container overhead uses the
1176 /// 3-word (24 B on 64-bit) `Vec`/`String` header as the charge.
1177 ///
1178 /// O(index entries): operator/monitoring surface (`memory_stats` /
1179 /// `spg_memory_stats`), not a query path.
1180 #[must_use]
1181 pub fn approx_resident_bytes(&self) -> u64 {
1182 const HEADER: usize = 24; // Vec/String 3-word header on 64-bit.
1183 let loc = core::mem::size_of::<RowLocator>();
1184 match self {
1185 IndexKind::BTree(map) => {
1186 let key = core::mem::size_of::<IndexKey>();
1187 map.iter()
1188 .map(|(_, locs)| (key + HEADER + locs.len() * loc) as u64)
1189 .sum()
1190 }
1191 IndexKind::Nsw(g) => {
1192 // `levels` is one byte per node; each layer's adjacency
1193 // is a `Vec<u32>` per node whose actual length we walk
1194 // (the dense layer-0 list dominates, but upper layers
1195 // are sparse — the old estimate ignored that).
1196 let mut b = g.levels.len() as u64;
1197 for layer in &g.layers {
1198 for nbrs in layer.iter() {
1199 b += (HEADER + nbrs.len() * core::mem::size_of::<u32>()) as u64;
1200 }
1201 }
1202 b
1203 }
1204 // BRIN carries NO in-memory key→locator map (the (min,max)
1205 // summaries live in cold-segment sidecars on disk); the
1206 // resident footprint is just the column-type token.
1207 IndexKind::Brin { .. } => core::mem::size_of::<DataType>() as u64,
1208 IndexKind::Gin(map) | IndexKind::GinTrgm(map) | IndexKind::GinFulltext(map) => map
1209 .iter()
1210 .map(|(word, postings)| {
1211 (word.len() + HEADER + HEADER + postings.len() * loc) as u64
1212 })
1213 .sum(),
1214 }
1215 }
1216}
1217
1218/// Multi-layer HNSW graph (v2.13). Each node is assigned a `top_level`;
1219/// it appears in layers `0..=top_level`. Higher layers are sparser, so
1220/// search starts from the entry at the top layer, greedy-descends to
1221/// layer 0, and beam-searches there. Layer 0 keeps a larger neighbour
1222/// budget (`m_max_0 = 2 * m` per the HNSW paper); upper layers cap at
1223/// `m`. The struct name stays `NswGraph` so external users / on-disk
1224/// callers don't have to track a rename — the algorithm changed, the
1225/// data slot didn't.
1226#[derive(Debug, Clone)]
1227pub struct NswGraph {
1228 /// Max neighbours per node on layers ≥ 1.
1229 pub m: usize,
1230 /// Max neighbours on layer 0 (the dense bottom layer). HNSW
1231 /// convention: `m_max_0 = 2 * m`.
1232 pub m_max_0: usize,
1233 /// Entry point — the node that sits on the topmost layer. Search
1234 /// always starts here.
1235 pub entry: Option<usize>,
1236 /// Top layer of the entry node (== `layers.len() - 1` when populated).
1237 pub entry_level: u8,
1238 /// `levels[i]` = top layer of node `i`. Nodes whose vector cell is
1239 /// NULL / non-Vector have `levels[i] = 0` and no neighbour entries.
1240 ///
1241 /// v5.5.0: backed by `PersistentVec` so `NswGraph::clone` (and the
1242 /// `Catalog::clone` on every group-commit write that contains it) is O(1)
1243 /// structural-sharing instead of an O(N) element copy.
1244 pub levels: PersistentVec<u8>,
1245 /// `layers[l][i]` = neighbours of node `i` at layer `l`. Inner vec
1246 /// is empty when node `i` doesn't reach layer `l`.
1247 ///
1248 /// v5.5.0: the per-node middle dimension (the O(N) one) is a
1249 /// `PersistentVec`; the outer layer dimension stays a plain `Vec`
1250 /// (layer count ≤ 8, so its clone is O(1) in practice) and the inner
1251 /// neighbour list stays a `Vec` (bounded by `m_max_0`).
1252 ///
1253 /// v6.1.x: neighbour slot widened from `usize` (8 B on 64-bit) to
1254 /// `u32` (4 B). Row indices are catalog-bounded by `u32::MAX` (4G
1255 /// rows per table); the cast at the NSW boundary asserts this. At
1256 /// 1M dim-128 SQ8, layer 0 adjacency alone shrinks by ~128 MiB
1257 /// — the largest single contribution to the v6.0.5-measured
1258 /// 624 MiB ambition gap. On-disk format already used u32 LE, so
1259 /// this is a pure in-memory layout change; no `FILE_VERSION` bump.
1260 pub layers: Vec<PersistentVec<Vec<u32>>>,
1261}
1262
1263impl NswGraph {
1264 fn new(m: usize) -> Self {
1265 Self {
1266 m,
1267 m_max_0: m.saturating_mul(2),
1268 entry: None,
1269 entry_level: 0,
1270 levels: PersistentVec::new(),
1271 layers: alloc::vec![PersistentVec::new()],
1272 }
1273 }
1274
1275 /// Max-neighbour budget for layer `l`.
1276 pub const fn cap_for_layer(&self, layer: u8) -> usize {
1277 if layer == 0 { self.m_max_0 } else { self.m }
1278 }
1279}
1280
1281/// Deterministic level assignment, seeded on the row index so the same
1282/// insert order reproduces the same topology. Distribution is roughly
1283/// HNSW-flavoured with `mL ≈ 1/ln(M) ≈ 0.36` for M=16: each 4-bit
1284/// chunk that comes up zero promotes the node one layer (so P(level ≥
1285/// L) ≈ (1/16)^L).
1286#[allow(clippy::verbose_bit_mask)] // clippy suggests trailing_zeros(); we need an explicit MAX cap and a stable distribution shape.
1287pub fn nsw_assign_level(row_idx: usize) -> u8 {
1288 const MAX_LEVEL: u8 = 7; // 7 ⇒ ~16^7 ≈ 2.7e8 expected nodes between promotions; ample.
1289 // SplitMix-style mixer — cheap and seedable.
1290 let mut x = (row_idx as u64).wrapping_mul(0x9E37_79B9_7F4A_7C15);
1291 x ^= x >> 30;
1292 x = x.wrapping_mul(0xBF58_476D_1CE4_E5B9);
1293 x ^= x >> 27;
1294 x = x.wrapping_mul(0x94D0_49BB_1331_11EB);
1295 x ^= x >> 31;
1296 // Count contiguous low-end zero nibbles (4-bit chunks). Each zero
1297 // nibble has probability 1/16, mirroring HNSW's `mL ≈ 1/ln(M)` for
1298 // M=16. `trailing_zeros / 4` would lose the ordering when x = 0, so
1299 // a plain loop with a cap is clearer.
1300 let mut level: u8 = 0;
1301 while x & 0xF == 0 && level < MAX_LEVEL {
1302 level += 1;
1303 x >>= 4;
1304 }
1305 level
1306}
1307
1308impl Index {
1309 fn new_btree(name: String, column_position: usize) -> Self {
1310 Self {
1311 name,
1312 column_position,
1313 kind: IndexKind::BTree(PersistentBTreeMap::new()),
1314 included_columns: Vec::new(),
1315 partial_predicate: None,
1316 expression: None,
1317 is_unique: false,
1318 extra_column_positions: Vec::new(),
1319 }
1320 }
1321
1322 fn new_nsw(name: String, column_position: usize, m: usize) -> Self {
1323 Self {
1324 name,
1325 column_position,
1326 kind: IndexKind::Nsw(NswGraph::new(m)),
1327 included_columns: Vec::new(),
1328 partial_predicate: None,
1329 expression: None,
1330 is_unique: false,
1331 extra_column_positions: Vec::new(),
1332 }
1333 }
1334
1335 /// v6.7.1 — BRIN index constructor. BRIN carries no in-memory
1336 /// data; the `column_type` snapshot is used by the segment
1337 /// encoder + planner for type-checking range predicates.
1338 fn new_brin(name: String, column_position: usize, column_type: DataType) -> Self {
1339 Self {
1340 name,
1341 column_position,
1342 kind: IndexKind::Brin { column_type },
1343 included_columns: Vec::new(),
1344 partial_predicate: None,
1345 expression: None,
1346 is_unique: false,
1347 extra_column_positions: Vec::new(),
1348 }
1349 }
1350
1351 /// v7.12.3 — GIN inverted-index constructor. Empty posting-list
1352 /// map; caller (typically [`Table::add_gin_index`] or
1353 /// [`Table::restore_gin_index`]) populates it from existing rows
1354 /// or from a deserialised snapshot.
1355 fn new_gin(name: String, column_position: usize) -> Self {
1356 Self {
1357 name,
1358 column_position,
1359 kind: IndexKind::Gin(PersistentBTreeMap::new()),
1360 included_columns: Vec::new(),
1361 partial_predicate: None,
1362 expression: None,
1363 is_unique: false,
1364 extra_column_positions: Vec::new(),
1365 }
1366 }
1367
1368 /// v7.15.0 — `gin_trgm_ops`-flavoured GIN constructor. Same
1369 /// shape as `new_gin` but the posting-list keys are 3-byte
1370 /// trigram shingles (`pg_trgm`-compatible) and the column
1371 /// type is `TEXT` / `VARCHAR` (not `TSVECTOR`).
1372 fn new_gin_trgm(name: String, column_position: usize) -> Self {
1373 Self {
1374 name,
1375 column_position,
1376 kind: IndexKind::GinTrgm(PersistentBTreeMap::new()),
1377 included_columns: Vec::new(),
1378 partial_predicate: None,
1379 expression: None,
1380 is_unique: false,
1381 extra_column_positions: Vec::new(),
1382 }
1383 }
1384
1385 /// v7.17.0 Phase 2.2 — MySQL `FULLTEXT KEY` GIN constructor.
1386 /// Same shape as `new_gin_trgm` but the posting-list keys
1387 /// are lower-cased word lexemes (`to_tsvector('simple', col)`
1388 /// equivalent) instead of trigrams, and the column type is
1389 /// `TEXT` / `VARCHAR` (not `TSVECTOR`).
1390 fn new_gin_fulltext(name: String, column_position: usize) -> Self {
1391 Self {
1392 name,
1393 column_position,
1394 kind: IndexKind::GinFulltext(PersistentBTreeMap::new()),
1395 included_columns: Vec::new(),
1396 partial_predicate: None,
1397 expression: None,
1398 is_unique: false,
1399 extra_column_positions: Vec::new(),
1400 }
1401 }
1402
1403 /// Look up the locators stored under `key` (B-tree only). Returns
1404 /// an empty slice when the key is absent or the index isn't a
1405 /// BTree — callers can treat both cases uniformly.
1406 ///
1407 /// v5.1: return type widened from `&[usize]` to `&[RowLocator]`.
1408 /// Pre-v5.2 callers can read the slice and `.as_hot().unwrap()`
1409 /// each entry (no `Cold` variants exist until the freezer lands);
1410 /// post-v5.2 callers dispatch hot vs. cold per locator.
1411 pub fn lookup_eq(&self, key: &IndexKey) -> &[RowLocator] {
1412 match &self.kind {
1413 IndexKind::BTree(m) => m.get(key).map_or(&[][..], Vec::as_slice),
1414 // BRIN / NSW / GIN / trigram-GIN / fulltext-GIN have
1415 // no IndexKey-keyed map; lookup is a no-op. GIN uses
1416 // [`Index::gin_lookup_word`] instead.
1417 IndexKind::Nsw(_)
1418 | IndexKind::Brin { .. }
1419 | IndexKind::Gin(_)
1420 | IndexKind::GinTrgm(_)
1421 | IndexKind::GinFulltext(_) => &[][..],
1422 }
1423 }
1424
1425 /// v7.12.3 — GIN posting-list lookup. Returns the row locators
1426 /// whose `tsvector` cell contains `word`. Empty when the word is
1427 /// absent from the index or this isn't a GIN index.
1428 pub fn gin_lookup_word(&self, word: &str) -> &[RowLocator] {
1429 match &self.kind {
1430 // v7.17.0 Phase 2.2 — fulltext-GIN shares the same
1431 // lexeme-keyed posting list shape as the
1432 // tsvector-typed GIN, so the same lookup applies.
1433 IndexKind::Gin(m) | IndexKind::GinFulltext(m) => {
1434 m.get(&String::from(word)).map_or(&[][..], Vec::as_slice)
1435 }
1436 IndexKind::BTree(_)
1437 | IndexKind::Nsw(_)
1438 | IndexKind::Brin { .. }
1439 | IndexKind::GinTrgm(_) => &[][..],
1440 }
1441 }
1442
1443 /// v7.15.0 — trigram-GIN posting-list lookup. Returns the row
1444 /// locators whose indexed `TEXT` cell contains the trigram
1445 /// `tri`. Empty when the trigram is absent or this isn't a
1446 /// trigram-GIN index.
1447 pub fn gin_trgm_lookup(&self, tri: &str) -> &[RowLocator] {
1448 match &self.kind {
1449 IndexKind::GinTrgm(m) => m.get(&String::from(tri)).map_or(&[][..], Vec::as_slice),
1450 IndexKind::BTree(_)
1451 | IndexKind::Nsw(_)
1452 | IndexKind::Brin { .. }
1453 | IndexKind::Gin(_)
1454 | IndexKind::GinFulltext(_) => &[][..],
1455 }
1456 }
1457
1458 /// Borrow the NSW graph (if this is an NSW index). Callers that need
1459 /// the graph for a kNN search go through here.
1460 pub const fn nsw(&self) -> Option<&NswGraph> {
1461 match &self.kind {
1462 IndexKind::Nsw(g) => Some(g),
1463 IndexKind::BTree(_)
1464 | IndexKind::Brin { .. }
1465 | IndexKind::Gin(_)
1466 | IndexKind::GinTrgm(_)
1467 | IndexKind::GinFulltext(_) => None,
1468 }
1469 }
1470
1471 /// v6.7.1 — true when this index is a BRIN (block range) index.
1472 /// Used by the segment encoder to opt into BRIN sidecar emission
1473 /// at freeze time, and by the planner to opt into page-skipping
1474 /// on range predicates.
1475 pub const fn is_brin(&self) -> bool {
1476 matches!(self.kind, IndexKind::Brin { .. })
1477 }
1478
1479 /// v7.15.0 — true when this index is a trigram GIN
1480 /// (`gin_trgm_ops`-flavoured). Used by the LIKE planner to
1481 /// opt into trigram acceleration.
1482 pub const fn is_gin_trgm(&self) -> bool {
1483 matches!(self.kind, IndexKind::GinTrgm(_))
1484 }
1485
1486 /// v7.12.3 — true when this index is a GIN inverted index.
1487 /// Used by the planner to opt into posting-list acceleration on
1488 /// `WHERE col @@ tsquery` predicates.
1489 pub const fn is_gin(&self) -> bool {
1490 matches!(self.kind, IndexKind::Gin(_))
1491 }
1492
1493 /// v7.17.0 Phase 2.2 — true when this index is a fulltext
1494 /// GIN over a TEXT / VARCHAR column (MySQL `FULLTEXT KEY`
1495 /// surface). Used by the planner to opt the FULLTEXT-indexed
1496 /// column into MATCH AGAINST acceleration.
1497 pub const fn is_gin_fulltext(&self) -> bool {
1498 matches!(self.kind, IndexKind::GinFulltext(_))
1499 }
1500}
1501
1502/// In-memory table: schema + a persistent row vector + secondary indices.
1503///
1504/// v4.39: `rows` is a [`PersistentVec`] (Bitmapped Vector Trie, 32-way) so
1505/// `Table::clone()` is `O(1)` — the whole reason for v4.39's existence is
1506/// to make `Catalog::clone()` cheap inside the v4.34 auto-commit wrap.
1507///
1508/// v5.2.1: `hot_bytes` tracks the encoded byte size of every row currently
1509/// in [`Self::rows`], summed over rows. Updated incrementally by `insert`
1510/// (+= encoded row size), `delete_rows` (-= removed rows' encoded sizes),
1511/// and `update_row` (-= old size, += new size). The value is what the
1512/// v5.2 freezer reads to decide when to demote cold rows — when the
1513/// catalog-wide sum crosses `SPG_HOT_TIER_BYTES` (default 4 GiB) the
1514/// freezer thread wakes. v5.2.1 ships measurement only; the freezer
1515/// itself lands in v5.2.2. Stored as `u64` so a single field clone in
1516/// `Catalog::clone` stays at the O(1) invariant v4.39 built.
1517#[derive(Debug, Clone)]
1518pub struct Table {
1519 schema: TableSchema,
1520 rows: PersistentVec<Row>,
1521 indices: Vec<Index>,
1522 hot_bytes: u64,
1523 /// v6.7.0 — cached count of rows currently materialised in the
1524 /// cold tier via `RowLocator::Cold` entries across THIS table's
1525 /// indices. Populated by `ANALYZE` (walks every BTree index and
1526 /// counts Cold locators); the count survives until the next
1527 /// ANALYZE recomputes it. Surfaced via `spg_statistic.cold_row_count`
1528 /// and `spg_stat_segment.table_name`.
1529 ///
1530 /// Honest scope: this is a CACHED count, not a live one.
1531 /// Freezer / promote / DELETE don't currently update the cache
1532 /// incrementally — they invalidate it by setting the
1533 /// `cold_row_count_stale` flag, and the next ANALYZE re-walks.
1534 /// Incremental maintenance is a v6.7.x candidate if observation
1535 /// shows the ANALYZE walk cost dominates.
1536 cold_row_count: u64,
1537 /// v6.7.0 — set when the cached `cold_row_count` may be wrong
1538 /// because rows moved into / out of the cold tier since the last
1539 /// ANALYZE. The virtual-table surface reports the cached value
1540 /// regardless (operators run ANALYZE to refresh).
1541 cold_row_count_stale: bool,
1542}
1543
1544/// Catalog: insertion-ordered `Vec<Table>` for stable iter / serialize,
1545/// plus a `BTreeMap<String, usize>` sidecar index so `get` / `get_mut`
1546/// run in O(log n) instead of the old linear scan with per-element
1547/// string compares.
1548///
1549/// A pure `BTreeMap<String, Table>` was tried in an interim version
1550/// of v3.1.2 and regressed the single-table catalog benches by ~10%
1551/// (the per-element `BTreeMap` overhead outweighs the lookup win
1552/// when n is small). The sidecar shape preserves the insertion-order
1553/// iteration the on-disk encoding relies on and keeps `last_mut`
1554/// (used by the deserialize hot path) cheap.
1555#[derive(Debug, Clone, Default)]
1556pub struct Catalog {
1557 tables: Vec<Table>,
1558 /// `name → tables[index]`. Kept in lock-step with `tables`.
1559 /// `create_table` is the only write path.
1560 by_name: BTreeMap<String, usize>,
1561 /// v5.1: in-memory cold-tier segments. Side-loaded via
1562 /// [`Catalog::load_segment_bytes`] — they live outside the
1563 /// catalog snapshot (caller persists them as separate files
1564 /// and re-loads on boot, until v5.3's `CatalogManifest` makes
1565 /// that wiring automatic). `RowLocator::Cold { segment_id, .. }`
1566 /// indexes this `Vec`. Cleared on `Catalog::new` / fresh
1567 /// `deserialize`.
1568 ///
1569 /// `Arc` wrap keeps `Catalog::clone` at O(N segments) bumps
1570 /// (rather than O(total segment bytes) memcpy) so the v4.42
1571 /// group-commit pre-image rollback invariant — clone is
1572 /// effectively free — survives the cold-tier addition.
1573 ///
1574 /// v6.7.3 — slots became `Option<…>` so cold-segment compaction
1575 /// can tombstone merged sources without breaking the
1576 /// `segment_id = index_into_vec` contract that on-disk
1577 /// `RowLocator::Cold { segment_id }` already serialized.
1578 /// `None` slot = the segment was retired by compaction; the
1579 /// physical file may still be on disk (next CHECKPOINT writes
1580 /// a manifest that no longer lists it, and the file becomes
1581 /// an orphan eligible for offline cleanup).
1582 cold_segments: Vec<Option<Arc<OwnedSegment>>>,
1583 /// v7.12.4 — user-defined functions (PL/pgSQL + SQL).
1584 /// Keyed by function name (PG overloading is out of scope).
1585 /// Bodies are stored as the raw source text the parser saw
1586 /// between `$$ ... $$`; the engine re-parses on each
1587 /// invocation. This keeps `spg-storage` free of `spg-sql`
1588 /// dependency — same pattern as partial-index predicates.
1589 functions: BTreeMap<String, FunctionDef>,
1590 /// v7.12.4 — triggers in insertion order. Multiple triggers
1591 /// per table / event fire in this order (matching PG's
1592 /// alphabetical-by-default with insertion-stable tie-break
1593 /// behaviour — we just keep insertion order for now).
1594 triggers: Vec<TriggerDef>,
1595 /// v7.17.0 — catalogued SEQUENCE objects (Phase 1.1). Each
1596 /// `nextval(name)` reaches in here, atomically increments
1597 /// `last_value` / flips `is_called`, returns the new value.
1598 /// Persisted in catalog FILE_VERSION 26+; older catalogs
1599 /// deserialise with an empty map.
1600 sequences: BTreeMap<String, SequenceDef>,
1601 /// v7.17.0 — catalogued VIEW objects (Phase 1.2). Each
1602 /// `SELECT FROM v` at engine exec-time looks up `v` here and
1603 /// prepends the view body as a synthetic CTE. Persisted in
1604 /// catalog FILE_VERSION 27+; older catalogs deserialise with
1605 /// an empty map.
1606 views: BTreeMap<String, ViewDef>,
1607 /// v7.17.0 — catalogued MATERIALIZED VIEW source registry
1608 /// (Phase 1.3). Maps name → SELECT source. The materialised
1609 /// rows themselves live as a regular `Table` with the same
1610 /// name; REFRESH re-parses + re-executes the source against
1611 /// the table. Persisted in catalog FILE_VERSION 28+;
1612 /// older catalogs deserialise with an empty map.
1613 materialized_views: BTreeMap<String, String>,
1614 /// v7.17.0 — catalogued user-defined ENUM types (Phase 1.4).
1615 /// Maps name → label list. Columns reference these by name
1616 /// via `ColumnSchema.user_enum_type`. Persisted in catalog
1617 /// FILE_VERSION 29+; older catalogs deserialise with an empty
1618 /// map.
1619 enum_types: BTreeMap<String, EnumDef>,
1620 /// v7.17.0 — catalogued user-defined DOMAIN types (Phase 1.5).
1621 /// Maps name → base + CHECK constraints. Columns reference
1622 /// these by name via `ColumnSchema.user_domain_type`.
1623 /// Persisted in catalog FILE_VERSION 30+; older catalogs
1624 /// deserialise with an empty map.
1625 domain_types: BTreeMap<String, DomainDef>,
1626 /// v7.17.0 — schema-namespace registry (Phase 1.6). Tracks
1627 /// which schemas exist. `public`, `pg_catalog`, and
1628 /// `information_schema` are built-in and always present.
1629 /// Schema-qualified table references still strip the prefix
1630 /// at lookup time per v7.16-and-earlier — full
1631 /// schema-as-isolation is v7.18+ scope. Persisted in catalog
1632 /// FILE_VERSION 31+; older catalogs deserialise with just
1633 /// the built-ins.
1634 schemas: alloc::collections::BTreeSet<String>,
1635}
1636
1637/// v7.12.4 — catalogued user-defined function. `body` is the raw
1638/// source text between `$$ ... $$`; the engine re-parses it on
1639/// invocation. This keeps the storage codec stable when the
1640/// PL/pgSQL surface grows (no breaking-change risk on the disk
1641/// format).
1642#[derive(Debug, Clone, PartialEq, Eq)]
1643pub struct FunctionDef {
1644 pub name: String,
1645 /// Display form of the argument list, e.g.
1646 /// `"(name TEXT, ts TIMESTAMP)"`. Empty `"()"` for the trigger
1647 /// function shape. Parser-side canonicalised before storage.
1648 pub args_repr: String,
1649 /// Display form of the return type, e.g. `"TRIGGER"` /
1650 /// `"INT"` / `"SETOF text"`. The engine special-cases
1651 /// `"TRIGGER"` (case-insensitive) to gate trigger-only
1652 /// semantics (NEW/OLD).
1653 pub returns: String,
1654 /// `LANGUAGE` clause, lowercased. `"plpgsql"` / `"sql"`.
1655 pub language: String,
1656 /// Source body of the function. PL/pgSQL: includes the
1657 /// surrounding `BEGIN ... END;`. SQL: includes the
1658 /// statement(s). The engine re-parses on invocation; bad
1659 /// bodies surface as a parse error at CALL time, not CREATE.
1660 pub body: String,
1661}
1662
1663/// v7.12.4 — catalogued trigger. References its function by
1664/// name; the function must exist at TRIGGER creation time
1665/// (forward references are deferred to v7.12.5+).
1666#[derive(Debug, Clone, PartialEq, Eq)]
1667pub struct TriggerDef {
1668 pub name: String,
1669 /// Watched table. Trigger is dropped when the table drops.
1670 pub table: String,
1671 /// `"BEFORE"` / `"AFTER"` / `"INSTEAD OF"`. Stored as the
1672 /// uppercased keyword so deserialised catalogs round-trip
1673 /// without canonicalisation surprises.
1674 pub timing: String,
1675 /// Each entry is one of `"INSERT"` / `"UPDATE"` / `"DELETE"`
1676 /// / `"TRUNCATE"`. `INSERT OR UPDATE` parses to two entries.
1677 pub events: Vec<String>,
1678 /// `"ROW"` / `"STATEMENT"`. v7.12.4 ships `"ROW"` only;
1679 /// `"STATEMENT"` parses and persists but the executor
1680 /// refuses it at trigger fire time.
1681 pub for_each: String,
1682 /// Name of the PL/pgSQL function to invoke.
1683 pub function: String,
1684 /// v7.13.0 — `UPDATE OF col, col, …` column-list filter
1685 /// (mailrs round-5 G7). Non-empty means the trigger fires
1686 /// only when at least one of these columns appears in the
1687 /// UPDATE's SET list. Empty = no column filter. Stored in
1688 /// catalog FILE_VERSION 23+; older catalogs deserialise with
1689 /// an empty vec.
1690 pub update_columns: Vec<String>,
1691 /// v7.16.1 — whether the trigger fires when its watched
1692 /// event occurs. Toggled by `ALTER TABLE … { ENABLE |
1693 /// DISABLE } TRIGGER …`; pg_dump --disable-triggers wraps
1694 /// every data block with a DISABLE/ENABLE pair so the
1695 /// rows already-computed in prod don't get re-rewritten.
1696 /// Defaults to `true` at CREATE TRIGGER time. Stored in
1697 /// catalog FILE_VERSION 25+; older catalogs deserialise
1698 /// with `enabled = true`.
1699 pub enabled: bool,
1700}
1701
1702/// v7.17.0 — catalogued SEQUENCE. PG semantics: a counter object
1703/// returning monotonically increasing values via `nextval(name)`.
1704/// `last_value` is the most recent value handed out; `is_called`
1705/// is false until the first `nextval`/`setval`. Stored separately
1706/// from tables in the catalog.
1707#[derive(Debug, Clone, PartialEq, Eq)]
1708pub struct SequenceDef {
1709 pub name: String,
1710 /// Data type — narrows the i64 range. PG default BIGINT.
1711 pub data_type: SequenceDataType,
1712 pub start: i64,
1713 pub increment: i64,
1714 pub min_value: i64,
1715 pub max_value: i64,
1716 pub cache: i64,
1717 pub cycle: bool,
1718 /// `OWNED BY` target — `(table, column)` or NONE.
1719 pub owned_by: Option<(String, String)>,
1720 /// Most recently handed-out value. Meaningless when
1721 /// `is_called == false`; in that case the NEXT `nextval`
1722 /// will return `start`.
1723 pub last_value: i64,
1724 pub is_called: bool,
1725}
1726
1727/// v7.17.0 — sequence integer width.
1728#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1729pub enum SequenceDataType {
1730 SmallInt,
1731 Int,
1732 BigInt,
1733}
1734
1735/// v7.17.0 Phase 1.6 — built-in schema names that every Catalog
1736/// understands without an explicit CREATE SCHEMA. Used by
1737/// [`Catalog::schema_exists`] and the engine's schema-qualified
1738/// lookup path.
1739#[must_use]
1740pub fn is_builtin_schema(name: &str) -> bool {
1741 name.eq_ignore_ascii_case("public")
1742 || name.eq_ignore_ascii_case("pg_catalog")
1743 || name.eq_ignore_ascii_case("information_schema")
1744}
1745
1746/// v7.17.0 — parse a PG-canonical UUID text representation into the
1747/// 16-byte network-order layout used by `Value::Uuid`. Accepted input
1748/// shapes (all case-insensitive):
1749/// * Canonical hyphenated 8-4-4-4-12 (`550e8400-e29b-41d4-a716-446655440000`)
1750/// * Unhyphenated 32-char hex (`550e8400e29b41d4a716446655440000`)
1751/// * Either form wrapped in `{ ... }`
1752///
1753/// Returns `None` for any malformed input (wrong length, non-hex
1754/// characters, misplaced hyphens). The caller surfaces a SQL error
1755/// at coercion time — silent acceptance of garbage would mask
1756/// application bugs and is exactly the divergence from PG that
1757/// breaks the 0-change cutover promise.
1758#[must_use]
1759pub fn parse_uuid_str(input: &str) -> Option<[u8; 16]> {
1760 let s = input.trim();
1761 // Strip surrounding braces if present.
1762 let s = if let Some(inner) = s.strip_prefix('{').and_then(|x| x.strip_suffix('}')) {
1763 inner
1764 } else {
1765 s
1766 };
1767 // Two valid shapes after braces are stripped: 32 hex chars or
1768 // the canonical 36-char hyphenated form.
1769 let hex: String = match s.len() {
1770 32 => s.to_ascii_lowercase(),
1771 36 => {
1772 // Hyphens must be exactly at positions 8, 13, 18, 23.
1773 let b = s.as_bytes();
1774 if b[8] != b'-' || b[13] != b'-' || b[18] != b'-' || b[23] != b'-' {
1775 return None;
1776 }
1777 let mut out = String::with_capacity(32);
1778 out.push_str(&s[0..8]);
1779 out.push_str(&s[9..13]);
1780 out.push_str(&s[14..18]);
1781 out.push_str(&s[19..23]);
1782 out.push_str(&s[24..36]);
1783 out.make_ascii_lowercase();
1784 out
1785 }
1786 _ => return None,
1787 };
1788 let bytes = hex.as_bytes();
1789 let mut out = [0u8; 16];
1790 for i in 0..16 {
1791 let hi = hex_nibble(bytes[i * 2])?;
1792 let lo = hex_nibble(bytes[i * 2 + 1])?;
1793 out[i] = (hi << 4) | lo;
1794 }
1795 Some(out)
1796}
1797
1798fn hex_nibble(b: u8) -> Option<u8> {
1799 match b {
1800 b'0'..=b'9' => Some(b - b'0'),
1801 b'a'..=b'f' => Some(10 + b - b'a'),
1802 b'A'..=b'F' => Some(10 + b - b'A'),
1803 _ => None,
1804 }
1805}
1806
1807/// v7.17.0 — render a `Value::Uuid` payload as the canonical
1808/// lowercase 8-4-4-4-12 hyphenated form PG `text` cast surfaces.
1809#[must_use]
1810pub fn format_uuid(b: &[u8; 16]) -> String {
1811 const HEX: &[u8; 16] = b"0123456789abcdef";
1812 let mut out = String::with_capacity(36);
1813 for (i, byte) in b.iter().enumerate() {
1814 if matches!(i, 4 | 6 | 8 | 10) {
1815 out.push('-');
1816 }
1817 out.push(HEX[(byte >> 4) as usize] as char);
1818 out.push(HEX[(byte & 0x0f) as usize] as char);
1819 }
1820 out
1821}
1822
1823/// v7.17.0 Phase 1.5 — catalogued user-defined DOMAIN. A domain
1824/// is a named CHECK-constrained alias over a built-in type;
1825/// columns bound to it inherit the base type plus the CHECK
1826/// predicates + NOT NULL + DEFAULT at INSERT/UPDATE time.
1827/// `default` / `checks` are stored as Display-form source so
1828/// `spg-storage` stays free of `spg-sql` dependency — same
1829/// pattern as FunctionDef / ViewDef.
1830#[derive(Debug, Clone, PartialEq, Eq)]
1831pub struct DomainDef {
1832 pub name: String,
1833 pub base_type: DataType,
1834 pub nullable: bool,
1835 pub default: Option<String>,
1836 pub checks: Vec<String>,
1837}
1838
1839/// v7.17.0 Phase 1.4 — catalogued user-defined ENUM type. The
1840/// label vector is order-preserving (PG enum ordering follows the
1841/// declared order). At INSERT/UPDATE on a column bound to this
1842/// enum, the engine looks up the value against `labels` and
1843/// rejects non-members.
1844#[derive(Debug, Clone, PartialEq, Eq)]
1845pub struct EnumDef {
1846 pub name: String,
1847 pub labels: Vec<String>,
1848}
1849
1850/// v7.17.0 Phase 1.2 — catalogued VIEW. The body is stored as the
1851/// raw source text the parser saw between `AS` and the statement
1852/// terminator; the engine re-parses on each invocation. Same
1853/// pattern as `FunctionDef` — keeps `spg-storage` free of
1854/// `spg-sql` dependency.
1855#[derive(Debug, Clone, PartialEq, Eq)]
1856pub struct ViewDef {
1857 pub name: String,
1858 /// Optional `(col, col, …)` rename list. Empty when the body's
1859 /// projected names are used directly.
1860 pub columns: Vec<String>,
1861 /// Raw SELECT source. Display-rendered at storage time so the
1862 /// catalog round-trips a deterministic form regardless of
1863 /// whitespace / comments in the original input. Re-parsed at
1864 /// SELECT-from-view time to materialise as a synthetic CTE.
1865 pub body: String,
1866}
1867
1868impl SequenceDataType {
1869 /// PG default min/max per AS clause.
1870 pub fn default_bounds(self, increment_positive: bool) -> (i64, i64) {
1871 match self {
1872 Self::SmallInt => {
1873 if increment_positive {
1874 (1, i64::from(i16::MAX))
1875 } else {
1876 (i64::from(i16::MIN), -1)
1877 }
1878 }
1879 Self::Int => {
1880 if increment_positive {
1881 (1, i64::from(i32::MAX))
1882 } else {
1883 (i64::from(i32::MIN), -1)
1884 }
1885 }
1886 Self::BigInt => {
1887 if increment_positive {
1888 (1, i64::MAX)
1889 } else {
1890 (i64::MIN, -1)
1891 }
1892 }
1893 }
1894 }
1895}
1896
1897impl Catalog {
1898 pub const fn new() -> Self {
1899 Self {
1900 tables: Vec::new(),
1901 by_name: BTreeMap::new(),
1902 cold_segments: Vec::new(),
1903 functions: BTreeMap::new(),
1904 triggers: Vec::new(),
1905 sequences: BTreeMap::new(),
1906 views: BTreeMap::new(),
1907 materialized_views: BTreeMap::new(),
1908 enum_types: BTreeMap::new(),
1909 domain_types: BTreeMap::new(),
1910 schemas: alloc::collections::BTreeSet::new(),
1911 }
1912 }
1913
1914 /// v7.12.4 — read-only view of catalogued user-defined
1915 /// functions. Engine callers go through here to look up the
1916 /// function body before re-parsing it for invocation.
1917 pub const fn functions(&self) -> &BTreeMap<String, FunctionDef> {
1918 &self.functions
1919 }
1920
1921 /// v7.12.4 — register a new user-defined function. With
1922 /// `or_replace = false`, errors if the name is taken. The
1923 /// engine validates the body before passing it here.
1924 pub fn create_function(
1925 &mut self,
1926 def: FunctionDef,
1927 or_replace: bool,
1928 ) -> Result<(), StorageError> {
1929 if !or_replace && self.functions.contains_key(&def.name) {
1930 return Err(StorageError::Corrupt(format!(
1931 "function {:?} already exists (drop or use CREATE OR REPLACE)",
1932 def.name
1933 )));
1934 }
1935 self.functions.insert(def.name.clone(), def);
1936 Ok(())
1937 }
1938
1939 /// v7.12.4 — remove a user-defined function by name. Returns
1940 /// `true` if a function was removed, `false` if none matched.
1941 /// Caller decides whether to surface `if_exists` semantics.
1942 pub fn drop_function(&mut self, name: &str) -> bool {
1943 self.functions.remove(name).is_some()
1944 }
1945
1946 /// v7.17.0 — read-only handle to catalogued sequences.
1947 pub const fn sequences(&self) -> &BTreeMap<String, SequenceDef> {
1948 &self.sequences
1949 }
1950
1951 /// v7.17.0 — register a new SEQUENCE. Errors if `name`
1952 /// collides with an existing sequence and `if_not_exists`
1953 /// is false.
1954 pub fn create_sequence(
1955 &mut self,
1956 def: SequenceDef,
1957 if_not_exists: bool,
1958 ) -> Result<(), StorageError> {
1959 if self.sequences.contains_key(&def.name) {
1960 if if_not_exists {
1961 return Ok(());
1962 }
1963 return Err(StorageError::Corrupt(format!(
1964 "sequence {:?} already exists",
1965 def.name
1966 )));
1967 }
1968 self.sequences.insert(def.name.clone(), def);
1969 Ok(())
1970 }
1971
1972 /// v7.17.0 — remove a SEQUENCE by name. Returns `true` if a
1973 /// sequence was removed, `false` if none matched. Caller
1974 /// surfaces IF EXISTS semantics.
1975 pub fn drop_sequence(&mut self, name: &str) -> bool {
1976 self.sequences.remove(name).is_some()
1977 }
1978
1979 /// v7.17.0 — atomic nextval. Increments `last_value` per
1980 /// `increment`, returns the new value, sets `is_called`.
1981 /// Returns an error on CYCLE-less overflow.
1982 pub fn sequence_next_value(&mut self, name: &str) -> Result<i64, StorageError> {
1983 let Some(seq) = self.sequences.get_mut(name) else {
1984 return Err(StorageError::Corrupt(format!(
1985 "sequence {name:?} does not exist"
1986 )));
1987 };
1988 // PG semantics: when !is_called (fresh sequence or
1989 // setval(_, false)), the next nextval returns the stored
1990 // `last_value`. When is_called, it advances by `increment`
1991 // and CYCLE-wraps on overflow.
1992 let candidate = if seq.is_called {
1993 let next = seq.last_value.checked_add(seq.increment).ok_or_else(|| {
1994 StorageError::Corrupt(format!("sequence {name:?} arithmetic overflow"))
1995 })?;
1996 if seq.increment > 0 {
1997 if next > seq.max_value {
1998 if seq.cycle {
1999 seq.min_value
2000 } else {
2001 return Err(StorageError::Corrupt(format!(
2002 "sequence {name:?} reached MAXVALUE ({})",
2003 seq.max_value
2004 )));
2005 }
2006 } else {
2007 next
2008 }
2009 } else if next < seq.min_value {
2010 if seq.cycle {
2011 seq.max_value
2012 } else {
2013 return Err(StorageError::Corrupt(format!(
2014 "sequence {name:?} reached MINVALUE ({})",
2015 seq.min_value
2016 )));
2017 }
2018 } else {
2019 next
2020 }
2021 } else {
2022 seq.last_value
2023 };
2024 seq.last_value = candidate;
2025 seq.is_called = true;
2026 Ok(candidate)
2027 }
2028
2029 /// v7.17.0 — currval. Errors if the session has never called
2030 /// nextval on this sequence (PG semantics). At the catalog
2031 /// level we approximate "session" with "is_called persisted";
2032 /// the engine session-tracking layer can wrap this for the
2033 /// strict per-session semantics later.
2034 pub fn sequence_current_value(&self, name: &str) -> Result<i64, StorageError> {
2035 let Some(seq) = self.sequences.get(name) else {
2036 return Err(StorageError::Corrupt(format!(
2037 "sequence {name:?} does not exist"
2038 )));
2039 };
2040 if !seq.is_called {
2041 return Err(StorageError::Corrupt(format!(
2042 "currval of sequence {name:?} is not yet defined in this session"
2043 )));
2044 }
2045 Ok(seq.last_value)
2046 }
2047
2048 /// v7.17.0 — setval(name, value [, is_called]). PG returns
2049 /// `value` regardless. `is_called=true` means the NEXT
2050 /// nextval will return `value + increment`; `is_called=false`
2051 /// means the next nextval will return `value`.
2052 pub fn sequence_set_value(
2053 &mut self,
2054 name: &str,
2055 value: i64,
2056 is_called: bool,
2057 ) -> Result<i64, StorageError> {
2058 let Some(seq) = self.sequences.get_mut(name) else {
2059 return Err(StorageError::Corrupt(format!(
2060 "sequence {name:?} does not exist"
2061 )));
2062 };
2063 seq.last_value = value;
2064 seq.is_called = is_called;
2065 Ok(value)
2066 }
2067
2068 /// v7.17.0 Phase 1.2 — read-only handle to catalogued views.
2069 pub const fn views(&self) -> &BTreeMap<String, ViewDef> {
2070 &self.views
2071 }
2072
2073 /// v7.17.0 Phase 1.2 — install a VIEW. `or_replace=true`
2074 /// overwrites an existing entry; `if_not_exists=true` is a
2075 /// silent no-op when the name is taken. Errors if both flags
2076 /// are off and the name collides.
2077 pub fn create_view(
2078 &mut self,
2079 def: ViewDef,
2080 or_replace: bool,
2081 if_not_exists: bool,
2082 ) -> Result<(), StorageError> {
2083 if self.views.contains_key(&def.name) {
2084 if or_replace {
2085 self.views.insert(def.name.clone(), def);
2086 return Ok(());
2087 }
2088 if if_not_exists {
2089 return Ok(());
2090 }
2091 return Err(StorageError::Corrupt(format!(
2092 "view {:?} already exists",
2093 def.name
2094 )));
2095 }
2096 // Reject name collision with tables / sequences — same
2097 // namespace per PG.
2098 if self.by_name.contains_key(&def.name) {
2099 return Err(StorageError::Corrupt(format!(
2100 "view {:?} would shadow an existing table",
2101 def.name
2102 )));
2103 }
2104 if self.sequences.contains_key(&def.name) {
2105 return Err(StorageError::Corrupt(format!(
2106 "view {:?} would shadow an existing sequence",
2107 def.name
2108 )));
2109 }
2110 self.views.insert(def.name.clone(), def);
2111 Ok(())
2112 }
2113
2114 /// v7.17.0 Phase 1.2 — remove a view by name. Returns true if
2115 /// a view was removed.
2116 pub fn drop_view(&mut self, name: &str) -> bool {
2117 self.views.remove(name).is_some()
2118 }
2119
2120 /// v7.17.0 Phase 1.3 — read-only handle to the materialised-
2121 /// view source registry. Each entry pairs with a regular
2122 /// table of the same name that holds the cached rows.
2123 pub const fn materialized_views(&self) -> &BTreeMap<String, String> {
2124 &self.materialized_views
2125 }
2126
2127 /// v7.17.0 Phase 1.3 — register a source for a materialised
2128 /// view. Caller has already created the backing table.
2129 pub fn register_materialized_view(&mut self, name: String, body: String) {
2130 self.materialized_views.insert(name, body);
2131 }
2132
2133 /// v7.17.0 Phase 1.3 — drop the source registry entry. Returns
2134 /// true if a source was unregistered. Caller separately drops
2135 /// the backing table.
2136 pub fn drop_materialized_view_source(&mut self, name: &str) -> bool {
2137 self.materialized_views.remove(name).is_some()
2138 }
2139
2140 /// v7.17.0 Phase 1.4 — read-only handle to user-defined ENUM
2141 /// catalog.
2142 pub const fn enum_types(&self) -> &BTreeMap<String, EnumDef> {
2143 &self.enum_types
2144 }
2145
2146 /// v7.17.0 Phase 1.4 — install a new ENUM type. Errors if
2147 /// `name` collides with an existing enum (no IF NOT EXISTS
2148 /// per PG semantics for CREATE TYPE).
2149 pub fn create_enum_type(&mut self, def: EnumDef) -> Result<(), StorageError> {
2150 if self.enum_types.contains_key(&def.name) {
2151 return Err(StorageError::Corrupt(format!(
2152 "type {:?} already exists",
2153 def.name
2154 )));
2155 }
2156 self.enum_types.insert(def.name.clone(), def);
2157 Ok(())
2158 }
2159
2160 /// v7.17.0 Phase 1.4 — drop an ENUM type by name. Returns
2161 /// true if a type was removed.
2162 pub fn drop_enum_type(&mut self, name: &str) -> bool {
2163 self.enum_types.remove(name).is_some()
2164 }
2165
2166 /// v7.17.0 Phase 1.5 — read-only handle to DOMAIN catalog.
2167 pub const fn domain_types(&self) -> &BTreeMap<String, DomainDef> {
2168 &self.domain_types
2169 }
2170
2171 /// v7.17.0 Phase 1.5 — install a DOMAIN. Errors on collision
2172 /// with an existing domain.
2173 pub fn create_domain_type(&mut self, def: DomainDef) -> Result<(), StorageError> {
2174 if self.domain_types.contains_key(&def.name) {
2175 return Err(StorageError::Corrupt(format!(
2176 "domain {:?} already exists",
2177 def.name
2178 )));
2179 }
2180 self.domain_types.insert(def.name.clone(), def);
2181 Ok(())
2182 }
2183
2184 /// v7.17.0 Phase 1.5 — drop a DOMAIN by name.
2185 pub fn drop_domain_type(&mut self, name: &str) -> bool {
2186 self.domain_types.remove(name).is_some()
2187 }
2188
2189 /// v7.17.0 Phase 1.6 — read-only handle to the user-created
2190 /// schema registry. Built-in schemas (`public`, `pg_catalog`,
2191 /// `information_schema`) are NOT included here; use
2192 /// [`schema_exists`](Self::schema_exists) for the full
2193 /// check.
2194 pub const fn user_schemas(&self) -> &alloc::collections::BTreeSet<String> {
2195 &self.schemas
2196 }
2197
2198 /// v7.17.0 Phase 1.6 — schema-name resolver. Returns true
2199 /// for built-in schemas + every user-CREATEd one. Used by
2200 /// CREATE SCHEMA collision checks and (future) by
2201 /// information_schema.schemata.
2202 pub fn schema_exists(&self, name: &str) -> bool {
2203 is_builtin_schema(name) || self.schemas.contains(name)
2204 }
2205
2206 /// v7.17.0 Phase 1.6 — register a new schema. Errors if the
2207 /// name already exists and `if_not_exists=false`. Built-in
2208 /// names cannot be redeclared.
2209 pub fn create_schema(&mut self, name: String, if_not_exists: bool) -> Result<(), StorageError> {
2210 if is_builtin_schema(&name) {
2211 if if_not_exists {
2212 return Ok(());
2213 }
2214 return Err(StorageError::Corrupt(format!(
2215 "schema {name:?} is built-in and cannot be redeclared"
2216 )));
2217 }
2218 if self.schemas.contains(&name) {
2219 if if_not_exists {
2220 return Ok(());
2221 }
2222 return Err(StorageError::Corrupt(format!(
2223 "schema {name:?} already exists"
2224 )));
2225 }
2226 self.schemas.insert(name);
2227 Ok(())
2228 }
2229
2230 /// v7.17.0 Phase 1.6 — drop a user-created schema. Returns
2231 /// true if a schema was removed. Built-in names always
2232 /// return false (cannot be dropped). Tables that previously
2233 /// used the schema as a prefix keep their bare name and stay
2234 /// queryable — this is the "prefix routing, not isolation"
2235 /// posture documented in v7.17 Phase 1.6.
2236 pub fn drop_schema(&mut self, name: &str) -> Result<bool, StorageError> {
2237 if is_builtin_schema(name) {
2238 return Err(StorageError::Corrupt(format!(
2239 "schema {name:?} is built-in and cannot be dropped"
2240 )));
2241 }
2242 Ok(self.schemas.remove(name))
2243 }
2244
2245 /// v7.17.0 — ALTER SEQUENCE option merge. Caller-provided
2246 /// updates overwrite the matching fields; unset fields keep
2247 /// their stored values. RESTART variants update last_value
2248 /// directly per PG: `RESTART` resets to current `start`;
2249 /// `RESTART WITH n` resets to `n`.
2250 #[allow(clippy::too_many_arguments)]
2251 pub fn alter_sequence(
2252 &mut self,
2253 name: &str,
2254 increment: Option<i64>,
2255 min_value: Option<i64>,
2256 max_value: Option<i64>,
2257 start: Option<i64>,
2258 restart: Option<Option<i64>>,
2259 cache: Option<i64>,
2260 cycle: Option<bool>,
2261 owned_by: Option<Option<(String, String)>>,
2262 ) -> Result<(), StorageError> {
2263 let Some(seq) = self.sequences.get_mut(name) else {
2264 return Err(StorageError::Corrupt(format!(
2265 "sequence {name:?} does not exist"
2266 )));
2267 };
2268 if let Some(v) = increment {
2269 seq.increment = v;
2270 }
2271 if let Some(v) = min_value {
2272 seq.min_value = v;
2273 }
2274 if let Some(v) = max_value {
2275 seq.max_value = v;
2276 }
2277 if let Some(v) = start {
2278 seq.start = v;
2279 }
2280 if let Some(restart_value) = restart {
2281 seq.last_value = restart_value.unwrap_or(seq.start);
2282 seq.is_called = false;
2283 }
2284 if let Some(v) = cache {
2285 seq.cache = v;
2286 }
2287 if let Some(v) = cycle {
2288 seq.cycle = v;
2289 }
2290 if let Some(v) = owned_by {
2291 seq.owned_by = v;
2292 }
2293 Ok(())
2294 }
2295
2296 /// v7.12.4 — read-only slice of all catalogued triggers.
2297 /// Engine row-write paths filter this by (table, event,
2298 /// timing) and fire matches in slice order.
2299 pub fn triggers(&self) -> &[TriggerDef] {
2300 &self.triggers
2301 }
2302
2303 /// v7.15.0 — mutable handle to the trigger slice for
2304 /// `ALTER TABLE … RENAME COLUMN`, which rewrites every
2305 /// `update_columns` entry that referenced the renamed
2306 /// column.
2307 pub fn triggers_mut(&mut self) -> &mut Vec<TriggerDef> {
2308 &mut self.triggers
2309 }
2310
2311 /// v7.12.4 — register a new trigger. With `or_replace = false`,
2312 /// errors when a trigger with the same name already exists on
2313 /// the same table (PG scoping rule — trigger names are
2314 /// per-table, not global). Trigger function must already
2315 /// exist in the catalog at registration time.
2316 pub fn create_trigger(
2317 &mut self,
2318 def: TriggerDef,
2319 or_replace: bool,
2320 ) -> Result<(), StorageError> {
2321 if !self.by_name.contains_key(&def.table) {
2322 return Err(StorageError::TableNotFound {
2323 name: def.table.clone(),
2324 });
2325 }
2326 if !self.functions.contains_key(&def.function) {
2327 return Err(StorageError::Corrupt(format!(
2328 "trigger {:?} references unknown function {:?}",
2329 def.name, def.function
2330 )));
2331 }
2332 let dup = self
2333 .triggers
2334 .iter()
2335 .position(|t| t.name == def.name && t.table == def.table);
2336 match (dup, or_replace) {
2337 (Some(_), false) => Err(StorageError::Corrupt(format!(
2338 "trigger {:?} already exists on table {:?}",
2339 def.name, def.table
2340 ))),
2341 (Some(i), true) => {
2342 self.triggers[i] = def;
2343 Ok(())
2344 }
2345 (None, _) => {
2346 self.triggers.push(def);
2347 Ok(())
2348 }
2349 }
2350 }
2351
2352 /// v7.12.4 — remove a trigger by `(name, table)`. Returns
2353 /// `true` if one was removed.
2354 pub fn drop_trigger(&mut self, name: &str, table: &str) -> bool {
2355 let before = self.triggers.len();
2356 self.triggers
2357 .retain(|t| !(t.name == name && t.table == table));
2358 before != self.triggers.len()
2359 }
2360
2361 pub fn create_table(&mut self, schema: TableSchema) -> Result<(), StorageError> {
2362 if self.by_name.contains_key(&schema.name) {
2363 return Err(StorageError::DuplicateTable {
2364 name: schema.name.clone(),
2365 });
2366 }
2367 let idx = self.tables.len();
2368 let name = schema.name.clone();
2369 self.tables.push(Table::new(schema));
2370 self.by_name.insert(name, idx);
2371 Ok(())
2372 }
2373
2374 pub fn get(&self, name: &str) -> Option<&Table> {
2375 let idx = *self.by_name.get(name)?;
2376 self.tables.get(idx)
2377 }
2378
2379 pub fn get_mut(&mut self, name: &str) -> Option<&mut Table> {
2380 let idx = *self.by_name.get(name)?;
2381 self.tables.get_mut(idx)
2382 }
2383
2384 pub fn table_count(&self) -> usize {
2385 self.tables.len()
2386 }
2387
2388 /// v7.14.0 — remove a table by name. Returns `true` when the
2389 /// table existed (and is now gone), `false` when it didn't.
2390 /// Used by `DROP TABLE` from pg_dump / mysqldump preambles
2391 /// where the dump re-creates schema and starts with
2392 /// `DROP TABLE IF EXISTS`.
2393 pub fn drop_table(&mut self, name: &str) -> bool {
2394 let Some(idx) = self.by_name.remove(name) else {
2395 return false;
2396 };
2397 // swap_remove invalidates the trailing index → rebuild
2398 // by_name for affected entries.
2399 self.tables.swap_remove(idx);
2400 // Re-stamp moved table's index slot in by_name.
2401 if idx < self.tables.len() {
2402 let moved_name = self.tables[idx].schema.name.clone();
2403 self.by_name.insert(moved_name, idx);
2404 }
2405 true
2406 }
2407
2408 /// v7.16.2 — rename a table (mailrs round-10 A.5). Updates
2409 /// the schema name, the catalog name → index map, and
2410 /// rewrites every reference dangling at the table name:
2411 /// * every FK on every OTHER table whose `parent_table`
2412 /// pointed at the old name now points at the new
2413 /// name, so FK enforcement keeps working
2414 /// * every trigger watching the table updates its `table`
2415 /// field
2416 /// Returns `Ok` on success; `Err(StorageError::TableNotFound)`
2417 /// when the old name isn't in the catalog and
2418 /// `Err(StorageError::DuplicateTable)` when the new name is
2419 /// already taken.
2420 pub fn rename_table(&mut self, old: &str, new: &str) -> Result<(), StorageError> {
2421 if old == new {
2422 return Ok(());
2423 }
2424 if self.by_name.contains_key(new) {
2425 return Err(StorageError::Corrupt(format!(
2426 "rename_table: target name {new:?} already exists"
2427 )));
2428 }
2429 let idx = self
2430 .by_name
2431 .remove(old)
2432 .ok_or_else(|| StorageError::TableNotFound { name: old.into() })?;
2433 self.tables[idx].schema.name = new.to_string();
2434 self.by_name.insert(new.to_string(), idx);
2435 for t in &mut self.tables {
2436 for fk in &mut t.schema.foreign_keys {
2437 if fk.parent_table == old {
2438 fk.parent_table = new.to_string();
2439 }
2440 }
2441 }
2442 for trig in &mut self.triggers {
2443 if trig.table == old {
2444 trig.table = new.to_string();
2445 }
2446 }
2447 Ok(())
2448 }
2449
2450 /// v7.16.2 — rename an index by name. Walks every table
2451 /// since the index lives on its owning table; updates the
2452 /// name in place. Errors with `IndexNotFound` when no
2453 /// index matches. mailrs round-10 A.5.
2454 pub fn rename_index(&mut self, old: &str, new: &str) -> Result<(), StorageError> {
2455 if old == new {
2456 return Ok(());
2457 }
2458 // Reject the new name if it already exists anywhere.
2459 for t in &self.tables {
2460 if t.indices.iter().any(|i| i.name == new) {
2461 return Err(StorageError::Corrupt(format!(
2462 "rename_index: target name {new:?} already exists"
2463 )));
2464 }
2465 }
2466 for t in &mut self.tables {
2467 for i in &mut t.indices {
2468 if i.name == old {
2469 i.name = new.to_string();
2470 return Ok(());
2471 }
2472 }
2473 }
2474 Err(StorageError::IndexNotFound { name: old.into() })
2475 }
2476
2477 /// v7.14.0 — remove a named index across the catalog.
2478 /// Returns `true` when found + dropped.
2479 pub fn drop_named_index(&mut self, name: &str) -> bool {
2480 for t in &mut self.tables {
2481 let before = t.indices.len();
2482 t.indices.retain(|i| i.name != name);
2483 if t.indices.len() != before {
2484 return true;
2485 }
2486 }
2487 false
2488 }
2489
2490 /// Borrow-free copy of every table's name in catalog order
2491 /// (= insertion order, matching the on-disk encoding).
2492 pub fn table_names(&self) -> Vec<String> {
2493 self.tables.iter().map(|t| t.schema.name.clone()).collect()
2494 }
2495
2496 /// v5.1: register a cold-tier segment that already lives in
2497 /// memory (caller did the file read). Returns the
2498 /// `segment_id` that `RowLocator::Cold { segment_id, .. }`
2499 /// will reference — currently this is just the index into
2500 /// `cold_segments`, but treat it as an opaque token.
2501 ///
2502 /// Storage is `no_std`, so file I/O is the caller's
2503 /// responsibility — `spg-server` reads the file and forwards
2504 /// the bytes here. The bytes stay resident in the catalog
2505 /// for the life of the `Catalog`, parsed only once.
2506 pub fn load_segment_bytes(&mut self, bytes: Vec<u8>) -> Result<u32, StorageError> {
2507 let id = u32::try_from(self.cold_segments.len()).map_err(|_| {
2508 StorageError::Corrupt("cold segment count would exceed u32::MAX".into())
2509 })?;
2510 let seg = OwnedSegment::from_bytes(bytes)
2511 .map_err(|e| StorageError::Corrupt(format!("cold segment parse failed: {e}")))?;
2512 self.cold_segments.push(Some(Arc::new(seg)));
2513 Ok(id)
2514 }
2515
2516 /// v6.7.3 — register a cold-tier segment at a specific id. Used
2517 /// by the spg-server manifest-boot path so segments whose
2518 /// neighbouring ids were retired by compaction still get back
2519 /// the same `segment_id` they had pre-restart (the
2520 /// `RowLocator::Cold { segment_id }` baked into the BTree-index
2521 /// snapshot persists across restart and must continue to
2522 /// resolve).
2523 ///
2524 /// Pads the Vec with `None` slots up to `target_id` if needed.
2525 /// Errors when the target slot is already occupied (would
2526 /// stomp another segment), the parse fails, or `target_id`
2527 /// exceeds `u32::MAX`.
2528 pub fn load_segment_bytes_at(
2529 &mut self,
2530 target_id: u32,
2531 bytes: Vec<u8>,
2532 ) -> Result<(), StorageError> {
2533 let seg = OwnedSegment::from_bytes(bytes)
2534 .map_err(|e| StorageError::Corrupt(format!("cold segment parse failed: {e}")))?;
2535 let idx = target_id as usize;
2536 while self.cold_segments.len() <= idx {
2537 self.cold_segments.push(None);
2538 }
2539 if self.cold_segments[idx].is_some() {
2540 return Err(StorageError::Corrupt(format!(
2541 "load_segment_bytes_at: segment_id {target_id} already occupied"
2542 )));
2543 }
2544 self.cold_segments[idx] = Some(Arc::new(seg));
2545 Ok(())
2546 }
2547
2548 /// v6.7.3 — retire a cold-tier segment slot (compaction-driven).
2549 /// The physical file is the caller's concern (typically kept
2550 /// on disk until the next CHECKPOINT writes a manifest that
2551 /// no longer lists it); this just flips the in-memory slot
2552 /// to `None` so later cold lookups for `segment_id` resolve
2553 /// as "unknown" instead of returning a stale row.
2554 ///
2555 /// No-op when the slot is already `None`. Errors only when
2556 /// `segment_id` is out of bounds.
2557 pub fn tombstone_segment(&mut self, segment_id: u32) -> Result<(), StorageError> {
2558 let idx = segment_id as usize;
2559 if idx >= self.cold_segments.len() {
2560 return Err(StorageError::Corrupt(format!(
2561 "tombstone_segment: segment_id {segment_id} out of bounds (len={})",
2562 self.cold_segments.len()
2563 )));
2564 }
2565 self.cold_segments[idx] = None;
2566 Ok(())
2567 }
2568
2569 /// Number of *active* (non-tombstoned) cold segments.
2570 #[must_use]
2571 pub fn cold_segment_count(&self) -> usize {
2572 self.cold_segments.iter().filter(|s| s.is_some()).count()
2573 }
2574
2575 /// Slot count including tombstones (= the next id the
2576 /// no-arg `load_segment_bytes` would allocate).
2577 #[must_use]
2578 pub fn cold_segment_slot_count(&self) -> usize {
2579 self.cold_segments.len()
2580 }
2581
2582 /// v6.2.7 — list every *active* cold-tier segment id known to
2583 /// this catalog (skips compaction tombstones since v6.7.3).
2584 /// Used by EXPLAIN ANALYZE to annotate scan nodes with the
2585 /// segments they could have walked.
2586 #[must_use]
2587 pub fn cold_segment_ids_global(&self) -> Vec<u32> {
2588 self.cold_segments
2589 .iter()
2590 .enumerate()
2591 .filter_map(|(i, s)| s.as_ref().map(|_| i as u32))
2592 .collect()
2593 }
2594
2595 /// v5.2.1: sum of `Table::hot_bytes` across every table. The v5.2
2596 /// freezer compares this against `SPG_HOT_TIER_BYTES` (parsed at
2597 /// server startup; default 4 GiB) and wakes when the budget is
2598 /// crossed. Pre-freezer (v5.2.1) this is measurement-only — the
2599 /// counter exposes whether the budget is being approached without
2600 /// triggering any demotion.
2601 #[must_use]
2602 pub fn hot_tier_bytes(&self) -> u64 {
2603 self.tables
2604 .iter()
2605 .map(Table::hot_bytes)
2606 .fold(0u64, u64::saturating_add)
2607 }
2608
2609 /// v5.2.2: freeze the **first** `max_rows` rows of `table_name`'s
2610 /// hot tier into a brand-new cold-tier segment. The named `BTree`
2611 /// index supplies the per-row PK (its column must be an integer
2612 /// type — v5.2.2 only supports `IndexKey::Int` PKs, matching the
2613 /// `index_key_as_u64` constraint used by the cold-tier lookup
2614 /// path). On success returns a [`FreezeReport`] with the
2615 /// freshly-allocated segment id, the count of rows that moved,
2616 /// the encoded segment bytes (so the caller can persist them to
2617 /// disk for later reload via `SPG_PRELOAD_COLD_SEGMENT`), and the
2618 /// hot-tier byte delta that was reclaimed.
2619 ///
2620 /// **Semantics**:
2621 /// 1. The first `max_rows` rows (by hot-tier position — same as
2622 /// insertion order under v4.39 `PersistentVec`) are read.
2623 /// 2. Rows are sorted ascending by PK and serialised into a new
2624 /// segment via [`encode_segment`].
2625 /// 3. The hot rows are dropped via [`Table::delete_rows`]; the
2626 /// `rebuild_indices` it triggers regenerates `Hot` locators
2627 /// for every remaining row (their positions shift down by
2628 /// `max_rows`). Existing `Cold` locators in this index — from
2629 /// a previous freeze — are also rebuilt **but with empty
2630 /// payload** since rebuild reads only `self.rows`; this
2631 /// routine re-registers them at the end of the call so the
2632 /// user-visible state preserves all prior cold locators.
2633 /// 4. The new segment is loaded into `self.cold_segments` via
2634 /// [`Catalog::load_segment_bytes`] (allocating a fresh
2635 /// `segment_id`). New `Cold` locators are registered on the
2636 /// named index — one per frozen row.
2637 ///
2638 /// **v5.2.2 limits** (relaxed in later sub-versions):
2639 /// - INSERT-only flow: subsequent UPDATE/DELETE on a frozen row
2640 /// returns a stale-locator error (no promote-on-write until
2641 /// v5.2.3).
2642 /// - Single-table scope: callers iterate tables themselves.
2643 /// - All-or-nothing: returns `Err` and leaves catalog unchanged
2644 /// if any step fails before the atomic swap point.
2645 ///
2646 /// Errors:
2647 /// - [`StorageError::Corrupt`] for missing table/index, non-`BTree`
2648 /// index, non-integer PK column, `max_rows == 0`, or
2649 /// `max_rows > row_count`.
2650 /// - The encoder's [`SegmentError`] surfaces as `Corrupt` (the
2651 /// only realistic source is "a single row is larger than the
2652 /// page size"; SPG schemas don't hit it in practice).
2653 pub fn freeze_oldest_to_cold(
2654 &mut self,
2655 table_name: &str,
2656 index_name: &str,
2657 max_rows: usize,
2658 ) -> Result<FreezeReport, StorageError> {
2659 // --- validation phase: never mutates ---------------------
2660 if max_rows == 0 {
2661 return Err(StorageError::Corrupt(
2662 "freeze_oldest_to_cold: max_rows must be > 0".into(),
2663 ));
2664 }
2665 let table = self.get(table_name).ok_or_else(|| {
2666 StorageError::Corrupt(format!(
2667 "freeze_oldest_to_cold: table {table_name:?} not found"
2668 ))
2669 })?;
2670 if max_rows > table.rows.len() {
2671 return Err(StorageError::Corrupt(format!(
2672 "freeze_oldest_to_cold: max_rows {max_rows} > row_count {}",
2673 table.rows.len()
2674 )));
2675 }
2676 let idx = table
2677 .indices
2678 .iter()
2679 .find(|i| i.name == index_name)
2680 .ok_or_else(|| {
2681 StorageError::Corrupt(format!(
2682 "freeze_oldest_to_cold: index {index_name:?} not found on {table_name:?}"
2683 ))
2684 })?;
2685 if !matches!(idx.kind, IndexKind::BTree(_)) {
2686 return Err(StorageError::Corrupt(format!(
2687 "freeze_oldest_to_cold: index {index_name:?} is NSW; only BTree indices may freeze"
2688 )));
2689 }
2690 let column_position = idx.column_position;
2691
2692 // --- segment build phase: reads only --------------------
2693 let schema = table.schema.clone();
2694 let mut to_freeze: Vec<(u64, Vec<u8>, IndexKey)> = Vec::with_capacity(max_rows);
2695 for row_idx in 0..max_rows {
2696 let row = table.rows.get(row_idx).expect("bounds-checked above");
2697 let key = IndexKey::from_value(&row.values[column_position]).ok_or_else(|| {
2698 StorageError::Corrupt(format!(
2699 "freeze_oldest_to_cold: row {row_idx} has NULL / non-key value in index column"
2700 ))
2701 })?;
2702 let pk_u64 = index_key_as_u64(&key).ok_or_else(|| {
2703 StorageError::Corrupt(format!(
2704 "freeze_oldest_to_cold: index {index_name:?} column type is non-integer; \
2705 v5.2.2 cold tier requires IndexKey::Int (Text PK lands in v5.5+)"
2706 ))
2707 })?;
2708 to_freeze.push((pk_u64, encode_row_body_dense(row, &schema), key));
2709 }
2710 // encode_segment requires ascending u64 keys. Sort by PK
2711 // before encoding; the caller's row-position order is not
2712 // necessarily PK order (e.g. workloads that insert random
2713 // PKs).
2714 to_freeze.sort_by_key(|(k, _, _)| *k);
2715 // Reject duplicate PKs — encode_segment also rejects them
2716 // (`SegmentError::UnsortedKey`), but the resulting error
2717 // message there is misleading. Surface a clearer one.
2718 for w in to_freeze.windows(2) {
2719 if w[0].0 == w[1].0 {
2720 return Err(StorageError::Corrupt(format!(
2721 "freeze_oldest_to_cold: duplicate PK {} in freeze batch",
2722 w[0].0
2723 )));
2724 }
2725 }
2726 // Snapshot the (key, locator) pairs that will be registered
2727 // post-swap. Cloning the IndexKey out before the move makes
2728 // the registration loop borrow-free.
2729 let post_swap_keys: Vec<IndexKey> = to_freeze.iter().map(|(_, _, k)| k.clone()).collect();
2730 // Segment encode is now infallible w.r.t. ordering. Map the
2731 // `SegmentError` into a `StorageError::Corrupt` so the
2732 // public surface stays one error type.
2733 let seg_rows: Vec<(u64, Vec<u8>)> = to_freeze
2734 .into_iter()
2735 .map(|(k, body, _)| (k, body))
2736 .collect();
2737 let frozen_rows = seg_rows.len();
2738 let (seg_bytes, _meta) = encode_segment(seg_rows.into_iter(), 0.01, SEGMENT_PAGE_BYTES)
2739 .map_err(|e| StorageError::Corrupt(format!("freeze_oldest_to_cold: encode: {e}")))?;
2740
2741 // --- atomic swap phase: mutations only past this point ---
2742 // v5.2.3 made `Table::rebuild_indices` preserve every Cold
2743 // locator across the per-table rebuild, so `delete_rows`
2744 // below no longer wipes prior-freeze cold entries. The pre-
2745 // v5.2.3 capture-then-re-register that used to live here
2746 // was removed in v5.3.1 — keeping it would double-count
2747 // every prior-frozen key's Cold locator on each subsequent
2748 // freeze.
2749 let bytes_before = self.get(table_name).expect("just validated").hot_bytes();
2750 let positions: Vec<usize> = (0..max_rows).collect();
2751 let t_mut = self
2752 .get_mut(table_name)
2753 .expect("just validated; still present");
2754 let removed = t_mut.delete_rows(&positions);
2755 debug_assert_eq!(removed, max_rows, "delete_rows count matches request");
2756 let bytes_after = t_mut.hot_bytes();
2757 let bytes_freed = bytes_before.saturating_sub(bytes_after);
2758
2759 let segment_id = self
2760 .load_segment_bytes(seg_bytes.clone())
2761 .map_err(|e| StorageError::Corrupt(format!("freeze_oldest_to_cold: load: {e}")))?;
2762 let new_cold = post_swap_keys.into_iter().map(|k| {
2763 (
2764 k,
2765 RowLocator::Cold {
2766 segment_id,
2767 page_offset: 0,
2768 },
2769 )
2770 });
2771 let t_mut = self.get_mut(table_name).expect("still present");
2772 t_mut.register_cold_locators(index_name, new_cold)?;
2773
2774 Ok(FreezeReport {
2775 segment_id,
2776 frozen_rows,
2777 bytes_freed,
2778 segment_bytes: seg_bytes,
2779 })
2780 }
2781
2782 /// v5.1: borrow the cold segment at `segment_id`. Used by the
2783 /// spg-server preload path to enumerate (key, locator) pairs
2784 /// after loading a segment, so it can call
2785 /// [`Table::register_cold_locators`] without re-parsing the
2786 /// bytes.
2787 #[must_use]
2788 pub fn cold_segment(&self, segment_id: u32) -> Option<&OwnedSegment> {
2789 self.cold_segments
2790 .get(segment_id as usize)
2791 .and_then(|s| s.as_deref())
2792 }
2793
2794 /// v5.1: resolve a single `RowLocator::Cold` to its underlying
2795 /// `Row`. Decoupled from [`Catalog::lookup_by_pk`] so callers
2796 /// iterating a multi-locator slice (e.g. the engine's index
2797 /// seek path) can dispatch per locator instead of getting back
2798 /// only the first row for a key. Returns `None` when the
2799 /// segment isn't registered, the key isn't `u64`-coercible, or
2800 /// the segment doesn't actually carry the key (bloom or page-
2801 /// index reject).
2802 pub fn resolve_cold_locator(
2803 &self,
2804 table_name: &str,
2805 segment_id: u32,
2806 key: &IndexKey,
2807 ) -> Option<Row> {
2808 let t = self.get(table_name)?;
2809 let u64_key = index_key_as_u64(key)?;
2810 let seg = self.cold_segments.get(segment_id as usize)?.as_ref()?;
2811 let payload = seg.lookup(u64_key)?;
2812 let (row, _) = decode_row_body_dense(&payload, &t.schema, seg.codec_version()).ok()?;
2813 Some(row)
2814 }
2815
2816 /// v5.1: indexed PK lookup that dispatches per locator,
2817 /// returning the first matching row from either the hot tier
2818 /// (`Table::rows`) or a registered cold segment.
2819 ///
2820 /// The cold path requires the index column to be coercible to
2821 /// a `u64` (the segment's PK type) and the segment payload to
2822 /// be a [`encode_row_body_dense`]-encoded row body for the
2823 /// same schema. v5.1 ships this for BIGINT / INT / SMALLINT
2824 /// PKs; other types fall through to hot-only behavior.
2825 ///
2826 /// Returns `None` if (a) the table or index doesn't exist,
2827 /// (b) the key isn't in the index at all, or (c) the key was
2828 /// resolved to a stale locator (Hot index out of range, Cold
2829 /// segment id unknown, segment lookup miss). Does not surface
2830 /// segment-decode errors — those would indicate corrupted
2831 /// cold-tier files and should be caught at
2832 /// [`Catalog::load_segment_bytes`] time.
2833 pub fn lookup_by_pk(&self, table: &str, index_name: &str, key: &IndexKey) -> Option<Row> {
2834 let t = self.get(table)?;
2835 let idx = t.indices.iter().find(|i| i.name == index_name)?;
2836 let locators = idx.lookup_eq(key);
2837 let cold_u64_key = index_key_as_u64(key);
2838 for loc in locators {
2839 match *loc {
2840 RowLocator::Hot(i) => {
2841 if let Some(row) = t.rows.get(i) {
2842 return Some(row.clone());
2843 }
2844 }
2845 RowLocator::Cold {
2846 segment_id,
2847 page_offset: _,
2848 } => {
2849 let Some(u64_key) = cold_u64_key else {
2850 // Key type not coercible to u64 — cold tier
2851 // only handles BIGINT/INT/SMALLINT in v5.1.
2852 continue;
2853 };
2854 let Some(seg) = self
2855 .cold_segments
2856 .get(segment_id as usize)
2857 .and_then(|s| s.as_deref())
2858 else {
2859 // v6.7.3 — `None` slot = compaction
2860 // retired this segment; the live locator
2861 // on a freshly-compacted index points to
2862 // the merged segment_id, so a Cold hit
2863 // here against a tombstone means the BTree
2864 // entry hasn't been swapped yet (mid-
2865 // compaction reader race) or the caller is
2866 // looking up a stale snapshot. Skip — the
2867 // next locator in the list, if any, is
2868 // typically the merged segment.
2869 continue;
2870 };
2871 let Some(payload) = seg.lookup(u64_key) else {
2872 continue;
2873 };
2874 let (row, _) =
2875 decode_row_body_dense(&payload, &t.schema, seg.codec_version()).ok()?;
2876 return Some(row);
2877 }
2878 }
2879 }
2880 None
2881 }
2882
2883 /// v5.2.3: promote a frozen row back to the hot tier so an
2884 /// UPDATE / DELETE can mutate it. Reads the cold-tier row body
2885 /// (decoded from its registered segment), pushes it into
2886 /// `table.rows` via [`Table::insert`] (which also adds a fresh
2887 /// `Hot(new_idx)` locator on `index_name`), then retires the
2888 /// shadowed `Cold` locator via
2889 /// [`Table::remove_cold_locators_for_key`]. The cold-tier row
2890 /// in the segment file becomes garbage — recoverable when a
2891 /// future cold-segment compaction job lands.
2892 ///
2893 /// Returns:
2894 /// - `Ok(Some(new_hot_idx))` when the key resolved through a
2895 /// cold locator and the promote completed. `new_hot_idx` is
2896 /// the position the row now occupies in `table.rows`.
2897 /// - `Ok(None)` when the key has no Cold locator on the index
2898 /// (already hot, or wasn't present at all). Callers treat this
2899 /// as "nothing to do here, fall back to the hot-only path".
2900 ///
2901 /// Errors when the table / index doesn't exist, the index isn't
2902 /// `BTree`, the cold segment is missing / can't decode the row,
2903 /// or the inferred row body fails `Table::insert` validation.
2904 pub fn promote_cold_row(
2905 &mut self,
2906 table_name: &str,
2907 index_name: &str,
2908 key: &IndexKey,
2909 ) -> Result<Option<usize>, StorageError> {
2910 let cold_loc = self.find_cold_locator(table_name, index_name, key)?;
2911 let Some((segment_id, _page_offset)) = cold_loc else {
2912 return Ok(None);
2913 };
2914 let u64_key = index_key_as_u64(key).ok_or_else(|| {
2915 StorageError::Corrupt(
2916 "promote_cold_row: key type not coercible to u64 (cold tier requires integer PK)"
2917 .into(),
2918 )
2919 })?;
2920 // Read the row body from the segment. Borrow the segment +
2921 // schema short-term so we can then take `&mut self` for the
2922 // hot-side insert.
2923 let schema = self
2924 .get(table_name)
2925 .ok_or_else(|| {
2926 StorageError::Corrupt(format!("promote_cold_row: table {table_name:?} not found"))
2927 })?
2928 .schema
2929 .clone();
2930 let seg = self
2931 .cold_segments
2932 .get(segment_id as usize)
2933 .and_then(|s| s.as_ref())
2934 .ok_or_else(|| {
2935 StorageError::Corrupt(format!(
2936 "promote_cold_row: segment {segment_id} not registered on catalog"
2937 ))
2938 })?;
2939 let payload = seg.lookup(u64_key).ok_or_else(|| {
2940 StorageError::Corrupt(format!(
2941 "promote_cold_row: key {u64_key} resolves to segment {segment_id} \
2942 but the segment's bloom/page lookup didn't return a row"
2943 ))
2944 })?;
2945 let (row, _consumed) = decode_row_body_dense(&payload, &schema, seg.codec_version())?;
2946 // Insert the promoted row into the hot tier. `Table::insert`
2947 // appends to `self.rows`, adds a `Hot(new_idx)` locator to
2948 // every BTree index covering the row's keyed columns, and
2949 // increments `hot_bytes`.
2950 let t = self
2951 .get_mut(table_name)
2952 .expect("table existed at lookup time");
2953 t.insert(row)?;
2954 let new_hot_idx =
2955 t.rows.len().checked_sub(1).ok_or_else(|| {
2956 StorageError::Corrupt("promote_cold_row: empty after insert".into())
2957 })?;
2958 // The hot insert added Hot(new_idx) alongside the still-
2959 // present Cold locator. Drop the Cold entry so future
2960 // lookups return only the fresh hot row.
2961 t.remove_cold_locators_for_key(index_name, key)?;
2962 Ok(Some(new_hot_idx))
2963 }
2964
2965 /// v5.2.3: shadow a frozen row's index entry. Used by DELETE
2966 /// when the row to remove lives in a cold-tier segment — the
2967 /// row body stays in the segment file (becoming garbage) but
2968 /// every `Cold` locator for `key` on `index_name` is removed
2969 /// so PK lookups stop returning it.
2970 ///
2971 /// Returns the number of cold locators retired (0 when the key
2972 /// has no cold entries — the DELETE fell on a hot row or a
2973 /// key that was already absent). Errors when the table /
2974 /// index doesn't exist or the index isn't `BTree`.
2975 ///
2976 /// Cold-segment compaction (which merges shadowed-heavy
2977 /// segments and reclaims their disk footprint) lands in a
2978 /// later v5.x sub-version; until then, repeated UPDATE/DELETE
2979 /// of cold rows can amplify cold-segment disk usage by up to
2980 /// 1-2× — still well under typical LSM-tree shadowing because
2981 /// SPG segments are bulk-baked, not write-merged.
2982 pub fn shadow_cold_row(
2983 &mut self,
2984 table_name: &str,
2985 index_name: &str,
2986 key: &IndexKey,
2987 ) -> Result<usize, StorageError> {
2988 let t = self.get_mut(table_name).ok_or_else(|| {
2989 StorageError::Corrupt(format!("shadow_cold_row: table {table_name:?} not found"))
2990 })?;
2991 t.remove_cold_locators_for_key(index_name, key)
2992 }
2993
2994 /// v6.7.4 — read-only slice preparation for the parallel
2995 /// freezer. Walks rows in `row_range`, builds the
2996 /// `(pk_u64, encoded_body, IndexKey)` triples that the
2997 /// coordinator's k-way merge consumes, sorts the slice by
2998 /// `pk_u64`, and returns a [`FreezeSlice`].
2999 ///
3000 /// Caller invariants:
3001 /// - `row_range.end <= table.rows.len()` (caller's job to
3002 /// compute the partition).
3003 /// - All slices passed to `commit_freeze_slices` must cover a
3004 /// contiguous half-open range `[0, total_max_rows)` with no
3005 /// gaps and no overlaps. The coordinator validates this
3006 /// invariant before committing.
3007 ///
3008 /// `&self`-only — multiple workers can run this concurrently
3009 /// against the same `Catalog` reference under the engine's
3010 /// write lock (workers don't mutate; the coordinator does).
3011 pub fn prepare_freeze_slice(
3012 &self,
3013 table_name: &str,
3014 index_name: &str,
3015 row_range: core::ops::Range<usize>,
3016 ) -> Result<FreezeSlice, StorageError> {
3017 let table = self.get(table_name).ok_or_else(|| {
3018 StorageError::Corrupt(format!(
3019 "prepare_freeze_slice: table {table_name:?} not found"
3020 ))
3021 })?;
3022 let idx = table
3023 .indices
3024 .iter()
3025 .find(|i| i.name == index_name)
3026 .ok_or_else(|| {
3027 StorageError::Corrupt(format!(
3028 "prepare_freeze_slice: index {index_name:?} not found on {table_name:?}"
3029 ))
3030 })?;
3031 if !matches!(idx.kind, IndexKind::BTree(_)) {
3032 return Err(StorageError::Corrupt(format!(
3033 "prepare_freeze_slice: index {index_name:?} is NSW; only BTree indices may freeze"
3034 )));
3035 }
3036 if row_range.end > table.rows.len() {
3037 return Err(StorageError::Corrupt(format!(
3038 "prepare_freeze_slice: row_range end {} > row_count {}",
3039 row_range.end,
3040 table.rows.len()
3041 )));
3042 }
3043 let column_position = idx.column_position;
3044 let schema = table.schema.clone();
3045 let mut rows: Vec<(u64, Vec<u8>, IndexKey)> = Vec::with_capacity(row_range.len());
3046 for row_idx in row_range.clone() {
3047 let row = table.rows.get(row_idx).expect("bounds-checked above");
3048 let key = IndexKey::from_value(&row.values[column_position]).ok_or_else(|| {
3049 StorageError::Corrupt(format!(
3050 "prepare_freeze_slice: row {row_idx} has NULL / non-key value in index column"
3051 ))
3052 })?;
3053 let pk_u64 = index_key_as_u64(&key).ok_or_else(|| {
3054 StorageError::Corrupt(format!(
3055 "prepare_freeze_slice: index {index_name:?} column type is non-integer; \
3056 v5.2.2 cold tier requires IndexKey::Int (Text PK lands in v5.5+)"
3057 ))
3058 })?;
3059 rows.push((pk_u64, encode_row_body_dense(row, &schema), key));
3060 }
3061 rows.sort_by_key(|(k, _, _)| *k);
3062 Ok(FreezeSlice { row_range, rows })
3063 }
3064
3065 /// v6.7.4 — coordinator commit step. Merges N
3066 /// [`FreezeSlice`]s into one segment via the standard
3067 /// [`encode_segment`] path, atomically swaps the catalog
3068 /// state (delete the union row range + register Cold
3069 /// locators + load the segment).
3070 ///
3071 /// Validates that the slices cover a contiguous, gap-free,
3072 /// overlap-free half-open range starting at index 0 (the
3073 /// freezer always freezes "oldest first" — same semantics as
3074 /// the single-threaded [`Catalog::freeze_oldest_to_cold`]).
3075 ///
3076 /// Empty `slices` → no-op success (returns a zero-row report
3077 /// without mutating). Total row count = `Σ slice.rows.len()`.
3078 pub fn commit_freeze_slices(
3079 &mut self,
3080 table_name: &str,
3081 index_name: &str,
3082 slices: Vec<FreezeSlice>,
3083 ) -> Result<FreezeReport, StorageError> {
3084 // --- validation phase: never mutates ---------------------
3085 let table = self.get(table_name).ok_or_else(|| {
3086 StorageError::Corrupt(format!(
3087 "commit_freeze_slices: table {table_name:?} not found"
3088 ))
3089 })?;
3090 let idx = table
3091 .indices
3092 .iter()
3093 .find(|i| i.name == index_name)
3094 .ok_or_else(|| {
3095 StorageError::Corrupt(format!(
3096 "commit_freeze_slices: index {index_name:?} not found on {table_name:?}"
3097 ))
3098 })?;
3099 if !matches!(idx.kind, IndexKind::BTree(_)) {
3100 return Err(StorageError::Corrupt(format!(
3101 "commit_freeze_slices: index {index_name:?} is NSW; only BTree indices may freeze"
3102 )));
3103 }
3104 // Validate slice coverage: contiguous from 0, no gaps, no
3105 // overlaps. Allow the caller to pass slices in any order —
3106 // sort by row_range.start first.
3107 let mut ordered = slices;
3108 ordered.sort_by_key(|s| s.row_range.start);
3109 // Drop fully-empty slices that fell out of an uneven
3110 // partition; they carry no data but contribute to the
3111 // contiguity check, so keep them in line.
3112 let mut expected_start = 0usize;
3113 for s in &ordered {
3114 if s.row_range.start != expected_start {
3115 return Err(StorageError::Corrupt(format!(
3116 "commit_freeze_slices: gap/overlap at row {}; expected start {}",
3117 s.row_range.start, expected_start
3118 )));
3119 }
3120 expected_start = s.row_range.end;
3121 }
3122 let max_rows = expected_start;
3123 if max_rows > table.rows.len() {
3124 return Err(StorageError::Corrupt(format!(
3125 "commit_freeze_slices: total row range {} exceeds row_count {}",
3126 max_rows,
3127 table.rows.len()
3128 )));
3129 }
3130 if max_rows == 0 {
3131 return Ok(FreezeReport {
3132 segment_id: u32::MAX,
3133 frozen_rows: 0,
3134 bytes_freed: 0,
3135 segment_bytes: Vec::new(),
3136 });
3137 }
3138
3139 // --- segment build phase: reads only --------------------
3140 // K-way merge of already-sorted slices. Each slice's rows
3141 // are ascending by pk_u64; we keep a per-slice cursor and
3142 // pull the next-smallest head until every cursor drains.
3143 let total_rows: usize = ordered.iter().map(|s| s.rows.len()).sum();
3144 if total_rows != max_rows {
3145 return Err(StorageError::Corrupt(format!(
3146 "commit_freeze_slices: total slice rows {total_rows} ≠ row_range coverage {max_rows}"
3147 )));
3148 }
3149 let mut cursors: Vec<usize> = alloc::vec![0; ordered.len()];
3150 let mut merged: Vec<(u64, Vec<u8>, IndexKey)> = Vec::with_capacity(total_rows);
3151 loop {
3152 // Pick the slice whose head row has the smallest key
3153 // and isn't yet exhausted.
3154 let mut pick: Option<usize> = None;
3155 for (i, c) in cursors.iter().enumerate() {
3156 let slice = &ordered[i];
3157 if *c >= slice.rows.len() {
3158 continue;
3159 }
3160 match pick {
3161 None => pick = Some(i),
3162 Some(j) => {
3163 if slice.rows[*c].0 < ordered[j].rows[cursors[j]].0 {
3164 pick = Some(i);
3165 }
3166 }
3167 }
3168 }
3169 let Some(i) = pick else { break };
3170 let row = ordered[i].rows[cursors[i]].clone();
3171 cursors[i] += 1;
3172 merged.push(row);
3173 }
3174 // Reject duplicate PKs — same error as the single-threaded
3175 // path so callers get a uniform surface.
3176 for w in merged.windows(2) {
3177 if w[0].0 == w[1].0 {
3178 return Err(StorageError::Corrupt(format!(
3179 "commit_freeze_slices: duplicate PK {} across slices",
3180 w[0].0
3181 )));
3182 }
3183 }
3184 let post_swap_keys: Vec<IndexKey> = merged.iter().map(|(_, _, k)| k.clone()).collect();
3185 let seg_rows: Vec<(u64, Vec<u8>)> =
3186 merged.into_iter().map(|(k, body, _)| (k, body)).collect();
3187 let frozen_rows = seg_rows.len();
3188 let (seg_bytes, _meta) = encode_segment(seg_rows.into_iter(), 0.01, SEGMENT_PAGE_BYTES)
3189 .map_err(|e| StorageError::Corrupt(format!("commit_freeze_slices: encode: {e}")))?;
3190
3191 // --- atomic swap phase: mutations only past this point ---
3192 let bytes_before = self.get(table_name).expect("just validated").hot_bytes();
3193 let positions: Vec<usize> = (0..max_rows).collect();
3194 let t_mut = self
3195 .get_mut(table_name)
3196 .expect("just validated; still present");
3197 let removed = t_mut.delete_rows(&positions);
3198 debug_assert_eq!(removed, max_rows, "delete_rows count matches request");
3199 let bytes_after = t_mut.hot_bytes();
3200 let bytes_freed = bytes_before.saturating_sub(bytes_after);
3201
3202 let segment_id = self
3203 .load_segment_bytes(seg_bytes.clone())
3204 .map_err(|e| StorageError::Corrupt(format!("commit_freeze_slices: load: {e}")))?;
3205 let new_cold = post_swap_keys.into_iter().map(|k| {
3206 (
3207 k,
3208 RowLocator::Cold {
3209 segment_id,
3210 page_offset: 0,
3211 },
3212 )
3213 });
3214 let t_mut = self.get_mut(table_name).expect("still present");
3215 t_mut.register_cold_locators(index_name, new_cold)?;
3216
3217 Ok(FreezeReport {
3218 segment_id,
3219 frozen_rows,
3220 bytes_freed,
3221 segment_bytes: seg_bytes,
3222 })
3223 }
3224
3225 /// v6.7.3 — compact every cold segment on `(table, index)` whose
3226 /// `OwnedSegment::bytes().len()` is below `target_segment_bytes`
3227 /// into a single larger merged segment. Rows present in source
3228 /// segment payloads but no longer referenced by any
3229 /// `RowLocator::Cold` on the index (DELETE'd + frozen rows
3230 /// retired via [`Catalog::shadow_cold_row`]) are GC'd in the
3231 /// merge.
3232 ///
3233 /// **Semantics**:
3234 /// 1. Walk the BTree index to collect every Cold locator that
3235 /// targets a small (< threshold) segment. Each such
3236 /// `(key, segment_id)` becomes a row in the merged segment;
3237 /// payload is looked up from the source segment in-place.
3238 /// 2. Encode the collected rows into one new segment via
3239 /// [`encode_segment`]; register it via
3240 /// [`Catalog::load_segment_bytes`] (allocating a fresh
3241 /// `merged_segment_id` at the end of `cold_segments`).
3242 /// 3. Rewrite the BTree index in one pass: every
3243 /// `RowLocator::Cold { segment_id ∈ sources }` becomes
3244 /// `RowLocator::Cold { segment_id = merged_id, page_offset = 0 }`.
3245 /// Hot locators are untouched.
3246 /// 4. Tombstone every source slot via
3247 /// [`Catalog::tombstone_segment`]. Source segment payloads
3248 /// are no longer reachable through the catalog; the on-disk
3249 /// files are the caller's concern.
3250 ///
3251 /// On fewer than 2 candidate segments the catalog is **not**
3252 /// mutated and a no-op report (`merged_segment_id: None`,
3253 /// `sources: []`) is returned. This is the routine case — a
3254 /// freshly-frozen table has at most 1 small segment, no merge
3255 /// possible.
3256 ///
3257 /// Atomicity: every mutating step runs after the read-only
3258 /// gather phase, so a panic before the merge encode leaves the
3259 /// catalog unchanged. The mutation block itself (load + rewrite +
3260 /// tombstone) takes only `&mut self` — callers serialise the
3261 /// engine write lock outside this function.
3262 ///
3263 /// Errors when the table / index doesn't exist, the index isn't
3264 /// `BTree`, the index column type isn't u64-coercible (cold-tier
3265 /// pre-condition), or a source segment fails its in-place
3266 /// row-body lookup (would indicate prior catalog corruption).
3267 pub fn compact_cold_segments(
3268 &mut self,
3269 table_name: &str,
3270 index_name: &str,
3271 target_segment_bytes: u64,
3272 ) -> Result<CompactReport, StorageError> {
3273 // --- validation phase ----------------------------------
3274 let t = self.get(table_name).ok_or_else(|| {
3275 StorageError::Corrupt(format!(
3276 "compact_cold_segments: table {table_name:?} not found"
3277 ))
3278 })?;
3279 let idx = t
3280 .indices
3281 .iter()
3282 .find(|i| i.name == index_name)
3283 .ok_or_else(|| {
3284 StorageError::Corrupt(format!(
3285 "compact_cold_segments: index {index_name:?} not found on {table_name:?}"
3286 ))
3287 })?;
3288 let map = match &idx.kind {
3289 IndexKind::BTree(m) => m,
3290 IndexKind::Nsw(_)
3291 | IndexKind::Brin { .. }
3292 | IndexKind::Gin(_)
3293 | IndexKind::GinTrgm(_)
3294 | IndexKind::GinFulltext(_) => {
3295 return Err(StorageError::Corrupt(format!(
3296 "compact_cold_segments: index {index_name:?} is not BTree; \
3297 compaction applies only to BTree cold-tier indices"
3298 )));
3299 }
3300 };
3301
3302 // --- gather phase --------------------------------------
3303 // Step A: every segment_id this BTree index Cold-references.
3304 let mut referenced_ids: BTreeSet<u32> = BTreeSet::new();
3305 for (_key, locators) in map.iter() {
3306 for loc in locators {
3307 if let RowLocator::Cold { segment_id, .. } = loc {
3308 referenced_ids.insert(*segment_id);
3309 }
3310 }
3311 }
3312 // Step B: keep only the small + still-active ones.
3313 let candidate_set: BTreeSet<u32> = referenced_ids
3314 .into_iter()
3315 .filter(|id| {
3316 self.cold_segments
3317 .get(*id as usize)
3318 .and_then(|s| s.as_deref())
3319 .is_some_and(|s| (s.bytes().len() as u64) < target_segment_bytes)
3320 })
3321 .collect();
3322 if candidate_set.len() < 2 {
3323 return Ok(CompactReport {
3324 sources: Vec::new(),
3325 merged_segment_id: None,
3326 merged_segment_bytes: Vec::new(),
3327 merged_rows: 0,
3328 deleted_rows_pruned: 0,
3329 bytes_reclaimed_estimate: 0,
3330 });
3331 }
3332 // Step C: pre-count source rows for the deleted-pruned metric.
3333 let mut source_row_count: usize = 0;
3334 let mut source_byte_total: u64 = 0;
3335 for &id in &candidate_set {
3336 let seg = self.cold_segments[id as usize]
3337 .as_ref()
3338 .expect("candidate selected only when slot is Some");
3339 source_row_count = source_row_count.saturating_add(seg.meta().num_rows as usize);
3340 source_byte_total = source_byte_total.saturating_add(seg.bytes().len() as u64);
3341 }
3342 // Step D: collect (key, body) pairs from every live Cold
3343 // locator pointing at a candidate. dedupe by key — one
3344 // BTree key resolves to at most one cold payload (the
3345 // freezer + promote/shadow flow keeps Cold locators
3346 // unique per key).
3347 let mut collected: BTreeMap<u64, (Vec<u8>, IndexKey)> = BTreeMap::new();
3348 for (key, locators) in map.iter() {
3349 for loc in locators {
3350 let RowLocator::Cold { segment_id, .. } = loc else {
3351 continue;
3352 };
3353 if !candidate_set.contains(segment_id) {
3354 continue;
3355 }
3356 let u64_key = index_key_as_u64(key).ok_or_else(|| {
3357 StorageError::Corrupt(format!(
3358 "compact_cold_segments: index {index_name:?} has non-integer Cold key; \
3359 cold tier requires IndexKey::Int (Text PK lands in v5.5+)"
3360 ))
3361 })?;
3362 let seg = self.cold_segments[*segment_id as usize]
3363 .as_ref()
3364 .expect("candidate slot guaranteed Some above");
3365 let payload = seg.lookup(u64_key).ok_or_else(|| {
3366 StorageError::Corrupt(format!(
3367 "compact_cold_segments: BTree {index_name:?} points key={u64_key} \
3368 at segment {segment_id} but the segment lookup missed"
3369 ))
3370 })?;
3371 collected.insert(u64_key, (payload, key.clone()));
3372 break;
3373 }
3374 }
3375 let merged_rows = collected.len();
3376 let deleted_rows_pruned = source_row_count.saturating_sub(merged_rows);
3377
3378 // Step E: encode the merged segment. `BTreeMap<u64, _>`
3379 // iteration is ascending by key, which is what
3380 // `encode_segment` requires.
3381 let seg_rows: Vec<(u64, Vec<u8>)> = collected
3382 .iter()
3383 .map(|(k, (body, _))| (*k, body.clone()))
3384 .collect();
3385 let (seg_bytes, _meta) = encode_segment(seg_rows.into_iter(), 0.01, SEGMENT_PAGE_BYTES)
3386 .map_err(|e| StorageError::Corrupt(format!("compact_cold_segments: encode: {e}")))?;
3387 let merged_bytes_len = seg_bytes.len() as u64;
3388
3389 // --- atomic mutation phase ------------------------------
3390 let merged_segment_id = self
3391 .load_segment_bytes(seg_bytes.clone())
3392 .map_err(|e| StorageError::Corrupt(format!("compact_cold_segments: load: {e}")))?;
3393
3394 // Rewrite the BTree index: every Cold locator pointing at
3395 // a candidate source becomes a Cold locator pointing at
3396 // the merged segment. Use a flat collect-then-replace
3397 // pattern so we never hold a `&self` borrow across the
3398 // `&mut self` write.
3399 let entries: Vec<(IndexKey, Vec<RowLocator>)> = {
3400 let t = self
3401 .get(table_name)
3402 .expect("table existed at the start of this fn");
3403 let idx = t
3404 .indices
3405 .iter()
3406 .find(|i| i.name == index_name)
3407 .expect("index existed at the start of this fn");
3408 let IndexKind::BTree(map) = &idx.kind else {
3409 unreachable!("validated above");
3410 };
3411 map.iter().map(|(k, v)| (k.clone(), v.clone())).collect()
3412 };
3413 let t_mut = self
3414 .get_mut(table_name)
3415 .expect("table existed at the start of this fn");
3416 let idx_mut = t_mut
3417 .indices
3418 .iter_mut()
3419 .find(|i| i.name == index_name)
3420 .expect("index existed at the start of this fn");
3421 let IndexKind::BTree(map_mut) = &mut idx_mut.kind else {
3422 unreachable!("validated above");
3423 };
3424 for (key, locators) in entries {
3425 let mut new_locs: Vec<RowLocator> = Vec::with_capacity(locators.len());
3426 let mut changed = false;
3427 for loc in &locators {
3428 match *loc {
3429 RowLocator::Cold {
3430 segment_id,
3431 page_offset: _,
3432 } if candidate_set.contains(&segment_id) => {
3433 let replacement = RowLocator::Cold {
3434 segment_id: merged_segment_id,
3435 page_offset: 0,
3436 };
3437 if !new_locs.contains(&replacement) {
3438 new_locs.push(replacement);
3439 }
3440 changed = true;
3441 }
3442 other => new_locs.push(other),
3443 }
3444 }
3445 if changed {
3446 map_mut.insert_mut(key, new_locs);
3447 }
3448 }
3449
3450 // Tombstone every source slot. Last step — failures here
3451 // would leave the segment double-referenced in both
3452 // memory + manifest, but `tombstone_segment` only errors
3453 // on out-of-bounds, which we've already validated.
3454 for &id in &candidate_set {
3455 self.tombstone_segment(id)?;
3456 }
3457
3458 let bytes_reclaimed_estimate = source_byte_total.saturating_sub(merged_bytes_len);
3459 Ok(CompactReport {
3460 sources: candidate_set.into_iter().collect(),
3461 merged_segment_id: Some(merged_segment_id),
3462 merged_segment_bytes: seg_bytes,
3463 merged_rows,
3464 deleted_rows_pruned,
3465 bytes_reclaimed_estimate,
3466 })
3467 }
3468
3469 /// Internal helper: scan `(table, index)` for a `Cold` locator
3470 /// keyed by `key`. Returns `Ok(Some((segment_id, page_offset)))`
3471 /// when found, `Ok(None)` when the key has only hot entries
3472 /// or no entries at all, `Err` on the same input-validation
3473 /// errors as the public `promote_cold_row` / `shadow_cold_row`.
3474 fn find_cold_locator(
3475 &self,
3476 table_name: &str,
3477 index_name: &str,
3478 key: &IndexKey,
3479 ) -> Result<Option<(u32, u32)>, StorageError> {
3480 let t = self.get(table_name).ok_or_else(|| {
3481 StorageError::Corrupt(format!("find_cold_locator: table {table_name:?} not found"))
3482 })?;
3483 let idx = t
3484 .indices
3485 .iter()
3486 .find(|i| i.name == index_name)
3487 .ok_or_else(|| {
3488 StorageError::Corrupt(format!(
3489 "find_cold_locator: index {index_name:?} not found on {table_name:?}"
3490 ))
3491 })?;
3492 if !matches!(idx.kind, IndexKind::BTree(_)) {
3493 return Err(StorageError::Corrupt(format!(
3494 "find_cold_locator: index {index_name:?} is NSW; promote-on-write only applies to BTree indices"
3495 )));
3496 }
3497 for loc in idx.lookup_eq(key) {
3498 if let RowLocator::Cold {
3499 segment_id,
3500 page_offset,
3501 } = *loc
3502 {
3503 return Ok(Some((segment_id, page_offset)));
3504 }
3505 }
3506 Ok(None)
3507 }
3508}
3509
3510/// Coerce an [`IndexKey`] to the `u64` that v5.1 cold-tier
3511/// segments use as their on-disk PK. Returns `None` for keys that
3512/// aren't representable as `u64` — Text PKs need a hash mapping
3513/// the segment writer baked in (deferred to v5.2+), Bool PKs are
3514/// almost never wide enough to be sharded into a cold tier.
3515fn index_key_as_u64(key: &IndexKey) -> Option<u64> {
3516 match key {
3517 // Reinterpret the i64 bit pattern as u64. Cold-tier segments
3518 // are sorted by this u64 view, so the chosen interpretation
3519 // only has to match between insert (bake_segment / freezer)
3520 // and lookup — using cast_unsigned keeps both sides honest
3521 // and silences clippy::cast_sign_loss.
3522 IndexKey::Int(n) => Some(n.cast_unsigned()),
3523 // Text / Bool / Uuid PKs aren't representable as u64 and so
3524 // can't participate in the u64-sorted cold-tier segment
3525 // PK layout. Same deferral story as Text — lookup falls
3526 // through the in-memory btree.
3527 IndexKey::Text(_) | IndexKey::Bool(_) | IndexKey::Uuid(_) => None,
3528 }
3529}
3530
3531#[derive(Debug, Clone, PartialEq, Eq)]
3532#[non_exhaustive]
3533pub enum StorageError {
3534 DuplicateTable {
3535 name: String,
3536 },
3537 TableNotFound {
3538 name: String,
3539 },
3540 ArityMismatch {
3541 expected: usize,
3542 actual: usize,
3543 },
3544 TypeMismatch {
3545 column: String,
3546 expected: DataType,
3547 actual: DataType,
3548 position: usize,
3549 },
3550 NullInNotNull {
3551 column: String,
3552 },
3553 /// Index with this name already exists on the table.
3554 DuplicateIndex {
3555 name: String,
3556 },
3557 /// Column referenced by an index doesn't exist on the table.
3558 ColumnNotFound {
3559 column: String,
3560 },
3561 /// On-disk format failed to parse — corrupted file, wrong magic, truncated
3562 /// payload, or unknown tag bytes.
3563 Corrupt(String),
3564 /// v6.0.4 — ALTER INDEX targeted an index name that doesn't
3565 /// exist on any table in this catalog.
3566 IndexNotFound {
3567 name: String,
3568 },
3569 /// v6.0.4 — operation requested isn't supported on this index
3570 /// kind / column type (e.g. ALTER INDEX REBUILD on a `BTree`
3571 /// index, or REBUILD WITH (encoding=…) on a non-vector column).
3572 Unsupported(String),
3573}
3574
3575impl fmt::Display for StorageError {
3576 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3577 match self {
3578 Self::DuplicateTable { name } => write!(f, "table already exists: {name}"),
3579 Self::TableNotFound { name } => write!(f, "table not found: {name}"),
3580 Self::ArityMismatch { expected, actual } => write!(
3581 f,
3582 "row arity mismatch: expected {expected} columns, got {actual}"
3583 ),
3584 Self::TypeMismatch {
3585 column,
3586 expected,
3587 actual,
3588 position,
3589 } => write!(
3590 f,
3591 "type mismatch in column {column:?} (position {position}): expected {expected}, got {actual}"
3592 ),
3593 Self::NullInNotNull { column } => {
3594 write!(f, "NULL value in NOT NULL column {column:?}")
3595 }
3596 Self::DuplicateIndex { name } => write!(f, "index already exists: {name}"),
3597 Self::ColumnNotFound { column } => write!(f, "column not found: {column}"),
3598 Self::Corrupt(detail) => write!(f, "corrupt on-disk format: {detail}"),
3599 Self::IndexNotFound { name } => write!(f, "index not found: {name}"),
3600 Self::Unsupported(detail) => write!(f, "unsupported: {detail}"),
3601 }
3602 }
3603}
3604
3605impl ColumnSchema {
3606 pub fn new(name: impl Into<String>, ty: DataType, nullable: bool) -> Self {
3607 Self {
3608 name: name.into(),
3609 ty,
3610 nullable,
3611 default: None,
3612 runtime_default: None,
3613 auto_increment: false,
3614 user_enum_type: None,
3615 user_domain_type: None,
3616 on_update_runtime: None,
3617 collation: Collation::Binary,
3618 is_unsigned: false,
3619 inline_enum_variants: None,
3620 inline_set_variants: None,
3621 }
3622 }
3623
3624 /// Builder-style helper to attach a default value to an otherwise
3625 /// plain column schema. Used by the engine when CREATE TABLE
3626 /// specifies `column TYPE DEFAULT <expr>`.
3627 #[must_use]
3628 pub fn with_default(mut self, default: Value) -> Self {
3629 self.default = Some(default);
3630 self
3631 }
3632
3633 /// v7.9.21 — builder for runtime-evaluated defaults
3634 /// (`DEFAULT now()`, `DEFAULT CURRENT_TIMESTAMP`, …).
3635 /// `expr` is the Expr's `Display` form, re-parsed by the
3636 /// engine at each INSERT.
3637 #[must_use]
3638 pub fn with_runtime_default(mut self, expr: impl Into<String>) -> Self {
3639 self.runtime_default = Some(expr.into());
3640 self
3641 }
3642
3643 /// Builder-style helper to mark a column as `AUTO_INCREMENT`.
3644 #[must_use]
3645 pub const fn with_auto_increment(mut self) -> Self {
3646 self.auto_increment = true;
3647 self
3648 }
3649}
3650
3651impl TableSchema {
3652 pub fn new(name: impl Into<String>, columns: Vec<ColumnSchema>) -> Self {
3653 Self {
3654 name: name.into(),
3655 columns,
3656 hot_tier_bytes: None,
3657 foreign_keys: Vec::new(),
3658 uniqueness_constraints: Vec::new(),
3659 checks: Vec::new(),
3660 }
3661 }
3662}
3663
3664// =========================================================================
3665// Persistent binary format for the catalog.
3666//
3667// Layout (little-endian throughout):
3668//
3669// [magic "SPGDB001" 8 bytes][version u8]
3670// [table_count u32]
3671// for each table:
3672// [name_len u16][name bytes]
3673// [col_count u16]
3674// for each col:
3675// [name_len u16][name bytes]
3676// [type_tag u8 + optional payload]
3677// 1=Int 2=BigInt 3=Float 4=Text 5=Bool
3678// 6=Vector(u32 dim)
3679// 7=SmallInt
3680// 8=Varchar(u32 max)
3681// 9=Char(u32 size)
3682// 10=Numeric(u8 precision, u8 scale)
3683// 11=Date
3684// 12=Timestamp
3685// [nullable u8] 0/1
3686// [default_tag u8] 0=none 1=value (followed by [value_tag u8] + bytes)
3687// [row_count u32]
3688// for each row, for each col, one [value_tag u8] + value bytes:
3689// tag 0 (Null) → no body
3690// tag 1 (Int) → i32 LE
3691// tag 2 (BigInt) → i64 LE
3692// tag 3 (Float) → f64 LE
3693// tag 4 (Text) → u16 LE len + UTF-8 bytes
3694// tag 5 (Bool) → u8 0/1
3695// tag 6 (Vector) → u32 LE dim + dim×f32 LE
3696// tag 7 (SmallInt) → i16 LE
3697// tag 8 (Numeric) → i128 LE (16 bytes) + u8 scale
3698// tag 9 (Date) → i32 LE (days since Unix epoch)
3699// tag 10 (Timestamp) → i64 LE (microseconds since Unix epoch)
3700//
3701// Bumped to version 3 when NUMERIC was added; to version 4 when
3702// AUTO_INCREMENT (per-column flag) + NSW index `kind` byte landed;
3703// to version 5 when DATE / TIMESTAMP were added; to version 6 when
3704// NSW graph topology started travelling on disk (v2.7); to version 7
3705// when the NSW topology became multi-layer HNSW (v2.13); to version 8
3706// when row encoding switched to schema-driven dense layout (v3.0.2 —
3707// per-row NULL bitmap + per-column fixed-width body, no per-cell type
3708// tag).
3709// =========================================================================
3710
3711const FILE_MAGIC: &[u8; 8] = b"SPGDB001";
3712/// Current catalog snapshot format version emitted by [`Catalog::serialize`].
3713///
3714/// v9 (v5.2) extends v8 by serialising `BTree` index entries directly — every
3715/// `(IndexKey, Vec<RowLocator>)` pair travels on disk with the v5.1
3716/// `RowLocator::write_le` tag-prefixed codec. v8 `BTree` indices stored no
3717/// entries at all (the map was rebuilt from `Table::rows` on load); v9
3718/// preserves on-disk Cold locators so freezer-produced cold-tier index
3719/// entries survive a catalog snapshot round-trip. v8 readers are accepted
3720/// by version dispatch in [`Catalog::deserialize`] — every entry decodes
3721/// as `RowLocator::Hot(_)` via `add_index` rebuild, identical to v5.1
3722/// behaviour.
3723/// v6.7.2 — bumped from 10 to 11 to append per-table
3724/// `hot_tier_bytes: Option<u64>` after the per-table indices
3725/// section. v10 catalogs (v6.7.1) load with `hot_tier_bytes =
3726/// None` for every table (the deserialiser short-circuits when
3727/// version < 11). v11 snapshots written by a pre-v6.7.2 binary
3728/// fail loudly at the version check, matching the v6.1.2 /
3729/// v6.1.4 / v6.2.0 / v6.7.1 envelope-bump upgrade fences.
3730///
3731/// v6.8.0 — bumped from 11 to 12: per-index
3732/// `included_columns: Vec<u16>` appended at the tail of each
3733/// index payload. v11 (= v6.7.2) catalogs load with
3734/// `included_columns = Vec::new()` for every index — same
3735/// "older readers, append-only extension" pattern as the v6.7.2
3736/// hot_tier_bytes byte.
3737/// v7.13.0 — bumped from 22 to 23. mailrs round-5 G3 / G10.
3738/// Per-table appendix gains two new sections:
3739/// * `checks: Vec<String>` — CHECK predicate sources (Display
3740/// form of the AST Expr); re-parsed on INSERT/UPDATE to
3741/// enforce against candidate rows. Same persistence pattern
3742/// as `Index::partial_predicate`.
3743/// * Per `UniquenessConstraint`: trailing `nulls_not_distinct:
3744/// u8` flag for PG 15+ `UNIQUE NULLS NOT DISTINCT (cols)`
3745/// semantics.
3746/// v22 catalogs deserialise with empty `checks` and every UC
3747/// at `nulls_not_distinct = false`.
3748/// v24 introduces:
3749/// * Index kind tag 4 = trigram-GIN (`gin_trgm_ops`-flavoured
3750/// `USING gin` over a TEXT/VARCHAR column). Payload shape is
3751/// identical to tag-3 GIN (String → Vec<RowLocator>); the
3752/// keys are PG-compatible 3-byte trigram shingles instead of
3753/// tsvector lexemes. v23 catalogs deserialise unchanged — no
3754/// v23 writer ever emitted tag 4.
3755/// v25 introduces:
3756/// * Per `TriggerDef`: trailing `enabled: u8` flag (mailrs
3757/// round-9 A.2.b — `ALTER TABLE … { ENABLE | DISABLE }
3758/// TRIGGER …`). v24 catalogs deserialise with every trigger
3759/// `enabled = true`, matching pre-v7.16.1 behaviour.
3760/// v26 introduces (v7.17.0 Phase 1.1):
3761/// * Trailing SEQUENCE catalog block after triggers. Encoded
3762/// as `u32 count` followed by per-sequence:
3763/// `name`, `data_type: u8` (0=SmallInt,1=Int,2=BigInt),
3764/// `start i64`, `increment i64`, `min_value i64`,
3765/// `max_value i64`, `cache i64`, `cycle u8`,
3766/// `owned_by_tag u8` (0=NONE, 1=Column → `table`,`column`),
3767/// `last_value i64`, `is_called u8`. v25-and-below catalogs
3768/// deserialise with an empty sequences map.
3769/// v27 introduces (v7.17.0 Phase 1.2):
3770/// * Trailing VIEW catalog block after sequences. Encoded as
3771/// `u32 count` followed by per-view:
3772/// `name`, `column_count u16`, then column names, then
3773/// `body` long-string. v26-and-below catalogs deserialise
3774/// with an empty views map.
3775/// v28 introduces (v7.17.0 Phase 1.3):
3776/// * Trailing MATERIALIZED VIEW source registry block after
3777/// views. Encoded as `u32 count` followed by per-entry:
3778/// `name`, `body` long-string. The materialised rows live
3779/// as a regular Table of the same name (already covered by
3780/// the pre-existing tables block). v27-and-below catalogs
3781/// deserialise with an empty map.
3782/// v29 introduces (v7.17.0 Phase 1.4):
3783/// * Per-table user_enum_type appendix (after the CHECK
3784/// appendix). Layout: `u16 count` followed by per-binding
3785/// `[u16 col_pos][str enum_name]`. Only columns whose
3786/// `user_enum_type` is Some land here; the catalog stays
3787/// compact for the common no-enum case.
3788/// * Trailing ENUM types catalog block after materialized
3789/// views. Encoded as `u32 count` followed by per-entry:
3790/// `name`, `u16 label_count`, then `label_count` short
3791/// strings. v28-and-below catalogs deserialise with an
3792/// empty enum_types map and every column's
3793/// `user_enum_type = None`.
3794/// v30 introduces (v7.17.0 Phase 1.5):
3795/// * Per-table user_domain_type appendix (after the
3796/// user_enum_type appendix). Same shape as the enum one.
3797/// * Trailing DOMAIN types catalog block after the enum
3798/// block. Encoded as `u32 count` followed by per-entry:
3799/// `name`, `data_type` byte, `nullable u8`,
3800/// `default_present u8` + optional default string,
3801/// `u16 check_count` then `check_count` Display-form
3802/// CHECK strings. v29-and-below catalogs deserialise with
3803/// an empty domain_types map and `user_domain_type = None`.
3804/// v31 introduces (v7.17.0 Phase 1.6):
3805/// * Trailing user-schemas block after the DOMAIN block.
3806/// Encoded as `u32 count` followed by `count` schema-name
3807/// short strings. Built-in schemas (`public`, `pg_catalog`,
3808/// `information_schema`) are NOT serialised — they're
3809/// hardcoded in `is_builtin_schema`. v30-and-below catalogs
3810/// deserialise with an empty user-schemas set.
3811/// v32 introduces (v7.17.0 Phase 2.1):
3812/// * Per-table on_update_runtime appendix (after the
3813/// user_domain_type appendix). Layout: `u16 count` followed
3814/// by per-binding `[u16 col_pos][str expr_src]`. Only
3815/// columns whose `on_update_runtime` is Some land here;
3816/// the catalog stays compact when no MySQL-shaped table
3817/// uses the attribute. v31-and-below catalogs deserialise
3818/// with every column's `on_update_runtime = None`.
3819/// v33 introduces (v7.17.0 Phase 2.2):
3820/// * Index kind tag 5 = fulltext-GIN (MySQL `FULLTEXT KEY`
3821/// surface over a TEXT / VARCHAR column). Payload shape is
3822/// identical to tag-3 / tag-4 GIN (`String → Vec<RowLocator>`);
3823/// the keys are lower-cased word lexemes (same rule as
3824/// `to_tsvector('simple', text)`). v32 catalogs deserialise
3825/// unchanged — no v32 writer ever emitted tag 5, and FULLTEXT
3826/// KEY was silently dropped pre-v7.17 so no rebuild shim is
3827/// needed for round-tripped catalogs.
3828/// v34 introduces (v7.17.0 Phase 2.5):
3829/// * Per-table collation appendix (after the on_update_runtime
3830/// appendix). Sparse layout: only columns whose `collation`
3831/// is non-Binary land here. `u16 count` then per-binding
3832/// `[u16 col_pos][u8 collation_tag]` where the tag matches
3833/// `Collation::TAG_*`. Snapshots written by v33-and-below
3834/// readers deserialise every column with `collation =
3835/// Binary`, preserving the prior byte-wise compare
3836/// semantics. Unknown tags read back as Binary too — keeps
3837/// a forward-compat path if a future v35 adds variants
3838/// and someone rolls back to a v34 reader.
3839/// v35 introduces (v7.17.0 Phase 4.4):
3840/// * Per-table is_unsigned appendix (after the collation
3841/// appendix). Sparse layout: only `is_unsigned = true`
3842/// columns land. `u16 count` then per-binding `[u16 col_pos]`.
3843/// v34-and-below catalogs deserialise every column as
3844/// `is_unsigned = false`, preserving the prior silent-
3845/// accept behaviour for negative inserts on UNSIGNED columns.
3846/// v46 introduces (v7.23, mailrs round-14):
3847/// * Escaped short-string codec — `write_str` lengths >= 0xFFFF
3848/// emit `[u16 0xFFFF][u32 real_len]` so TEXT cells (mail bodies,
3849/// document text) above 64 KiB encode instead of panicking.
3850/// One-way upgrade: v45-and-below readers reject v46 catalogs
3851/// loudly via the version gate; v46 readers decode v45 catalogs
3852/// with the plain-u16 rules (0xFFFF is a legitimate length
3853/// there).
3854/// v47 introduces (v7.27, mailrs round-21):
3855/// * Escaped lengths for the REMAINING u16-length cell payloads —
3856/// BYTEA cells, TEXT[] elements, tsvector lexemes and tsquery
3857/// terms — the same `[u16 0xFFFF][u32 real_len]` escape v46
3858/// gave short strings. Round-14 fixed TEXT and missed these;
3859/// round-21 fired the BYTEA twin during a production migration.
3860/// One-way upgrade, same posture as v46.
3861const FILE_VERSION: u8 = 47;
3862/// Oldest format version [`Catalog::deserialize`] still accepts. v8 is the
3863/// v3.0.2 dense-row layout; pre-v8 catalogs require an offline migration.
3864const MIN_SUPPORTED_FILE_VERSION: u8 = 8;
3865
3866// IndexKey wire format (v9):
3867// tag 0 = Int → [i64 LE]
3868// tag 1 = Text → [u16 LE len + UTF-8 bytes] (via write_str / read_str)
3869// tag 2 = Bool → [u8 0/1]
3870const INDEX_KEY_TAG_INT: u8 = 0;
3871const INDEX_KEY_TAG_TEXT: u8 = 1;
3872const INDEX_KEY_TAG_BOOL: u8 = 2;
3873/// v7.17.0 — `IndexKey::Uuid([u8; 16])`. Body = raw 16 bytes
3874/// (RFC 4122 byte order). Persisted only in FILE_VERSION 36+
3875/// catalogs.
3876const INDEX_KEY_TAG_UUID: u8 = 3;
3877
3878impl Catalog {
3879 /// Serialize the whole catalog (schema + every row) into a self-contained
3880 /// byte buffer. Format is documented above the impl block.
3881 pub fn serialize(&self) -> Vec<u8> {
3882 let mut out = Vec::with_capacity(64);
3883 out.extend_from_slice(FILE_MAGIC);
3884 out.push(FILE_VERSION);
3885 write_u32(
3886 &mut out,
3887 u32::try_from(self.tables.len()).expect("≤ 4G tables"),
3888 );
3889 for t in &self.tables {
3890 write_str(&mut out, &t.schema.name);
3891 write_u16(
3892 &mut out,
3893 u16::try_from(t.schema.columns.len()).expect("≤ 65k columns/table"),
3894 );
3895 for c in &t.schema.columns {
3896 write_str(&mut out, &c.name);
3897 write_data_type(&mut out, c.ty);
3898 out.push(u8::from(c.nullable));
3899 match &c.default {
3900 None => out.push(0),
3901 Some(v) => {
3902 out.push(1);
3903 write_value(&mut out, v);
3904 }
3905 }
3906 out.push(u8::from(c.auto_increment));
3907 }
3908 write_u32(
3909 &mut out,
3910 u32::try_from(t.rows.len()).expect("≤ 4G rows/table"),
3911 );
3912 // v3.0.2 dense row encoding (FILE_VERSION 8): per-row NULL
3913 // bitmap, then tightly-packed bodies. Identical wire format
3914 // as before — extracted into `encode_row_body_dense` so cold-
3915 // tier segments (v5.1+) can share the encoding.
3916 for row in &t.rows {
3917 out.extend_from_slice(&encode_row_body_dense(row, &t.schema));
3918 }
3919 // Index definitions. Per-index payload:
3920 // [name][col_pos u16][kind u8]
3921 // kind 0 = B-tree (no params — rebuilt on load)
3922 // kind 1 = NSW graph (u16 M + serialized graph)
3923 // For NSW the graph topology travels on disk so startup
3924 // doesn't re-run the O(n²M) rebuild — see v2.7 notes.
3925 write_u16(
3926 &mut out,
3927 u16::try_from(t.indices.len()).expect("≤ 65k indices/table"),
3928 );
3929 for idx in &t.indices {
3930 write_str(&mut out, &idx.name);
3931 write_u16(
3932 &mut out,
3933 u16::try_from(idx.column_position).expect("≤ 65k columns/table"),
3934 );
3935 match &idx.kind {
3936 IndexKind::BTree(map) => {
3937 out.push(0);
3938 // v9: serialise the full PB map. Each entry's
3939 // RowLocator list travels with the tag-prefixed
3940 // codec from `row_locator::write_le`, so freezer-
3941 // produced Cold locators survive a snapshot
3942 // round-trip. v8 BTree wrote nothing here and
3943 // rebuilt from rows — v9 readers tolerate v8 by
3944 // version dispatch in `Catalog::deserialize`.
3945 write_u32(
3946 &mut out,
3947 u32::try_from(map.len()).expect("≤ 4G index entries/index"),
3948 );
3949 for (key, locators) in map {
3950 write_index_key(&mut out, key);
3951 write_u32(
3952 &mut out,
3953 u32::try_from(locators.len()).expect("≤ 4G locators/key"),
3954 );
3955 for loc in locators {
3956 loc.write_le(&mut out);
3957 }
3958 }
3959 }
3960 IndexKind::Nsw(g) => {
3961 out.push(1);
3962 write_u16(&mut out, u16::try_from(g.m).expect("≤ 65k NSW neighbours"));
3963 write_nsw_graph(&mut out, g);
3964 }
3965 IndexKind::Brin { column_type } => {
3966 // v6.7.1 — tag byte 2 = BRIN. Payload is the
3967 // column type code (1 byte mapping to the
3968 // shared DataType numeric encoding); no
3969 // further data — BRIN summaries live in
3970 // cold segments, not the catalog.
3971 out.push(2);
3972 write_data_type(&mut out, *column_type);
3973 }
3974 IndexKind::Gin(map) => {
3975 // v7.12.3 — tag byte 3 = GIN. Payload mirrors
3976 // the BTree encoding but with String (lexeme
3977 // word) keys instead of IndexKey. Tag-prefixed
3978 // RowLocator codec so freezer-produced Cold
3979 // locators survive snapshot round-trip.
3980 // FILE_VERSION 21+; v20 catalogs never wrote a
3981 // GIN index (the AM degraded to BTree fallback
3982 // pre-v7.12.3), so no migration shim is needed.
3983 out.push(3);
3984 write_u32(
3985 &mut out,
3986 u32::try_from(map.len()).expect("≤ 4G GIN posting lists"),
3987 );
3988 for (word, locators) in map {
3989 write_str(&mut out, word);
3990 write_u32(
3991 &mut out,
3992 u32::try_from(locators.len()).expect("≤ 4G locators/posting list"),
3993 );
3994 for loc in locators {
3995 loc.write_le(&mut out);
3996 }
3997 }
3998 }
3999 IndexKind::GinTrgm(map) => {
4000 // v7.15.0 — tag byte 4 = GinTrgm
4001 // (`gin_trgm_ops` GIN over a TEXT column).
4002 // Payload shape is identical to tag-3 GIN —
4003 // `String → Vec<RowLocator>` posting lists.
4004 // The String keys are 3-byte trigrams instead
4005 // of tsvector lexemes; the deserializer
4006 // dispatches on the tag, not the key shape.
4007 // FILE_VERSION 24+; v23 catalogs never wrote
4008 // a trigram-GIN.
4009 out.push(4);
4010 write_u32(
4011 &mut out,
4012 u32::try_from(map.len()).expect("≤ 4G trigram-GIN posting lists"),
4013 );
4014 for (tri, locators) in map {
4015 write_str(&mut out, tri);
4016 write_u32(
4017 &mut out,
4018 u32::try_from(locators.len()).expect("≤ 4G locators/posting list"),
4019 );
4020 for loc in locators {
4021 loc.write_le(&mut out);
4022 }
4023 }
4024 }
4025 IndexKind::GinFulltext(map) => {
4026 // v7.17.0 Phase 2.2 — tag byte 5 =
4027 // GinFulltext (MySQL `FULLTEXT KEY` GIN
4028 // over a TEXT/VARCHAR column). Payload
4029 // shape mirrors tag-3 / tag-4 GIN —
4030 // `String → Vec<RowLocator>` posting
4031 // lists keyed by lower-cased word
4032 // lexemes. FILE_VERSION 33+; v32 catalogs
4033 // never wrote a fulltext-GIN (FULLTEXT
4034 // KEY was silently dropped pre-v7.17).
4035 out.push(5);
4036 write_u32(
4037 &mut out,
4038 u32::try_from(map.len()).expect("≤ 4G fulltext-GIN posting lists"),
4039 );
4040 for (lex, locators) in map {
4041 write_str(&mut out, lex);
4042 write_u32(
4043 &mut out,
4044 u32::try_from(locators.len()).expect("≤ 4G locators/posting list"),
4045 );
4046 for loc in locators {
4047 loc.write_le(&mut out);
4048 }
4049 }
4050 }
4051 }
4052 // v6.8.0 — included_columns appendix per index.
4053 // Layout: [u16 num_included][num × u16 column_position].
4054 // v11 readers stop before this u16 (deserialise loop
4055 // gated on version >= 12); v12+ readers always
4056 // consume it. Empty Vec serialises as a bare 0u16.
4057 write_u16(
4058 &mut out,
4059 u16::try_from(idx.included_columns.len()).expect("≤ 65k INCLUDE columns/index"),
4060 );
4061 for col_pos in &idx.included_columns {
4062 write_u16(
4063 &mut out,
4064 u16::try_from(*col_pos).expect("≤ 65k columns/table"),
4065 );
4066 }
4067 // v6.8.1 — partial_predicate appendix per index.
4068 // Layout: [u8 has_pred][u16 LE len][bytes (if has_pred)].
4069 // Same v12 gate as included_columns.
4070 match &idx.partial_predicate {
4071 None => out.push(0),
4072 Some(pred) => {
4073 out.push(1);
4074 write_str(&mut out, pred);
4075 }
4076 }
4077 // v6.8.2 — expression appendix. Same shape as
4078 // partial_predicate.
4079 match &idx.expression {
4080 None => out.push(0),
4081 Some(expr) => {
4082 out.push(1);
4083 write_str(&mut out, expr);
4084 }
4085 }
4086 // v7.9.29 — is_unique appendix (FILE_VERSION 16+).
4087 // Single byte 0/1. v15-and-below readers stop before
4088 // this byte; v16 readers always consume it. mailrs K1.
4089 out.push(u8::from(idx.is_unique));
4090 // v7.9.29 — extra_column_positions appendix.
4091 // Layout: [u16 count][count × u16 column_position].
4092 write_u16(
4093 &mut out,
4094 u16::try_from(idx.extra_column_positions.len())
4095 .expect("≤ 65k extra cols / index"),
4096 );
4097 for cp in &idx.extra_column_positions {
4098 write_u16(&mut out, u16::try_from(*cp).expect("≤ 65k columns/table"));
4099 }
4100 }
4101 // v6.7.2 — per-table hot_tier_bytes Option<u64>.
4102 // Layout: [u8 has_value][u64 LE value (if has_value)].
4103 // v10 readers stop before this byte (deserialise loop
4104 // gated on version >= 11); v11+ readers always
4105 // consume it.
4106 match t.schema.hot_tier_bytes {
4107 None => out.push(0),
4108 Some(n) => {
4109 out.push(1);
4110 out.extend_from_slice(&n.to_le_bytes());
4111 }
4112 }
4113 // v7.6.1 — FOREIGN KEY appendix (catalog FILE_VERSION 13+).
4114 // Layout: [u16 LE fk_count]
4115 // per fk:
4116 // [u8 has_name] [str name (if has_name)]
4117 // [u16 LE local_arity] [u16 LE local_pos]*arity
4118 // [str parent_table]
4119 // [u16 LE parent_arity] [u16 LE parent_pos]*arity
4120 // [u8 on_delete_tag] [u8 on_update_tag]
4121 // Older catalogs (v12 and below) skip this block entirely;
4122 // their reader stops before this byte.
4123 write_u16(
4124 &mut out,
4125 u16::try_from(t.schema.foreign_keys.len()).expect("≤ 65k FKs/table"),
4126 );
4127 for fk in &t.schema.foreign_keys {
4128 match &fk.name {
4129 None => out.push(0),
4130 Some(n) => {
4131 out.push(1);
4132 write_str(&mut out, n);
4133 }
4134 }
4135 write_u16(
4136 &mut out,
4137 u16::try_from(fk.local_columns.len()).expect("≤ 65k FK columns"),
4138 );
4139 for &p in &fk.local_columns {
4140 write_u16(&mut out, u16::try_from(p).expect("≤ 65k columns/table"));
4141 }
4142 write_str(&mut out, &fk.parent_table);
4143 write_u16(
4144 &mut out,
4145 u16::try_from(fk.parent_columns.len()).expect("≤ 65k FK parent columns"),
4146 );
4147 for &p in &fk.parent_columns {
4148 write_u16(&mut out, u16::try_from(p).expect("≤ 65k columns/table"));
4149 }
4150 out.push(fk.on_delete.tag());
4151 out.push(fk.on_update.tag());
4152 }
4153 // v7.9.19 — UniquenessConstraint appendix (catalog
4154 // FILE_VERSION 15+). Layout per table after the FK
4155 // block:
4156 // [u16 count]
4157 // per constraint:
4158 // [u8 is_primary_key]
4159 // [u16 arity][u16 col_pos]*arity
4160 // Older catalogs (v14 and below) skip this block.
4161 write_u16(
4162 &mut out,
4163 u16::try_from(t.schema.uniqueness_constraints.len())
4164 .expect("≤ 65k uniqueness constraints/table"),
4165 );
4166 for uc in &t.schema.uniqueness_constraints {
4167 out.push(u8::from(uc.is_primary_key));
4168 write_u16(
4169 &mut out,
4170 u16::try_from(uc.columns.len()).expect("≤ 65k cols in uniqueness constraint"),
4171 );
4172 for &p in &uc.columns {
4173 write_u16(&mut out, u16::try_from(p).expect("≤ 65k columns/table"));
4174 }
4175 // v7.13.0 — `nulls_not_distinct` flag
4176 // (FILE_VERSION 23+). Always written by writers at
4177 // version 23+; deserialise gates on `version >= 23`
4178 // so v22-and-below catalogs round-trip cleanly.
4179 out.push(u8::from(uc.nulls_not_distinct));
4180 }
4181 // v7.9.21 — runtime_default appendix per table.
4182 // Layout: [u16 count] then for each:
4183 // [u16 col_pos][str expr]
4184 // Only columns whose runtime_default is Some land here;
4185 // catalog stays compact for the common literal-default
4186 // case.
4187 let mut rt_defaults: Vec<(usize, &str)> = Vec::new();
4188 for (i, c) in t.schema.columns.iter().enumerate() {
4189 if let Some(e) = &c.runtime_default {
4190 rt_defaults.push((i, e.as_str()));
4191 }
4192 }
4193 write_u16(
4194 &mut out,
4195 u16::try_from(rt_defaults.len()).expect("≤ 65k runtime defaults/table"),
4196 );
4197 for (pos, expr) in rt_defaults {
4198 write_u16(&mut out, u16::try_from(pos).expect("≤ 65k columns/table"));
4199 write_str(&mut out, expr);
4200 }
4201 // v7.13.0 — CHECK constraint appendix per table.
4202 // Layout: [u16 count] then `count` Display-form
4203 // expression strings. Re-parsed on every INSERT/UPDATE
4204 // by the engine. FILE_VERSION 23+ only; v22 readers
4205 // never reach this block because the writer also moves
4206 // to v23 in lock-step.
4207 write_u16(
4208 &mut out,
4209 u16::try_from(t.schema.checks.len()).expect("≤ 65k CHECK constraints/table"),
4210 );
4211 for c in &t.schema.checks {
4212 write_str(&mut out, c.as_str());
4213 }
4214 // v7.17.0 Phase 1.4 — per-table user_enum_type
4215 // appendix. Layout: [u16 count] then
4216 // [u16 col_pos][str enum_name] per binding. Only
4217 // columns whose user_enum_type is Some land here.
4218 let mut enum_bindings: Vec<(usize, &str)> = Vec::new();
4219 for (i, c) in t.schema.columns.iter().enumerate() {
4220 if let Some(e) = &c.user_enum_type {
4221 enum_bindings.push((i, e.as_str()));
4222 }
4223 }
4224 write_u16(
4225 &mut out,
4226 u16::try_from(enum_bindings.len()).expect("≤ 65k enum-typed columns/table"),
4227 );
4228 for (pos, ename) in enum_bindings {
4229 write_u16(&mut out, u16::try_from(pos).expect("≤ 65k columns/table"));
4230 write_str(&mut out, ename);
4231 }
4232 // v7.17.0 Phase 1.5 — per-table user_domain_type
4233 // appendix. Same layout as the enum one. v29-and-
4234 // below readers stop after the enum appendix.
4235 let mut domain_bindings: Vec<(usize, &str)> = Vec::new();
4236 for (i, c) in t.schema.columns.iter().enumerate() {
4237 if let Some(d) = &c.user_domain_type {
4238 domain_bindings.push((i, d.as_str()));
4239 }
4240 }
4241 write_u16(
4242 &mut out,
4243 u16::try_from(domain_bindings.len()).expect("≤ 65k domain-typed columns/table"),
4244 );
4245 for (pos, dname) in domain_bindings {
4246 write_u16(&mut out, u16::try_from(pos).expect("≤ 65k columns/table"));
4247 write_str(&mut out, dname);
4248 }
4249 // v7.17.0 Phase 2.1 — per-table on_update_runtime
4250 // appendix. Sparse: only ON UPDATE-bound columns.
4251 let mut on_update_bindings: Vec<(usize, &str)> = Vec::new();
4252 for (i, c) in t.schema.columns.iter().enumerate() {
4253 if let Some(e) = &c.on_update_runtime {
4254 on_update_bindings.push((i, e.as_str()));
4255 }
4256 }
4257 write_u16(
4258 &mut out,
4259 u16::try_from(on_update_bindings.len()).expect("≤ 65k ON UPDATE columns/table"),
4260 );
4261 for (pos, expr_src) in on_update_bindings {
4262 write_u16(&mut out, u16::try_from(pos).expect("≤ 65k columns/table"));
4263 write_str(&mut out, expr_src);
4264 }
4265 // v7.17.0 Phase 2.5 — per-table collation appendix.
4266 // Sparse: only non-Binary columns land. Layout:
4267 // `[u16 count][u16 col_pos][u8 tag] × count`.
4268 let mut coll_bindings: Vec<(usize, u8)> = Vec::new();
4269 for (i, c) in t.schema.columns.iter().enumerate() {
4270 let tag = match c.collation {
4271 Collation::Binary => continue,
4272 Collation::CaseInsensitive => Collation::TAG_CASE_INSENSITIVE,
4273 };
4274 coll_bindings.push((i, tag));
4275 }
4276 write_u16(
4277 &mut out,
4278 u16::try_from(coll_bindings.len()).expect("≤ 65k collation bindings/table"),
4279 );
4280 for (pos, tag) in coll_bindings {
4281 write_u16(&mut out, u16::try_from(pos).expect("≤ 65k columns/table"));
4282 out.push(tag);
4283 }
4284 // v7.17.0 Phase 4.4 — per-table is_unsigned appendix.
4285 // Sparse: only UNSIGNED columns land. Layout:
4286 // `[u16 count][u16 col_pos] × count`.
4287 let mut unsigned_bindings: Vec<usize> = Vec::new();
4288 for (i, c) in t.schema.columns.iter().enumerate() {
4289 if c.is_unsigned {
4290 unsigned_bindings.push(i);
4291 }
4292 }
4293 write_u16(
4294 &mut out,
4295 u16::try_from(unsigned_bindings.len()).expect("≤ 65k UNSIGNED columns/table"),
4296 );
4297 for pos in unsigned_bindings {
4298 write_u16(&mut out, u16::try_from(pos).expect("≤ 65k columns/table"));
4299 }
4300 // v7.17.0 Phase 3.P0-36 — per-table inline_enum_variants
4301 // appendix. Sparse: only ENUM columns land. Layout:
4302 // `[u16 count] then per binding [u16 col_pos]
4303 // [u16 variant_count] then variant strings`.
4304 // FILE_VERSION 41+; v40 readers never reach this block.
4305 let mut enum_inline_bindings: Vec<(usize, &[String])> = Vec::new();
4306 for (i, c) in t.schema.columns.iter().enumerate() {
4307 if let Some(vs) = &c.inline_enum_variants {
4308 enum_inline_bindings.push((i, vs.as_slice()));
4309 }
4310 }
4311 write_u16(
4312 &mut out,
4313 u16::try_from(enum_inline_bindings.len()).expect("≤ 65k inline-ENUM columns/table"),
4314 );
4315 for (pos, variants) in enum_inline_bindings {
4316 write_u16(&mut out, u16::try_from(pos).expect("≤ 65k columns/table"));
4317 write_u16(
4318 &mut out,
4319 u16::try_from(variants.len()).expect("≤ 65k variants/ENUM"),
4320 );
4321 for v in variants {
4322 write_str(&mut out, v.as_str());
4323 }
4324 }
4325 // v7.17.0 Phase 3.P0-37 — per-table inline_set_variants
4326 // appendix. Same layout as the inline ENUM block.
4327 // FILE_VERSION 42+; v41 readers never reach this block.
4328 let mut set_inline_bindings: Vec<(usize, &[String])> = Vec::new();
4329 for (i, c) in t.schema.columns.iter().enumerate() {
4330 if let Some(vs) = &c.inline_set_variants {
4331 set_inline_bindings.push((i, vs.as_slice()));
4332 }
4333 }
4334 write_u16(
4335 &mut out,
4336 u16::try_from(set_inline_bindings.len()).expect("≤ 65k inline-SET columns/table"),
4337 );
4338 for (pos, variants) in set_inline_bindings {
4339 write_u16(&mut out, u16::try_from(pos).expect("≤ 65k columns/table"));
4340 write_u16(
4341 &mut out,
4342 u16::try_from(variants.len()).expect("≤ 65k variants/SET"),
4343 );
4344 for v in variants {
4345 write_str(&mut out, v.as_str());
4346 }
4347 }
4348 }
4349 // v7.12.4 — catalog-wide appendix: user-defined functions
4350 // then triggers. FILE_VERSION 22+ only. v21 and earlier
4351 // readers stop after the last table; v22 readers always
4352 // consume two `u32` counts (possibly zero).
4353 //
4354 // Function entry layout:
4355 // [str name] [str args_repr] [str returns]
4356 // [str language] [str body]
4357 // Trigger entry layout:
4358 // [str name] [str table] [str timing]
4359 // [u16 event_count] (event_count × str)
4360 // [str for_each] [str function]
4361 write_u32(
4362 &mut out,
4363 u32::try_from(self.functions.len()).expect("≤ 4G functions"),
4364 );
4365 for fd in self.functions.values() {
4366 write_str(&mut out, &fd.name);
4367 write_str(&mut out, &fd.args_repr);
4368 write_str(&mut out, &fd.returns);
4369 write_str(&mut out, &fd.language);
4370 write_str_long(&mut out, &fd.body);
4371 }
4372 write_u32(
4373 &mut out,
4374 u32::try_from(self.triggers.len()).expect("≤ 4G triggers"),
4375 );
4376 for td in &self.triggers {
4377 write_str(&mut out, &td.name);
4378 write_str(&mut out, &td.table);
4379 write_str(&mut out, &td.timing);
4380 write_u16(
4381 &mut out,
4382 u16::try_from(td.events.len()).expect("≤ 65k events / trigger"),
4383 );
4384 for ev in &td.events {
4385 write_str(&mut out, ev);
4386 }
4387 write_str(&mut out, &td.for_each);
4388 write_str(&mut out, &td.function);
4389 // v7.13.0 — `UPDATE OF cols` filter
4390 // (FILE_VERSION 23+). v22 readers omit; v23 writers
4391 // always emit (possibly zero).
4392 write_u16(
4393 &mut out,
4394 u16::try_from(td.update_columns.len()).expect("≤ 65k cols / trigger"),
4395 );
4396 for c in &td.update_columns {
4397 write_str(&mut out, c);
4398 }
4399 // v7.16.1 — TriggerDef.enabled (FILE_VERSION 25+).
4400 out.push(u8::from(td.enabled));
4401 }
4402 // v7.17.0 Phase 1.1 — SEQUENCE catalog block (FILE_VERSION 26+).
4403 write_u32(
4404 &mut out,
4405 u32::try_from(self.sequences.len()).expect("≤ 4G sequences"),
4406 );
4407 for seq in self.sequences.values() {
4408 write_str(&mut out, &seq.name);
4409 out.push(match seq.data_type {
4410 SequenceDataType::SmallInt => 0,
4411 SequenceDataType::Int => 1,
4412 SequenceDataType::BigInt => 2,
4413 });
4414 out.extend_from_slice(&seq.start.to_le_bytes());
4415 out.extend_from_slice(&seq.increment.to_le_bytes());
4416 out.extend_from_slice(&seq.min_value.to_le_bytes());
4417 out.extend_from_slice(&seq.max_value.to_le_bytes());
4418 out.extend_from_slice(&seq.cache.to_le_bytes());
4419 out.push(u8::from(seq.cycle));
4420 match &seq.owned_by {
4421 None => out.push(0),
4422 Some((table, column)) => {
4423 out.push(1);
4424 write_str(&mut out, table);
4425 write_str(&mut out, column);
4426 }
4427 }
4428 out.extend_from_slice(&seq.last_value.to_le_bytes());
4429 out.push(u8::from(seq.is_called));
4430 }
4431 // v7.17.0 Phase 1.2 — VIEW catalog block (FILE_VERSION 27+).
4432 write_u32(
4433 &mut out,
4434 u32::try_from(self.views.len()).expect("≤ 4G views"),
4435 );
4436 for view in self.views.values() {
4437 write_str(&mut out, &view.name);
4438 write_u16(
4439 &mut out,
4440 u16::try_from(view.columns.len()).expect("≤ 65k cols / view"),
4441 );
4442 for c in &view.columns {
4443 write_str(&mut out, c);
4444 }
4445 write_str_long(&mut out, &view.body);
4446 }
4447 // v7.17.0 Phase 1.3 — MATERIALIZED VIEW source registry
4448 // (FILE_VERSION 28+). The backing rows live as a regular
4449 // table of the same name already in the tables block.
4450 write_u32(
4451 &mut out,
4452 u32::try_from(self.materialized_views.len()).expect("≤ 4G materialized views"),
4453 );
4454 for (name, body) in &self.materialized_views {
4455 write_str(&mut out, name);
4456 write_str_long(&mut out, body);
4457 }
4458 // v7.17.0 Phase 1.4 — ENUM types catalog block
4459 // (FILE_VERSION 29+).
4460 write_u32(
4461 &mut out,
4462 u32::try_from(self.enum_types.len()).expect("≤ 4G enum types"),
4463 );
4464 for e in self.enum_types.values() {
4465 write_str(&mut out, &e.name);
4466 write_u16(
4467 &mut out,
4468 u16::try_from(e.labels.len()).expect("≤ 65k labels / enum"),
4469 );
4470 for l in &e.labels {
4471 write_str(&mut out, l);
4472 }
4473 }
4474 // v7.17.0 Phase 1.5 — DOMAIN types catalog block
4475 // (FILE_VERSION 30+).
4476 write_u32(
4477 &mut out,
4478 u32::try_from(self.domain_types.len()).expect("≤ 4G domain types"),
4479 );
4480 for d in self.domain_types.values() {
4481 write_str(&mut out, &d.name);
4482 write_data_type(&mut out, d.base_type);
4483 out.push(u8::from(d.nullable));
4484 match &d.default {
4485 None => out.push(0),
4486 Some(s) => {
4487 out.push(1);
4488 write_str(&mut out, s);
4489 }
4490 }
4491 write_u16(
4492 &mut out,
4493 u16::try_from(d.checks.len()).expect("≤ 65k CHECKs / domain"),
4494 );
4495 for c in &d.checks {
4496 write_str(&mut out, c);
4497 }
4498 }
4499 // v7.17.0 Phase 1.6 — user-schemas registry
4500 // (FILE_VERSION 31+). Built-ins are hardcoded in
4501 // `is_builtin_schema` and not persisted.
4502 write_u32(
4503 &mut out,
4504 u32::try_from(self.schemas.len()).expect("≤ 4G schemas"),
4505 );
4506 for name in &self.schemas {
4507 write_str(&mut out, name);
4508 }
4509 out
4510 }
4511
4512 /// Deserialize a previously-serialized catalog. Rejects bad magic, version
4513 /// mismatch, unknown tags, truncation, and trailing bytes.
4514 pub fn deserialize(buf: &[u8]) -> Result<Self, StorageError> {
4515 let mut cur = Cursor::new(buf);
4516 let magic = cur.take(8)?;
4517 if magic != FILE_MAGIC {
4518 return Err(StorageError::Corrupt(format!(
4519 "bad magic: expected SPGDB001, got {magic:?}"
4520 )));
4521 }
4522 let version = cur.read_u8()?;
4523 if !(MIN_SUPPORTED_FILE_VERSION..=FILE_VERSION).contains(&version) {
4524 return Err(StorageError::Corrupt(format!(
4525 "unsupported file version: {version} (supported: {MIN_SUPPORTED_FILE_VERSION}..={FILE_VERSION})"
4526 )));
4527 }
4528 // v7.23/v7.27 — escape decoding is version-gated (see
4529 // STR_LEN_ESCAPE / Cursor::codec_version).
4530 cur.codec_version = version;
4531 let table_count = cur.read_u32()? as usize;
4532 let mut cat = Self::new();
4533 for _ in 0..table_count {
4534 deserialize_table(&mut cur, &mut cat, version)?;
4535 }
4536 // v7.12.4 — catalog-wide function + trigger appendix.
4537 // FILE_VERSION 22+ only; v21 and earlier catalogs stop
4538 // after the last table.
4539 if version >= 22 {
4540 let fn_count = cur.read_u32()? as usize;
4541 for _ in 0..fn_count {
4542 let name = cur.read_str()?;
4543 let args_repr = cur.read_str()?;
4544 let returns = cur.read_str()?;
4545 let language = cur.read_str()?;
4546 let body = cur.read_str_long()?;
4547 cat.functions.insert(
4548 name.clone(),
4549 FunctionDef {
4550 name,
4551 args_repr,
4552 returns,
4553 language,
4554 body,
4555 },
4556 );
4557 }
4558 let trg_count = cur.read_u32()? as usize;
4559 for _ in 0..trg_count {
4560 let name = cur.read_str()?;
4561 let table = cur.read_str()?;
4562 let timing = cur.read_str()?;
4563 let ev_count = cur.read_u16()? as usize;
4564 let mut events = Vec::with_capacity(ev_count);
4565 for _ in 0..ev_count {
4566 events.push(cur.read_str()?);
4567 }
4568 let for_each = cur.read_str()?;
4569 let function = cur.read_str()?;
4570 // v7.13.0 — trailing `UPDATE OF cols` filter
4571 // (FILE_VERSION 23+ only; v22 catalogs omit and
4572 // deserialise with an empty vec).
4573 let update_columns = if version >= 23 {
4574 let n = cur.read_u16()? as usize;
4575 let mut cols = Vec::with_capacity(n);
4576 for _ in 0..n {
4577 cols.push(cur.read_str()?);
4578 }
4579 cols
4580 } else {
4581 Vec::new()
4582 };
4583 // v7.16.1 — TriggerDef.enabled (FILE_VERSION 25+).
4584 // v24-and-below catalogs deserialise with `true`
4585 // — pre-v7.16.1 every trigger always fired.
4586 let enabled = if version >= 25 {
4587 cur.read_u8()? != 0
4588 } else {
4589 true
4590 };
4591 cat.triggers.push(TriggerDef {
4592 name,
4593 table,
4594 timing,
4595 events,
4596 for_each,
4597 function,
4598 update_columns,
4599 enabled,
4600 });
4601 }
4602 }
4603 // v7.17.0 Phase 1.1 — SEQUENCE block (FILE_VERSION 26+).
4604 // v25-and-below catalogs omit; we leave the map empty.
4605 if version >= 26 {
4606 let seq_count = cur.read_u32()? as usize;
4607 for _ in 0..seq_count {
4608 let name = cur.read_str()?;
4609 let data_type = match cur.read_u8()? {
4610 0 => SequenceDataType::SmallInt,
4611 1 => SequenceDataType::Int,
4612 2 => SequenceDataType::BigInt,
4613 other => {
4614 return Err(StorageError::Corrupt(format!(
4615 "unknown SEQUENCE data-type tag {other}"
4616 )));
4617 }
4618 };
4619 let start = cur.read_i64()?;
4620 let increment = cur.read_i64()?;
4621 let min_value = cur.read_i64()?;
4622 let max_value = cur.read_i64()?;
4623 let cache = cur.read_i64()?;
4624 let cycle = cur.read_u8()? != 0;
4625 let owned_by = match cur.read_u8()? {
4626 0 => None,
4627 1 => {
4628 let t = cur.read_str()?;
4629 let c = cur.read_str()?;
4630 Some((t, c))
4631 }
4632 other => {
4633 return Err(StorageError::Corrupt(format!(
4634 "unknown SEQUENCE owned-by tag {other}"
4635 )));
4636 }
4637 };
4638 let last_value = cur.read_i64()?;
4639 let is_called = cur.read_u8()? != 0;
4640 cat.sequences.insert(
4641 name.clone(),
4642 SequenceDef {
4643 name,
4644 data_type,
4645 start,
4646 increment,
4647 min_value,
4648 max_value,
4649 cache,
4650 cycle,
4651 owned_by,
4652 last_value,
4653 is_called,
4654 },
4655 );
4656 }
4657 }
4658 // v7.17.0 Phase 1.2 — VIEW block (FILE_VERSION 27+).
4659 // v26-and-below catalogs omit; we leave the map empty.
4660 if version >= 27 {
4661 let view_count = cur.read_u32()? as usize;
4662 for _ in 0..view_count {
4663 let name = cur.read_str()?;
4664 let col_count = cur.read_u16()? as usize;
4665 let mut columns = Vec::with_capacity(col_count);
4666 for _ in 0..col_count {
4667 columns.push(cur.read_str()?);
4668 }
4669 let body = cur.read_str_long()?;
4670 cat.views.insert(
4671 name.clone(),
4672 ViewDef {
4673 name,
4674 columns,
4675 body,
4676 },
4677 );
4678 }
4679 }
4680 // v7.17.0 Phase 1.3 — MATERIALIZED VIEW source registry
4681 // (FILE_VERSION 28+). v27-and-below catalogs omit.
4682 if version >= 28 {
4683 let mv_count = cur.read_u32()? as usize;
4684 for _ in 0..mv_count {
4685 let name = cur.read_str()?;
4686 let body = cur.read_str_long()?;
4687 cat.materialized_views.insert(name, body);
4688 }
4689 }
4690 // v7.17.0 Phase 1.4 — ENUM types catalog block
4691 // (FILE_VERSION 29+).
4692 if version >= 29 {
4693 let etype_count = cur.read_u32()? as usize;
4694 for _ in 0..etype_count {
4695 let name = cur.read_str()?;
4696 let label_count = cur.read_u16()? as usize;
4697 let mut labels = Vec::with_capacity(label_count);
4698 for _ in 0..label_count {
4699 labels.push(cur.read_str()?);
4700 }
4701 cat.enum_types
4702 .insert(name.clone(), EnumDef { name, labels });
4703 }
4704 }
4705 // v7.17.0 Phase 1.5 — DOMAIN types catalog block
4706 // (FILE_VERSION 30+).
4707 if version >= 30 {
4708 let dtype_count = cur.read_u32()? as usize;
4709 for _ in 0..dtype_count {
4710 let name = cur.read_str()?;
4711 let base_type = cur.read_data_type()?;
4712 let nullable = cur.read_u8()? != 0;
4713 let default = match cur.read_u8()? {
4714 0 => None,
4715 1 => Some(cur.read_str()?),
4716 other => {
4717 return Err(StorageError::Corrupt(format!(
4718 "unknown DOMAIN default tag {other}"
4719 )));
4720 }
4721 };
4722 let check_count = cur.read_u16()? as usize;
4723 let mut checks = Vec::with_capacity(check_count);
4724 for _ in 0..check_count {
4725 checks.push(cur.read_str()?);
4726 }
4727 cat.domain_types.insert(
4728 name.clone(),
4729 DomainDef {
4730 name,
4731 base_type,
4732 nullable,
4733 default,
4734 checks,
4735 },
4736 );
4737 }
4738 }
4739 // v7.17.0 Phase 1.6 — user-schemas registry
4740 // (FILE_VERSION 31+).
4741 if version >= 31 {
4742 let sch_count = cur.read_u32()? as usize;
4743 for _ in 0..sch_count {
4744 let name = cur.read_str()?;
4745 cat.schemas.insert(name);
4746 }
4747 }
4748 if cur.pos < buf.len() {
4749 return Err(StorageError::Corrupt(format!(
4750 "trailing bytes: {} unread",
4751 buf.len() - cur.pos
4752 )));
4753 }
4754 Ok(cat)
4755 }
4756}
4757
4758#[cfg(test)]
4759mod tests;