Merge branch '10-run-diesel-database-migrations-automatically' into 'main'

Run Diesel database migrations automatically

Closes #10

See merge request libretunes/libretunes!4
This commit is contained in:
2024-02-15 23:55:03 -05:00
7 changed files with 114 additions and 1 deletions

View File

@ -6,4 +6,6 @@ fn main() {
"cargo:rustc-cfg=target=\"{}\"",
std::env::var("TARGET").unwrap()
);
println!("cargo:rerun-if-changed=migrations");
}

View File

@ -13,6 +13,12 @@ use diesel::{
r2d2::Pool,
};
use diesel_migrations::{
embed_migrations,
EmbeddedMigrations,
MigrationHarness,
};
// See https://leward.eu/notes-on-diesel-a-rust-orm/
// Define some types to make it easier to work with Diesel
@ -95,5 +101,15 @@ pub fn get_db_conn() -> PgPooledConn {
DB_POOL.get().expect("Failed to get a database connection from the pool.")
}
/// Embedded database migrations into the binary
const DB_MIGRATIONS: EmbeddedMigrations = embed_migrations!();
/// Run any pending migrations in the database
/// Always safe to call, as it will only run migrations that have not already been run
pub fn migrate() {
let db_con = &mut get_db_conn();
db_con.run_pending_migrations(DB_MIGRATIONS).expect("Could not run database migrations");
}
}
}

View File

@ -8,6 +8,9 @@ extern crate openssl;
#[macro_use]
extern crate diesel;
#[cfg(feature = "ssr")]
extern crate diesel_migrations;
#[cfg(feature = "ssr")]
#[actix_web::main]
async fn main() -> std::io::Result<()> {
@ -19,6 +22,9 @@ async fn main() -> std::io::Result<()> {
use dotenv::dotenv;
dotenv().ok();
// Bring the database up to date
libretunes::database::migrate();
let session_secret_key = if let Ok(key) = std::env::var("SESSION_SECRET_KEY") {
Key::from(key.as_bytes())
} else {