Skip to main content

sunday_slate/
db.rs

1use std::{str::FromStr, time::Duration};
2
3use sqlx::{
4    migrate::Migrator,
5    sqlite::{
6        SqliteConnectOptions, SqliteConnection, SqliteJournalMode, SqlitePool, SqlitePoolOptions,
7        SqliteSynchronous,
8    },
9};
10
11static MIGRATOR: Migrator = sqlx::migrate!("./migrations");
12
13#[derive(Clone)]
14pub struct Db {
15    read: SqlitePool,
16    write: SqlitePool,
17}
18
19impl Db {
20    /// Runs the crate's migrations against a caller-built test pool.
21    #[cfg(any(feature = "test-support", test))]
22    pub async fn migrate_pool(pool: &SqlitePool) -> Result<(), sqlx::migrate::MigrateError> {
23        MIGRATOR.run(pool).await
24    }
25
26    pub async fn open(path: &str) -> anyhow::Result<Self> {
27        let base = SqliteConnectOptions::from_str(path)?
28            .create_if_missing(true)
29            .journal_mode(SqliteJournalMode::Wal)
30            .synchronous(SqliteSynchronous::Normal)
31            .foreign_keys(true)
32            .busy_timeout(Duration::from_secs(10))
33            .optimize_on_close(true, None)
34            .pragma("cache_size", "-20000")
35            .pragma("temp_store", "memory")
36            .pragma("mmap_size", "134217728")
37            .pragma("journal_size_limit", "67108864");
38
39        let write = SqlitePoolOptions::new()
40            .max_connections(1)
41            .acquire_timeout(Duration::from_secs(30))
42            .connect_with(base.clone())
43            .await?;
44
45        MIGRATOR.run(&write).await?;
46
47        let read = SqlitePoolOptions::new()
48            .max_connections(8)
49            .acquire_timeout(Duration::from_secs(5))
50            .connect_with(base.read_only(true))
51            .await?;
52
53        Ok(Self { read, write })
54    }
55
56    /// Returns the read pool.
57    pub fn reader(&self) -> &SqlitePool {
58        &self.read
59    }
60
61    /// Run a write inside a BEGIN IMMEDIATE transaction. Commits on Ok, rolls back on Err.
62    pub async fn write_tx<F, T, E>(&self, f: F) -> Result<T, E>
63    where
64        F: for<'c> AsyncFnOnce(&'c mut SqliteConnection) -> Result<T, E>,
65        E: From<sqlx::Error>,
66    {
67        let mut conn = self.write.acquire().await.map_err(E::from)?;
68        sqlx::query("BEGIN IMMEDIATE")
69            .execute(&mut *conn)
70            .await
71            .map_err(E::from)?;
72
73        match f(&mut *conn).await {
74            Ok(v) => {
75                sqlx::query("COMMIT")
76                    .execute(&mut *conn)
77                    .await
78                    .map_err(E::from)?;
79                Ok(v)
80            }
81            Err(e) => {
82                let _ = sqlx::query("ROLLBACK").execute(&mut *conn).await;
83                Err(e)
84            }
85        }
86    }
87
88    /// Test-only constructor: `read` and `write` both alias the same pool.
89    /// The production read/write split and `max_connections=1` write
90    /// serialization do not apply. Tests own their database, so
91    /// serialization is unnecessary.
92    ///
93    /// Tests that need concurrent writes (multiple in-flight `oneshot`
94    /// requests hitting handlers that write) must NOT use this — they
95    /// need a real production-shaped `Db`. No existing tests do that.
96    #[cfg(any(feature = "test-support", test))]
97    pub fn test(pool: SqlitePool) -> Self {
98        Self {
99            read: pool.clone(),
100            write: pool,
101        }
102    }
103}
104
105#[cfg(test)]
106mod tests {
107    use super::*;
108
109    #[sqlx::test]
110    async fn test_db_test_constructor(pool: SqlitePool) {
111        let db = Db::test(pool.clone());
112        // Both reader and writer pool should serve the same underlying database
113        let mut write_conn = db.write.acquire().await.unwrap();
114        sqlx::query("CREATE TABLE IF NOT EXISTS widgets (id INTEGER PRIMARY KEY)")
115            .execute(&mut *write_conn)
116            .await
117            .unwrap();
118
119        // Read through the reader pool — the table should be visible
120        let mut read_conn = db.reader().acquire().await.unwrap();
121        let tables: Vec<(String,)> =
122            sqlx::query_as("SELECT name FROM sqlite_master WHERE type='table' AND name='widgets'")
123                .fetch_all(&mut *read_conn)
124                .await
125                .unwrap();
126        assert_eq!(tables.len(), 1);
127        assert_eq!(tables[0].0, "widgets");
128    }
129}