diff --git a/src/db.rs b/src/db.rs index c43a77d..5eb83ce 100644 --- a/src/db.rs +++ b/src/db.rs @@ -7,6 +7,7 @@ use axum_login::{ }; use session_store::SqliteSessionStore; use sqlx::{ + migrate::Migrator, sqlite::{SqliteConnectOptions, SqlitePoolOptions}, SqlitePool, }; @@ -34,20 +35,32 @@ pub async fn get_pool() -> SqlitePool { }) }; - dbg!(&db_filename); - let conn_opts = SqliteConnectOptions::new() .foreign_keys(true) .auto_vacuum(sqlx::sqlite::SqliteAutoVacuum::Incremental) .filename(&db_filename) - .busy_timeout(Duration::from_secs(TIMEOUT)); + .busy_timeout(Duration::from_secs(TIMEOUT)) + .create_if_missing(true); - // setup connection pool - SqlitePoolOptions::new() + let pool = SqlitePoolOptions::new() .max_connections(MAX_CONNS) .connect_with(conn_opts) .await - .expect("can't connect to database") + .expect("can't connect to database"); + + let mut m = Migrator::new(std::path::Path::new("./migrations")) + .await + .expect("Should be able to read the migration directory."); + + let m = m.set_locking(true); + + m.run(&pool) + .await + .expect("Should be able to run the migration."); + + tracing::info!("Ran migrations"); + + pool } pub async fn session_layer(pool: SqlitePool, secret: &[u8]) -> SessionLayer { @@ -80,6 +93,21 @@ pub async fn auth_layer( AuthLayer::new(store, secret) } +#[cfg(test)] +mod tests { + use std::time::Duration; + + #[tokio::test] + async fn it_migrates_the_db() { + let db = super::get_pool().await; + tokio::time::sleep(Duration::from_secs(2)).await; + let r = sqlx::query("select count(*) from witches") + .fetch_one(&db) + .await; + assert!(r.is_ok()); + } +} + //-************************************************************************ // Session store sub-module, not a public lib. //-************************************************************************