sqlite-hardened 0.1.1

Opinionated, correct-by-default sqlx SQLite pool (WAL, foreign_keys, busy_timeout, synchronous=NORMAL) with a BEGIN IMMEDIATE helper and safe in-memory pools.
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
//! Correct-by-default [`sqlx`] SQLite pool, with the footgun fixes built in.
//!
//! [`HardenedSqlite`] builds a [`SqlitePool`] with sane defaults — WAL, foreign
//! keys ON, a 5-second busy-timeout, `synchronous = NORMAL`, and
//! `create_if_missing` — plus two helpers: [`begin_immediate`] for safe
//! read-then-write transactions, and correct, uniquely-named in-memory pools
//! for tests. Every default is overridable via the builder.
//!
//! # Quick start
//!
//! ```no_run
//! use sqlite_hardened::{HardenedSqlite, SqlitePoolExt};
//!
//! # async fn run() -> Result<(), Box<dyn std::error::Error>> {
//! // WAL + foreign_keys + busy_timeout + synchronous=NORMAL, all applied.
//! let pool = HardenedSqlite::new("sqlite://app.db").connect().await?;
//!
//! // BEGIN IMMEDIATE — a read-then-write transaction that can't hit a
//! // busy-snapshot error under WAL's single-writer rule.
//! let mut tx = pool.begin_immediate().await?;
//! sqlx::query("UPDATE counters SET n = n + 1")
//!     .execute(&mut *tx)
//!     .await?;
//! tx.commit().await?;
//! # Ok(())
//! # }
//! ```
//!
//! # Overriding a default
//!
//! ```no_run
//! use sqlite_hardened::HardenedSqlite;
//! use std::time::Duration;
//!
//! # async fn run() -> Result<(), Box<dyn std::error::Error>> {
//! let pool = HardenedSqlite::new("sqlite://app.db")
//!     .foreign_keys(false)
//!     .busy_timeout(Duration::from_secs(2))
//!     .max_connections(16)
//!     .connect()
//!     .await?;
//! # Ok(())
//! # }
//! ```
//!
//! # In-memory pools for tests
//!
//! `":memory:"` yields a uniquely-named `cache=shared` database with one pinned
//! connection, so parallel test pools don't collide and the schema isn't
//! destroyed when the pool idles to zero connections.
//!
//! ```no_run
//! use sqlite_hardened::HardenedSqlite;
//!
//! # async fn run() -> Result<(), Box<dyn std::error::Error>> {
//! let pool = HardenedSqlite::new(":memory:").connect().await?;
//! # Ok(())
//! # }
//! ```
//!
//! # URL params vs. the builder
//!
//! The connection URL is parsed first, so pass-through params (`filename`,
//! `mode`, `vfs`, `cache`, …) are honored. The hardened settings are then
//! always enforced from the builder — a URL query param cannot weaken them.

use sqlx::sqlite::{SqliteConnectOptions, SqliteJournalMode, SqlitePoolOptions, SqliteSynchronous};
use sqlx::SqlitePool;
use sqlx::{Sqlite, Transaction};
use std::str::FromStr;
use std::sync::atomic::{AtomicU64, Ordering};
use std::time::Duration;

#[derive(Debug, thiserror::Error)]
pub enum Error {
    #[error(transparent)]
    Sqlx(#[from] sqlx::Error),
}
pub type Result<T> = std::result::Result<T, Error>;

/// Builder for a hardened `SqlitePool`.
pub struct HardenedSqlite {
    url: String,
    journal_mode: SqliteJournalMode,
    foreign_keys: bool,
    busy_timeout: Duration,
    synchronous: SqliteSynchronous,
    create_if_missing: bool,
    max_connections: u32,
    min_connections: Option<u32>,
    memory_name: Option<String>,
}

impl HardenedSqlite {
    /// New builder with the hardened defaults:
    /// WAL, foreign_keys ON, busy_timeout 5s, synchronous NORMAL,
    /// create_if_missing, max_connections 8.
    pub fn new(url: impl Into<String>) -> Self {
        Self {
            url: url.into(),
            journal_mode: SqliteJournalMode::Wal,
            foreign_keys: true,
            busy_timeout: Duration::from_secs(5),
            synchronous: SqliteSynchronous::Normal,
            create_if_missing: true,
            max_connections: 8,
            min_connections: None,
            memory_name: None,
        }
    }

