slabs-db 0.2.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
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
//! 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 11 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`
//! - `slabs_idempotency_keys`
//! - `slabs_audit_log`
//!
//! # 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 11 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);

CREATE TABLE IF NOT EXISTS slabs_idempotency_keys (
    scope TEXT NOT NULL,
    key TEXT NOT NULL,
    response_json TEXT,
    created_at TEXT NOT NULL,
    PRIMARY KEY (scope, key)
);

CREATE TABLE IF NOT EXISTS slabs_audit_log (
    id TEXT PRIMARY KEY NOT NULL,
    actor_id TEXT,
    action TEXT NOT NULL,
    target_type TEXT NOT NULL,
    target_id TEXT NOT NULL,
    metadata_json TEXT NOT NULL DEFAULT '{}',
    created_at TEXT NOT NULL
);
CREATE INDEX IF NOT EXISTS idx_slabs_audit_log_target ON slabs_audit_log (target_type, target_id, created_at DESC);
";

/// Framework-owned `PostgreSQL` DDL for the 11 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);

CREATE TABLE IF NOT EXISTS slabs_idempotency_keys (
    scope TEXT NOT NULL,
    key TEXT NOT NULL,
    response_json TEXT,
    created_at TEXT NOT NULL,
    PRIMARY KEY (scope, key)
);

CREATE TABLE IF NOT EXISTS slabs_audit_log (
    id TEXT PRIMARY KEY NOT NULL,
    actor_id TEXT,
    action TEXT NOT NULL,
    target_type TEXT NOT NULL,
    target_id TEXT NOT NULL,
    metadata_json TEXT NOT NULL DEFAULT '{}',
    created_at TEXT NOT NULL
);
CREATE INDEX IF NOT EXISTS idx_slabs_audit_log_target ON slabs_audit_log (target_type, target_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 "))
    }
}

/// Query parameters for cursor-based (keyset) pagination.
#[derive(Debug, Clone, Default, serde::Deserialize)]
pub struct Pagination {
    /// Requested maximum number of items per page.
    pub limit: Option<u32>,
    /// Opaque cursor returned as `next_cursor` by the previous page.
    pub cursor: Option<String>,
}

impl Pagination {
    /// Resolves the page size, clamping it between `1` and `max_limit.max(1)`.
    ///
    /// Falls back to `default_limit` when [`Pagination::limit`] is `None`.
    #[must_use]
    pub fn clamped_limit(&self, default_limit: u32, max_limit: u32) -> i64 {
        let upper = max_limit.max(1);
        let raw = self.limit.unwrap_or(default_limit);
        i64::from(raw.clamp(1, upper))
    }

    /// Returns `clamped_limit + 1` so callers can detect whether more rows exist without a `COUNT(*)`.
    #[must_use]
    pub fn fetch_limit(&self, default_limit: u32, max_limit: u32) -> i64 {
        self.clamped_limit(default_limit, max_limit) + 1
    }
}

/// One page of cursor-paginated results.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct CursorPage<T> {
    /// Items returned for the current page.
    pub items: Vec<T>,
    /// Cursor of the last item when more rows exist, or `None` on the final page.
    pub next_cursor: Option<String>,
    /// Whether additional rows exist beyond this page.
    pub has_more: bool,
}

impl<T> CursorPage<T> {
    /// Builds a [`CursorPage`] from rows fetched with `LIMIT (limit + 1)`.
    ///
    /// Truncates `rows` to `limit`, sets `has_more` when an extra row was present,
    /// and computes `next_cursor` from the last retained row via `cursor_fn`.
    #[must_use]
    pub fn from_rows(mut rows: Vec<T>, limit: usize, cursor_fn: impl Fn(&T) -> String) -> Self {
        let has_more = rows.len() > limit;
        if has_more {
            rows.truncate(limit);
        }
        let next_cursor = if has_more {
            rows.last().map(cursor_fn)
        } else {
            None
        };
        Self {
            items: rows,
            next_cursor,
            has_more,
        }
    }
}

/// Persisted audit event row stored in `slabs_audit_log`.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, sqlx::FromRow)]
pub struct AuditEntry {
    /// Prefixed audit entry identifier (`aud_<ulid>`).
    pub id: String,
    /// Optional identifier of the user or service that performed the action.
    pub actor_id: Option<String>,
    /// Action name describing what happened (for example `"room.archived"`).
    pub action: String,
    /// Logical type of the affected resource (for example `"room"`).
    pub target_type: String,
    /// Identifier of the affected resource.
    pub target_id: String,
    /// JSON-serialized metadata payload attached to the audit event.
    pub metadata_json: String,
    /// RFC 3339 UTC timestamp when the audit entry was created.
    pub created_at: String,
}

/// Transactional audit log backed by the `slabs_audit_log` system table.
#[derive(Debug, Clone)]
pub struct AuditLog {
    db: Db,
}

