slabs-db 0.1.0

Low-level SQLite/SQLx raw-SQL battery with WAL tuning, explicit transactions, migrations, and schema.sql dump
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
//! Raw-SQL database library for Slabs.
//!
//! This crate owns the tuned `SQLite` WAL wrapper ([`Db`]), the optional `PostgreSQL` wrapper ([`PgDb`]),
//! URL engine detection ([`DbEngine`]), framework system schemas ([`SYSTEM_SCHEMA_SQL`], [`POSTGRES_SYSTEM_SCHEMA_SQL`]),
//! and FTS5 query escaping ([`fts5_query`]). It also re-exports [`QueryBuilder`] for dynamic parameterized SQL.
//!
//! # Owned types and system tables
//!
//! Calling [`Db::init_system_tables`], [`Db::migrate`], or [`Db::migrate_dir`] (and the matching [`PgDb`] methods)
//! creates these 9 framework tables if they do not exist:
//!
//! - `slabs_sessions`
//! - `slabs_magic_links`
//! - `slabs_access_tokens`
//! - `slabs_jobs`
//! - `slabs_cache`
//! - `slabs_mail_outbox`
//! - `slabs_blobs`
//! - `slabs_webhooks`
//! - `slabs_webhook_deliveries`
//!
//! # Invariants
//!
//! - **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)`).
//! - **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.
//! - **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.
//! - **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).
//! - **Parameterized SQL only**: always bind untrusted input with `sqlx::query`, `sqlx::query_as`, or [`QueryBuilder`]. Never interpolate user strings into SQL text.
//! - **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`.
//!
//! # Usage
//!
//! ```rust,no_run
//! use slabs_core::SlabResult;
//! use slabs_db::{fts5_query, Db};
//!
//! async fn example() -> SlabResult<()> {
//!     let db = Db::connect("sqlite://app.db?mode=rwc").await?;
//!     db.init_system_tables().await?;
//!
//!     // Concurrent SELECT on the read-only WAL pool.
//!     let (count,): (i64,) = sqlx::query_as("SELECT COUNT(*) FROM slabs_jobs")
//!         .fetch_one(db.reader())
//!         .await?;
//!
//!     // Multi-step write inside an explicit BEGIN IMMEDIATE transaction.
//!     let mut tx = db.begin().await?;
//!     sqlx::query("DELETE FROM slabs_cache WHERE cache_key = ?")
//!         .bind("stale_key")
//!         .execute(&mut *tx)
//!         .await?;
//!     tx.commit().await?;
//!
//!     // Safe FTS5 query construction for user input.
//!     if let Some(match_expr) = fts5_query("deploy \"prod\"") {
//!         assert_eq!(match_expr, "\"deploy\"* AND \"prod\"*");
//!     }
//!     let _ = count;
//!     Ok(())
//! }
//! ```

use slabs_core::{SlabError, SlabResult};
use sqlx::{
    migrate::Migrator,
    postgres::PgPoolOptions,
    sqlite::{SqliteConnectOptions, SqliteJournalMode, SqlitePoolOptions, SqliteSynchronous},
    PgPool, Postgres, Sqlite, SqlitePool, Transaction,
};
use std::fmt::Write as _;
use std::path::Path;
use std::str::FromStr;
use std::time::Duration;

pub use sqlx::QueryBuilder;

/// Database engine detected from a `DATABASE_URL` string.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DbEngine {
    /// Embedded `SQLite` database.
    Sqlite,
    /// Networked `PostgreSQL` database.
    Postgres,
}

impl DbEngine {
    /// Detects the [`DbEngine`] from a database connection URL.
    ///
    /// Returns [`DbEngine::Postgres`] when the trimmed, lowercased URL starts with
    /// `"postgres://"` or `"postgresql://"`, and [`DbEngine::Sqlite`] otherwise.
    #[must_use]
    pub fn detect(database_url: &str) -> Self {
        let lower = database_url.trim().to_ascii_lowercase();
        if lower.starts_with("postgres://") || lower.starts_with("postgresql://") {
            Self::Postgres
        } else {
            Self::Sqlite
        }
    }
}