    pub fn journal_mode(mut self, m: SqliteJournalMode) -> Self {
        self.journal_mode = m;
        self
    }
    pub fn foreign_keys(mut self, on: bool) -> Self {
        self.foreign_keys = on;
        self
    }
    pub fn busy_timeout(mut self, d: Duration) -> Self {
        self.busy_timeout = d;
        self
    }
    pub fn synchronous(mut self, s: SqliteSynchronous) -> Self {
        self.synchronous = s;
        self
    }
    pub fn create_if_missing(mut self, on: bool) -> Self {
        self.create_if_missing = on;
        self
    }
    pub fn max_connections(mut self, n: u32) -> Self {
        self.max_connections = n;
        self
    }
    pub fn min_connections(mut self, n: u32) -> Self {
        self.min_connections = Some(n);
        self
    }
    /// Force a specific shared-cache in-memory name (else auto-salted).
    pub fn memory_name(mut self, name: impl Into<String>) -> Self {
        self.memory_name = Some(name.into());
        self
    }

    fn is_memory(&self) -> bool {
        is_memory_url(&self.url)
    }

    /// Build the `SqliteConnectOptions` without connecting.
    pub fn connect_options(&self) -> Result<SqliteConnectOptions> {
        let opts = if self.is_memory() {
            // Explicit unique file:...?mode=memory&cache=shared — NOT a bare
            // ":memory:" URL, which sqlx would turn into SQLITE_OPEN_MEMORY and
            // collapse every pool onto one anonymous shared cache. WAL is
            // meaningless for memory DBs, so it's skipped here.
            let name = self.memory_name.clone().unwrap_or_else(salted_memory_name);
            SqliteConnectOptions::new()
                .filename(format!("file:{name}?mode=memory&cache=shared"))
                .create_if_missing(true)
                .foreign_keys(self.foreign_keys)
                .busy_timeout(self.busy_timeout)
                .synchronous(self.synchronous)
        } else {
            SqliteConnectOptions::from_str(&self.url)?
                .create_if_missing(self.create_if_missing)
                .journal_mode(self.journal_mode)
                .foreign_keys(self.foreign_keys)
                .busy_timeout(self.busy_timeout)
                .synchronous(self.synchronous)
        };
        Ok(opts)
    }

    /// The PRAGMA statements this builder would apply, in order — for callers
    /// on rusqlite or another driver who want the same hardening without the
    /// sqlx pool. WAL is omitted for in-memory configurations.
    ///
    /// # Examples
    ///
    /// ```
    /// use sqlite_hardened::HardenedSqlite;
    ///
    /// let stmts = HardenedSqlite::new("sqlite://app.db").pragma_statements();
    /// assert_eq!(stmts[0], "PRAGMA journal_mode = WAL;");
    /// assert!(stmts.iter().any(|s| s == "PRAGMA foreign_keys = ON;"));
    /// assert!(stmts.iter().any(|s| s == "PRAGMA busy_timeout = 5000;"));
    /// ```
    pub fn pragma_statements(&self) -> Vec<String> {
        let mut v = Vec::new();
        if !self.is_memory() {
            let jm = match self.journal_mode {
                SqliteJournalMode::Wal => "WAL",
                SqliteJournalMode::Delete => "DELETE",
                SqliteJournalMode::Truncate => "TRUNCATE",
                SqliteJournalMode::Persist => "PERSIST",
                SqliteJournalMode::Memory => "MEMORY",
                SqliteJournalMode::Off => "OFF",
            };
            v.push(format!("PRAGMA journal_mode = {jm};"));
        }
        v.push(format!(
            "PRAGMA foreign_keys = {};",
            if self.foreign_keys { "ON" } else { "OFF" }
        ));
        v.push(format!(
            "PRAGMA busy_timeout = {};",
            self.busy_timeout.as_millis()
        ));
        let sync = match self.synchronous {
            SqliteSynchronous::Off => "OFF",
            SqliteSynchronous::Normal => "NORMAL",
            SqliteSynchronous::Full => "FULL",
            SqliteSynchronous::Extra => "EXTRA",
        };
        v.push(format!("PRAGMA synchronous = {sync};"));
        v
    }