impl AuditLog {
    /// Creates an [`AuditLog`] handle backed by `db`.
    #[must_use]
    pub fn new(db: Db) -> Self {
        Self { db }
    }

    /// Inserts an audit entry inside an open `SQLite` transaction so it commits or rolls back atomically.
    ///
    /// Returns the generated `aud_<ulid>` identifier.
    pub async fn record_in_tx(
        &self,
        tx: &mut Transaction<'_, Sqlite>,
        actor_id: Option<&str>,
        action: &str,
        target_type: &str,
        target_id: &str,
        metadata: &serde_json::Value,
    ) -> SlabResult<String> {
        let id = slabs_core::id::new("aud");
        let created_at = chrono::Utc::now().to_rfc3339();
        let metadata_json = serde_json::to_string(metadata)
            .map_err(|e| SlabError::internal(format!("failed to serialize audit metadata: {e}")))?;

        sqlx::query(
            "INSERT INTO slabs_audit_log (id, actor_id, action, target_type, target_id, metadata_json, created_at)
             VALUES (?, ?, ?, ?, ?, ?, ?)",
        )
        .bind(&id)
        .bind(actor_id)
        .bind(action)
        .bind(target_type)
        .bind(target_id)
        .bind(&metadata_json)
        .bind(&created_at)
        .execute(&mut **tx)
        .await?;

        Ok(id)
    }

    /// Lists up to `limit` most recent audit entries for a specific `(target_type, target_id)` on the read pool.
    pub async fn list_for_target(
        &self,
        target_type: &str,
        target_id: &str,
        limit: i64,
    ) -> SlabResult<Vec<AuditEntry>> {
        let rows: Vec<AuditEntry> = sqlx::query_as(
            "SELECT id, actor_id, action, target_type, target_id, metadata_json, created_at
             FROM slabs_audit_log
             WHERE target_type = ? AND target_id = ?
             ORDER BY created_at DESC, id DESC
             LIMIT ?",
        )
        .bind(target_type)
        .bind(target_id)
        .bind(limit)
        .fetch_all(self.db.reader())
        .await?;
        Ok(rows)
    }

    /// Lists up to `limit` most recent audit entries across all targets on the read pool.
    pub async fn list_recent(&self, limit: i64) -> SlabResult<Vec<AuditEntry>> {
        let rows: Vec<AuditEntry> = sqlx::query_as(
            "SELECT id, actor_id, action, target_type, target_id, metadata_json, created_at
             FROM slabs_audit_log
             ORDER BY created_at DESC, id DESC
             LIMIT ?",
        )
        .bind(limit)
        .fetch_all(self.db.reader())
        .await?;
        Ok(rows)
    }
}

