forked from lavina/lavina
1
0
Fork 0
lavina/crates/lavina-core/src/repo/mod.rs

49 lines
1.1 KiB
Rust
Raw Normal View History

2023-07-07 13:09:24 +00:00
//! Storage and persistence logic.
use std::str::FromStr;
use serde::Deserialize;
use sqlx::sqlite::SqliteConnectOptions;
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::*;
mod auth;
mod dialog;
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-10 23:56:39 +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-10 23:56:39 +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-10 23:34:01 +00:00
pub async fn close(self) {
2024-05-10 23:56:39 +00:00
let res = self.conn.into_inner();
2024-05-10 23:34:01 +00:00
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
}