allowthem_core/db.rs
1use sqlx::SqlitePool;
2use sqlx::sqlite::{SqliteConnectOptions, SqliteJournalMode};
3use std::str::FromStr;
4use std::time::Duration;
5
6use crate::error::AuthError;
7
8/// Handle to the allowthem database.
9///
10/// Wraps a `SqlitePool` and guarantees that migrations have been applied.
11/// All query code receives a `&Db` and calls `db.pool()` to access the pool.
12pub struct Db {
13 pool: SqlitePool,
14}
15
16impl Db {
17 /// Create a `Db` from an integrator-provided pool and run migrations.
18 ///
19 /// This is the embedded-mode constructor. The caller is responsible for
20 /// configuring `PRAGMA foreign_keys = ON` on their pool's
21 /// `SqliteConnectOptions` — this constructor cannot set per-connection
22 /// pragmas on a pool it did not create.
23 ///
24 /// Migrations are idempotent: safe to call on a pool that has already
25 /// been migrated. SQLx tracks applied migrations in `_sqlx_migrations`
26 /// and `CREATE TABLE IF NOT EXISTS` in the SQL is a no-op on existing tables.
27 ///
28 /// `ignore_missing` is set so that migrations from the integrating application
29 /// already recorded in `_sqlx_migrations` do not cause an error — those are
30 /// the integrator's own migrations, not allowthem's.
31 pub async fn new(pool: SqlitePool) -> Result<Self, AuthError> {
32 sqlx::migrate!("./migrations")
33 .set_ignore_missing(true)
34 .run(&pool)
35 .await
36 .map_err(sqlx::Error::from)?;
37 Ok(Self { pool })
38 }
39
40 /// Create a pool from a URL, apply pragmas, run migrations, and return a `Db`.
41 ///
42 /// Configures the pool with:
43 /// - `PRAGMA foreign_keys = ON` — FK constraint enforcement
44 /// - `PRAGMA journal_mode = WAL` — concurrent reads (silently ignored for `:memory:`)
45 /// - `PRAGMA busy_timeout = 5000` — wait under contention instead of immediate SQLITE_BUSY
46 pub async fn connect(url: &str) -> Result<Self, AuthError> {
47 let opts = SqliteConnectOptions::from_str(url)?
48 .pragma("foreign_keys", "ON")
49 .journal_mode(SqliteJournalMode::Wal)
50 .busy_timeout(Duration::from_millis(5000));
51 let pool = SqlitePool::connect_with(opts).await?;
52 Self::new(pool).await
53 }
54
55 /// Return a reference to the underlying connection pool.
56 pub fn pool(&self) -> &SqlitePool {
57 &self.pool
58 }
59}