2023-07-07 13:09:24 +00:00
|
|
|
//! Storage and persistence logic.
|
|
|
|
|
|
|
|
|
|
use std::str::FromStr;
|
2023-08-16 14:30:02 +00:00
|
|
|
use std::sync::Arc;
|
2023-07-07 13:09:24 +00:00
|
|
|
|
|
|
|
|
use serde::Deserialize;
|
|
|
|
|
use sqlx::sqlite::SqliteConnectOptions;
|
2024-05-10 21:50:34 +00:00
|
|
|
use sqlx::{ConnectOptions, Connection, SqliteConnection};
|
2023-08-16 14:30:02 +00:00
|
|
|
use tokio::sync::Mutex;
|
2023-07-07 13:09:24 +00:00
|
|
|
|
|
|
|
|
use crate::prelude::*;
|
|
|
|
|
|
2024-04-23 16:31:00 +00:00
|
|
|
mod auth;
|
2024-04-23 16:26:40 +00:00
|
|
|
mod dialog;
|
2024-04-15 09:06:10 +00:00
|
|
|
mod room;
|
|
|
|
|
mod user;
|
|
|
|
|
|
2023-07-07 13:09:24 +00:00
|
|
|
#[derive(Deserialize, Debug, Clone)]
|
|
|
|
|
pub struct StorageConfig {
|
|
|
|
|
pub db_path: String,
|
|
|
|
|
}
|
|
|
|
|
|
2023-08-16 14:30:02 +00:00
|
|
|
#[derive(Clone)]
|
2023-07-07 13:09:24 +00:00
|
|
|
pub struct Storage {
|
2023-08-16 14:30:02 +00:00
|
|
|
conn: Arc<Mutex<SqliteConnection>>,
|
2023-07-07 13:09:24 +00:00
|
|
|
}
|
|
|
|
|
impl Storage {
|
|
|
|
|
pub async fn open(config: StorageConfig) -> Result<Storage> {
|
|
|
|
|
let opts = SqliteConnectOptions::from_str(&*config.db_path)?.create_if_missing(true);
|
|
|
|
|
let mut conn = opts.connect().await?;
|
|
|
|
|
|
|
|
|
|
let migrator = sqlx::migrate!();
|
|
|
|
|
|
|
|
|
|
migrator.run(&mut conn).await?;
|
|
|
|
|
log::info!("Migrations passed");
|
|
|
|
|
|
2023-08-16 14:30:02 +00:00
|
|
|
let conn = Arc::new(Mutex::new(conn));
|
2023-07-07 13:09:24 +00:00
|
|
|
Ok(Storage { conn })
|
|
|
|
|
}
|
2023-08-16 14:30:02 +00:00
|
|
|
|
2023-09-30 23:12:11 +00:00
|
|
|
pub async fn close(self) -> Result<()> {
|
2023-08-16 14:30:02 +00:00
|
|
|
let res = match Arc::try_unwrap(self.conn) {
|
|
|
|
|
Ok(e) => e,
|
2023-09-30 23:12:11 +00:00
|
|
|
Err(_) => return Err(fail("failed to acquire DB ownership on shutdown")),
|
2023-08-16 14:30:02 +00:00
|
|
|
};
|
|
|
|
|
let res = res.into_inner();
|
|
|
|
|
res.close().await?;
|
|
|
|
|
Ok(())
|
|
|
|
|
}
|
2023-08-17 13:41:28 +00:00
|
|
|
}
|