Skip to main content

slabs_db/
lib.rs

1//! Raw-SQL database library for Slabs.
2//!
3//! This crate owns the tuned `SQLite` WAL wrapper ([`Db`]), the optional `PostgreSQL` wrapper ([`PgDb`]),
4//! URL engine detection ([`DbEngine`]), framework system schemas ([`SYSTEM_SCHEMA_SQL`], [`POSTGRES_SYSTEM_SCHEMA_SQL`]),
5//! and FTS5 query escaping ([`fts5_query`]). It also re-exports [`QueryBuilder`] for dynamic parameterized SQL.
6//!
7//! # Owned types and system tables
8//!
9//! Calling [`Db::init_system_tables`], [`Db::migrate`], or [`Db::migrate_dir`] (and the matching [`PgDb`] methods)
10//! creates these 11 framework tables if they do not exist:
11//!
12//! - `slabs_sessions`
13//! - `slabs_magic_links`
14//! - `slabs_access_tokens`
15//! - `slabs_jobs`
16//! - `slabs_cache`
17//! - `slabs_mail_outbox`
18//! - `slabs_blobs`
19//! - `slabs_webhooks`
20//! - `slabs_webhook_deliveries`
21//! - `slabs_idempotency_keys`
22//! - `slabs_audit_log`
23//!
24//! # Invariants
25//!
26//! - **Split WAL pools on file-backed `SQLite`**: [`Db::reader`] returns a read-only pool with up to 16 connections for concurrent `SELECT` queries. [`Db::writer`] and [`Db::pool`] return a dedicated single-connection writer pool (`max_connections(1)`).
27//! - **Explicit `BEGIN IMMEDIATE` transactions**: [`Db::begin`] opens a `BEGIN IMMEDIATE` transaction on the single writer pool. Use it for multi-step mutations so `SQLite` acquires the write lock up front and avoids `SQLITE_BUSY_SNAPSHOT` lock-upgrade failures.
28//! - **In-memory test databases share one connection**: when `database_url` is `"sqlite::memory:"` or contains `"mode=memory"`, [`Db::connect`] clones the single writer pool for [`Db::reader`] because `SQLite` isolates in-memory databases per connection.
29//! - **Tuned `SQLite` pragmas**: [`Db::connect`] sets `foreign_keys = ON`, `synchronous = NORMAL`, `cache_size = -64000`, `temp_store = MEMORY`, and `busy_timeout` (10s writer, 5s reader). File-backed databases also enable `journal_mode = WAL` and `mmap_size = 268435456` (256 MiB).
30//! - **Parameterized SQL only**: always bind untrusted input with `sqlx::query`, `sqlx::query_as`, or [`QueryBuilder`]. Never interpolate user strings into SQL text.
31//! - **FTS5 search escaping**: pass untrusted search strings through [`fts5_query`] before binding to an FTS5 `MATCH ?` clause. It strips double quotes and wraps each whitespace token as `"token"*` joined with `AND`.
32//!
33//! # Usage
34//!
35//! ```rust,no_run
36//! use slabs_core::SlabResult;
37//! use slabs_db::{fts5_query, Db};
38//!
39//! async fn example() -> SlabResult<()> {
40//!     let db = Db::connect("sqlite://app.db?mode=rwc").await?;
41//!     db.init_system_tables().await?;
42//!
43//!     // Concurrent SELECT on the read-only WAL pool.
44//!     let (count,): (i64,) = sqlx::query_as("SELECT COUNT(*) FROM slabs_jobs")
45//!         .fetch_one(db.reader())
46//!         .await?;
47//!
48//!     // Multi-step write inside an explicit BEGIN IMMEDIATE transaction.
49//!     let mut tx = db.begin().await?;
50//!     sqlx::query("DELETE FROM slabs_cache WHERE cache_key = ?")
51//!         .bind("stale_key")
52//!         .execute(&mut *tx)
53//!         .await?;
54//!     tx.commit().await?;
55//!
56//!     // Safe FTS5 query construction for user input.
57//!     if let Some(match_expr) = fts5_query("deploy \"prod\"") {
58//!         assert_eq!(match_expr, "\"deploy\"* AND \"prod\"*");
59//!     }
60//!     let _ = count;
61//!     Ok(())
62//! }
63//! ```
64
65use slabs_core::{SlabError, SlabResult};
66use sqlx::{
67    migrate::Migrator,
68    postgres::PgPoolOptions,
69    sqlite::{SqliteConnectOptions, SqliteJournalMode, SqlitePoolOptions, SqliteSynchronous},
70    PgPool, Postgres, Sqlite, SqlitePool, Transaction,
71};
72use std::fmt::Write as _;
73use std::path::Path;
74use std::str::FromStr;
75use std::time::Duration;
76
77pub use sqlx::QueryBuilder;
78
79/// Database engine detected from a `DATABASE_URL` string.
80#[derive(Debug, Clone, Copy, PartialEq, Eq)]
81pub enum DbEngine {
82    /// Embedded `SQLite` database.
83    Sqlite,
84    /// Networked `PostgreSQL` database.
85    Postgres,
86}
87
88impl DbEngine {
89    /// Detects the [`DbEngine`] from a database connection URL.
90    ///
91    /// Returns [`DbEngine::Postgres`] when the trimmed, lowercased URL starts with
92    /// `"postgres://"` or `"postgresql://"`, and [`DbEngine::Sqlite`] otherwise.
93    #[must_use]
94    pub fn detect(database_url: &str) -> Self {
95        let lower = database_url.trim().to_ascii_lowercase();
96        if lower.starts_with("postgres://") || lower.starts_with("postgresql://") {
97            Self::Postgres
98        } else {
99            Self::Sqlite
100        }
101    }
102}
103
104/// Framework-owned `SQLite` DDL for the 11 system tables and their indexes.
105///
106/// Applied idempotently by [`Db::init_system_tables`], [`Db::migrate`], and [`Db::migrate_dir`].
107pub const SYSTEM_SCHEMA_SQL: &str = r"
108CREATE TABLE IF NOT EXISTS slabs_sessions (
109    id TEXT PRIMARY KEY NOT NULL,
110    user_id TEXT NOT NULL,
111    role TEXT NOT NULL DEFAULT 'member',
112    token_hash TEXT NOT NULL UNIQUE,
113    expires_at TEXT NOT NULL,
114    created_at TEXT NOT NULL
115);
116CREATE INDEX IF NOT EXISTS idx_slabs_sessions_user_id ON slabs_sessions(user_id);
117CREATE INDEX IF NOT EXISTS idx_slabs_sessions_expires_at ON slabs_sessions(expires_at);
118
119CREATE TABLE IF NOT EXISTS slabs_magic_links (
120    id TEXT PRIMARY KEY NOT NULL,
121    email TEXT NOT NULL,
122    purpose TEXT NOT NULL DEFAULT 'sign_in',
123    code_hash TEXT NOT NULL UNIQUE,
124    expires_at TEXT NOT NULL,
125    created_at TEXT NOT NULL
126);
127CREATE INDEX IF NOT EXISTS idx_slabs_magic_links_expires_at ON slabs_magic_links(expires_at);
128
129CREATE TABLE IF NOT EXISTS slabs_access_tokens (
130    id TEXT PRIMARY KEY NOT NULL,
131    user_id TEXT NOT NULL,
132    role TEXT NOT NULL DEFAULT 'member',
133    description TEXT NOT NULL DEFAULT '',
134    permission TEXT NOT NULL DEFAULT 'write',
135    token_hash TEXT NOT NULL UNIQUE,
136    last_used_at TEXT,
137    expires_at TEXT,
138    created_at TEXT NOT NULL
139);
140CREATE INDEX IF NOT EXISTS idx_slabs_access_tokens_user_id ON slabs_access_tokens(user_id);
141
142CREATE TABLE IF NOT EXISTS slabs_jobs (
143    id TEXT PRIMARY KEY NOT NULL,
144    job_name TEXT NOT NULL,
145    queue TEXT NOT NULL DEFAULT 'default',
146    payload_json TEXT NOT NULL,
147    status TEXT NOT NULL DEFAULT 'pending',
148    attempts INTEGER NOT NULL DEFAULT 0,
149    max_attempts INTEGER NOT NULL DEFAULT 5,
150    run_at TEXT NOT NULL,
151    last_error TEXT,
152    created_at TEXT NOT NULL,
153    updated_at TEXT NOT NULL
154);
155CREATE INDEX IF NOT EXISTS idx_slabs_jobs_poll ON slabs_jobs(status, run_at, created_at);
156
157CREATE TABLE IF NOT EXISTS slabs_cache (
158    cache_key TEXT PRIMARY KEY NOT NULL,
159    value_text TEXT NOT NULL,
160    expires_at TEXT NOT NULL,
161    updated_at TEXT NOT NULL
162);
163CREATE INDEX IF NOT EXISTS idx_slabs_cache_expires_at ON slabs_cache(expires_at);
164
165CREATE TABLE IF NOT EXISTS slabs_mail_outbox (
166    id TEXT PRIMARY KEY NOT NULL,
167    from_addr TEXT NOT NULL,
168    to_addr TEXT NOT NULL,
169    subject TEXT NOT NULL,
170    text_body TEXT NOT NULL,
171    html_body TEXT,
172    sent_at TEXT NOT NULL
173);
174
175CREATE TABLE IF NOT EXISTS slabs_blobs (
176    id TEXT PRIMARY KEY NOT NULL,
177    filename TEXT NOT NULL,
178    content_type TEXT NOT NULL,
179    byte_size INTEGER NOT NULL,
180    checksum_sha256 TEXT NOT NULL,
181    storage_key TEXT NOT NULL UNIQUE,
182    created_at TEXT NOT NULL
183);
184
185CREATE TABLE IF NOT EXISTS slabs_webhooks (
186    id TEXT PRIMARY KEY NOT NULL,
187    scope_id TEXT NOT NULL,
188    name TEXT NOT NULL,
189    url TEXT NOT NULL,
190    signing_secret TEXT NOT NULL,
191    subscribed_actions_json TEXT NOT NULL,
192    active INTEGER NOT NULL DEFAULT 1,
193    created_at TEXT NOT NULL
194);
195CREATE INDEX IF NOT EXISTS idx_slabs_webhooks_scope ON slabs_webhooks(scope_id, active);
196
197CREATE TABLE IF NOT EXISTS slabs_webhook_deliveries (
198    id TEXT PRIMARY KEY NOT NULL,
199    webhook_id TEXT NOT NULL REFERENCES slabs_webhooks(id) ON DELETE CASCADE,
200    action TEXT NOT NULL,
201    payload_json TEXT NOT NULL,
202    signature TEXT NOT NULL,
203    status TEXT NOT NULL DEFAULT 'pending',
204    response_status INTEGER,
205    last_error TEXT,
206    created_at TEXT NOT NULL,
207    delivered_at TEXT
208);
209CREATE INDEX IF NOT EXISTS idx_slabs_webhook_deliveries_webhook ON slabs_webhook_deliveries(webhook_id, created_at DESC);
210
211CREATE TABLE IF NOT EXISTS slabs_idempotency_keys (
212    scope TEXT NOT NULL,
213    key TEXT NOT NULL,
214    response_json TEXT,
215    created_at TEXT NOT NULL,
216    PRIMARY KEY (scope, key)
217);
218
219CREATE TABLE IF NOT EXISTS slabs_audit_log (
220    id TEXT PRIMARY KEY NOT NULL,
221    actor_id TEXT,
222    action TEXT NOT NULL,
223    target_type TEXT NOT NULL,
224    target_id TEXT NOT NULL,
225    metadata_json TEXT NOT NULL DEFAULT '{}',
226    created_at TEXT NOT NULL
227);
228CREATE INDEX IF NOT EXISTS idx_slabs_audit_log_target ON slabs_audit_log (target_type, target_id, created_at DESC);
229";
230
231/// Framework-owned `PostgreSQL` DDL for the 11 system tables and their indexes.
232///
233/// Uses `TIMESTAMPTZ`, `JSONB`, `BIGINT`, and `BOOLEAN` column types.
234/// Applied idempotently by [`PgDb::init_system_tables`], [`PgDb::migrate`], and [`PgDb::migrate_dir`].
235pub const POSTGRES_SYSTEM_SCHEMA_SQL: &str = r"
236CREATE TABLE IF NOT EXISTS slabs_sessions (
237    id TEXT PRIMARY KEY NOT NULL,
238    user_id TEXT NOT NULL,
239    role TEXT NOT NULL DEFAULT 'member',
240    token_hash TEXT NOT NULL UNIQUE,
241    expires_at TIMESTAMPTZ NOT NULL,
242    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
243);
244CREATE INDEX IF NOT EXISTS idx_slabs_sessions_user_id ON slabs_sessions(user_id);
245CREATE INDEX IF NOT EXISTS idx_slabs_sessions_expires_at ON slabs_sessions(expires_at);
246
247CREATE TABLE IF NOT EXISTS slabs_magic_links (
248    id TEXT PRIMARY KEY NOT NULL,
249    email TEXT NOT NULL,
250    purpose TEXT NOT NULL DEFAULT 'sign_in',
251    code_hash TEXT NOT NULL UNIQUE,
252    expires_at TIMESTAMPTZ NOT NULL,
253    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
254);
255CREATE INDEX IF NOT EXISTS idx_slabs_magic_links_expires_at ON slabs_magic_links(expires_at);
256
257CREATE TABLE IF NOT EXISTS slabs_access_tokens (
258    id TEXT PRIMARY KEY NOT NULL,
259    user_id TEXT NOT NULL,
260    role TEXT NOT NULL DEFAULT 'member',
261    description TEXT NOT NULL DEFAULT '',
262    permission TEXT NOT NULL DEFAULT 'write',
263    token_hash TEXT NOT NULL UNIQUE,
264    last_used_at TIMESTAMPTZ,
265    expires_at TIMESTAMPTZ,
266    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
267);
268CREATE INDEX IF NOT EXISTS idx_slabs_access_tokens_user_id ON slabs_access_tokens(user_id);
269
270CREATE TABLE IF NOT EXISTS slabs_jobs (
271    id TEXT PRIMARY KEY NOT NULL,
272    job_name TEXT NOT NULL,
273    queue TEXT NOT NULL DEFAULT 'default',
274    payload_json JSONB NOT NULL,
275    status TEXT NOT NULL DEFAULT 'pending',
276    attempts BIGINT NOT NULL DEFAULT 0,
277    max_attempts BIGINT NOT NULL DEFAULT 5,
278    run_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
279    last_error TEXT,
280    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
281    updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
282);
283CREATE INDEX IF NOT EXISTS idx_slabs_jobs_poll ON slabs_jobs(status, run_at, created_at);
284
285CREATE TABLE IF NOT EXISTS slabs_cache (
286    cache_key TEXT PRIMARY KEY NOT NULL,
287    value_text TEXT NOT NULL,
288    expires_at TIMESTAMPTZ NOT NULL,
289    updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
290);
291CREATE INDEX IF NOT EXISTS idx_slabs_cache_expires_at ON slabs_cache(expires_at);
292
293CREATE TABLE IF NOT EXISTS slabs_mail_outbox (
294    id TEXT PRIMARY KEY NOT NULL,
295    from_addr TEXT NOT NULL,
296    to_addr TEXT NOT NULL,
297    subject TEXT NOT NULL,
298    text_body TEXT NOT NULL,
299    html_body TEXT,
300    sent_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
301);
302
303CREATE TABLE IF NOT EXISTS slabs_blobs (
304    id TEXT PRIMARY KEY NOT NULL,
305    filename TEXT NOT NULL,
306    content_type TEXT NOT NULL,
307    byte_size BIGINT NOT NULL,
308    checksum_sha256 TEXT NOT NULL,
309    storage_key TEXT NOT NULL UNIQUE,
310    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
311);
312
313CREATE TABLE IF NOT EXISTS slabs_webhooks (
314    id TEXT PRIMARY KEY NOT NULL,
315    scope_id TEXT NOT NULL,
316    name TEXT NOT NULL,
317    url TEXT NOT NULL,
318    signing_secret TEXT NOT NULL,
319    subscribed_actions_json JSONB NOT NULL,
320    active BOOLEAN NOT NULL DEFAULT TRUE,
321    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
322);
323CREATE INDEX IF NOT EXISTS idx_slabs_webhooks_scope ON slabs_webhooks(scope_id, active);
324
325CREATE TABLE IF NOT EXISTS slabs_webhook_deliveries (
326    id TEXT PRIMARY KEY NOT NULL,
327    webhook_id TEXT NOT NULL REFERENCES slabs_webhooks(id) ON DELETE CASCADE,
328    action TEXT NOT NULL,
329    payload_json JSONB NOT NULL,
330    signature TEXT NOT NULL,
331    status TEXT NOT NULL DEFAULT 'pending',
332    response_status INTEGER,
333    last_error TEXT,
334    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
335    delivered_at TIMESTAMPTZ
336);
337CREATE INDEX IF NOT EXISTS idx_slabs_webhook_deliveries_webhook ON slabs_webhook_deliveries(webhook_id, created_at DESC);
338
339CREATE TABLE IF NOT EXISTS slabs_idempotency_keys (
340    scope TEXT NOT NULL,
341    key TEXT NOT NULL,
342    response_json TEXT,
343    created_at TEXT NOT NULL,
344    PRIMARY KEY (scope, key)
345);
346
347CREATE TABLE IF NOT EXISTS slabs_audit_log (
348    id TEXT PRIMARY KEY NOT NULL,
349    actor_id TEXT,
350    action TEXT NOT NULL,
351    target_type TEXT NOT NULL,
352    target_id TEXT NOT NULL,
353    metadata_json TEXT NOT NULL DEFAULT '{}',
354    created_at TEXT NOT NULL
355);
356CREATE INDEX IF NOT EXISTS idx_slabs_audit_log_target ON slabs_audit_log (target_type, target_id, created_at DESC);
357";
358
359/// Converts untrusted user search text into an FTS5 prefix-AND `MATCH` expression.
360///
361/// Splits on whitespace, strips `"` characters from every token, wraps each remaining
362/// token as `"token"*`, and joins them with `AND`.
363/// Returns `None` when the input contains no non-empty tokens after stripping quotes.
364#[must_use]
365pub fn fts5_query(raw: &str) -> Option<String> {
366    let terms: Vec<String> = raw
367        .split_whitespace()
368        .map(|tok| tok.replace('"', ""))
369        .filter(|tok| !tok.is_empty())
370        .map(|tok| format!("\"{tok}\"*"))
371        .collect();
372    if terms.is_empty() {
373        None
374    } else {
375        Some(terms.join(" AND "))
376    }
377}
378
379/// Query parameters for cursor-based (keyset) pagination.
380#[derive(Debug, Clone, Default, serde::Deserialize)]
381pub struct Pagination {
382    /// Requested maximum number of items per page.
383    pub limit: Option<u32>,
384    /// Opaque cursor returned as `next_cursor` by the previous page.
385    pub cursor: Option<String>,
386}
387
388impl Pagination {
389    /// Resolves the page size, clamping it between `1` and `max_limit.max(1)`.
390    ///
391    /// Falls back to `default_limit` when [`Pagination::limit`] is `None`.
392    #[must_use]
393    pub fn clamped_limit(&self, default_limit: u32, max_limit: u32) -> i64 {
394        let upper = max_limit.max(1);
395        let raw = self.limit.unwrap_or(default_limit);
396        i64::from(raw.clamp(1, upper))
397    }
398
399    /// Returns `clamped_limit + 1` so callers can detect whether more rows exist without a `COUNT(*)`.
400    #[must_use]
401    pub fn fetch_limit(&self, default_limit: u32, max_limit: u32) -> i64 {
402        self.clamped_limit(default_limit, max_limit) + 1
403    }
404}
405
406/// One page of cursor-paginated results.
407#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
408pub struct CursorPage<T> {
409    /// Items returned for the current page.
410    pub items: Vec<T>,
411    /// Cursor of the last item when more rows exist, or `None` on the final page.
412    pub next_cursor: Option<String>,
413    /// Whether additional rows exist beyond this page.
414    pub has_more: bool,
415}
416
417impl<T> CursorPage<T> {
418    /// Builds a [`CursorPage`] from rows fetched with `LIMIT (limit + 1)`.
419    ///
420    /// Truncates `rows` to `limit`, sets `has_more` when an extra row was present,
421    /// and computes `next_cursor` from the last retained row via `cursor_fn`.
422    #[must_use]
423    pub fn from_rows(mut rows: Vec<T>, limit: usize, cursor_fn: impl Fn(&T) -> String) -> Self {
424        let has_more = rows.len() > limit;
425        if has_more {
426            rows.truncate(limit);
427        }
428        let next_cursor = if has_more {
429            rows.last().map(cursor_fn)
430        } else {
431            None
432        };
433        Self {
434            items: rows,
435            next_cursor,
436            has_more,
437        }
438    }
439}
440
441/// Persisted audit event row stored in `slabs_audit_log`.
442#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, sqlx::FromRow)]
443pub struct AuditEntry {
444    /// Prefixed audit entry identifier (`aud_<ulid>`).
445    pub id: String,
446    /// Optional identifier of the user or service that performed the action.
447    pub actor_id: Option<String>,
448    /// Action name describing what happened (for example `"room.archived"`).
449    pub action: String,
450    /// Logical type of the affected resource (for example `"room"`).
451    pub target_type: String,
452    /// Identifier of the affected resource.
453    pub target_id: String,
454    /// JSON-serialized metadata payload attached to the audit event.
455    pub metadata_json: String,
456    /// RFC 3339 UTC timestamp when the audit entry was created.
457    pub created_at: String,
458}
459
460/// Transactional audit log backed by the `slabs_audit_log` system table.
461#[derive(Debug, Clone)]
462pub struct AuditLog {
463    db: Db,
464}
465
466impl AuditLog {
467    /// Creates an [`AuditLog`] handle backed by `db`.
468    #[must_use]
469    pub fn new(db: Db) -> Self {
470        Self { db }
471    }
472
473    /// Inserts an audit entry inside an open `SQLite` transaction so it commits or rolls back atomically.
474    ///
475    /// Returns the generated `aud_<ulid>` identifier.
476    pub async fn record_in_tx(
477        &self,
478        tx: &mut Transaction<'_, Sqlite>,
479        actor_id: Option<&str>,
480        action: &str,
481        target_type: &str,
482        target_id: &str,
483        metadata: &serde_json::Value,
484    ) -> SlabResult<String> {
485        let id = slabs_core::id::new("aud");
486        let created_at = chrono::Utc::now().to_rfc3339();
487        let metadata_json = serde_json::to_string(metadata)
488            .map_err(|e| SlabError::internal(format!("failed to serialize audit metadata: {e}")))?;
489
490        sqlx::query(
491            "INSERT INTO slabs_audit_log (id, actor_id, action, target_type, target_id, metadata_json, created_at)
492             VALUES (?, ?, ?, ?, ?, ?, ?)",
493        )
494        .bind(&id)
495        .bind(actor_id)
496        .bind(action)
497        .bind(target_type)
498        .bind(target_id)
499        .bind(&metadata_json)
500        .bind(&created_at)
501        .execute(&mut **tx)
502        .await?;
503
504        Ok(id)
505    }
506
507    /// Lists up to `limit` most recent audit entries for a specific `(target_type, target_id)` on the read pool.
508    pub async fn list_for_target(
509        &self,
510        target_type: &str,
511        target_id: &str,
512        limit: i64,
513    ) -> SlabResult<Vec<AuditEntry>> {
514        let rows: Vec<AuditEntry> = sqlx::query_as(
515            "SELECT id, actor_id, action, target_type, target_id, metadata_json, created_at
516             FROM slabs_audit_log
517             WHERE target_type = ? AND target_id = ?
518             ORDER BY created_at DESC, id DESC
519             LIMIT ?",
520        )
521        .bind(target_type)
522        .bind(target_id)
523        .bind(limit)
524        .fetch_all(self.db.reader())
525        .await?;
526        Ok(rows)
527    }
528
529    /// Lists up to `limit` most recent audit entries across all targets on the read pool.
530    pub async fn list_recent(&self, limit: i64) -> SlabResult<Vec<AuditEntry>> {
531        let rows: Vec<AuditEntry> = sqlx::query_as(
532            "SELECT id, actor_id, action, target_type, target_id, metadata_json, created_at
533             FROM slabs_audit_log
534             ORDER BY created_at DESC, id DESC
535             LIMIT ?",
536        )
537        .bind(limit)
538        .fetch_all(self.db.reader())
539        .await?;
540        Ok(rows)
541    }
542}
543
544/// Raw-SQL `SQLite` database wrapper tuned for concurrent WAL workloads.
545///
546/// Holds two pools on file-backed databases:
547/// - A single-connection writer pool (`max_connections(1)`) used by [`Db::writer`], [`Db::pool`], and [`Db::begin`] (`BEGIN IMMEDIATE`).
548/// - A 16-connection read-only pool used by [`Db::reader`] for parallel `SELECT` queries.
549///
550/// In-memory databases (`sqlite::memory:` or `mode=memory`) share the single writer pool for both reads and writes.
551#[derive(Debug, Clone)]
552pub struct Db {
553    read_pool: SqlitePool,
554    write_pool: SqlitePool,
555}
556
557impl Db {
558    /// Connects to a `SQLite` database with tuned WAL pragmas and split read/write pools.
559    ///
560    /// Creates the database file when missing and enables `foreign_keys = ON`, `synchronous = NORMAL`,
561    /// `cache_size = -64000`, and `temp_store = MEMORY`. File-backed databases also enable
562    /// `journal_mode = WAL`, `mmap_size = 268435456`, and a separate 16-connection read-only pool.
563    /// Returns [`SlabError::Internal`] if `database_url` cannot be parsed.
564    pub async fn connect(database_url: &str) -> SlabResult<Self> {
565        let is_memory = database_url == "sqlite::memory:" || database_url.contains("mode=memory");
566
567        let mut write_opts = SqliteConnectOptions::from_str(database_url)
568            .map_err(|e| SlabError::internal(format!("invalid DATABASE_URL: {e}")))?
569            .create_if_missing(true)
570            .foreign_keys(true)
571            .busy_timeout(Duration::from_secs(10))
572            .synchronous(SqliteSynchronous::Normal)
573            .pragma("cache_size", "-64000")
574            .pragma("temp_store", "MEMORY");
575
576        if !is_memory {
577            write_opts = write_opts
578                .journal_mode(SqliteJournalMode::Wal)
579                .pragma("mmap_size", "268435456");
580        }
581
582        // Single dedicated writer guarantees serialized writes without SQLITE_BUSY thrashing.
583        let write_pool = SqlitePoolOptions::new()
584            .max_connections(1)
585            .acquire_timeout(Duration::from_secs(10))
586            .connect_with(write_opts)
587            .await?;
588
589        let read_pool = if is_memory {
590            // In-memory SQLite databases are per-connection, so share the single pool in tests.
591            write_pool.clone()
592        } else {
593            let read_opts = SqliteConnectOptions::from_str(database_url)
594                .map_err(|e| SlabError::internal(format!("invalid DATABASE_URL: {e}")))?
595                .read_only(true)
596                .foreign_keys(true)
597                .busy_timeout(Duration::from_secs(5))
598                .pragma("cache_size", "-64000")
599                .pragma("temp_store", "MEMORY")
600                .pragma("mmap_size", "268435456");
601
602            SqlitePoolOptions::new()
603                .max_connections(16)
604                .acquire_timeout(Duration::from_secs(5))
605                .connect_with(read_opts)
606                .await?
607        };
608
609        Ok(Self {
610            read_pool,
611            write_pool,
612        })
613    }
614
615    /// Returns the default pool, which aliases the single-connection writer pool.
616    ///
617    /// Prefer [`Db::reader`] for read-only `SELECT` queries so reads run concurrently on file-backed databases.
618    #[must_use]
619    pub fn pool(&self) -> &SqlitePool {
620        &self.write_pool
621    }
622
623    /// Returns the concurrent read-only WAL pool (up to 16 connections on file-backed databases).
624    ///
625    /// Use this pool for `SELECT` queries. Executing write statements on a file-backed reader pool fails.
626    #[must_use]
627    pub fn reader(&self) -> &SqlitePool {
628        &self.read_pool
629    }
630
631    /// Returns the dedicated single-connection writer pool (`max_connections(1)`).
632    ///
633    /// Serializes writes in-process with a 10-second `busy_timeout` to prevent `SQLITE_BUSY` thrashing.
634    #[must_use]
635    pub fn writer(&self) -> &SqlitePool {
636        &self.write_pool
637    }
638
639    /// Opens an explicit `BEGIN IMMEDIATE` transaction on the single writer connection.
640    ///
641    /// Acquires the write lock at transaction start, avoiding deferred lock-upgrade `SQLITE_BUSY_SNAPSHOT` errors.
642    pub async fn begin(&self) -> SlabResult<Transaction<'_, Sqlite>> {
643        Ok(self.write_pool.begin_with("BEGIN IMMEDIATE").await?)
644    }
645
646    /// Executes [`SYSTEM_SCHEMA_SQL`] against the writer pool to create all 11 system tables idempotently.
647    pub async fn init_system_tables(&self) -> SlabResult<()> {
648        sqlx::raw_sql(SYSTEM_SCHEMA_SQL)
649            .execute(&self.write_pool)
650            .await?;
651        Ok(())
652    }
653
654    /// Creates system tables if missing and runs all pending migrations from `migrator` on the writer pool.
655    ///
656    /// Wraps migration failures in [`SlabError::Internal`].
657    pub async fn migrate(&self, migrator: &Migrator) -> SlabResult<()> {
658        self.init_system_tables().await?;
659        migrator
660            .run(&self.write_pool)
661            .await
662            .map_err(|e| SlabError::internal(format!("migration failed: {e}")))?;
663        Ok(())
664    }
665
666    /// Creates system tables if missing and runs all SQL migrations located in `dir` on the writer pool.
667    ///
668    /// Wraps directory load and migration failures in [`SlabError::Internal`].
669    pub async fn migrate_dir(&self, dir: &Path) -> SlabResult<()> {
670        self.init_system_tables().await?;
671        let migrator = Migrator::new(dir)
672            .await
673            .map_err(|e| SlabError::internal(format!("failed to load migrations: {e}")))?;
674        self.migrate(&migrator).await
675    }
676
677    /// Exports the current `SQLite` schema DDL from `sqlite_master` on the read pool.
678    ///
679    /// Excludes internal `sqlite_%` and `_sqlx_%` objects and orders statements by table, index, trigger, then view.
680    pub async fn dump_schema_sql(&self) -> SlabResult<String> {
681        let rows: Vec<(String, String, Option<String>)> = sqlx::query_as(
682            "SELECT type, name, sql
683             FROM sqlite_master
684             WHERE sql IS NOT NULL
685               AND name NOT LIKE 'sqlite_%'
686               AND name NOT LIKE '_sqlx_%'
687             ORDER BY
688               CASE type
689                 WHEN 'table' THEN 1
690                 WHEN 'index' THEN 2
691                 WHEN 'trigger' THEN 3
692                 WHEN 'view' THEN 4
693                 ELSE 5
694               END,
695               name ASC",
696        )
697        .fetch_all(&self.read_pool)
698        .await?;
699
700        let mut out = String::from(
701            "-- Auto-generated by slabs-db (SQLite). Single-file schema truth for humans and agents.\n\n",
702        );
703        for (_kind, _name, sql) in rows {
704            if let Some(stmt) = sql {
705                out.push_str(stmt.trim());
706                if !stmt.trim_end().ends_with(';') {
707                    out.push(';');
708                }
709                out.push_str("\n\n");
710            }
711        }
712        Ok(out)
713    }
714
715    /// Reads a `.sql` file from disk and executes its statements against the writer pool.
716    ///
717    /// Intended for seed scripts such as `slabs db seed`. Empty or whitespace-only files are a no-op.
718    pub async fn execute_sql_file(&self, path: &Path) -> SlabResult<()> {
719        let sql = std::fs::read_to_string(path).map_err(|e| {
720            SlabError::internal(format!("failed to read SQL file {}: {e}", path.display()))
721        })?;
722        if sql.trim().is_empty() {
723            return Ok(());
724        }
725        sqlx::raw_sql(&sql).execute(&self.write_pool).await?;
726        Ok(())
727    }
728
729    /// Executes `SELECT 1` against the read pool to verify database connectivity.
730    pub async fn ping(&self) -> SlabResult<()> {
731        let _: (i64,) = sqlx::query_as("SELECT 1")
732            .fetch_one(&self.read_pool)
733            .await?;
734        Ok(())
735    }
736}
737
738/// Raw-SQL `PostgreSQL` database wrapper for multi-node deployments.
739#[derive(Debug, Clone)]
740pub struct PgDb {
741    pool: PgPool,
742}
743
744impl PgDb {
745    /// Connects to a `PostgreSQL` database with up to 20 pooled connections and a 5-second acquire timeout.
746    pub async fn connect(database_url: &str) -> SlabResult<Self> {
747        let pool = PgPoolOptions::new()
748            .max_connections(20)
749            .acquire_timeout(Duration::from_secs(5))
750            .connect(database_url)
751            .await?;
752        Ok(Self { pool })
753    }
754
755    /// Returns the underlying `sqlx` `PostgreSQL` connection pool.
756    #[must_use]
757    pub fn pool(&self) -> &PgPool {
758        &self.pool
759    }
760
761    /// Begins a new `PostgreSQL` transaction on the pool.
762    pub async fn begin(&self) -> SlabResult<Transaction<'_, Postgres>> {
763        Ok(self.pool.begin().await?)
764    }
765
766    /// Executes [`POSTGRES_SYSTEM_SCHEMA_SQL`] to create all 11 system tables idempotently.
767    pub async fn init_system_tables(&self) -> SlabResult<()> {
768        sqlx::raw_sql(POSTGRES_SYSTEM_SCHEMA_SQL)
769            .execute(&self.pool)
770            .await?;
771        Ok(())
772    }
773
774    /// Creates system tables if missing and runs all pending migrations from `migrator`.
775    ///
776    /// Wraps migration failures in [`SlabError::Internal`].
777    pub async fn migrate(&self, migrator: &Migrator) -> SlabResult<()> {
778        self.init_system_tables().await?;
779        migrator
780            .run(&self.pool)
781            .await
782            .map_err(|e| SlabError::internal(format!("postgres migration failed: {e}")))?;
783        Ok(())
784    }
785
786    /// Creates system tables if missing and runs all SQL migrations located in `dir`.
787    ///
788    /// Wraps directory load and migration failures in [`SlabError::Internal`].
789    pub async fn migrate_dir(&self, dir: &Path) -> SlabResult<()> {
790        self.init_system_tables().await?;
791        let migrator = Migrator::new(dir)
792            .await
793            .map_err(|e| SlabError::internal(format!("failed to load migrations: {e}")))?;
794        self.migrate(&migrator).await
795    }
796
797    /// Exports `public` schema tables and indexes from `information_schema.columns` and `pg_indexes`.
798    ///
799    /// Excludes `_sqlx_%` internal migration tables.
800    pub async fn dump_schema_sql(&self) -> SlabResult<String> {
801        let cols: Vec<(String, String, String, String, Option<String>)> = sqlx::query_as(
802            "SELECT table_name, column_name, data_type, is_nullable, column_default
803             FROM information_schema.columns
804             WHERE table_schema = 'public'
805               AND table_name NOT LIKE '_sqlx_%'
806             ORDER BY table_name ASC, ordinal_position ASC",
807        )
808        .fetch_all(&self.pool)
809        .await?;
810
811        let indexes: Vec<(String,)> = sqlx::query_as(
812            "SELECT indexdef
813             FROM pg_indexes
814             WHERE schemaname = 'public'
815               AND tablename NOT LIKE '_sqlx_%'
816             ORDER BY tablename ASC, indexname ASC",
817        )
818        .fetch_all(&self.pool)
819        .await?;
820
821        let mut out = String::from(
822            "-- Auto-generated by slabs-db (PostgreSQL). Single-file schema truth for humans and agents.\n\n",
823        );
824
825        let mut current_table: Option<String> = None;
826        for (table, col, dtype, nullable, default) in cols {
827            if current_table.as_deref() == Some(table.as_str()) {
828                out.push_str(",\n");
829            } else {
830                if current_table.is_some() {
831                    out.push_str(");\n\n");
832                }
833                let _ = writeln!(out, "CREATE TABLE {table} (");
834                current_table = Some(table);
835            }
836            let _ = write!(out, "    {col} {dtype}");
837            if nullable == "NO" {
838                out.push_str(" NOT NULL");
839            }
840            if let Some(def) = default {
841                let _ = write!(out, " DEFAULT {def}");
842            }
843        }
844        if current_table.is_some() {
845            out.push_str("\n);\n\n");
846        }
847
848        for (indexdef,) in indexes {
849            out.push_str(&indexdef);
850            if !indexdef.ends_with(';') {
851                out.push(';');
852            }
853            out.push_str("\n\n");
854        }
855
856        Ok(out)
857    }
858
859    /// Reads a `.sql` file from disk and executes its statements against the `PostgreSQL` pool.
860    ///
861    /// Intended for seed scripts such as `slabs db seed`. Empty or whitespace-only files are a no-op.
862    pub async fn execute_sql_file(&self, path: &Path) -> SlabResult<()> {
863        let sql = std::fs::read_to_string(path).map_err(|e| {
864            SlabError::internal(format!("failed to read SQL file {}: {e}", path.display()))
865        })?;
866        if sql.trim().is_empty() {
867            return Ok(());
868        }
869        sqlx::raw_sql(&sql).execute(&self.pool).await?;
870        Ok(())
871    }
872
873    /// Executes `SELECT 1` against the `PostgreSQL` pool to verify database connectivity.
874    pub async fn ping(&self) -> SlabResult<()> {
875        let _: (i32,) = sqlx::query_as("SELECT 1").fetch_one(&self.pool).await?;
876        Ok(())
877    }
878}
879
880#[cfg(test)]
881mod tests {
882    use super::*;
883
884    #[test]
885    fn detects_sqlite_and_postgres_urls() {
886        assert_eq!(DbEngine::detect("sqlite::memory:"), DbEngine::Sqlite);
887        assert_eq!(
888            DbEngine::detect("sqlite://app.db?mode=rwc"),
889            DbEngine::Sqlite
890        );
891        assert_eq!(
892            DbEngine::detect("postgres://user:pass@localhost:5432/slabs"),
893            DbEngine::Postgres
894        );
895        assert_eq!(
896            DbEngine::detect("postgresql://localhost/slabs"),
897            DbEngine::Postgres
898        );
899    }
900
901    #[test]
902    fn fts5_query_safely_quotes_user_input() {
903        assert_eq!(
904            fts5_query(r#"hello "world" fts5"#),
905            Some(r#""hello"* AND "world"* AND "fts5"*"#.to_string())
906        );
907        assert_eq!(fts5_query("   "), None);
908    }
909
910    #[tokio::test]
911    async fn split_wal_pools_handle_concurrent_writers_and_readers_without_sqlite_busy() {
912        let path =
913            std::env::temp_dir().join(format!("slabs_wal_stress_{}.db", slabs_core::id::new("db")));
914        let url = format!("sqlite://{}", path.display());
915        let db = Db::connect(&url).await.unwrap();
916        sqlx::query("CREATE TABLE items (id INTEGER PRIMARY KEY AUTOINCREMENT, val TEXT NOT NULL)")
917            .execute(db.writer())
918            .await
919            .unwrap();
920
921        let mut handles = Vec::new();
922        // 24 concurrent writers using BEGIN IMMEDIATE + 24 concurrent readers on WAL read_pool
923        for i in 0..24 {
924            let db_w = db.clone();
925            handles.push(tokio::spawn(async move {
926                let mut tx = db_w.begin().await.unwrap();
927                sqlx::query("INSERT INTO items (val) VALUES (?)")
928                    .bind(format!("item-{i}"))
929                    .execute(&mut *tx)
930                    .await
931                    .unwrap();
932                tx.commit().await.unwrap();
933            }));
934
935            let db_r = db.clone();
936            handles.push(tokio::spawn(async move {
937                let _count: (i64,) = sqlx::query_as("SELECT COUNT(*) FROM items")
938                    .fetch_one(db_r.reader())
939                    .await
940                    .unwrap();
941            }));
942        }
943
944        for h in handles {
945            h.await.unwrap();
946        }
947
948        let (total,): (i64,) = sqlx::query_as("SELECT COUNT(*) FROM items")
949            .fetch_one(db.reader())
950            .await
951            .unwrap();
952        assert_eq!(total, 24);
953
954        let _ = std::fs::remove_file(&path);
955        let _ = std::fs::remove_file(format!("{}-wal", path.display()));
956        let _ = std::fs::remove_file(format!("{}-shm", path.display()));
957    }
958
959    #[test]
960    fn pagination_clamps_limits_and_computes_fetch_limit() {
961        let default_page = Pagination::default();
962        assert_eq!(default_page.clamped_limit(20, 100), 20);
963        assert_eq!(default_page.fetch_limit(20, 100), 21);
964
965        let zero_page = Pagination {
966            limit: Some(0),
967            cursor: None,
968        };
969        assert_eq!(zero_page.clamped_limit(20, 100), 1);
970        assert_eq!(zero_page.fetch_limit(20, 100), 2);
971
972        let huge_page = Pagination {
973            limit: Some(500),
974            cursor: Some("cur_1".into()),
975        };
976        assert_eq!(huge_page.clamped_limit(20, 100), 100);
977        assert_eq!(huge_page.fetch_limit(20, 100), 101);
978        assert_eq!(huge_page.cursor.as_deref(), Some("cur_1"));
979    }
980
981    #[test]
982    fn cursor_page_from_rows_truncates_and_sets_next_cursor() {
983        let page = CursorPage::from_rows(vec![10, 20, 30], 2, ToString::to_string);
984        assert_eq!(page.items, vec![10, 20]);
985        assert!(page.has_more);
986        assert_eq!(page.next_cursor.as_deref(), Some("20"));
987
988        let exact = CursorPage::from_rows(vec![10, 20], 2, ToString::to_string);
989        assert_eq!(exact.items, vec![10, 20]);
990        assert!(!exact.has_more);
991        assert!(exact.next_cursor.is_none());
992
993        let empty = CursorPage::from_rows(Vec::<i32>::new(), 2, ToString::to_string);
994        assert_eq!(empty.items, Vec::<i32>::new());
995        assert!(!empty.has_more);
996        assert!(empty.next_cursor.is_none());
997    }
998
999    #[tokio::test]
1000    async fn audit_log_commits_and_rolls_back_atomically_with_tx() {
1001        let db = Db::connect("sqlite::memory:").await.unwrap();
1002        db.init_system_tables().await.unwrap();
1003        let audit = AuditLog::new(db.clone());
1004
1005        // Committed transaction persists audit entry
1006        let mut tx = db.begin().await.unwrap();
1007        let entry_id = audit
1008            .record_in_tx(
1009                &mut tx,
1010                Some("usr_1"),
1011                "room.created",
1012                "room",
1013                "room_1",
1014                &serde_json::json!({ "name": "Lobby" }),
1015            )
1016            .await
1017            .unwrap();
1018        assert!(entry_id.starts_with("aud_"));
1019        tx.commit().await.unwrap();
1020
1021        // Rolled back transaction does not persist audit entry
1022        let mut rollback_tx = db.begin().await.unwrap();
1023        let _rolled_back_id = audit
1024            .record_in_tx(
1025                &mut rollback_tx,
1026                Some("usr_2"),
1027                "room.deleted",
1028                "room",
1029                "room_1",
1030                &serde_json::json!({ "reason": "rolled back" }),
1031            )
1032            .await
1033            .unwrap();
1034        rollback_tx.rollback().await.unwrap();
1035
1036        // Second committed entry on another target to verify filtering
1037        let mut tx2 = db.begin().await.unwrap();
1038        let _other_id = audit
1039            .record_in_tx(
1040                &mut tx2,
1041                None,
1042                "user.invited",
1043                "user",
1044                "usr_9",
1045                &serde_json::json!({}),
1046            )
1047            .await
1048            .unwrap();
1049        tx2.commit().await.unwrap();
1050
1051        let room_entries = audit.list_for_target("room", "room_1", 10).await.unwrap();
1052        assert_eq!(room_entries.len(), 1);
1053        assert_eq!(room_entries[0].id, entry_id);
1054        assert_eq!(room_entries[0].actor_id.as_deref(), Some("usr_1"));
1055        assert_eq!(room_entries[0].action, "room.created");
1056        assert_eq!(room_entries[0].target_type, "room");
1057        assert_eq!(room_entries[0].target_id, "room_1");
1058        assert_eq!(room_entries[0].metadata_json, r#"{"name":"Lobby"}"#);
1059
1060        let recent = audit.list_recent(10).await.unwrap();
1061        assert_eq!(recent.len(), 2);
1062
1063        let recent_limited = audit.list_recent(1).await.unwrap();
1064        assert_eq!(recent_limited.len(), 1);
1065    }
1066
1067    #[tokio::test]
1068    async fn execute_sql_file_runs_seed_statements_and_handles_empty_or_missing() {
1069        let db = Db::connect("sqlite::memory:").await.unwrap();
1070        db.init_system_tables().await.unwrap();
1071
1072        let seed_path = std::env::temp_dir().join(format!(
1073            "slabs_seed_test_{}.sql",
1074            slabs_core::id::new("sql")
1075        ));
1076        std::fs::write(
1077            &seed_path,
1078            "CREATE TABLE widgets (id TEXT PRIMARY KEY, name TEXT NOT NULL);\n\
1079             INSERT INTO widgets (id, name) VALUES ('w_1', 'Alpha');\n\
1080             INSERT INTO widgets (id, name) VALUES ('w_2', 'Beta');\n",
1081        )
1082        .unwrap();
1083
1084        db.execute_sql_file(&seed_path).await.unwrap();
1085        let (count,): (i64,) = sqlx::query_as("SELECT COUNT(*) FROM widgets")
1086            .fetch_one(db.reader())
1087            .await
1088            .unwrap();
1089        assert_eq!(count, 2);
1090
1091        // Blank seed file is a no-op
1092        std::fs::write(&seed_path, "   \n\t  ").unwrap();
1093        db.execute_sql_file(&seed_path).await.unwrap();
1094        let _ = std::fs::remove_file(&seed_path);
1095
1096        // Missing file returns an internal error
1097        let missing = std::env::temp_dir().join("slabs_definitely_missing_seed.sql");
1098        assert!(db.execute_sql_file(&missing).await.is_err());
1099
1100        // Both system schemas declare the new v0.2.0 system tables
1101        assert!(SYSTEM_SCHEMA_SQL.contains("slabs_idempotency_keys"));
1102        assert!(SYSTEM_SCHEMA_SQL.contains("slabs_audit_log"));
1103        assert!(POSTGRES_SYSTEM_SCHEMA_SQL.contains("slabs_idempotency_keys"));
1104        assert!(POSTGRES_SYSTEM_SCHEMA_SQL.contains("slabs_audit_log"));
1105    }
1106}