2023-07-07 13:09:24 +00:00
|
|
|
//! Storage and persistence logic.
|
|
|
|
|
|
|
|
|
|
use std::str::FromStr;
|
|
|
|
|
|
|
|
|
|
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,
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
pub struct Storage {
|
2024-05-13 14:32:45 +00:00
|
|
|
conn: 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");
|
|
|
|
|
|
2024-05-13 14:32:45 +00:00
|
|
|
let conn = Mutex::new(conn);
|
2023-07-07 13:09:24 +00:00
|
|
|
Ok(Storage { conn })
|
|
|
|
|
}
|
2023-08-16 14:30:02 +00:00
|
|
|
|
2024-05-13 14:32:45 +00:00
|
|
|
pub async fn close(self) {
|
|
|
|
|
let res = self.conn.into_inner();
|
|
|
|
|
match res.close().await {
|
|
|
|
|
Ok(_) => {}
|
|
|
|
|
Err(e) => {
|
|
|
|
|
tracing::error!("Failed to close the DB connection: {e:?}");
|
|
|
|
|
}
|
|
|
|
|
}
|
2023-08-16 14:30:02 +00:00
|
|
|
}
|
2023-08-17 13:41:28 +00:00
|
|
|
}
|