spg_embedded/lib.rs
1// v7.7.2 — every public item in this crate must carry a
2// doc-comment; new code that adds a `pub` without one fails CI.
3#![deny(missing_docs)]
4
5//! # spg-embedded
6//!
7//! Ergonomic embedded-mode entry point for SPG. Wraps the
8//! `spg-engine` execution layer for in-process applications
9//! that don't want to spin up a TCP listener / fork to the
10//! `spg-server` binary.
11//!
12//! ## Quick start
13//!
14//! ```no_run
15//! use spg_embedded::Database;
16//!
17//! // On-disk, durable. WAL fsynced per commit; auto-checkpoint
18//! // at 4 MiB WAL by default.
19//! let mut db = Database::open_path("/data/app.db").unwrap();
20//! db.execute("CREATE TABLE users (id INT NOT NULL, name TEXT)").unwrap();
21//! db.execute("INSERT INTO users VALUES (1, 'alice')").unwrap();
22//! let rows = db.query("SELECT name FROM users WHERE id = 1").unwrap();
23//! for row in &rows {
24//! println!("{:?}", row);
25//! }
26//! ```
27//!
28//! ## Production checklist (v7.5)
29//!
30//! - **Persistence**: `Database::open_path(p)` writes a
31//! crash-consistent WAL + periodic checkpoint snapshot. The
32//! on-disk format is byte-identical to what `spg-server`
33//! produces, so a database can move between modes without
34//! conversion.
35//! - **Durability**: every `execute()` that mutates calls
36//! `fsync` before returning `Ok`. There is no group commit
37//! in embedded mode — every commit pays one fsync. If you
38//! need batch throughput, wrap multiple statements in
39//! [`Database::with_transaction`] which fsyncs only at
40//! commit.
41//! - **Concurrency**: [`Database`] is `Send` but **not** `Sync`.
42//! Share across threads via `Arc<Mutex<Database>>`. The
43//! single-writer model is intentional — see
44//! [STABILITY § A1](https://github.com/lihao/spg/blob/master/STABILITY.md).
45//! - **Background work**: [`Database::spawn_background_freezer`]
46//! moves cold rows to disk-resident segments while you keep
47//! serving requests. It runs in a dedicated thread; drop the
48//! returned [`FreezerHandle`] (or call `stop()`) for clean
49//! shutdown.
50//! - **Errors**: all public enums ([`EngineError`],
51//! [`QueryResult`], [`Value`]) are `#[non_exhaustive]`. Match
52//! them with a wildcard arm so future v7.x releases can add
53//! variants without breaking your code.
54//!
55//! ## Panic contract
56//!
57//! - **No `execute()` / `query()` call panics on user input.**
58//! Malformed SQL, type mismatches, missing tables — all
59//! return `Err(EngineError::…)`. If you observe a panic on
60//! a user-controlled string, that is a bug; file an issue.
61//! - The library panics **only** on internal invariant
62//! violations (e.g., catalog snapshot magic mismatch, WAL
63//! record CRC sentinel corruption that survived the boot-
64//! time validation). These represent silent disk corruption
65//! and an unwind would leak inconsistent state, so the
66//! release profile uses `panic = abort` — your host process
67//! dies fast rather than continuing on poisoned data.
68//! - If you cannot tolerate `panic = abort`, build with
69//! `--profile release-dbg` (keeps unwind tables) and use
70//! `std::panic::catch_unwind` at your application boundary.
71//!
72//! ## Why a separate crate?
73//!
74//! `spg-engine` is `no_std`-compatible (vendored alloc-only).
75//! The embedded-mode entry point uses `std` (filesystem,
76//! threading), so it lives in its own crate to keep the
77//! `no_std` boundary clean.
78
79pub use spg_engine::{Engine, EngineError, ParsedStatement, QueryResult};
80pub use spg_storage::{ColumnSchema, DataType, Value};
81
82/// v7.16.0 — handle for a parsed-and-planned SQL statement.
83/// Hand off to [`Database::execute_prepared`] / [`Database::query_prepared`]
84/// with a `&[Value]` slice carrying the bind parameters (PG-style
85/// `$1`, `$2`, … positional). Cheap to `Clone`; the underlying AST
86/// is shared by handle copies and cloned per bind call by the
87/// engine's executor.
88///
89/// The handle holds a snapshot of the AST at prepare time. If
90/// the engine's plan cache evicts the entry between prepare and
91/// execute (e.g. ANALYZE bumps the statistics version) the
92/// stored AST keeps working — `execute_prepared` operates on
93/// the handle's clone, not the cache entry.
94#[derive(Debug, Clone)]
95pub struct Statement {
96 /// The parsed + planned AST. `spg-engine::prepare_cached`
97 /// returns it as a clone of the cached plan, so any rewrite
98 /// passes (`expand_group_by_all`, `reorder_joins`, …) have
99 /// already run.
100 pub(crate) stmt: ParsedStatement,
101 /// Original SQL source, kept for `Display` / debug only.
102 /// WAL persistence renders from the AST so a bind-time
103 /// rewrite of `$1..$N` survives replay.
104 pub(crate) sql: String,
105}
106
107impl Statement {
108 /// Borrow the original SQL source — useful for tracing and
109 /// debug logs. WAL replay does NOT use this; it serialises
110 /// the bind-final AST instead.
111 #[must_use]
112 pub fn sql(&self) -> &str {
113 &self.sql
114 }
115}
116
117/// v7.16.0 — internal WAL helper. Mirrors what
118/// `Engine::execute_prepared` does to the cloned AST so the WAL
119/// record carries the bind-final SQL text (so replay's
120/// simple-query path reconstructs the same row state without
121/// needing the original `Statement` handle to still be alive).
122/// Errors from the underlying engine helper would only fire if
123/// the bind-final stmt referenced a placeholder past the params
124/// slice — and that case has already errored in the executor
125/// above before this helper runs, so we discard the Result here.
126fn wal_render_with_params(stmt: &mut ParsedStatement, params: &[Value]) {
127 let _ = spg_engine::substitute_placeholders(stmt, params);
128}
129
130use std::collections::BTreeMap;
131use std::fs::{File, OpenOptions};
132use std::io::{Seek, SeekFrom, Write};
133use std::path::{Path, PathBuf};
134use std::sync::atomic::{AtomicBool, Ordering};
135use std::sync::{Arc, Mutex};
136use std::thread::{self, JoinHandle};
137use std::time::{Duration, SystemTime, UNIX_EPOCH};
138
139/// v7.11.3 — wall-clock provider injected into every embedded
140/// `Engine`. Microseconds since the Unix epoch; clamps to
141/// `i64::MAX` if the system clock is far-future. Used by SQL's
142/// `NOW()` / `CURRENT_TIMESTAMP` / `CURRENT_DATE` rewrite layer
143/// so PG-idiomatic time queries work without the caller wiring
144/// their own clock.
145fn wall_clock_micros() -> i64 {
146 SystemTime::now()
147 .duration_since(UNIX_EPOCH)
148 .map_or(0, |d| i64::try_from(d.as_micros()).unwrap_or(i64::MAX))
149}
150
151use spg_manifest::{CatalogManifest, ColdSegmentEntry, manifest_path as spg_manifest_path};
152
153// -- v7.1 WAL format constants (mirror `spg-server`'s) ---------
154// Kept private so callers can't mis-frame records; the v3 layout
155// is the same the server uses, so a `spg-server` boot can read a
156// database an embedded process wrote and vice versa.
157const WAL_V2_SENTINEL: u32 = 0x8000_0000;
158const WAL_V3_FLAG: u32 = 0x4000_0000;
159const WAL_V3_TYPE_AUTO_COMMIT_SQL: u8 = 0x01;
160
161/// v7.1 — auto-checkpoint threshold. Once the WAL grows past
162/// this many bytes, the next successful `execute()` call ends
163/// with a `checkpoint()` so the WAL stays bounded. Tunable via
164/// `SPG_EMBEDDED_CHECKPOINT_BYTES` env.
165fn default_checkpoint_threshold_bytes() -> u64 {
166 std::env::var("SPG_EMBEDDED_CHECKPOINT_BYTES")
167 .ok()
168 .and_then(|s| s.parse::<u64>().ok())
169 .filter(|&n| n > 0)
170 .unwrap_or(4 * 1024 * 1024)
171}
172
173/// v7.1 — encode one v3 `auto_commit_sql` record. Layout:
174///
175/// ```text
176/// [u32 LE (len | WAL_V2_SENTINEL | WAL_V3_FLAG)]
177/// [u32 LE crc32 over (type_byte || sql_bytes)]
178/// [u8 type = 0x01]
179/// [sql bytes]
180/// ```
181fn encode_v3_auto_commit(sql: &str) -> Vec<u8> {
182 let payload = sql.as_bytes();
183 let mut crc_buf = Vec::with_capacity(1 + payload.len());
184 crc_buf.push(WAL_V3_TYPE_AUTO_COMMIT_SQL);
185 crc_buf.extend_from_slice(payload);
186 let crc = spg_crypto::crc32::crc32(&crc_buf);
187 let header = ((payload.len() as u32) | WAL_V2_SENTINEL | WAL_V3_FLAG).to_le_bytes();
188 let mut out = Vec::with_capacity(4 + 4 + 1 + payload.len());
189 out.extend_from_slice(&header);
190 out.extend_from_slice(&crc.to_le_bytes());
191 out.push(WAL_V3_TYPE_AUTO_COMMIT_SQL);
192 out.extend_from_slice(payload);
193 out
194}
195
196/// v7.1 — decode + apply every record in `wal_bytes` to `engine`.
197/// Returns the count of records successfully applied. A truncated
198/// trailing record (mid-write torn) is dropped silently — the
199/// same recovery story `spg-server`'s boot path uses.
200fn replay_wal_into_engine(wal_bytes: &[u8], engine: &mut Engine) -> Result<usize, String> {
201 let mut applied = 0usize;
202 let mut cur = 0usize;
203 while cur < wal_bytes.len() {
204 if wal_bytes.len() - cur < 4 {
205 // Trailing partial header — torn write, drop and stop.
206 break;
207 }
208 let raw_len = u32::from_le_bytes(wal_bytes[cur..cur + 4].try_into().unwrap());
209 let is_v2 = raw_len & WAL_V2_SENTINEL != 0;
210 let is_v3 = is_v2 && (raw_len & WAL_V3_FLAG != 0);
211 let len_mask = if is_v3 {
212 !(WAL_V2_SENTINEL | WAL_V3_FLAG)
213 } else {
214 !WAL_V2_SENTINEL
215 };
216 let rec_len = (raw_len & len_mask) as usize;
217 let header_len = if is_v3 {
218 9
219 } else if is_v2 {
220 8
221 } else {
222 4
223 };
224 if wal_bytes.len() - cur < header_len + rec_len {
225 // Torn record at the tail — drop, stop.
226 break;
227 }
228 if is_v3 {
229 let type_byte = wal_bytes[cur + 8];
230 match type_byte {
231 WAL_V3_TYPE_AUTO_COMMIT_SQL => {}
232 0x02 => {
233 // durability_checkpoint marker — skip, no SQL.
234 cur += header_len + rec_len;
235 continue;
236 }
237 other => {
238 return Err(format!(
239 "WAL replay: unknown v3 type byte {other:#04x} at offset {cur}"
240 ));
241 }
242 }
243 }
244 let sql_bytes = &wal_bytes[cur + header_len..cur + header_len + rec_len];
245 let sql = std::str::from_utf8(sql_bytes)
246 .map_err(|e| format!("WAL replay: non-UTF-8 SQL at offset {cur}: {e}"))?;
247 engine
248 .execute(sql)
249 .map_err(|e| format!("WAL replay: apply {sql:?} at offset {cur} rejected: {e:?}"))?;
250 applied += 1;
251 cur += header_len + rec_len;
252 }
253 Ok(applied)
254}
255
256/// v7.1 — predicate for "should the next `execute()` mutate the
257/// WAL?" Returns `false` for SELECT / SHOW / EXPLAIN / BEGIN /
258/// COMMIT / ROLLBACK and the SPG-specific verbs that don't go
259/// through the auto-commit record path on the server (CHECKPOINT,
260/// COMPACT). Conservative: anything we don't explicitly know is
261/// read-only falls through to "write a WAL record".
262fn sql_is_read_only(sql: &str) -> bool {
263 let t = sql.trim_start();
264 let head = t
265 .split(|c: char| c.is_whitespace() || c == ';' || c == '(')
266 .next()
267 .unwrap_or("");
268 matches!(
269 head.to_ascii_lowercase().as_str(),
270 "select"
271 | "show"
272 | "explain"
273 | "begin"
274 | "commit"
275 | "rollback"
276 | "checkpoint"
277 | "compact"
278 | "wait"
279 | "with"
280 )
281}
282
283/// Embedded SPG database handle. Owns an `Engine` + provides
284/// ergonomic wrappers around `execute` and `query`. Drops the
285/// engine on `Drop` — no WAL flush / fsync, because v6.10.3
286/// is in-memory only.
287#[derive(Debug)]
288pub struct Database {
289 engine: Engine,
290 /// v7.1 — persistence sidecar. When `Some(p)`, every
291 /// `execute(sql)` that mutates state appends a v3
292 /// `auto_commit_sql` WAL record + fsyncs before the call
293 /// returns; `Drop` writes a final catalog snapshot to
294 /// `<db_path>` so the next session boots from a clean
295 /// snapshot + an empty WAL. `None` = in-memory only (the
296 /// v6.10.3 shape).
297 persistence: Option<PersistenceCtx>,
298}
299
300#[derive(Debug)]
301#[allow(dead_code)] // `wal_path` is read at boot; kept for Drop/diag introspection.
302struct PersistenceCtx {
303 db_path: PathBuf,
304 wal_path: PathBuf,
305 wal: File,
306 /// Cached WAL file length so each `execute()` doesn't have
307 /// to stat. Refreshed on append + on `checkpoint()` (which
308 /// truncates back to 0).
309 wal_len: u64,
310 checkpoint_threshold_bytes: u64,
311 /// v7.1.4 — `<db_path>.spg/segments/` directory. Cold-tier
312 /// segments produced by `freeze_oldest_to_cold` / compaction
313 /// are persisted here as `seg_<id>.spg` files; the manifest
314 /// at `<db_path>.spg/manifest.v10` records every active
315 /// segment + its CRC32 so the next boot can verify + reload.
316 cold_segments_dir: PathBuf,
317 cold_segment_paths: BTreeMap<u32, PathBuf>,
318}
319
320impl Database {
321 /// Open a fresh in-memory database. No WAL, no catalog
322 /// snapshot on disk — perfect for tests + short-lived
323 /// CLI tools.
324 #[must_use]
325 pub fn open_in_memory() -> Self {
326 Self {
327 engine: Engine::new().with_clock(wall_clock_micros),
328 persistence: None,
329 }
330 }
331
332 /// v7.1 — Open or create a persistent database backed by
333 /// the file at `db_path`. The WAL lives at `db_path` +
334 /// ".wal" (e.g. `./data/spg.db` → `./data/spg.db.wal`). Boot
335 /// path:
336 ///
337 /// 1. If `db_path` exists, restore the catalog snapshot.
338 /// 2. If the WAL exists, replay every record into the
339 /// restored engine — the same recovery story
340 /// `spg-server` uses.
341 /// 3. Open the WAL in append+sync mode so subsequent
342 /// `execute()` writes durably commit (one fsync per
343 /// mutation).
344 ///
345 /// `Drop` writes a final catalog snapshot + truncates the
346 /// WAL — operators that need a sync barrier at a specific
347 /// point use `checkpoint()` explicitly.
348 pub fn open_path(db_path: impl AsRef<Path>) -> Result<Self, EngineError> {
349 let db_path = db_path.as_ref().to_path_buf();
350 let wal_path = {
351 let mut p = db_path.clone();
352 let name = p
353 .file_name()
354 .map(|n| {
355 let mut s = n.to_os_string();
356 s.push(".wal");
357 s
358 })
359 .unwrap_or_else(|| std::ffi::OsString::from(".wal"));
360 p.set_file_name(name);
361 p
362 };
363 if let Some(parent) = db_path.parent()
364 && !parent.as_os_str().is_empty()
365 {
366 std::fs::create_dir_all(parent).map_err(io_err)?;
367 }
368 let mut engine = if db_path.exists() {
369 let bytes = std::fs::read(&db_path).map_err(io_err)?;
370 let engine = Engine::restore_envelope(&bytes).map_err(|e| {
371 EngineError::Storage(spg_storage::StorageError::Corrupt(format!(
372 "restore from {}: {e}",
373 db_path.display()
374 )))
375 })?;
376 engine.with_clock(wall_clock_micros)
377 } else {
378 Engine::new().with_clock(wall_clock_micros)
379 };
380 // v7.1.4 — manifest-driven cold-segment reload. The
381 // manifest sidecar pairs the catalog snapshot CRC with a
382 // list of `(segment_id, path, crc32)` triples; verify
383 // before loading so a torn or stale manifest doesn't
384 // surface phantom data.
385 let cold_segments_dir = {
386 let parent = db_path.parent().unwrap_or_else(|| Path::new("."));
387 let stem = db_path
388 .file_stem()
389 .unwrap_or_else(|| std::ffi::OsStr::new("db"))
390 .to_string_lossy()
391 .into_owned();
392 parent.join(format!("{stem}.spg")).join("segments")
393 };
394 let mut cold_segment_paths: BTreeMap<u32, PathBuf> = BTreeMap::new();
395 let manifest_pth = spg_manifest_path(&db_path);
396 if manifest_pth.exists() && db_path.exists() {
397 let m_bytes = std::fs::read(&manifest_pth).map_err(io_err)?;
398 if let Ok(m) = CatalogManifest::deserialize(&m_bytes) {
399 let snap_bytes = std::fs::read(&db_path).map_err(io_err)?;
400 let snap_crc = spg_crypto::crc32::crc32(&snap_bytes);
401 if snap_crc == m.catalog_crc32 {
402 for entry in &m.cold_segments {
403 if let Ok(seg_bytes) = std::fs::read(&entry.path) {
404 let computed = spg_crypto::crc32::crc32(&seg_bytes);
405 if computed != entry.crc32 {
406 eprintln!(
407 "spg-embedded: manifest skip segment {}: CRC mismatch",
408 entry.segment_id
409 );
410 continue;
411 }
412 if engine.catalog().cold_segment(entry.segment_id).is_some() {
413 // Already loaded via Catalog::clone path (shouldn't happen
414 // since Engine::new + restore_envelope don't populate cold).
415 continue;
416 }
417 let mut new_cat = engine.catalog().clone();
418 if let Err(e) =
419 new_cat.load_segment_bytes_at(entry.segment_id, seg_bytes)
420 {
421 eprintln!(
422 "spg-embedded: manifest load segment {} failed: {e}",
423 entry.segment_id
424 );
425 continue;
426 }
427 engine.replace_catalog(new_cat);
428 cold_segment_paths.insert(entry.segment_id, entry.path.clone());
429 } else {
430 eprintln!(
431 "spg-embedded: manifest skip segment {}: file unreadable",
432 entry.segment_id
433 );
434 }
435 }
436 }
437 }
438 }
439 if wal_path.exists() {
440 let wal_bytes = std::fs::read(&wal_path).map_err(io_err)?;
441 if !wal_bytes.is_empty() {
442 replay_wal_into_engine(&wal_bytes, &mut engine)
443 .map_err(|m| EngineError::Storage(spg_storage::StorageError::Corrupt(m)))?;
444 }
445 }
446 let wal = OpenOptions::new()
447 .create(true)
448 .append(true)
449 .read(true)
450 .open(&wal_path)
451 .map_err(io_err)?;
452 let wal_len = wal.metadata().map_err(io_err)?.len();
453 Ok(Self {
454 engine,
455 persistence: Some(PersistenceCtx {
456 db_path,
457 wal_path,
458 wal,
459 wal_len,
460 checkpoint_threshold_bytes: default_checkpoint_threshold_bytes(),
461 cold_segments_dir,
462 cold_segment_paths,
463 }),
464 })
465 }
466
467 /// v7.1.4 — freeze the oldest `max_rows` of `table_name`'s
468 /// hot tier into a brand-new cold-tier segment + persist
469 /// it to disk. Same semantics as `spg-server`'s freezer
470 /// thread; embedded just runs the freeze synchronously on
471 /// the caller's thread. Persistence + manifest update
472 /// happen as part of the next `checkpoint()` (or on Drop).
473 pub fn freeze_oldest_to_cold(
474 &mut self,
475 table_name: &str,
476 index_name: &str,
477 max_rows: usize,
478 ) -> Result<spg_storage::FreezeReport, EngineError> {
479 let report = self
480 .engine
481 .freeze_oldest_to_cold(table_name, index_name, max_rows)?;
482 if let Some(p) = &mut self.persistence {
483 std::fs::create_dir_all(&p.cold_segments_dir).map_err(io_err)?;
484 let final_path = p
485 .cold_segments_dir
486 .join(format!("seg_{}.spg", report.segment_id));
487 let tmp_path = p
488 .cold_segments_dir
489 .join(format!("seg_{}.spg.tmp", report.segment_id));
490 std::fs::write(&tmp_path, &report.segment_bytes).map_err(io_err)?;
491 std::fs::rename(&tmp_path, &final_path).map_err(io_err)?;
492 p.cold_segment_paths.insert(report.segment_id, final_path);
493 }
494 Ok(report)
495 }
496
497 /// v7.1 — override the auto-checkpoint WAL-size ceiling for
498 /// this `Database` instance. Default is
499 /// `SPG_EMBEDDED_CHECKPOINT_BYTES` env (4 MiB if unset); the
500 /// setter wins. No-op when the database is in-memory.
501 pub fn set_checkpoint_threshold_bytes(&mut self, bytes: u64) {
502 if let Some(p) = &mut self.persistence {
503 p.checkpoint_threshold_bytes = bytes.max(1);
504 }
505 }
506
507 /// v7.1 — flush a fresh catalog snapshot to `db_path` and
508 /// truncate the WAL. Idempotent; cheap when nothing has
509 /// happened since the last checkpoint. No-op when the
510 /// database is in-memory (no `db_path` configured).
511 ///
512 /// Called automatically when:
513 /// - the WAL grows past
514 /// `SPG_EMBEDDED_CHECKPOINT_BYTES` (default 4 MiB) at the
515 /// end of an `execute()`, and
516 /// - `Drop` runs (best-effort; checkpoint failure on drop is
517 /// logged to stderr).
518 pub fn checkpoint(&mut self) -> Result<(), EngineError> {
519 let snapshot = self.engine.snapshot();
520 let Some(p) = &mut self.persistence else {
521 return Ok(());
522 };
523 // Snapshot first (atomic via tmp+rename), then WAL
524 // truncate. Same order as `spg-server`'s CHECKPOINT —
525 // a crash between the two leaves the WAL holding
526 // already-snapshotted ops, which replay cleanly on the
527 // next boot (idempotent for SPG's standard DDL/DML
528 // mutations).
529 let tmp = {
530 let mut t = p.db_path.clone();
531 let mut name = t
532 .file_name()
533 .map(std::ffi::OsStr::to_os_string)
534 .unwrap_or_default();
535 name.push(".tmp");
536 t.set_file_name(name);
537 t
538 };
539 std::fs::write(&tmp, &snapshot).map_err(io_err)?;
540 std::fs::rename(&tmp, &p.db_path).map_err(io_err)?;
541 // v7.1.4 — refresh the manifest so the next boot can
542 // reload cold segments alongside the snapshot. Bytes
543 // come from the freshly-written snapshot file (= the
544 // canonical CRC source).
545 if !p.cold_segment_paths.is_empty() {
546 let snap_crc = spg_crypto::crc32::crc32(&snapshot);
547 let entries: Vec<ColdSegmentEntry> = p
548 .cold_segment_paths
549 .iter()
550 .filter_map(|(&segment_id, path)| {
551 let bytes = std::fs::read(path).ok()?;
552 Some(ColdSegmentEntry {
553 segment_id,
554 path: path.clone(),
555 crc32: spg_crypto::crc32::crc32(&bytes),
556 })
557 })
558 .collect();
559 let manifest = CatalogManifest {
560 catalog_crc32: snap_crc,
561 cold_segments: entries,
562 wal_baseline_offset: 0,
563 };
564 let m_bytes = manifest.serialize();
565 let m_path = spg_manifest_path(&p.db_path);
566 if let Some(dir) = m_path.parent() {
567 std::fs::create_dir_all(dir).map_err(io_err)?;
568 }
569 let m_tmp = {
570 let mut t = m_path.clone();
571 let mut name = t
572 .file_name()
573 .map(std::ffi::OsStr::to_os_string)
574 .unwrap_or_default();
575 name.push(".tmp");
576 t.set_file_name(name);
577 t
578 };
579 std::fs::write(&m_tmp, &m_bytes).map_err(io_err)?;
580 std::fs::rename(&m_tmp, &m_path).map_err(io_err)?;
581 }
582 p.wal.set_len(0).map_err(io_err)?;
583 p.wal.seek(SeekFrom::Start(0)).map_err(io_err)?;
584 p.wal.sync_data().map_err(io_err)?;
585 p.wal_len = 0;
586 Ok(())
587 }
588
589 /// Restore a database from a previously-captured catalog
590 /// snapshot. Pairs with `Database::snapshot()` for
591 /// round-tripping in-memory state without going through
592 /// the `spg-server` WAL.
593 pub fn restore(snapshot: &[u8]) -> Result<Self, EngineError> {
594 let engine = Engine::restore_envelope(snapshot).map_err(|e| {
595 EngineError::Storage(spg_storage::StorageError::Corrupt(format!("restore: {e}")))
596 })?;
597 Ok(Self {
598 engine,
599 persistence: None,
600 })
601 }
602
603 /// Take a catalog snapshot suitable for `Database::restore`.
604 /// The bytes are SPG's canonical catalog envelope (FILE_MAGIC
605 /// + version + payload); round-trips through every released
606 /// SPG version per the STABILITY contract.
607 #[must_use]
608 pub fn snapshot(&self) -> Vec<u8> {
609 self.engine.snapshot()
610 }
611
612 /// Execute a SQL statement and return the engine's
613 /// `QueryResult` verbatim. Pass-through for callers that
614 /// want to keep PG-flavoured column/row metadata.
615 ///
616 /// v7.1 — when the database was opened via `open_path`,
617 /// successful mutations are appended to the WAL + fsynced
618 /// before the call returns. A subsequent process crash will
619 /// recover state up to the last successful return from
620 /// `execute()`. Read-only statements (SELECT / SHOW /
621 /// EXPLAIN / BEGIN-COMMIT-ROLLBACK / CHECKPOINT / COMPACT
622 /// etc.) skip the WAL entirely.
623 pub fn execute(&mut self, sql: &str) -> Result<QueryResult, EngineError> {
624 let result = self.engine.execute(sql)?;
625 if self.persistence.is_some()
626 && !sql_is_read_only(sql)
627 && matches!(
628 &result,
629 QueryResult::CommandOk {
630 modified_catalog: true,
631 ..
632 }
633 )
634 {
635 // Append + sync the v3 record AFTER the in-memory
636 // exec succeeds, so a WAL record never describes a
637 // mutation that didn't actually apply. The crash
638 // window between in-memory commit and WAL fsync is
639 // bounded by one record — replay re-applies the
640 // statement idempotently on next boot if we crashed
641 // between (and SPG's DDL/DML are crash-idempotent at
642 // the granularities the wire protocol exposes).
643 let record = encode_v3_auto_commit(sql);
644 let p = self.persistence.as_mut().expect("checked above");
645 p.wal.write_all(&record).map_err(io_err)?;
646 p.wal.sync_data().map_err(io_err)?;
647 p.wal_len = p.wal_len.saturating_add(record.len() as u64);
648 if p.wal_len >= p.checkpoint_threshold_bytes {
649 self.checkpoint()?;
650 }
651 }
652 Ok(result)
653 }
654
655 /// v7.3.0 — typed-row variant of [`Database::query`]. Each
656 /// row decodes into a `T: FromSpgRow` so callers don't
657 /// pattern-match on `Value` themselves. Use [`spg_row!`] to
658 /// generate the impl, or write it by hand.
659 pub fn query_typed<T: FromSpgRow>(&mut self, sql: &str) -> Result<Vec<T>, EngineError> {
660 let rows = self.query(sql)?;
661 rows.into_iter().map(|r| T::from_spg_row(&r)).collect()
662 }
663
664 /// Run a SELECT and return rows as a `Vec<Vec<Value>>` —
665 /// strips the column-schema metadata for read-side
666 /// ergonomics. Errors on non-Rows results (DML / DDL
667 /// statements should go through `execute` instead).
668 pub fn query(&mut self, sql: &str) -> Result<Vec<Vec<Value>>, EngineError> {
669 match self.engine.execute(sql)? {
670 QueryResult::Rows { rows, .. } => Ok(rows.into_iter().map(|r| r.values).collect()),
671 QueryResult::CommandOk { .. } => Err(EngineError::Unsupported(
672 "query() expects a SELECT — use execute() for DML/DDL".into(),
673 )),
674 // v7.5.0 — QueryResult is #[non_exhaustive]; any future
675 // variant is not a SELECT row stream, treat as Unsupported.
676 _ => Err(EngineError::Unsupported(
677 "query() expects a SELECT — use execute() for DML/DDL".into(),
678 )),
679 }
680 }
681
682 /// v7.16.0 — column-aware variant of [`Self::query`].
683 /// Returns the column schema vec alongside the rows so
684 /// adapters (the spg-sqlx Row impl most notably) can drive
685 /// name + type-based column lookups. Errors on non-Rows
686 /// results identically to `query`.
687 pub fn query_with_columns(
688 &mut self,
689 sql: &str,
690 ) -> Result<(Vec<spg_storage::ColumnSchema>, Vec<Vec<Value>>), EngineError> {
691 match self.engine.execute(sql)? {
692 QueryResult::Rows { columns, rows } => {
693 Ok((columns, rows.into_iter().map(|r| r.values).collect()))
694 }
695 QueryResult::CommandOk { .. } => Err(EngineError::Unsupported(
696 "query_with_columns() expects a SELECT — use execute() for DML/DDL".into(),
697 )),
698 _ => Err(EngineError::Unsupported(
699 "query_with_columns() expects a SELECT — use execute() for DML/DDL".into(),
700 )),
701 }
702 }
703
704 /// v7.16.0 — column-aware variant of
705 /// [`Self::query_prepared`]. Same shape as
706 /// `query_with_columns` but driven from a prepared
707 /// statement + bound params.
708 pub fn query_prepared_with_columns(
709 &mut self,
710 stmt: &Statement,
711 params: &[Value],
712 ) -> Result<(Vec<spg_storage::ColumnSchema>, Vec<Vec<Value>>), EngineError> {
713 match self.engine.execute_prepared(stmt.stmt.clone(), params)? {
714 QueryResult::Rows { columns, rows } => {
715 Ok((columns, rows.into_iter().map(|r| r.values).collect()))
716 }
717 QueryResult::CommandOk { .. } => Err(EngineError::Unsupported(
718 "query_prepared_with_columns() expects a SELECT — use execute_prepared() for DML/DDL".into(),
719 )),
720 _ => Err(EngineError::Unsupported(
721 "query_prepared_with_columns() expects a SELECT — use execute_prepared() for DML/DDL".into(),
722 )),
723 }
724 }
725
726 /// Borrow the underlying engine. Escape hatch for callers
727 /// that need access to `spg-engine` APIs not yet surfaced
728 /// here (transactions, EXPLAIN ANALYZE, etc.).
729 #[must_use]
730 pub const fn engine(&self) -> &Engine {
731 &self.engine
732 }
733
734 /// Mutable borrow of the underlying engine. Same intent as
735 /// `engine()` but for write-side APIs (e.g. inserting
736 /// directly through `Catalog::insert` for high-throughput
737 /// bulk loads that bypass SQL parsing).
738 pub const fn engine_mut(&mut self) -> &mut Engine {
739 &mut self.engine
740 }
741
742 /// v7.16.0 — parse + plan a SQL string ONCE so subsequent
743 /// `execute_prepared` / `query_prepared` calls can re-bind
744 /// parameters without re-parsing. The returned [`Statement`]
745 /// is a thin handle around the AST + cached source SQL; it's
746 /// `Clone` so the same plan can drive many bind calls
747 /// concurrently (each call clones the AST and runs
748 /// placeholder substitution on the clone — the cached
749 /// plan stays intact).
750 ///
751 /// Plan caching follows the engine's existing version-aware
752 /// rule: a prepared `Statement` whose statistics version
753 /// has rolled (ANALYZE ran between prepare and execute)
754 /// will silently re-prepare under the hood. Callers don't
755 /// need to detect this.
756 ///
757 /// Placeholders in the SQL use PG's `$1`, `$2`, … convention.
758 /// `bind`-time `Value`s are passed as a slice; arity
759 /// mismatches surface as `EvalError::PlaceholderOutOfRange`
760 /// at `execute_prepared` time, not here.
761 ///
762 /// # Errors
763 /// Surfaces `EngineError` (parse error / plan rewrite
764 /// failure) from the underlying `Engine::prepare`.
765 pub fn prepare(&mut self, sql: &str) -> Result<Statement, EngineError> {
766 // Use the cached path so repeated prepares of the same
767 // SQL are O(1). The engine's plan cache stays shared
768 // across all callers of this Database — a single
769 // `PgPool`-shaped consumer (or, later, the spg-sqlx
770 // adapter) prepares once and reaps the win on every bind.
771 let stmt = self.engine.prepare_cached(sql).map_err(EngineError::Parse)?;
772 Ok(Statement {
773 stmt,
774 sql: sql.to_string(),
775 })
776 }
777
778 /// v7.16.0 — execute a prepared statement with bound
779 /// parameters. Mirrors `Engine::execute_prepared`: clones
780 /// the AST, substitutes `$1..$N` → `params[0..N-1]`, runs.
781 ///
782 /// Persistence (WAL fsync + auto-checkpoint) follows the
783 /// same rules as `execute(sql)`: mutating statements get a
784 /// WAL record AFTER the in-memory exec succeeds. The WAL
785 /// record carries the substituted, bind-final SQL, so
786 /// replay reconstructs the same row state without needing
787 /// the original prepared `Statement` to still be alive.
788 ///
789 /// # Errors
790 /// Propagates engine errors. Param arity mismatch surfaces
791 /// as `EvalError::PlaceholderOutOfRange`.
792 pub fn execute_prepared(
793 &mut self,
794 stmt: &Statement,
795 params: &[Value],
796 ) -> Result<QueryResult, EngineError> {
797 let result = self.engine.execute_prepared(stmt.stmt.clone(), params)?;
798 // WAL persistence on the bind-final SQL. Build the
799 // canonical Display form by re-printing the
800 // placeholder-substituted statement (cheap — the AST
801 // is already in hand from execute_prepared's internal
802 // clone) so replay's path is identical to the
803 // simple-query path.
804 if self.persistence.is_some()
805 && matches!(
806 &result,
807 QueryResult::CommandOk {
808 modified_catalog: true,
809 ..
810 }
811 )
812 {
813 // Render the AST back to SQL for WAL replay. The
814 // placeholder positions are already substituted in
815 // the executed clone; we re-substitute on a fresh
816 // clone here purely to obtain the canonical text.
817 let mut wal_stmt = stmt.stmt.clone();
818 // Use the engine's substitute_placeholders entry —
819 // exposed via execute_prepared above. Here we
820 // re-run the substitution only for Display.
821 crate::wal_render_with_params(&mut wal_stmt, params);
822 let canonical = format!("{wal_stmt}");
823 let record = encode_v3_auto_commit(&canonical);
824 let p = self.persistence.as_mut().expect("checked above");
825 p.wal.write_all(&record).map_err(io_err)?;
826 p.wal.sync_data().map_err(io_err)?;
827 p.wal_len = p.wal_len.saturating_add(record.len() as u64);
828 if p.wal_len >= p.checkpoint_threshold_bytes {
829 self.checkpoint()?;
830 }
831 }
832 Ok(result)
833 }
834
835 /// v7.16.0 — run a prepared SELECT with bound params and
836 /// return rows as `Vec<Vec<Value>>`, matching `query()`
837 /// shape. SELECTs are read-only so this never writes the
838 /// WAL.
839 ///
840 /// # Errors
841 /// Returns `Unsupported` if the prepared statement isn't a
842 /// SELECT (use `execute_prepared` for DML/DDL).
843 pub fn query_prepared(
844 &mut self,
845 stmt: &Statement,
846 params: &[Value],
847 ) -> Result<Vec<Vec<Value>>, EngineError> {
848 match self.engine.execute_prepared(stmt.stmt.clone(), params)? {
849 QueryResult::Rows { rows, .. } => Ok(rows.into_iter().map(|r| r.values).collect()),
850 QueryResult::CommandOk { .. } => Err(EngineError::Unsupported(
851 "query_prepared() expects a SELECT — use execute_prepared() for DML/DDL".into(),
852 )),
853 _ => Err(EngineError::Unsupported(
854 "query_prepared() expects a SELECT — use execute_prepared() for DML/DDL".into(),
855 )),
856 }
857 }
858
859 /// v7.2.0 — run `body` inside an implicit `BEGIN` /
860 /// `COMMIT` pair. The body receives `&mut Database` so it
861 /// can `execute()` / `query()` like any other code path;
862 /// the only difference is that every write in the body
863 /// lands inside one transaction, and a returned `Err` from
864 /// the body triggers `ROLLBACK` before the error propagates.
865 ///
866 /// Nested calls are not supported — SPG's transaction
867 /// model is single-writer with explicit `BEGIN` /
868 /// `COMMIT` / `ROLLBACK`, and a nested `with_transaction`
869 /// would hit `EngineError::Unsupported("nested
870 /// transaction")` at the inner `BEGIN`.
871 pub fn with_transaction<R, F>(&mut self, body: F) -> Result<R, EngineError>
872 where
873 F: FnOnce(&mut Self) -> Result<R, EngineError>,
874 {
875 self.execute("BEGIN")?;
876 match body(self) {
877 Ok(value) => {
878 self.execute("COMMIT")?;
879 Ok(value)
880 }
881 Err(e) => {
882 // Best-effort rollback. If ROLLBACK itself
883 // fails (rare — the engine reports it via
884 // `Unsupported` only when there's no active
885 // TX, which can't happen here) we surface the
886 // original body error, not the rollback error.
887 let _ = self.execute("ROLLBACK");
888 Err(e)
889 }
890 }
891 }
892}
893
894impl Default for Database {
895 fn default() -> Self {
896 Self::open_in_memory()
897 }
898}
899
900/// v7.7.5 — observability snapshot returned by
901/// [`Database::metrics`]. Plain data, no allocations beyond
902/// what the struct itself takes; cheap to construct and
903/// cheap to serialise.
904#[derive(Debug, Clone, Copy, PartialEq, Eq)]
905#[non_exhaustive]
906pub struct EmbeddedMetrics {
907 /// Total live row count across every user table (hot
908 /// tier only — cold-tier rows live in segment files).
909 pub hot_rows: u64,
910 /// Sum of `Table::hot_bytes` across every user table.
911 /// Tracks against the freezer's `hot_tier_bytes` budget.
912 pub hot_bytes: u64,
913 /// Number of cold-tier segments registered in the catalog.
914 /// Includes tombstoned slots (segments retired by
915 /// compaction whose disk file may still be on disk).
916 pub cold_segments: u64,
917 /// User-table count (excludes any future engine-managed
918 /// internal tables).
919 pub tables: u64,
920 /// WAL size at last `execute()` / `checkpoint()`. Zero
921 /// when the database is in-memory.
922 pub wal_bytes: u64,
923 /// `true` when the database was opened with `open_path` —
924 /// i.e. WAL + checkpoint persistence is active.
925 pub persistent: bool,
926}
927
928/// v7.2.1 — handle returned by `spawn_background_freezer`.
929/// Drop signals the worker thread to wind down + joins it,
930/// so a `Database` (or its shared `Arc<Mutex<Database>>`)
931/// can safely drop after the handle does.
932#[must_use = "the background freezer keeps running until this handle is dropped"]
933#[derive(Debug)]
934pub struct FreezerHandle {
935 shutdown: Arc<AtomicBool>,
936 join: Option<JoinHandle<()>>,
937}
938
939impl FreezerHandle {
940 /// v7.2.1 — request the worker stop + join. Idempotent;
941 /// safe to call from `Drop` (which also calls it).
942 pub fn stop(&mut self) {
943 self.shutdown.store(true, Ordering::Release);
944 if let Some(h) = self.join.take() {
945 let _ = h.join();
946 }
947 }
948}
949
950impl Drop for FreezerHandle {
951 fn drop(&mut self) {
952 self.stop();
953 }
954}
955
956/// v7.2.1 — knobs for `Database::spawn_background_freezer`.
957#[derive(Debug, Clone)]
958pub struct FreezerOptions {
959 /// Tick interval. Worker wakes every `tick`, checks the
960 /// catalog's `hot_tier_bytes`, and freezes if over budget.
961 pub tick: Duration,
962 /// Hot-tier byte budget. Exceeded → next tick freezes the
963 /// largest table's oldest `batch_rows` rows into a new
964 /// cold segment.
965 pub hot_tier_bytes: u64,
966 /// Max rows the freezer demotes per fire.
967 pub batch_rows: usize,
968 /// v7.7.4 — auto-compact threshold. When the catalog has
969 /// at least this many cold segments across all tables, the
970 /// freezer fires a compaction pass after its next freeze.
971 /// Set to `usize::MAX` to disable auto-compact entirely;
972 /// the default is `64`, matching the `spg-server` operating
973 /// point for SPG_COLD_COMPACT_SEGMENT_THRESHOLD.
974 pub compact_when_segments_exceed: usize,
975 /// v7.7.4 — target segment size for compaction merges,
976 /// in bytes. Default 64 MiB, mirroring `spg-server`. Small
977 /// segments below this size are merge candidates;
978 /// segments at or above stay untouched.
979 pub compact_target_bytes: u64,
980}
981
982impl Default for FreezerOptions {
983 fn default() -> Self {
984 // Match the `spg-server` freezer's default operating
985 // point (SPG_HOT_TIER_BYTES = 4 GiB, batch 1000 rows,
986 // tick every 1 s) so embedded behaviour is predictable
987 // for operators familiar with the server.
988 Self {
989 tick: Duration::from_secs(1),
990 hot_tier_bytes: 4 * 1024 * 1024 * 1024,
991 batch_rows: 1000,
992 compact_when_segments_exceed: 64,
993 compact_target_bytes: 64 * 1024 * 1024,
994 }
995 }
996}
997
998impl Database {
999 /// v7.7.4 — observe the catalog's cold-segment count.
1000 /// Useful for tests + dashboards that want to verify
1001 /// auto-compaction is firing.
1002 #[must_use]
1003 pub fn cold_segment_count(&self) -> usize {
1004 self.engine.catalog().cold_segment_count()
1005 }
1006
1007 /// v7.7.5 — observability snapshot. Returns a point-in-time
1008 /// view of the engine + persistence counters. Cheap (no
1009 /// locks beyond the existing `&self` borrow), so safe to
1010 /// call from a hot metrics-scrape path.
1011 ///
1012 /// Fields mirror the operational dashboard
1013 /// [`spg-server`](https://crates.io/crates/spg-server) exposes,
1014 /// minus the network counters that don't apply to embedded.
1015 #[must_use]
1016 pub fn metrics(&self) -> EmbeddedMetrics {
1017 let cat = self.engine.catalog();
1018 let mut hot_rows: u64 = 0;
1019 let mut hot_bytes: u64 = 0;
1020 for name in cat.table_names() {
1021 if let Some(t) = cat.get(&name) {
1022 hot_rows = hot_rows.saturating_add(t.row_count() as u64);
1023 hot_bytes = hot_bytes.saturating_add(t.hot_bytes());
1024 }
1025 }
1026 let (wal_bytes, persistent) = match &self.persistence {
1027 Some(p) => (p.wal_len, true),
1028 None => (0, false),
1029 };
1030 EmbeddedMetrics {
1031 hot_rows,
1032 hot_bytes,
1033 cold_segments: cat.cold_segment_count() as u64,
1034 tables: cat.table_count() as u64,
1035 wal_bytes,
1036 persistent,
1037 }
1038 }
1039
1040 /// v7.2.1 — spawn a background thread that periodically
1041 /// runs `freeze_oldest_to_cold` when the catalog-wide hot
1042 /// tier exceeds `opts.hot_tier_bytes`. The `Arc<Mutex<_>>`
1043 /// pattern matches the v7.2 sharing story: callers wrap
1044 /// their `Database` in `Arc::new(Mutex::new(db))` once,
1045 /// then clone the Arc for the worker + for foreground
1046 /// access. Return value is a handle whose `Drop` joins the
1047 /// worker.
1048 ///
1049 /// Picks the freeze target the same way `spg-server`'s
1050 /// freezer does: largest-`hot_bytes` user table with at
1051 /// least one BTree integer-PK index. Tables without a
1052 /// freezable index are skipped silently.
1053 pub fn spawn_background_freezer(
1054 db: Arc<Mutex<Database>>,
1055 opts: FreezerOptions,
1056 ) -> FreezerHandle {
1057 let shutdown = Arc::new(AtomicBool::new(false));
1058 let shutdown_for_thread = Arc::clone(&shutdown);
1059 let join = thread::Builder::new()
1060 .name("spg-embedded-freezer".into())
1061 .spawn(move || {
1062 background_freezer_loop(db, opts, shutdown_for_thread);
1063 })
1064 .expect("spawn background freezer thread");
1065 FreezerHandle {
1066 shutdown,
1067 join: Some(join),
1068 }
1069 }
1070}
1071
1072/// v7.2.1 — the freezer's main loop, factored out so the
1073/// `Database::spawn_background_freezer` path stays readable.
1074fn background_freezer_loop(
1075 db: Arc<Mutex<Database>>,
1076 opts: FreezerOptions,
1077 shutdown: Arc<AtomicBool>,
1078) {
1079 // Sleep in short slices so a shutdown request resolves
1080 // quickly (vs sleeping the full tick).
1081 let slice = Duration::from_millis(50.min(opts.tick.as_millis() as u64));
1082 let mut last_tick = std::time::Instant::now();
1083 loop {
1084 if shutdown.load(Ordering::Acquire) {
1085 return;
1086 }
1087 thread::sleep(slice);
1088 if last_tick.elapsed() < opts.tick {
1089 continue;
1090 }
1091 last_tick = std::time::Instant::now();
1092 let Ok(mut guard) = db.lock() else {
1093 return;
1094 };
1095 if guard.engine.catalog().hot_tier_bytes() <= opts.hot_tier_bytes {
1096 continue;
1097 }
1098 let Some((table, index)) = pick_freeze_target(&guard) else {
1099 continue;
1100 };
1101 let row_count = guard
1102 .engine
1103 .catalog()
1104 .get(&table)
1105 .map_or(0, spg_storage::Table::row_count);
1106 let to_freeze = opts.batch_rows.min(row_count);
1107 if to_freeze == 0 {
1108 continue;
1109 }
1110 if let Err(e) = guard.freeze_oldest_to_cold(&table, &index, to_freeze) {
1111 eprintln!("spg-embedded: background freeze on {table}.{index} failed: {e:?}");
1112 continue;
1113 }
1114 // v7.7.4 — auto-compact. If the catalog now carries
1115 // more cold segments than the configured threshold,
1116 // run a single compaction pass. Failures are reported
1117 // but don't kill the loop; the next tick will retry.
1118 let count = guard.engine.catalog().cold_segment_count();
1119 if count > opts.compact_when_segments_exceed {
1120 if let Err(e) = guard
1121 .engine
1122 .compact_cold_segments_with_target(opts.compact_target_bytes)
1123 {
1124 eprintln!(
1125 "spg-embedded: background compact failed (segments={count}, \
1126 threshold={}): {e:?}",
1127 opts.compact_when_segments_exceed,
1128 );
1129 }
1130 }
1131 }
1132}
1133
1134/// v7.2.1 — pick the highest-`hot_bytes` user table with a
1135/// BTree integer-PK index. Returns `(table, index_name)` so the
1136/// caller can dispatch through `freeze_oldest_to_cold`.
1137fn pick_freeze_target(db: &Database) -> Option<(String, String)> {
1138 let cat = db.engine.catalog();
1139 let mut best: Option<(String, String, u64)> = None;
1140 for name in cat.table_names() {
1141 let Some(t) = cat.get(&name) else { continue };
1142 if t.row_count() == 0 {
1143 continue;
1144 }
1145 let cols = &t.schema().columns;
1146 let Some(idx) = t.indices().iter().find(|i| {
1147 matches!(i.kind, spg_storage::IndexKind::BTree(_))
1148 && i.column_position < cols.len()
1149 && matches!(
1150 cols[i.column_position].ty,
1151 spg_storage::DataType::SmallInt
1152 | spg_storage::DataType::Int
1153 | spg_storage::DataType::BigInt
1154 )
1155 }) else {
1156 continue;
1157 };
1158 let hot = t.hot_bytes();
1159 match best {
1160 None => best = Some((name, idx.name.clone(), hot)),
1161 Some((_, _, best_hot)) if hot > best_hot => {
1162 best = Some((name, idx.name.clone(), hot));
1163 }
1164 _ => {}
1165 }
1166 }
1167 best.map(|(t, i, _)| (t, i))
1168}
1169
1170/// v7.7.6 — replay the first `to_seq` records of the WAL at
1171/// `wal_path` into a fresh engine and write the resulting
1172/// catalog snapshot to `out_db_path`. Same semantics as
1173/// `spg revert --wal … --to-seq N --out …` from the CLI:
1174///
1175/// - `to_seq == 0` → snapshot is the empty catalog
1176/// - WAL records beyond `to_seq` are not applied
1177/// - durability-checkpoint markers (v3 type 0x02) are
1178/// consumed without counting against the budget
1179///
1180/// Returns the number of statements actually applied
1181/// (`≤ to_seq`). The output snapshot is byte-identical to
1182/// what `Database::open_path(out_db_path)` would consume on
1183/// a subsequent open.
1184///
1185/// This is the "rewind" operator for an embedded database
1186/// that has been corrupted by a poison statement or a
1187/// half-applied migration. Pair with `cold_segment_paths`
1188/// preservation if your cold-tier files are still on disk.
1189///
1190/// # Errors
1191///
1192/// - `wal_path` unreadable or truncated mid-record
1193/// - WAL record decodes to invalid UTF-8 SQL
1194/// - WAL record's SQL is rejected by the engine
1195/// - `out_db_path` unwritable
1196pub fn revert_wal_to_seq(
1197 wal_path: impl AsRef<Path>,
1198 to_seq: u64,
1199 out_db_path: impl AsRef<Path>,
1200) -> Result<u64, EngineError> {
1201 let wal_bytes = std::fs::read(wal_path.as_ref()).map_err(io_err)?;
1202 let mut engine = Engine::new();
1203 let mut applied = 0u64;
1204 let mut cur = 0usize;
1205 while cur < wal_bytes.len() && applied < to_seq {
1206 let (sql_bytes, total) = decode_wal_record(&wal_bytes[cur..])?;
1207 cur += total;
1208 if sql_bytes.is_empty() {
1209 continue;
1210 }
1211 let sql = core::str::from_utf8(&sql_bytes).map_err(|e| {
1212 EngineError::Storage(spg_storage::StorageError::Corrupt(format!(
1213 "WAL record at offset {cur}: non-UTF-8 SQL: {e}"
1214 )))
1215 })?;
1216 engine.execute(sql)?;
1217 applied += 1;
1218 }
1219 let snapshot = engine.snapshot();
1220 std::fs::write(out_db_path.as_ref(), &snapshot).map_err(io_err)?;
1221 Ok(applied)
1222}
1223
1224/// v7.7.6 — decode one WAL record from a byte tail. Returns
1225/// `(sql_bytes, header_plus_payload_len)`. Handles the three
1226/// on-disk formats (v1 / v2 / v3) the same way the CLI
1227/// `decode_one_record` and the engine's `replay_wal_bytes`
1228/// do. CRCs are not re-validated; the caller's intent is
1229/// "apply", not "validate".
1230fn decode_wal_record(tail: &[u8]) -> Result<(Vec<u8>, usize), EngineError> {
1231 if tail.len() < 4 {
1232 return Err(EngineError::Storage(spg_storage::StorageError::Corrupt(
1233 format!("WAL truncated record: {} < 4 header bytes", tail.len()),
1234 )));
1235 }
1236 let raw_len = u32::from_le_bytes(tail[..4].try_into().unwrap());
1237 let is_v2 = raw_len & WAL_V2_SENTINEL != 0;
1238 let is_v3 = is_v2 && (raw_len & WAL_V3_FLAG != 0);
1239 let len_mask = if is_v3 {
1240 !(WAL_V2_SENTINEL | WAL_V3_FLAG)
1241 } else {
1242 !WAL_V2_SENTINEL
1243 };
1244 let rec_len = (raw_len & len_mask) as usize;
1245 let header_len = if is_v3 {
1246 9
1247 } else if is_v2 {
1248 8
1249 } else {
1250 4
1251 };
1252 if tail.len() < header_len + rec_len {
1253 return Err(EngineError::Storage(spg_storage::StorageError::Corrupt(
1254 format!(
1255 "WAL truncated record: header+payload {} > available {}",
1256 header_len + rec_len,
1257 tail.len()
1258 ),
1259 )));
1260 }
1261 let payload = &tail[header_len..header_len + rec_len];
1262 let sql_bytes = if is_v3 {
1263 let type_byte = tail[8];
1264 // v3 type 0x01 = auto_commit_sql (payload = SQL).
1265 // v3 type 0x02 = durability marker (payload = u64
1266 // offset, no SQL to apply). Anything else is unknown.
1267 if type_byte == WAL_V3_TYPE_AUTO_COMMIT_SQL {
1268 payload.to_vec()
1269 } else {
1270 // Caller treats empty payload as a skip-marker.
1271 Vec::new()
1272 }
1273 } else {
1274 payload.to_vec()
1275 };
1276 Ok((sql_bytes, header_len + rec_len))
1277}
1278
1279impl Drop for Database {
1280 fn drop(&mut self) {
1281 // v7.1 — best-effort final checkpoint when a persistent
1282 // Database leaves scope. Failures here go to stderr so
1283 // operators see them, but Drop can't propagate errors —
1284 // the WAL itself is already durable, so a checkpoint
1285 // miss only means the next boot replays a few more
1286 // records than strictly necessary.
1287 if self.persistence.is_some() {
1288 if let Err(e) = self.checkpoint() {
1289 eprintln!(
1290 "spg-embedded: final checkpoint on Drop failed: {e:?} \
1291 (WAL is intact; next open_path will replay)"
1292 );
1293 }
1294 }
1295 }
1296}
1297
1298/// v7.1 — turn a `std::io::Error` into the workspace's
1299/// `EngineError` shape. `EngineError::Storage(Corrupt(_))` is
1300/// the closest existing variant — io failures during boot or
1301/// during a WAL append surface as a storage-layer fault to
1302/// callers, which keeps the public error enum unchanged.
1303fn io_err(e: std::io::Error) -> EngineError {
1304 EngineError::Storage(spg_storage::StorageError::Corrupt(format!("io: {e}")))
1305}
1306
1307/// v7.2.2 — `Database` is `Send`, so the recommended sharing
1308/// pattern for multi-threaded callers is `Arc<Mutex<Database>>`:
1309///
1310/// ```no_run
1311/// use std::sync::{Arc, Mutex};
1312/// use spg_embedded::Database;
1313///
1314/// let db = Database::open_in_memory();
1315/// let shared = Arc::new(Mutex::new(db));
1316/// let shared_for_worker = Arc::clone(&shared);
1317/// std::thread::spawn(move || {
1318/// let mut guard = shared_for_worker.lock().unwrap();
1319/// guard.execute("INSERT INTO t VALUES (1)").unwrap();
1320/// });
1321/// ```
1322///
1323/// Internal `RwLock`-wrapped state — letting many threads
1324/// hold concurrent `&Database` for `SELECT` without contending
1325/// — is parked as STABILITY § "Out of v7.2"; multi-reader
1326/// embedded throughput needs a planner-side change to release
1327/// the engine read lock between scans, which is the v7.x
1328/// "Choice A" line of work already documented in v6.9.1's
1329/// carve-out.
1330#[allow(dead_code)]
1331fn _database_is_send() {
1332 fn assert_send<T: Send>() {}
1333 assert_send::<Database>();
1334}
1335
1336/// v6.10.3 — trait that maps a row's columns onto a user
1337/// struct's fields. v7.3.0 ships the [`spg_row!`] declarative
1338/// macro that generates `impl FromSpgRow for YourStruct` from
1339/// a struct definition (no proc-macro, no syn/quote/
1340/// proc-macro2 deps — the workspace's "0 external deps"
1341/// policy holds).
1342///
1343/// Implementors map a row's columns onto a user struct's
1344/// fields. Errors surface as `EngineError::Unsupported` so the
1345/// caller's error type stays uniform.
1346pub trait FromSpgRow: Sized {
1347 /// Decode one query result row into `Self`. Called once per
1348 /// row by [`Database::query_typed`]. The slice length equals
1349 /// the number of columns in the SELECT projection.
1350 fn from_spg_row(row: &[Value]) -> Result<Self, EngineError>;
1351}
1352
1353/// v7.3.0 — declarative macro that generates `FromSpgRow` impl
1354/// for a user struct. Avoids proc-macro deps
1355/// (syn/quote/proc-macro2) so the workspace's 0-deps policy
1356/// holds; the trade-off vs `#[derive(SpgRow)]` is that the
1357/// macro takes the entire struct definition (fields + types)
1358/// as input rather than annotating an existing struct.
1359///
1360/// ```no_run
1361/// use spg_embedded::{Database, spg_row, FromSpgRow};
1362///
1363/// spg_row! {
1364/// pub struct User {
1365/// pub id: i32,
1366/// pub name: String,
1367/// }
1368/// }
1369///
1370/// let mut db = Database::open_in_memory();
1371/// db.execute("CREATE TABLE users (id INT NOT NULL, name TEXT)").unwrap();
1372/// db.execute("INSERT INTO users VALUES (1, 'alice')").unwrap();
1373/// let users: Vec<User> = db.query_typed("SELECT id, name FROM users").unwrap();
1374/// ```
1375///
1376/// Supported field types: `i16`, `i32`, `i64`, `f32`, `f64`,
1377/// `bool`, `String`, `Vec<f32>` (for `VECTOR(N)` columns),
1378/// `Option<T>` of any of the above.
1379#[macro_export]
1380macro_rules! spg_row {
1381 (
1382 $(#[$meta:meta])*
1383 $vis:vis struct $name:ident {
1384 $(
1385 $(#[$fmeta:meta])*
1386 $fvis:vis $field:ident : $ty:ty,
1387 )*
1388 }
1389 ) => {
1390 $(#[$meta])*
1391 #[derive(Debug, Clone)]
1392 $vis struct $name {
1393 $(
1394 $(#[$fmeta])*
1395 $fvis $field : $ty,
1396 )*
1397 }
1398
1399 impl $crate::FromSpgRow for $name {
1400 fn from_spg_row(row: &[$crate::Value]) -> ::core::result::Result<Self, $crate::EngineError> {
1401 let mut __spg_row_iter = row.iter();
1402 $(
1403 let $field: $ty = {
1404 let v = __spg_row_iter
1405 .next()
1406 .ok_or_else(|| $crate::EngineError::Unsupported(
1407 ::std::format!(
1408 "spg_row! {}: missing column for field `{}`",
1409 ::core::stringify!($name),
1410 ::core::stringify!($field)
1411 )
1412 ))?;
1413 <$ty as $crate::FromSpgValue>::from_spg_value(v)
1414 .map_err(|e| $crate::EngineError::Unsupported(
1415 ::std::format!(
1416 "spg_row! {}: column `{}`: {}",
1417 ::core::stringify!($name),
1418 ::core::stringify!($field),
1419 e
1420 )
1421 ))?
1422 };
1423 )*
1424 Ok(Self { $($field,)* })
1425 }
1426 }
1427 };
1428}
1429
1430/// v7.3.0 — per-column decoder used by `spg_row!`. Surface
1431/// covers every numeric / text / bytes / bool variant in
1432/// `Value`, plus `Option<T>` for nullable columns.
1433pub trait FromSpgValue: Sized {
1434 /// Decode one cell into `Self`. The returned `&'static str`
1435 /// is a short diagnostic for type mismatches (e.g. `"expected
1436 /// integer, got TEXT"`); callers wrap it into their own
1437 /// error type.
1438 fn from_spg_value(v: &Value) -> Result<Self, &'static str>;
1439}
1440
1441macro_rules! impl_from_value_int {
1442 ($($t:ty),* $(,)?) => {
1443 $(
1444 impl FromSpgValue for $t {
1445 fn from_spg_value(v: &Value) -> Result<Self, &'static str> {
1446 match v {
1447 Value::SmallInt(n) => <$t>::try_from(*n).map_err(|_| "SmallInt does not fit target int type"),
1448 Value::Int(n) => <$t>::try_from(*n).map_err(|_| "Int does not fit target int type"),
1449 Value::BigInt(n) => <$t>::try_from(*n).map_err(|_| "BigInt does not fit target int type"),
1450 Value::Null => Err("NULL in non-Option int column"),
1451 _ => Err("non-integer value in int column"),
1452 }
1453 }
1454 }
1455 )*
1456 };
1457}
1458impl_from_value_int!(i16, i32, i64);
1459
1460impl FromSpgValue for f32 {
1461 fn from_spg_value(v: &Value) -> Result<Self, &'static str> {
1462 match v {
1463 Value::Float(f) => Ok(*f as f32),
1464 Value::Null => Err("NULL in non-Option float column"),
1465 _ => Err("non-float value in float column"),
1466 }
1467 }
1468}
1469
1470impl FromSpgValue for f64 {
1471 fn from_spg_value(v: &Value) -> Result<Self, &'static str> {
1472 match v {
1473 Value::Float(f) => Ok(*f),
1474 Value::Null => Err("NULL in non-Option float column"),
1475 _ => Err("non-float value in float column"),
1476 }
1477 }
1478}
1479
1480impl FromSpgValue for bool {
1481 fn from_spg_value(v: &Value) -> Result<Self, &'static str> {
1482 match v {
1483 Value::Bool(b) => Ok(*b),
1484 Value::Null => Err("NULL in non-Option bool column"),
1485 _ => Err("non-bool value in bool column"),
1486 }
1487 }
1488}
1489
1490impl FromSpgValue for String {
1491 fn from_spg_value(v: &Value) -> Result<Self, &'static str> {
1492 match v {
1493 Value::Text(s) => Ok(s.clone()),
1494 Value::Null => Err("NULL in non-Option text column"),
1495 _ => Err("non-text value in String column"),
1496 }
1497 }
1498}
1499
1500impl FromSpgValue for Vec<f32> {
1501 fn from_spg_value(v: &Value) -> Result<Self, &'static str> {
1502 match v {
1503 Value::Vector(xs) => Ok(xs.clone()),
1504 Value::Null => Err("NULL in non-Option vector column"),
1505 _ => Err("non-vector value in Vec<f32> column"),
1506 }
1507 }
1508}
1509
1510impl<T: FromSpgValue> FromSpgValue for Option<T> {
1511 fn from_spg_value(v: &Value) -> Result<Self, &'static str> {
1512 match v {
1513 Value::Null => Ok(None),
1514 other => T::from_spg_value(other).map(Some),
1515 }
1516 }
1517}
1518
1519#[cfg(test)]
1520mod tests {
1521 use super::*;
1522
1523 #[test]
1524 fn in_memory_create_insert_select() {
1525 let mut db = Database::open_in_memory();
1526 db.execute("CREATE TABLE t (id INT NOT NULL, name TEXT)")
1527 .unwrap();
1528 db.execute("INSERT INTO t VALUES (1, 'alice')").unwrap();
1529 db.execute("INSERT INTO t VALUES (2, 'bob')").unwrap();
1530 let rows = db.query("SELECT id FROM t WHERE id = 1").unwrap();
1531 assert_eq!(rows.len(), 1);
1532 match &rows[0][0] {
1533 Value::Int(1) => {}
1534 other => panic!("expected Int(1), got {other:?}"),
1535 }
1536 }
1537
1538 #[test]
1539 fn query_on_non_select_errors() {
1540 let mut db = Database::open_in_memory();
1541 db.execute("CREATE TABLE t (id INT)").unwrap();
1542 let r = db.query("INSERT INTO t VALUES (1)");
1543 assert!(r.is_err(), "query() on INSERT must error");
1544 }
1545
1546 #[test]
1547 fn snapshot_roundtrip() {
1548 let mut db = Database::open_in_memory();
1549 db.execute("CREATE TABLE t (id INT NOT NULL)").unwrap();
1550 db.execute("INSERT INTO t VALUES (42)").unwrap();
1551 let bytes = db.snapshot();
1552 let mut restored = Database::restore(&bytes).unwrap();
1553 let rows = restored.query("SELECT id FROM t WHERE id = 42").unwrap();
1554 assert_eq!(rows.len(), 1);
1555 match &rows[0][0] {
1556 Value::Int(42) => {}
1557 other => panic!("expected Int(42), got {other:?}"),
1558 }
1559 }
1560
1561 #[test]
1562 fn from_spg_row_trait_shape() {
1563 struct User {
1564 _id: i32,
1565 }
1566 impl FromSpgRow for User {
1567 fn from_spg_row(row: &[Value]) -> Result<Self, EngineError> {
1568 match row.first() {
1569 Some(Value::Int(n)) => Ok(Self { _id: *n }),
1570 _ => Err(EngineError::Unsupported("bad id".into())),
1571 }
1572 }
1573 }
1574 let row = vec![Value::Int(7)];
1575 let _u = User::from_spg_row(&row).unwrap();
1576 }
1577}