Skip to main content

mvsep_api_tester/db/
mod.rs

1pub mod migrations;
2pub mod repositories;
3pub mod tasks_db;
4pub mod user_config;
5
6use rusqlite::Connection;
7use std::sync::Mutex;
8
9pub struct Database {
10    pub conn: Mutex<Connection>,
11}
12
13impl Database {
14    pub fn new(db_path: Option<&str>) -> anyhow::Result<Self> {
15        let path = db_path
16            .map(|p| p.to_string())
17            .unwrap_or_else(|| crate::utils::paths::db_path().to_string_lossy().to_string());
18
19        let conn = Connection::open(&path)?;
20        conn.execute_batch("PRAGMA journal_mode=WAL")?;
21        conn.execute_batch("PRAGMA foreign_keys=ON")?;
22        conn.execute_batch("PRAGMA busy_timeout=5000")?;
23
24        let db = Self {
25            conn: Mutex::new(conn),
26        };
27
28        {
29            let locked = db
30                .conn
31                .lock()
32                .map_err(|e| anyhow::anyhow!("Poison error: {}", e))?;
33            migrations::run_migrations(&locked)?;
34        }
35
36        Ok(db)
37    }
38
39    pub fn with_conn<F, T>(&self, f: F) -> anyhow::Result<T>
40    where
41        F: FnOnce(&Connection) -> anyhow::Result<T>,
42    {
43        let conn = self
44            .conn
45            .lock()
46            .map_err(|e| anyhow::anyhow!("Database lock poisoned: {}", e))?;
47        f(&conn)
48    }
49
50    pub fn default_path() -> String {
51        crate::utils::paths::db_path().to_string_lossy().to_string()
52    }
53}