use std::time::Duration;
use sqlx::MySqlPool;
use sqlx::migrate::{MigrateError, Migrator};
use tracing::debug;
pub const DEFAULT_MIGRATION_LOCK_TIMEOUT: Duration = Duration::from_secs(30);
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum MigrationError {
#[error("migration lock name must contain between 1 and 64 bytes")]
InvalidLockName,
#[error("failed to acquire migration connection: {source}")]
AcquireConnection {
#[source]
source: sqlx::Error,
},
#[error("failed to acquire migration lock: {source}")]
AcquireLock {
#[source]
source: sqlx::Error,
},
#[error("migration lock was not acquired before the timeout elapsed")]
LockUnavailable,
#[error("failed to apply database migrations: {source}")]
Apply {
#[source]
source: MigrateError,
},
#[error("failed to release migration lock: {source}")]
ReleaseLock {
#[source]
source: sqlx::Error,
},
#[error("migration lock could not be released because it was no longer owned")]
LockNotOwned,
#[error(
"failed to apply database migrations ({migration}) and release the migration lock ({release})"
)]
ApplyAndRelease {
migration: MigrateError,
release: sqlx::Error,
},
#[error(
"failed to apply database migrations ({migration}) and the migration lock was no longer owned"
)]
ApplyAndLockNotOwned {
migration: MigrateError,
},
}
pub type MigrationResult<T> = Result<T, MigrationError>;
pub async fn run_migrations_with_lock(
pool: &MySqlPool,
migrator: &Migrator,
lock_name: &str,
) -> MigrationResult<()> {
run_migrations_with_lock_timeout(pool, migrator, lock_name, DEFAULT_MIGRATION_LOCK_TIMEOUT)
.await
}
pub async fn run_migrations_with_lock_timeout(
pool: &MySqlPool,
migrator: &Migrator,
lock_name: &str,
lock_timeout: Duration,
) -> MigrationResult<()> {
let lock_name = lock_name.trim();
if lock_name.is_empty() {
debug!("running database migrations without an advisory lock");
return migrator
.run(pool)
.await
.map_err(|source| MigrationError::Apply { source });
}
if lock_name.len() > 64 {
return Err(MigrationError::InvalidLockName);
}
let mut conn = pool
.acquire()
.await
.map_err(|source| MigrationError::AcquireConnection { source })?;
let timeout_seconds = lock_timeout.as_secs().min(i64::MAX as u64) as i64;
let acquired = sqlx::query_scalar::<_, Option<i64>>("SELECT GET_LOCK(?, ?)")
.bind(lock_name)
.bind(timeout_seconds)
.fetch_one(&mut *conn)
.await
.map_err(|source| MigrationError::AcquireLock { source })?;
if acquired != Some(1) {
return Err(MigrationError::LockUnavailable);
}
let migration_result = migrator.run(pool).await;
let release_result = sqlx::query_scalar::<_, Option<i64>>("SELECT RELEASE_LOCK(?)")
.bind(lock_name)
.fetch_one(&mut *conn)
.await;
match (migration_result, release_result) {
(Ok(()), Ok(Some(1))) => Ok(()),
(Ok(()), Ok(_)) => Err(MigrationError::LockNotOwned),
(Ok(()), Err(source)) => Err(MigrationError::ReleaseLock { source }),
(Err(source), Ok(Some(1))) => Err(MigrationError::Apply { source }),
(Err(migration), Ok(_)) => Err(MigrationError::ApplyAndLockNotOwned { migration }),
(Err(migration), Err(release)) => {
Err(MigrationError::ApplyAndRelease { migration, release })
}
}
}