    /// Build and connect the pool.
    pub async fn connect(self) -> Result<SqlitePool> {
        let opts = self.connect_options()?;
        let mut pool_opts = SqlitePoolOptions::new().max_connections(self.max_connections);
        // Pin one connection for in-memory DBs so the shared cache can't be
        // destroyed when the pool drops to zero live connections.
        let min = self
            .min_connections
            .map(|m| if self.is_memory() { m.max(1) } else { m })
            .or(if self.is_memory() { Some(1) } else { None });
        if let Some(m) = min {
            pool_opts = pool_opts.min_connections(m);
        }
        Ok(pool_opts.connect_with(opts).await?)
    }
}

/// True for the recognized in-memory URL spellings.
pub fn is_memory_url(url: &str) -> bool {
    matches!(url, ":memory:" | "sqlite::memory:" | "sqlite://:memory:")
}

static MEM_SERIAL: AtomicU64 = AtomicU64::new(0);

fn salted_memory_name() -> String {
    let n = MEM_SERIAL.fetch_add(1, Ordering::Relaxed);
    format!("sqlite-hardened-{}-{n}", std::process::id())
}

/// Begin a WRITE transaction with `BEGIN IMMEDIATE`.
///
/// sqlx's `pool.begin()` issues a deferred BEGIN: a transaction that reads
/// before it writes pins its read snapshot on the first statement, and if
/// another connection commits in between, the later write cannot upgrade —
/// SQLite returns a busy-snapshot error even *with* a busy_timeout, because the
/// conflict is logical, not a lock wait. `BEGIN IMMEDIATE` takes the write lock
/// up front, so a read-then-write transaction is safe under WAL's single-writer
/// rule.
///
/// Also available as [`SqlitePoolExt::begin_immediate`] (`pool.begin_immediate()`).
///
/// # Examples
///
/// ```no_run
/// use sqlite_hardened::{begin_immediate, HardenedSqlite};
///
/// # async fn run() -> Result<(), Box<dyn std::error::Error>> {
/// let pool = HardenedSqlite::new("sqlite://app.db").connect().await?;
/// let mut tx = begin_immediate(&pool).await?;
/// let n: i64 = sqlx::query_scalar("SELECT n FROM counters WHERE id = 1")
///     .fetch_one(&mut *tx)
///     .await?;
/// sqlx::query("UPDATE counters SET n = ? WHERE id = 1")
///     .bind(n + 1)
///     .execute(&mut *tx)
///     .await?;
/// tx.commit().await?;
/// # Ok(())
/// # }
/// ```
pub async fn begin_immediate(pool: &SqlitePool) -> Result<Transaction<'static, Sqlite>> {
    Ok(pool.begin_with("BEGIN IMMEDIATE").await?)
}

/// `pool.begin_immediate()` sugar.
#[allow(async_fn_in_trait)]
pub trait SqlitePoolExt {
    async fn begin_immediate(&self) -> Result<Transaction<'static, Sqlite>>;
}

