diff --git a/src/db/mod.rs b/src/db/mod.rs index c403ecb..c9ccc00 100644 --- a/src/db/mod.rs +++ b/src/db/mod.rs @@ -1,11 +1,29 @@ -use diesel::{Connection, sqlite::SqliteConnection}; +use diesel::{Connection, sqlite::{SqliteConnection, Sqlite}}; use hmac_sha256::Hash; +use diesel_migrations::{embed_migrations, EmbeddedMigrations, MigrationHarness}; use crate::{config::CORE_CFG, logging::{LogLevel, log}, to_hex}; pub mod schema; pub mod user; +pub const MIGRATIONS: EmbeddedMigrations = embed_migrations!("migrations"); + +fn run_migrations(connection: &mut impl MigrationHarness) -> bool { + match connection.run_pending_migrations(MIGRATIONS) { + Ok(m) => { + if m.len() > 0 { + log(LogLevel::Fatal, "db", "run_migrations", format!("New DB Version: {:?}", m[0]).as_str()); + } + return true + }, + Err(e) => { + log(LogLevel::Fatal, "db", "run_migrations", format!("Failed to run migrations: {:?}", e).as_str()); + return false + }, + } +} + pub fn connect() -> Option { let cfg = CORE_CFG.get().unwrap(); let t = SqliteConnection::establish(&cfg.sqlite_file); @@ -23,14 +41,15 @@ pub fn init_db() -> bool { if conn.is_none() { return false; } + let mut conn = conn.unwrap(); - let test_res = conn.unwrap().begin_test_transaction(); + let test_res = conn.begin_test_transaction(); if test_res.is_err() { log(LogLevel::Fatal, "Database", "init_db", format!("Test Transaction failed: {}", test_res.err().unwrap()).as_str()); return false; } - true + return run_migrations(&mut conn); } pub fn get_hashed_uid(user_id: &u64) -> String {