1
Fork 0

database: Create acrate_database_migrate bin that runs migrations

This commit is contained in:
Steffo 2024-11-18 09:45:03 +01:00
parent 09295b2ce8
commit ccae871d8e
Signed by: steffo
GPG key ID: 5ADA3868646C3FC0
2 changed files with 58 additions and 5 deletions

View file

@ -12,18 +12,21 @@ categories = ["database"]
[dependencies] [dependencies]
diesel = { version = "2.2.4", features = ["postgres", "uuid"] } diesel = { version = "2.2.4", features = ["postgres", "uuid"] }
diesel-async = { version = "0.5.1", features = ["postgres"] } 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" uuid = "1.11.0"
[features] [features]
# bin = ["diesel_migrations"] bin = ["diesel_migrations", "micronfig", "pretty_env_logger"]
[lib] [lib]
name = "acrate_database" name = "acrate_database"
# [[bin]] [[bin]]
# name = "acrate_database_migrate" name = "acrate_database_migrate"
# required-features = ["bin"] required-features = ["bin"]
[lints.clippy] [lints.clippy]
tabs-in-doc-comments = "allow" tabs-in-doc-comments = "allow"

View file

@ -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!")
}