36 lines
905 B
Rust
36 lines
905 B
Rust
|
|
use sqlx::sqlite::{SqliteConnectOptions, SqlitePool, SqlitePoolOptions};
|
||
|
|
use std::str::FromStr;
|
||
|
|
|
||
|
|
use crate::models::user::User;
|
||
|
|
|
||
|
|
pub struct Database {
|
||
|
|
pub pool: SqlitePool,
|
||
|
|
}
|
||
|
|
|
||
|
|
pub type DbId = i64;
|
||
|
|
|
||
|
|
impl Database {
|
||
|
|
pub async fn for_user(user: &User) -> Result<Self, anyhow::Error> {
|
||
|
|
let file = if user.ephemeral {
|
||
|
|
":memory:".to_string()
|
||
|
|
} else {
|
||
|
|
format!("./dbs/{}.db", user.username)
|
||
|
|
};
|
||
|
|
|
||
|
|
let db_options = SqliteConnectOptions::from_str(&file)?
|
||
|
|
.create_if_missing(true)
|
||
|
|
.to_owned();
|
||
|
|
|
||
|
|
let pool = SqlitePoolOptions::new().connect_with(db_options).await?;
|
||
|
|
|
||
|
|
let migrator = if user.username == "demo" {
|
||
|
|
sqlx::migrate!("./migrations/demo.db/")
|
||
|
|
} else {
|
||
|
|
sqlx::migrate!("./migrations/each_user/")
|
||
|
|
};
|
||
|
|
migrator.run(&pool).await?;
|
||
|
|
|
||
|
|
Ok(Self { pool })
|
||
|
|
}
|
||
|
|
}
|