2025-09-03 06:20:34 +09:00
|
|
|
pub mod migration;
|
|
|
|
|
|
|
|
|
|
use std::{cell::OnceCell, path::Path, sync::{LazyLock, OnceLock}};
|
|
|
|
|
|
|
|
|
|
use migration::migrate;
|
|
|
|
|
use rusqlite::{ffi::Error, Connection};
|
|
|
|
|
|
|
|
|
|
use crate::{config::StorageConfig, global::CONFIG};
|
|
|
|
|
|
|
|
|
|
static INITIALIZE_PARENT_DIRECTORY_RESULT: OnceLock<()> = OnceLock::new();
|
|
|
|
|
|
|
|
|
|
static MIGRATE_RESULT: OnceLock<()> = OnceLock::new();
|
|
|
|
|
|
|
|
|
|
fn initialize_parent_directory<P>(path: &P)
|
|
|
|
|
where
|
|
|
|
|
P: AsRef<Path>,
|
|
|
|
|
{
|
|
|
|
|
*INITIALIZE_PARENT_DIRECTORY_RESULT.get_or_init(|| {
|
|
|
|
|
let path2: &Path = path.as_ref();
|
|
|
|
|
if let Some(x) = path2.parent() {
|
|
|
|
|
if !x.exists() {
|
|
|
|
|
std::fs::create_dir_all(x).expect("Parent directory of the local database must be created.");
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
})
|
|
|
|
|
}
|
|
|
|
|
|
2025-09-03 07:41:11 +09:00
|
|
|
fn migrate_once(conn: &mut Connection) -> () {
|
2025-09-03 06:20:34 +09:00
|
|
|
*MIGRATE_RESULT.get_or_init(|| {
|
|
|
|
|
migrate(conn).expect("Local database migration should be done correctly")
|
|
|
|
|
})
|
|
|
|
|
|
|
|
|
|
}
|
2025-09-03 07:41:11 +09:00
|
|
|
pub trait LocalDatabaseConnection: Sized {
|
2025-09-03 06:20:34 +09:00
|
|
|
fn from_path<P>(path: &P) -> Self
|
|
|
|
|
where
|
|
|
|
|
P: AsRef<Path>;
|
2025-09-03 07:41:11 +09:00
|
|
|
fn from_storage_config(config: &StorageConfig) -> Self {
|
|
|
|
|
Self::from_path(&config.get_local_database_path())
|
2025-09-03 06:20:34 +09:00
|
|
|
}
|
|
|
|
|
fn from_global_storage_config() -> Self {
|
2025-09-03 07:41:11 +09:00
|
|
|
Self::from_storage_config(&CONFIG.get_unchecked().storage)
|
2025-09-03 06:20:34 +09:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
impl LocalDatabaseConnection for Connection {
|
|
|
|
|
fn from_path<P>(path: &P) -> Self
|
|
|
|
|
where
|
|
|
|
|
P: AsRef<Path>
|
|
|
|
|
{
|
|
|
|
|
initialize_parent_directory(path);
|
2025-09-03 07:41:11 +09:00
|
|
|
let mut conn = Connection::open(path).expect("local database connection must be opened without error");
|
|
|
|
|
migrate_once(&mut conn);
|
2025-09-03 06:20:34 +09:00
|
|
|
conn
|
|
|
|
|
}
|
|
|
|
|
}
|