impl SqlitePoolExt for SqlitePool {
    async fn begin_immediate(&self) -> Result<Transaction<'static, Sqlite>> {
        begin_immediate(self).await
    }
}

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

    async fn scalar(pool: &SqlitePool, sql: &str) -> i64 {
        sqlx::query_scalar::<_, i64>(sql)
            .fetch_one(pool)
            .await
            .unwrap()
    }

    #[tokio::test]
    async fn file_pool_applies_hardened_pragmas() {
        let tmp = tempfile::tempdir().unwrap();
        let db = tmp.path().join("t.db");
        let pool = HardenedSqlite::new(format!("sqlite://{}", db.display()))
            .connect()
            .await
            .unwrap();
        let jm: String = sqlx::query_scalar("PRAGMA journal_mode")
            .fetch_one(&pool)
            .await
            .unwrap();
        assert_eq!(jm.to_lowercase(), "wal");
        assert_eq!(scalar(&pool, "PRAGMA foreign_keys").await, 1);
        assert_eq!(scalar(&pool, "PRAGMA busy_timeout").await, 5000);
        assert_eq!(scalar(&pool, "PRAGMA synchronous").await, 1); // NORMAL
    }

    #[tokio::test]
    async fn overrides_are_honored() {
        let tmp = tempfile::tempdir().unwrap();
        let db = tmp.path().join("t.db");
        let pool = HardenedSqlite::new(format!("sqlite://{}", db.display()))
            .foreign_keys(false)
            .busy_timeout(Duration::from_secs(2))
            .connect()
            .await
            .unwrap();
        assert_eq!(scalar(&pool, "PRAGMA foreign_keys").await, 0);
        assert_eq!(scalar(&pool, "PRAGMA busy_timeout").await, 2000);
    }

    #[tokio::test]
    async fn in_memory_survives_drop_to_zero() {
        let pool = HardenedSqlite::new(":memory:").connect().await.unwrap();
        sqlx::query("CREATE TABLE t (id INTEGER PRIMARY KEY)")
            .execute(&pool)
            .await
            .unwrap();
        sqlx::query("INSERT INTO t (id) VALUES (1)")
            .execute(&pool)
            .await
            .unwrap();
        // Give any idle connection time to cycle; the pinned min-connection
        // keeps the shared-cache memdb alive so the table persists.
        tokio::time::sleep(std::time::Duration::from_millis(20)).await;
        let n = scalar(&pool, "SELECT COUNT(*) FROM t").await;
        assert_eq!(n, 1);
    }

    #[tokio::test]
    async fn two_memory_pools_are_isolated() {
        let a = HardenedSqlite::new(":memory:").connect().await.unwrap();
        let b = HardenedSqlite::new(":memory:").connect().await.unwrap();
        sqlx::query("CREATE TABLE only_in_a (x INTEGER)")
            .execute(&a)
            .await
            .unwrap();
        let seen: i64 = sqlx::query_scalar(
            "SELECT COUNT(*) FROM sqlite_master WHERE type='table' AND name='only_in_a'",
        )
        .fetch_one(&b)
        .await
        .unwrap();
        assert_eq!(seen, 0);
    }

    #[tokio::test]
    async fn begin_immediate_serializes_writers() {
        let tmp = tempfile::tempdir().unwrap();
        let db = tmp.path().join("t.db");
        let pool = HardenedSqlite::new(format!("sqlite://{}", db.display()))
            .connect()
            .await
            .unwrap();
        sqlx::query("CREATE TABLE c (n INTEGER)")
            .execute(&pool)
            .await
            .unwrap();
        sqlx::query("INSERT INTO c (n) VALUES (0)")
            .execute(&pool)
            .await
            .unwrap();

        // Two concurrent read-then-write transactions. With begin_immediate and
        // the 5s busy_timeout, the second waits for the first instead of hitting
        // a busy-snapshot error. Both increments must land → n == 2.
        let inc = |p: SqlitePool| async move {
            let mut tx = p.begin_immediate().await.unwrap();
            let cur: i64 = sqlx::query_scalar("SELECT n FROM c")
                .fetch_one(&mut *tx)
                .await
                .unwrap();
            sqlx::query("UPDATE c SET n = ?")
                .bind(cur + 1)
                .execute(&mut *tx)
                .await
                .unwrap();
            tx.commit().await.unwrap();
        };
        let (a, b) = (pool.clone(), pool.clone());
        let (ra, rb) = tokio::join!(tokio::spawn(inc(a)), tokio::spawn(inc(b)));
        ra.unwrap();
        rb.unwrap();

        let n: i64 = sqlx::query_scalar("SELECT n FROM c")
            .fetch_one(&pool)
            .await
            .unwrap();
        assert_eq!(n, 2, "both writers committed without a lost update");
    }

    #[test]
    fn pragma_statements_reflect_settings() {
        let stmts = HardenedSqlite::new("sqlite://x.db").pragma_statements();
        assert!(stmts.iter().any(|s| s == "PRAGMA journal_mode = WAL;"));
        assert!(stmts.iter().any(|s| s == "PRAGMA foreign_keys = ON;"));
        assert!(stmts.iter().any(|s| s == "PRAGMA busy_timeout = 5000;"));
        assert!(stmts.iter().any(|s| s == "PRAGMA synchronous = NORMAL;"));
    }

    #[test]
    fn pragma_statements_omit_wal_for_memory() {
        let stmts = HardenedSqlite::new(":memory:").pragma_statements();
        assert!(!stmts.iter().any(|s| s.contains("journal_mode")));
    }

    #[tokio::test]
    async fn hardened_settings_enforced_with_url_params_present() {
        let tmp = tempfile::tempdir().unwrap();
        let db = tmp.path().join("t.db");
        // `mode=rwc` is a pass-through param honored by from_str; the hardened
        // foreign_keys setting is still enforced (ON) alongside it.
        let url = format!("sqlite://{}?mode=rwc", db.display());
        let pool = HardenedSqlite::new(url).connect().await.unwrap();
        assert_eq!(scalar(&pool, "PRAGMA foreign_keys").await, 1);
        assert_eq!(scalar(&pool, "PRAGMA busy_timeout").await, 5000);
    }
}