/// 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 11 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)
    }

    /// Reads a `.sql` file from disk and executes its statements against the writer pool.
    ///
    /// Intended for seed scripts such as `slabs db seed`. Empty or whitespace-only files are a no-op.
    pub async fn execute_sql_file(&self, path: &Path) -> SlabResult<()> {
        let sql = std::fs::read_to_string(path).map_err(|e| {
            SlabError::internal(format!("failed to read SQL file {}: {e}", path.display()))
        })?;
        if sql.trim().is_empty() {
            return Ok(());
        }
        sqlx::raw_sql(&sql).execute(&self.write_pool).await?;
        Ok(())
    }

    /// 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 11 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)
    }

    /// Reads a `.sql` file from disk and executes its statements against the `PostgreSQL` pool.
    ///
    /// Intended for seed scripts such as `slabs db seed`. Empty or whitespace-only files are a no-op.
    pub async fn execute_sql_file(&self, path: &Path) -> SlabResult<()> {
        let sql = std::fs::read_to_string(path).map_err(|e| {
            SlabError::internal(format!("failed to read SQL file {}: {e}", path.display()))
        })?;
        if sql.trim().is_empty() {
            return Ok(());
        }
        sqlx::raw_sql(&sql).execute(&self.pool).await?;
        Ok(())
    }

    /// 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()));
    }

    #[test]
    fn pagination_clamps_limits_and_computes_fetch_limit() {
        let default_page = Pagination::default();
        assert_eq!(default_page.clamped_limit(20, 100), 20);
        assert_eq!(default_page.fetch_limit(20, 100), 21);

        let zero_page = Pagination {
            limit: Some(0),
            cursor: None,
        };
        assert_eq!(zero_page.clamped_limit(20, 100), 1);
        assert_eq!(zero_page.fetch_limit(20, 100), 2);

        let huge_page = Pagination {
            limit: Some(500),
            cursor: Some("cur_1".into()),
        };
        assert_eq!(huge_page.clamped_limit(20, 100), 100);
        assert_eq!(huge_page.fetch_limit(20, 100), 101);
        assert_eq!(huge_page.cursor.as_deref(), Some("cur_1"));
    }

    #[test]
    fn cursor_page_from_rows_truncates_and_sets_next_cursor() {
        let page = CursorPage::from_rows(vec![10, 20, 30], 2, ToString::to_string);
        assert_eq!(page.items, vec![10, 20]);
        assert!(page.has_more);
        assert_eq!(page.next_cursor.as_deref(), Some("20"));

        let exact = CursorPage::from_rows(vec![10, 20], 2, ToString::to_string);
        assert_eq!(exact.items, vec![10, 20]);
        assert!(!exact.has_more);
        assert!(exact.next_cursor.is_none());

        let empty = CursorPage::from_rows(Vec::<i32>::new(), 2, ToString::to_string);
        assert_eq!(empty.items, Vec::<i32>::new());
        assert!(!empty.has_more);
        assert!(empty.next_cursor.is_none());
    }

    #[tokio::test]
    async fn audit_log_commits_and_rolls_back_atomically_with_tx() {
        let db = Db::connect("sqlite::memory:").await.unwrap();
        db.init_system_tables().await.unwrap();
        let audit = AuditLog::new(db.clone());

        // Committed transaction persists audit entry
        let mut tx = db.begin().await.unwrap();
        let entry_id = audit
            .record_in_tx(
                &mut tx,
                Some("usr_1"),
                "room.created",
                "room",
                "room_1",
                &serde_json::json!({ "name": "Lobby" }),
            )
            .await
            .unwrap();
        assert!(entry_id.starts_with("aud_"));
        tx.commit().await.unwrap();

        // Rolled back transaction does not persist audit entry
        let mut rollback_tx = db.begin().await.unwrap();
        let _rolled_back_id = audit
            .record_in_tx(
                &mut rollback_tx,
                Some("usr_2"),
                "room.deleted",
                "room",
                "room_1",
                &serde_json::json!({ "reason": "rolled back" }),
            )
            .await
            .unwrap();
        rollback_tx.rollback().await.unwrap();

        // Second committed entry on another target to verify filtering
        let mut tx2 = db.begin().await.unwrap();
        let _other_id = audit
            .record_in_tx(
                &mut tx2,
                None,
                "user.invited",
                "user",
                "usr_9",
                &serde_json::json!({}),
            )
            .await
            .unwrap();
        tx2.commit().await.unwrap();

        let room_entries = audit.list_for_target("room", "room_1", 10).await.unwrap();
        assert_eq!(room_entries.len(), 1);
        assert_eq!(room_entries[0].id, entry_id);
        assert_eq!(room_entries[0].actor_id.as_deref(), Some("usr_1"));
        assert_eq!(room_entries[0].action, "room.created");
        assert_eq!(room_entries[0].target_type, "room");
        assert_eq!(room_entries[0].target_id, "room_1");
        assert_eq!(room_entries[0].metadata_json, r#"{"name":"Lobby"}"#);

        let recent = audit.list_recent(10).await.unwrap();
        assert_eq!(recent.len(), 2);

        let recent_limited = audit.list_recent(1).await.unwrap();
        assert_eq!(recent_limited.len(), 1);
    }

    #[tokio::test]
    async fn execute_sql_file_runs_seed_statements_and_handles_empty_or_missing() {
        let db = Db::connect("sqlite::memory:").await.unwrap();
        db.init_system_tables().await.unwrap();

        let seed_path = std::env::temp_dir().join(format!(
            "slabs_seed_test_{}.sql",
            slabs_core::id::new("sql")
        ));
        std::fs::write(
            &seed_path,
            "CREATE TABLE widgets (id TEXT PRIMARY KEY, name TEXT NOT NULL);\n\
             INSERT INTO widgets (id, name) VALUES ('w_1', 'Alpha');\n\
             INSERT INTO widgets (id, name) VALUES ('w_2', 'Beta');\n",
        )
        .unwrap();

        db.execute_sql_file(&seed_path).await.unwrap();
        let (count,): (i64,) = sqlx::query_as("SELECT COUNT(*) FROM widgets")
            .fetch_one(db.reader())
            .await
            .unwrap();
        assert_eq!(count, 2);

        // Blank seed file is a no-op
        std::fs::write(&seed_path, "   \n\t  ").unwrap();
        db.execute_sql_file(&seed_path).await.unwrap();
        let _ = std::fs::remove_file(&seed_path);

        // Missing file returns an internal error
        let missing = std::env::temp_dir().join("slabs_definitely_missing_seed.sql");
        assert!(db.execute_sql_file(&missing).await.is_err());

        // Both system schemas declare the new v0.2.0 system tables
        assert!(SYSTEM_SCHEMA_SQL.contains("slabs_idempotency_keys"));
        assert!(SYSTEM_SCHEMA_SQL.contains("slabs_audit_log"));
        assert!(POSTGRES_SYSTEM_SCHEMA_SQL.contains("slabs_idempotency_keys"));
        assert!(POSTGRES_SYSTEM_SCHEMA_SQL.contains("slabs_audit_log"));
    }
}