use std::path::PathBuf; use sqlx::{SqlitePool, sqlite::SqliteConnectOptions}; use crate::storage::migrate::migrate_db; #[derive(Clone)] pub(crate) struct App { pub(crate) db: SqlitePool, } impl App { pub(crate) async fn new(db_path: PathBuf) -> Result { let db = { let options = SqliteConnectOptions::new() .filename(&db_path) .optimize_on_close(true, None) .create_if_missing(true); SqlitePool::connect_with(options).await.map_err(|err| { app_create::Error::DbConnectionFailed { inner: err, db_path, } })? }; let me = Self { db }; migrate_db(&me).await?; Ok(me) } } pub(crate) mod app_create { use std::path::PathBuf; use crate::storage::migrate::migrate_db; #[derive(thiserror::Error, Debug)] pub(crate) enum Error { #[error("Failed to connect to the sqlite database at `{db_path}`, because: {inner}")] DbConnectionFailed { inner: sqlx::Error, db_path: PathBuf, }, #[error("Failed to migrate db to the current version")] MigrateDb(#[from] migrate_db::Error), } }