Skip to main content

max / makenotwork

1.2 KB · 36 lines History Blame Raw
1 //! SQLite connection helper.
2 //!
3 //! Migrations stay per-tool: `sqlx::migrate!` resolves its path at compile
4 //! time relative to the calling crate, so each daemon runs its own
5 //! `sqlx::migrate!("./migrations").run(&pool)`. This module owns only the
6 //! connect-with-sane-defaults step, which is identical everywhere.
7
8 use anyhow::Result;
9 use sqlx::SqlitePool;
10 use sqlx::sqlite::{SqliteConnectOptions, SqlitePoolOptions};
11 use std::path::Path;
12 use std::str::FromStr;
13
14 /// Open (creating if missing) a pooled SQLite connection with foreign keys on.
15 pub async fn connect(path: &Path) -> Result<SqlitePool> {
16 let url = format!("sqlite://{}?mode=rwc", path.display());
17 let opts = SqliteConnectOptions::from_str(&url)?
18 .create_if_missing(true)
19 .foreign_keys(true);
20 let pool = SqlitePoolOptions::new().max_connections(4).connect_with(opts).await?;
21 Ok(pool)
22 }
23
24 #[cfg(test)]
25 mod tests {
26 use super::*;
27
28 #[tokio::test]
29 async fn connect_creates_and_enables_foreign_keys() {
30 let dir = tempfile::tempdir().unwrap();
31 let pool = connect(&dir.path().join("t.db")).await.unwrap();
32 let fk: i64 = sqlx::query_scalar("PRAGMA foreign_keys").fetch_one(&pool).await.unwrap();
33 assert_eq!(fk, 1);
34 }
35 }
36