phoebe/phoebe/src/db.rs

27 lines
854 B
Rust

use sqlx::{sqlite::SqliteConnectOptions, SqlitePool};
use tokio::sync::OnceCell;
use tracing::debug;
static PHOEBE_DB_ROOT: OnceCell<String> = OnceCell::const_new();
async fn get_db_root() -> &'static str {
PHOEBE_DB_ROOT
.get_or_init(|| async {
std::env::var("PHOEBE_DB_ROOT")
.expect("PHOEBE_DB_ROOT environment variable was not set!")
})
.await
}
async fn create_or_open_sqlite(url: &str) -> sqlx::Result<SqlitePool> {
let options = url.parse::<SqliteConnectOptions>()?.create_if_missing(true);
SqlitePool::connect_with(options).await
}
pub async fn open(name: &str) -> sqlx::Result<SqlitePool> {
debug!("Opening {name} database…");
let db_root = get_db_root().await;
let db_url = format!("sqlite://{}/{}.db", db_root, name);
create_or_open_sqlite(&db_url).await
}