ch-database 0.2.1

Database and object storage primitives for SQLx, SpacetimeDB, and S3
Documentation
use std::time::Duration;

use sqlx::MySqlPool;
use sqlx::migrate::{MigrateError, Migrator};

/// Failures while acquiring the migration lock or applying migrations.
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum MigrationError {
    /// The lock name is empty or exceeds the portable 64-byte limit.
    #[error("migration lock name must contain between 1 and 64 bytes")]
    InvalidLockName,
    /// Another connection held the lock until the timeout elapsed.
    #[error("migration lock was not acquired before the timeout elapsed")]
    LockUnavailable,
    /// Acquiring, querying, or closing the database connection failed.
    #[error(transparent)]
    Database(#[from] sqlx::Error),
    /// SQLx could not validate or apply the migration set.
    #[error(transparent)]
    Apply(#[from] MigrateError),
}

/// Runs SQLx migrations under one named, connection-scoped advisory lock.
///
/// All runners for the same migration set must use the same `lock_name`.
/// `lock_timeout` bounds the server's lock wait; precision depends on the server.
/// It does not limit migration execution. The migrator is consumed so its built-in lock
/// can be replaced with this bounded lock without changing shared configuration.
///
/// Lock acquisition and migrations use one pool connection. That connection is
/// closed afterwards, releasing its locks even when migration fails or the task
/// is cancelled. If migration and connection cleanup both fail, the migration
/// error takes precedence.
pub async fn run_migrations(
    pool: &MySqlPool,
    mut migrator: Migrator,
    lock_name: &str,
    lock_timeout: Duration,
) -> Result<(), MigrationError> {
    if lock_name.is_empty() || lock_name.len() > 64 {
        return Err(MigrationError::InvalidLockName);
    }

    let mut connection = pool.acquire().await?;
    // Never return a session with a pending or acquired advisory lock to the pool.
    connection.close_on_drop();

    let acquired: i64 = sqlx::query_scalar("SELECT GET_LOCK(?, ?)")
        .bind(lock_name)
        .bind(lock_timeout.as_secs_f64())
        .fetch_one(&mut *connection)
        .await?;
    if acquired != 1 {
        return Err(MigrationError::LockUnavailable);
    }

    migrator.set_locking(false);
    // SQLx exposes this entry point for Send futures affected by Acquire lifetimes.
    let migration_result = migrator.run_direct(None, &mut *connection, false).await;
    let close_result = connection.close().await;
    migration_result?;
    close_result?;
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;

    #[tokio::test]
    async fn validates_lock_names_before_acquiring_a_connection() {
        let pool = MySqlPool::connect_lazy("mysql://localhost/unused").unwrap();
        pool.close().await;

        for name in ["", &"a".repeat(65), &"é".repeat(33)] {
            assert!(matches!(
                run_migrations(
                    &pool,
                    Migrator::with_migrations(vec![]),
                    name,
                    Duration::ZERO
                )
                .await,
                Err(MigrationError::InvalidLockName)
            ));
        }

        assert!(matches!(
            run_migrations(
                &pool,
                Migrator::with_migrations(vec![]),
                &"a".repeat(64),
                Duration::ZERO,
            )
            .await,
            Err(MigrationError::Database(sqlx::Error::PoolClosed))
        ));
    }

    #[test]
    fn errors_preserve_the_underlying_types() {
        fn assert_error<T: std::error::Error + Send + Sync + 'static>() {}
        assert_error::<MigrationError>();

        let error = MigrationError::from(MigrateError::Dirty(7));
        assert!(matches!(
            error,
            MigrationError::Apply(MigrateError::Dirty(7))
        ));
        assert_eq!(error.to_string(), MigrateError::Dirty(7).to_string());
    }
}