Outsource db pool creation in preparation for unit tests

This commit is contained in:
Lennart
2024-02-25 12:50:19 +01:00
parent 76c879b9f7
commit 509f8f7aeb
3 changed files with 17 additions and 14 deletions

View File

@@ -1,6 +1,6 @@
use anyhow::Result;
use async_trait::async_trait;
use sqlx::SqlitePool;
use sqlx::{sqlite::SqliteConnectOptions, Pool, Sqlite, SqlitePool};
use crate::{
calendar::{Calendar, CalendarStore},
@@ -111,3 +111,17 @@ impl CalendarStore for SqliteCalendarStore {
Ok(())
}
}
pub async fn create_db_pool(db_url: &str, migrate: bool) -> anyhow::Result<Pool<Sqlite>>{
let db = SqlitePool::connect_with(
SqliteConnectOptions::new()
.filename(db_url)
.create_if_missing(true),
)
.await?;
if migrate {
println!("Running database migrations");
sqlx::migrate!("./migrations").run(&db).await?;
}
Ok(db)
}

View File

@@ -6,10 +6,8 @@ use clap::Parser;
use config::{CalendarStoreConfig, SqliteCalendarStoreConfig, TomlCalendarStoreConfig};
use rustical_auth::AuthProvider;
use rustical_store::calendar::CalendarStore;
use rustical_store::sqlite_store::SqliteCalendarStore;
use rustical_store::sqlite_store::{create_db_pool, SqliteCalendarStore};
use rustical_store::toml_store::TomlCalendarStore;
use sqlx::sqlite::SqliteConnectOptions;
use sqlx::SqlitePool;
use std::fs;
use std::sync::Arc;
use tokio::sync::RwLock;
@@ -38,16 +36,7 @@ async fn get_cal_store(
}))
}
CalendarStoreConfig::Sqlite(SqliteCalendarStoreConfig { db_url }) => {
let db = SqlitePool::connect_with(
SqliteConnectOptions::new()
.filename(db_url)
.create_if_missing(true),
)
.await?;
if migrate {
println!("Running database migrations");
sqlx::migrate!("./migrations").run(&db).await?;
}
let db = create_db_pool(db_url, migrate).await?;
Arc::new(RwLock::new(SqliteCalendarStore::new(db)))
}
};