From ccae871d8e7f6a0fa514bdbf876d8be4bccd94f5 Mon Sep 17 00:00:00 2001 From: Stefano Pigozzi Date: Mon, 18 Nov 2024 09:45:03 +0100 Subject: [PATCH] `database`: Create `acrate_database_migrate` bin that runs migrations --- acrate_database/Cargo.toml | 13 +++-- .../src/bin/acrate_database_migrate.rs | 50 +++++++++++++++++++ 2 files changed, 58 insertions(+), 5 deletions(-) create mode 100644 acrate_database/src/bin/acrate_database_migrate.rs diff --git a/acrate_database/Cargo.toml b/acrate_database/Cargo.toml index 1c65bd1..89bab9d 100644 --- a/acrate_database/Cargo.toml +++ b/acrate_database/Cargo.toml @@ -12,18 +12,21 @@ categories = ["database"] [dependencies] diesel = { version = "2.2.4", features = ["postgres", "uuid"] } diesel-async = { version = "0.5.1", features = ["postgres"] } -# diesel_migrations = { version = "2.2.0", optional = true } +diesel_migrations = { version = "2.2.0", optional = true } +log = "0.4.22" +micronfig = { version = "0.3.0", optional = true } +pretty_env_logger = { version = "0.5.0", optional = true } uuid = "1.11.0" [features] -# bin = ["diesel_migrations"] +bin = ["diesel_migrations", "micronfig", "pretty_env_logger"] [lib] name = "acrate_database" -# [[bin]] -# name = "acrate_database_migrate" -# required-features = ["bin"] +[[bin]] +name = "acrate_database_migrate" +required-features = ["bin"] [lints.clippy] tabs-in-doc-comments = "allow" diff --git a/acrate_database/src/bin/acrate_database_migrate.rs b/acrate_database/src/bin/acrate_database_migrate.rs new file mode 100644 index 0000000..c678882 --- /dev/null +++ b/acrate_database/src/bin/acrate_database_migrate.rs @@ -0,0 +1,50 @@ +//! Run all migrations defined by [`acrate_database`]. +//! +//! This uses the configuration defined in [`acrate_database::config`]. +//! +//! ## Exit codes +//! +//! | Code | Meaning | +//! |-----:|---------| +//! | `0` | Migrations applied successfully | +//! | `1` | Couldn't connect to the database | +//! | `2` | Couldn't apply migrations | +//! | `101` | Configuration is invalid | +//! + +use std::process::exit; +use diesel::{Connection, PgConnection}; +use diesel_migrations::{EmbeddedMigrations, MigrationHarness}; + +mod config { + micronfig::config! { + ACRATE_DATABASE_DATABASE_URL: String, + } +} + +pub const MIGRATIONS: EmbeddedMigrations = diesel_migrations::embed_migrations!(); + +fn main() { + pretty_env_logger::init(); + log::info!("Logging initialized successfully!"); + + log::trace!("Determining database URL..."); + let db = config::ACRATE_DATABASE_DATABASE_URL(); + + log::debug!("Connecting to: {db:?}"); + let mut db = match PgConnection::establish(db) { + Err(e) => { + log::error!("Failed to connect to the PostgreSQL database: {e:#?}"); + exit(1); + } + Ok(db) => db, + }; + + log::debug!("Running migrations..."); + if let Err(e) = db.run_pending_migrations(MIGRATIONS) { + log::error!("Failed to perform migration: {e:#?}"); + exit(2); + }; + + log::info!("Migrations applied successfully!") +}