//! Database migrations using refinery. use anyhow::{Context, Result}; use refinery::embed_migrations; use tokio_postgres::NoTls; use tracing::info; use crate::config::DatabaseConfig; embed_migrations!("migrations"); /// Apply all pending database migrations. pub async fn run(config: &DatabaseConfig) -> Result<()> { let mut pg_config = tokio_postgres::Config::new(); pg_config.host(&config.host); pg_config.port(config.port); pg_config.dbname(&config.name); pg_config.user(&config.user); pg_config.password(&config.password); let (mut client, connection) = pg_config .connect(NoTls) .await .context("Failed to connect to database for migrations")?; tokio::spawn(async move { if let Err(e) = connection.await { tracing::error!("Database migration connection error: {}", e); } }); let report = migrations::runner() .run_async(&mut client) .await .context("Failed to apply database migrations")?; if report.applied_migrations().is_empty() { info!("No database migrations to apply"); } else { for migration in report.applied_migrations() { info!( version = migration.version(), name = migration.name(), "Applied database migration" ); } } Ok(()) }