| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 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 |
|
| 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 |
|