45 lines
1.5 KiB
Rust
45 lines
1.5 KiB
Rust
use crate::config::Config;
|
|
use anyhow::Context;
|
|
use sqlx::migrate::{MigrateDatabase, Migrator};
|
|
use sqlx::sqlite::{SqliteConnectOptions, SqliteJournalMode, SqliteSynchronous};
|
|
use sqlx::{Sqlite, SqlitePool};
|
|
use std::path::Path;
|
|
use std::str::FromStr;
|
|
use tracing::info;
|
|
|
|
pub async fn init_db(config: &Config) -> anyhow::Result<SqlitePool> {
|
|
let database_url = &config.database_url;
|
|
|
|
if database_url.starts_with("sqlite:") {
|
|
let db_path = database_url
|
|
.strip_prefix("sqlite:")
|
|
.unwrap_or(database_url);
|
|
if !Sqlite::database_exists(database_url).await.unwrap_or(false) {
|
|
Sqlite::create_database(database_url)
|
|
.await
|
|
.context("create sqlite database")?;
|
|
}
|
|
|
|
let options = SqliteConnectOptions::from_str(db_path)
|
|
.context("parse sqlite connect options")?
|
|
.journal_mode(SqliteJournalMode::Wal)
|
|
.synchronous(SqliteSynchronous::Normal)
|
|
.create_if_missing(true);
|
|
|
|
let pool = SqlitePool::connect_with(options)
|
|
.await
|
|
.context("connect to sqlite")?;
|
|
|
|
Migrator::new(Path::new("./migrations"))
|
|
.await
|
|
.context("load migrations")?
|
|
.run(&pool)
|
|
.await
|
|
.context("run migrations")?;
|
|
|
|
info!("Database initialized: {}", database_url);
|
|
Ok(pool)
|
|
} else {
|
|
anyhow::bail!("Unsupported DATABASE_URL: {}", database_url)
|
|
}
|
|
}
|