forked from lavina/lavina
49 lines
1.1 KiB
Rust
49 lines
1.1 KiB
Rust
//! Storage and persistence logic.
|
|
|
|
use std::str::FromStr;
|
|
|
|
use serde::Deserialize;
|
|
use sqlx::sqlite::SqliteConnectOptions;
|
|
use sqlx::{ConnectOptions, Connection, SqliteConnection};
|
|
use tokio::sync::Mutex;
|
|
|
|
use crate::prelude::*;
|
|
|
|
mod auth;
|
|
mod dialog;
|
|
mod room;
|
|
mod user;
|
|
|
|
#[derive(Deserialize, Debug, Clone)]
|
|
pub struct StorageConfig {
|
|
pub db_path: String,
|
|
}
|
|
|
|
pub struct Storage {
|
|
conn: Mutex<SqliteConnection>,
|
|
}
|
|
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");
|
|
|
|
let conn = Mutex::new(conn);
|
|
Ok(Storage { conn })
|
|
}
|
|
|
|
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:?}");
|
|
}
|
|
}
|
|
}
|
|
}
|