/// Framework-owned `SQLite` DDL for the 9 system tables and their indexes.
///
/// Applied idempotently by [`Db::init_system_tables`], [`Db::migrate`], and [`Db::migrate_dir`].
pub const SYSTEM_SCHEMA_SQL: &str = r"
CREATE TABLE IF NOT EXISTS slabs_sessions (
    id TEXT PRIMARY KEY NOT NULL,
    user_id TEXT NOT NULL,
    role TEXT NOT NULL DEFAULT 'member',
    token_hash TEXT NOT NULL UNIQUE,
    expires_at TEXT NOT NULL,
    created_at TEXT NOT NULL
);
CREATE INDEX IF NOT EXISTS idx_slabs_sessions_user_id ON slabs_sessions(user_id);
CREATE INDEX IF NOT EXISTS idx_slabs_sessions_expires_at ON slabs_sessions(expires_at);

CREATE TABLE IF NOT EXISTS slabs_magic_links (
    id TEXT PRIMARY KEY NOT NULL,
    email TEXT NOT NULL,
    purpose TEXT NOT NULL DEFAULT 'sign_in',
    code_hash TEXT NOT NULL UNIQUE,
    expires_at TEXT NOT NULL,
    created_at TEXT NOT NULL
);
CREATE INDEX IF NOT EXISTS idx_slabs_magic_links_expires_at ON slabs_magic_links(expires_at);

CREATE TABLE IF NOT EXISTS slabs_access_tokens (
    id TEXT PRIMARY KEY NOT NULL,
    user_id TEXT NOT NULL,
    role TEXT NOT NULL DEFAULT 'member',
    description TEXT NOT NULL DEFAULT '',
    permission TEXT NOT NULL DEFAULT 'write',
    token_hash TEXT NOT NULL UNIQUE,
    last_used_at TEXT,
    expires_at TEXT,
    created_at TEXT NOT NULL
);
CREATE INDEX IF NOT EXISTS idx_slabs_access_tokens_user_id ON slabs_access_tokens(user_id);

CREATE TABLE IF NOT EXISTS slabs_jobs (
    id TEXT PRIMARY KEY NOT NULL,
    job_name TEXT NOT NULL,
    queue TEXT NOT NULL DEFAULT 'default',
    payload_json TEXT NOT NULL,
    status TEXT NOT NULL DEFAULT 'pending',
    attempts INTEGER NOT NULL DEFAULT 0,
    max_attempts INTEGER NOT NULL DEFAULT 5,
    run_at TEXT NOT NULL,
    last_error TEXT,
    created_at TEXT NOT NULL,
    updated_at TEXT NOT NULL
);
CREATE INDEX IF NOT EXISTS idx_slabs_jobs_poll ON slabs_jobs(status, run_at, created_at);

CREATE TABLE IF NOT EXISTS slabs_cache (
    cache_key TEXT PRIMARY KEY NOT NULL,
    value_text TEXT NOT NULL,
    expires_at TEXT NOT NULL,
    updated_at TEXT NOT NULL
);
CREATE INDEX IF NOT EXISTS idx_slabs_cache_expires_at ON slabs_cache(expires_at);

CREATE TABLE IF NOT EXISTS slabs_mail_outbox (
    id TEXT PRIMARY KEY NOT NULL,
    from_addr TEXT NOT NULL,
    to_addr TEXT NOT NULL,
    subject TEXT NOT NULL,
    text_body TEXT NOT NULL,
    html_body TEXT,
    sent_at TEXT NOT NULL
);

CREATE TABLE IF NOT EXISTS slabs_blobs (
    id TEXT PRIMARY KEY NOT NULL,
    filename TEXT NOT NULL,
    content_type TEXT NOT NULL,
    byte_size INTEGER NOT NULL,
    checksum_sha256 TEXT NOT NULL,
    storage_key TEXT NOT NULL UNIQUE,
    created_at TEXT NOT NULL
);

CREATE TABLE IF NOT EXISTS slabs_webhooks (
    id TEXT PRIMARY KEY NOT NULL,
    scope_id TEXT NOT NULL,
    name TEXT NOT NULL,
    url TEXT NOT NULL,
    signing_secret TEXT NOT NULL,
    subscribed_actions_json TEXT NOT NULL,
    active INTEGER NOT NULL DEFAULT 1,
    created_at TEXT NOT NULL
);
CREATE INDEX IF NOT EXISTS idx_slabs_webhooks_scope ON slabs_webhooks(scope_id, active);

CREATE TABLE IF NOT EXISTS slabs_webhook_deliveries (
    id TEXT PRIMARY KEY NOT NULL,
    webhook_id TEXT NOT NULL REFERENCES slabs_webhooks(id) ON DELETE CASCADE,
    action TEXT NOT NULL,
    payload_json TEXT NOT NULL,
    signature TEXT NOT NULL,
    status TEXT NOT NULL DEFAULT 'pending',
    response_status INTEGER,
    last_error TEXT,
    created_at TEXT NOT NULL,
    delivered_at TEXT
);
CREATE INDEX IF NOT EXISTS idx_slabs_webhook_deliveries_webhook ON slabs_webhook_deliveries(webhook_id, created_at DESC);
";

/// Framework-owned `PostgreSQL` DDL for the 9 system tables and their indexes.
///
/// Uses `TIMESTAMPTZ`, `JSONB`, `BIGINT`, and `BOOLEAN` column types.
/// Applied idempotently by [`PgDb::init_system_tables`], [`PgDb::migrate`], and [`PgDb::migrate_dir`].
pub const POSTGRES_SYSTEM_SCHEMA_SQL: &str = r"
CREATE TABLE IF NOT EXISTS slabs_sessions (
    id TEXT PRIMARY KEY NOT NULL,
    user_id TEXT NOT NULL,
    role TEXT NOT NULL DEFAULT 'member',
    token_hash TEXT NOT NULL UNIQUE,
    expires_at TIMESTAMPTZ NOT NULL,
    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
CREATE INDEX IF NOT EXISTS idx_slabs_sessions_user_id ON slabs_sessions(user_id);
CREATE INDEX IF NOT EXISTS idx_slabs_sessions_expires_at ON slabs_sessions(expires_at);

CREATE TABLE IF NOT EXISTS slabs_magic_links (
    id TEXT PRIMARY KEY NOT NULL,
    email TEXT NOT NULL,
    purpose TEXT NOT NULL DEFAULT 'sign_in',
    code_hash TEXT NOT NULL UNIQUE,
    expires_at TIMESTAMPTZ NOT NULL,
    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
CREATE INDEX IF NOT EXISTS idx_slabs_magic_links_expires_at ON slabs_magic_links(expires_at);

CREATE TABLE IF NOT EXISTS slabs_access_tokens (
    id TEXT PRIMARY KEY NOT NULL,
    user_id TEXT NOT NULL,
    role TEXT NOT NULL DEFAULT 'member',
    description TEXT NOT NULL DEFAULT '',
    permission TEXT NOT NULL DEFAULT 'write',
    token_hash TEXT NOT NULL UNIQUE,
    last_used_at TIMESTAMPTZ,
    expires_at TIMESTAMPTZ,
    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
CREATE INDEX IF NOT EXISTS idx_slabs_access_tokens_user_id ON slabs_access_tokens(user_id);

CREATE TABLE IF NOT EXISTS slabs_jobs (
    id TEXT PRIMARY KEY NOT NULL,
    job_name TEXT NOT NULL,
    queue TEXT NOT NULL DEFAULT 'default',
    payload_json JSONB NOT NULL,
    status TEXT NOT NULL DEFAULT 'pending',
    attempts BIGINT NOT NULL DEFAULT 0,
    max_attempts BIGINT NOT NULL DEFAULT 5,
    run_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    last_error TEXT,
    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
CREATE INDEX IF NOT EXISTS idx_slabs_jobs_poll ON slabs_jobs(status, run_at, created_at);

CREATE TABLE IF NOT EXISTS slabs_cache (
    cache_key TEXT PRIMARY KEY NOT NULL,
    value_text TEXT NOT NULL,
    expires_at TIMESTAMPTZ NOT NULL,
    updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
CREATE INDEX IF NOT EXISTS idx_slabs_cache_expires_at ON slabs_cache(expires_at);

CREATE TABLE IF NOT EXISTS slabs_mail_outbox (
    id TEXT PRIMARY KEY NOT NULL,
    from_addr TEXT NOT NULL,
    to_addr TEXT NOT NULL,
    subject TEXT NOT NULL,
    text_body TEXT NOT NULL,
    html_body TEXT,
    sent_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

CREATE TABLE IF NOT EXISTS slabs_blobs (
    id TEXT PRIMARY KEY NOT NULL,
    filename TEXT NOT NULL,
    content_type TEXT NOT NULL,
    byte_size BIGINT NOT NULL,
    checksum_sha256 TEXT NOT NULL,
    storage_key TEXT NOT NULL UNIQUE,
    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

CREATE TABLE IF NOT EXISTS slabs_webhooks (
    id TEXT PRIMARY KEY NOT NULL,
    scope_id TEXT NOT NULL,
    name TEXT NOT NULL,
    url TEXT NOT NULL,
    signing_secret TEXT NOT NULL,
    subscribed_actions_json JSONB NOT NULL,
    active BOOLEAN NOT NULL DEFAULT TRUE,
    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
CREATE INDEX IF NOT EXISTS idx_slabs_webhooks_scope ON slabs_webhooks(scope_id, active);

CREATE TABLE IF NOT EXISTS slabs_webhook_deliveries (
    id TEXT PRIMARY KEY NOT NULL,
    webhook_id TEXT NOT NULL REFERENCES slabs_webhooks(id) ON DELETE CASCADE,
    action TEXT NOT NULL,
    payload_json JSONB NOT NULL,
    signature TEXT NOT NULL,
    status TEXT NOT NULL DEFAULT 'pending',
    response_status INTEGER,
    last_error TEXT,
    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    delivered_at TIMESTAMPTZ
);
CREATE INDEX IF NOT EXISTS idx_slabs_webhook_deliveries_webhook ON slabs_webhook_deliveries(webhook_id, created_at DESC);
";

/// Converts untrusted user search text into an FTS5 prefix-AND `MATCH` expression.
///
/// Splits on whitespace, strips `"` characters from every token, wraps each remaining
/// token as `"token"*`, and joins them with `AND`.
/// Returns `None` when the input contains no non-empty tokens after stripping quotes.
#[must_use]
pub fn fts5_query(raw: &str) -> Option<String> {
    let terms: Vec<String> = raw
        .split_whitespace()
        .map(|tok| tok.replace('"', ""))
        .filter(|tok| !tok.is_empty())
        .map(|tok| format!("\"{tok}\"*"))
        .collect();
    if terms.is_empty() {
        None
    } else {
        Some(terms.join(" AND "))
    }
}

/// Raw-SQL `SQLite` database wrapper tuned for concurrent WAL workloads.
///
/// Holds two pools on file-backed databases:
/// - A single-connection writer pool (`max_connections(1)`) used by [`Db::writer`], [`Db::pool`], and [`Db::begin`] (`BEGIN IMMEDIATE`).
/// - A 16-connection read-only pool used by [`Db::reader`] for parallel `SELECT` queries.
///
/// In-memory databases (`sqlite::memory:` or `mode=memory`) share the single writer pool for both reads and writes.
#[derive(Debug, Clone)]
pub struct Db {
    read_pool: SqlitePool,
    write_pool: SqlitePool,
}

impl Db {
    /// Connects to a `SQLite` database with tuned WAL pragmas and split read/write pools.
    ///
    /// Creates the database file when missing and enables `foreign_keys = ON`, `synchronous = NORMAL`,
    /// `cache_size = -64000`, and `temp_store = MEMORY`. File-backed databases also enable
    /// `journal_mode = WAL`, `mmap_size = 268435456`, and a separate 16-connection read-only pool.
    /// Returns [`SlabError::Internal`] if `database_url` cannot be parsed.
    pub async fn connect(database_url: &str) -> SlabResult<Self> {
        let is_memory = database_url == "sqlite::memory:" || database_url.contains("mode=memory");

        let mut write_opts = SqliteConnectOptions::from_str(database_url)
            .map_err(|e| SlabError::internal(format!("invalid DATABASE_URL: {e}")))?
            .create_if_missing(true)
            .foreign_keys(true)
            .busy_timeout(Duration::from_secs(10))
            .synchronous(SqliteSynchronous::Normal)
            .pragma("cache_size", "-64000")
            .pragma("temp_store", "MEMORY");

        if !is_memory {
            write_opts = write_opts
                .journal_mode(SqliteJournalMode::Wal)
                .pragma("mmap_size", "268435456");
        }

        // Single dedicated writer guarantees serialized writes without SQLITE_BUSY thrashing.
        let write_pool = SqlitePoolOptions::new()
            .max_connections(1)
            .acquire_timeout(Duration::from_secs(10))
            .connect_with(write_opts)
            .await?;

        let read_pool = if is_memory {
            // In-memory SQLite databases are per-connection, so share the single pool in tests.
            write_pool.clone()
        } else {
            let read_opts = SqliteConnectOptions::from_str(database_url)
                .map_err(|e| SlabError::internal(format!("invalid DATABASE_URL: {e}")))?
                .read_only(true)
                .foreign_keys(true)
                .busy_timeout(Duration::from_secs(5))
                .pragma("cache_size", "-64000")
                .pragma("temp_store", "MEMORY")
                .pragma("mmap_size", "268435456");

            SqlitePoolOptions::new()
                .max_connections(16)
                .acquire_timeout(Duration::from_secs(5))
                .connect_with(read_opts)
                .await?
        };

        Ok(Self {
            read_pool,
            write_pool,
        })
    }

    /// Returns the default pool, which aliases the single-connection writer pool.
    ///
    /// Prefer [`Db::reader`] for read-only `SELECT` queries so reads run concurrently on file-backed databases.
    #[must_use]
    pub fn pool(&self) -> &SqlitePool {
        &self.write_pool
    }

    /// Returns the concurrent read-only WAL pool (up to 16 connections on file-backed databases).
    ///
    /// Use this pool for `SELECT` queries. Executing write statements on a file-backed reader pool fails.
    #[must_use]
    pub fn reader(&self) -> &SqlitePool {
        &self.read_pool
    }

    /// Returns the dedicated single-connection writer pool (`max_connections(1)`).
    ///
    /// Serializes writes in-process with a 10-second `busy_timeout` to prevent `SQLITE_BUSY` thrashing.
    #[must_use]
    pub fn writer(&self) -> &SqlitePool {
        &self.write_pool
    }

    /// Opens an explicit `BEGIN IMMEDIATE` transaction on the single writer connection.
    ///
    /// Acquires the write lock at transaction start, avoiding deferred lock-upgrade `SQLITE_BUSY_SNAPSHOT` errors.
    pub async fn begin(&self) -> SlabResult<Transaction<'_, Sqlite>> {
        Ok(self.write_pool.begin_with("BEGIN IMMEDIATE").await?)
    }

    /// Executes [`SYSTEM_SCHEMA_SQL`] against the writer pool to create all 9 system tables idempotently.
    pub async fn init_system_tables(&self) -> SlabResult<()> {
        sqlx::raw_sql(SYSTEM_SCHEMA_SQL)
            .execute(&self.write_pool)
            .await?;
        Ok(())
    }

    /// Creates system tables if missing and runs all pending migrations from `migrator` on the writer pool.
    ///
    /// Wraps migration failures in [`SlabError::Internal`].
    pub async fn migrate(&self, migrator: &Migrator) -> SlabResult<()> {
        self.init_system_tables().await?;
        migrator
            .run(&self.write_pool)
            .await
            .map_err(|e| SlabError::internal(format!("migration failed: {e}")))?;
        Ok(())
    }

    /// Creates system tables if missing and runs all SQL migrations located in `dir` on the writer pool.
    ///
    /// Wraps directory load and migration failures in [`SlabError::Internal`].
    pub async fn migrate_dir(&self, dir: &Path) -> SlabResult<()> {
        self.init_system_tables().await?;
        let migrator = Migrator::new(dir)
            .await
            .map_err(|e| SlabError::internal(format!("failed to load migrations: {e}")))?;
        self.migrate(&migrator).await
    }

    /// Exports the current `SQLite` schema DDL from `sqlite_master` on the read pool.
    ///
    /// Excludes internal `sqlite_%` and `_sqlx_%` objects and orders statements by table, index, trigger, then view.
    pub async fn dump_schema_sql(&self) -> SlabResult<String> {
        let rows: Vec<(String, String, Option<String>)> = sqlx::query_as(
            "SELECT type, name, sql
             FROM sqlite_master
             WHERE sql IS NOT NULL
               AND name NOT LIKE 'sqlite_%'
               AND name NOT LIKE '_sqlx_%'
             ORDER BY
               CASE type
                 WHEN 'table' THEN 1
                 WHEN 'index' THEN 2
                 WHEN 'trigger' THEN 3
                 WHEN 'view' THEN 4
                 ELSE 5
               END,
               name ASC",
        )
        .fetch_all(&self.read_pool)
        .await?;

        let mut out = String::from(
            "-- Auto-generated by slabs-db (SQLite). Single-file schema truth for humans and agents.\n\n",
        );
        for (_kind, _name, sql) in rows {
            if let Some(stmt) = sql {
                out.push_str(stmt.trim());
                if !stmt.trim_end().ends_with(';') {
                    out.push(';');
                }
                out.push_str("\n\n");
            }
        }
        Ok(out)
    }

    /// Executes `SELECT 1` against the read pool to verify database connectivity.
    pub async fn ping(&self) -> SlabResult<()> {
        let _: (i64,) = sqlx::query_as("SELECT 1")
            .fetch_one(&self.read_pool)
            .await?;
        Ok(())
    }
}

/// Raw-SQL `PostgreSQL` database wrapper for multi-node deployments.
#[derive(Debug, Clone)]
pub struct PgDb {
    pool: PgPool,
}

impl PgDb {
    /// Connects to a `PostgreSQL` database with up to 20 pooled connections and a 5-second acquire timeout.
    pub async fn connect(database_url: &str) -> SlabResult<Self> {
        let pool = PgPoolOptions::new()
            .max_connections(20)
            .acquire_timeout(Duration::from_secs(5))
            .connect(database_url)
            .await?;
        Ok(Self { pool })
    }

    /// Returns the underlying `sqlx` `PostgreSQL` connection pool.
    #[must_use]
    pub fn pool(&self) -> &PgPool {
        &self.pool
    }

    /// Begins a new `PostgreSQL` transaction on the pool.
    pub async fn begin(&self) -> SlabResult<Transaction<'_, Postgres>> {
        Ok(self.pool.begin().await?)
    }

    /// Executes [`POSTGRES_SYSTEM_SCHEMA_SQL`] to create all 9 system tables idempotently.
    pub async fn init_system_tables(&self) -> SlabResult<()> {
        sqlx::raw_sql(POSTGRES_SYSTEM_SCHEMA_SQL)
            .execute(&self.pool)
            .await?;
        Ok(())
    }

    /// Creates system tables if missing and runs all pending migrations from `migrator`.
    ///
    /// Wraps migration failures in [`SlabError::Internal`].
    pub async fn migrate(&self, migrator: &Migrator) -> SlabResult<()> {
        self.init_system_tables().await?;
        migrator
            .run(&self.pool)
            .await
            .map_err(|e| SlabError::internal(format!("postgres migration failed: {e}")))?;
        Ok(())
    }

    /// Creates system tables if missing and runs all SQL migrations located in `dir`.
    ///
    /// Wraps directory load and migration failures in [`SlabError::Internal`].
    pub async fn migrate_dir(&self, dir: &Path) -> SlabResult<()> {
        self.init_system_tables().await?;
        let migrator = Migrator::new(dir)
            .await
            .map_err(|e| SlabError::internal(format!("failed to load migrations: {e}")))?;
        self.migrate(&migrator).await
    }

    /// Exports `public` schema tables and indexes from `information_schema.columns` and `pg_indexes`.
    ///
    /// Excludes `_sqlx_%` internal migration tables.
    pub async fn dump_schema_sql(&self) -> SlabResult<String> {
        let cols: Vec<(String, String, String, String, Option<String>)> = sqlx::query_as(
            "SELECT table_name, column_name, data_type, is_nullable, column_default
             FROM information_schema.columns
             WHERE table_schema = 'public'
               AND table_name NOT LIKE '_sqlx_%'
             ORDER BY table_name ASC, ordinal_position ASC",
        )
        .fetch_all(&self.pool)
        .await?;

        let indexes: Vec<(String,)> = sqlx::query_as(
            "SELECT indexdef
             FROM pg_indexes
             WHERE schemaname = 'public'
               AND tablename NOT LIKE '_sqlx_%'
             ORDER BY tablename ASC, indexname ASC",
        )
        .fetch_all(&self.pool)
        .await?;

        let mut out = String::from(
            "-- Auto-generated by slabs-db (PostgreSQL). Single-file schema truth for humans and agents.\n\n",
        );

        let mut current_table: Option<String> = None;
        for (table, col, dtype, nullable, default) in cols {
            if current_table.as_deref() == Some(table.as_str()) {
                out.push_str(",\n");
            } else {
                if current_table.is_some() {
                    out.push_str(");\n\n");
                }
                let _ = writeln!(out, "CREATE TABLE {table} (");
                current_table = Some(table);
            }
            let _ = write!(out, "    {col} {dtype}");
            if nullable == "NO" {
                out.push_str(" NOT NULL");
            }
            if let Some(def) = default {
                let _ = write!(out, " DEFAULT {def}");
            }
        }
        if current_table.is_some() {
            out.push_str("\n);\n\n");
        }

        for (indexdef,) in indexes {
            out.push_str(&indexdef);
            if !indexdef.ends_with(';') {
                out.push(';');
            }
            out.push_str("\n\n");
        }

        Ok(out)
    }

    /// Executes `SELECT 1` against the `PostgreSQL` pool to verify database connectivity.
    pub async fn ping(&self) -> SlabResult<()> {
        let _: (i32,) = sqlx::query_as("SELECT 1").fetch_one(&self.pool).await?;
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn detects_sqlite_and_postgres_urls() {
        assert_eq!(DbEngine::detect("sqlite::memory:"), DbEngine::Sqlite);
        assert_eq!(
            DbEngine::detect("sqlite://app.db?mode=rwc"),
            DbEngine::Sqlite
        );
        assert_eq!(
            DbEngine::detect("postgres://user:pass@localhost:5432/slabs"),
            DbEngine::Postgres
        );
        assert_eq!(
            DbEngine::detect("postgresql://localhost/slabs"),
            DbEngine::Postgres
        );
    }

    #[test]
    fn fts5_query_safely_quotes_user_input() {
        assert_eq!(
            fts5_query(r#"hello "world" fts5"#),
            Some(r#""hello"* AND "world"* AND "fts5"*"#.to_string())
        );
        assert_eq!(fts5_query("   "), None);
    }

    #[tokio::test]
    async fn split_wal_pools_handle_concurrent_writers_and_readers_without_sqlite_busy() {
        let path =
            std::env::temp_dir().join(format!("slabs_wal_stress_{}.db", slabs_core::id::new("db")));
        let url = format!("sqlite://{}", path.display());
        let db = Db::connect(&url).await.unwrap();
        sqlx::query("CREATE TABLE items (id INTEGER PRIMARY KEY AUTOINCREMENT, val TEXT NOT NULL)")
            .execute(db.writer())
            .await
            .unwrap();

        let mut handles = Vec::new();
        // 24 concurrent writers using BEGIN IMMEDIATE + 24 concurrent readers on WAL read_pool
        for i in 0..24 {
            let db_w = db.clone();
            handles.push(tokio::spawn(async move {
                let mut tx = db_w.begin().await.unwrap();
                sqlx::query("INSERT INTO items (val) VALUES (?)")
                    .bind(format!("item-{i}"))
                    .execute(&mut *tx)
                    .await
                    .unwrap();
                tx.commit().await.unwrap();
            }));

            let db_r = db.clone();
            handles.push(tokio::spawn(async move {
                let _count: (i64,) = sqlx::query_as("SELECT COUNT(*) FROM items")
                    .fetch_one(db_r.reader())
                    .await
                    .unwrap();
            }));
        }

        for h in handles {
            h.await.unwrap();
        }

        let (total,): (i64,) = sqlx::query_as("SELECT COUNT(*) FROM items")
            .fetch_one(db.reader())
            .await
            .unwrap();
        assert_eq!(total, 24);

        let _ = std::fs::remove_file(&path);
        let _ = std::fs::remove_file(format!("{}-wal", path.display()));
        let _ = std::fs::remove_file(format!("{}-shm", path.display()));
    }
}