Skip to main content

ch_database/mariadb/
migrate.rs

1use std::time::Duration;
2
3use sqlx::MySqlPool;
4use sqlx::migrate::{MigrateError, Migrator};
5
6/// Failures while acquiring the migration lock or applying migrations.
7#[derive(Debug, thiserror::Error)]
8#[non_exhaustive]
9pub enum MigrationError {
10    /// The lock name is empty or exceeds the portable 64-byte limit.
11    #[error("migration lock name must contain between 1 and 64 bytes")]
12    InvalidLockName,
13    /// Another connection held the lock until the timeout elapsed.
14    #[error("migration lock was not acquired before the timeout elapsed")]
15    LockUnavailable,
16    /// Acquiring, querying, or closing the database connection failed.
17    #[error(transparent)]
18    Database(#[from] sqlx::Error),
19    /// SQLx could not validate or apply the migration set.
20    #[error(transparent)]
21    Apply(#[from] MigrateError),
22}
23
24/// Runs SQLx migrations under one named, connection-scoped advisory lock.
25///
26/// All runners for the same migration set must use the same `lock_name`.
27/// `lock_timeout` bounds the server's lock wait; precision depends on the server.
28/// It does not limit migration execution. The migrator is consumed so its built-in lock
29/// can be replaced with this bounded lock without changing shared configuration.
30///
31/// Lock acquisition and migrations use one pool connection. That connection is
32/// closed afterwards, releasing its locks even when migration fails or the task
33/// is cancelled. If migration and connection cleanup both fail, the migration
34/// error takes precedence.
35pub async fn run_migrations(
36    pool: &MySqlPool,
37    mut migrator: Migrator,
38    lock_name: &str,
39    lock_timeout: Duration,
40) -> Result<(), MigrationError> {
41    if lock_name.is_empty() || lock_name.len() > 64 {
42        return Err(MigrationError::InvalidLockName);
43    }
44
45    let mut connection = pool.acquire().await?;
46    // Never return a session with a pending or acquired advisory lock to the pool.
47    connection.close_on_drop();
48
49    let acquired: i64 = sqlx::query_scalar("SELECT GET_LOCK(?, ?)")
50        .bind(lock_name)
51        .bind(lock_timeout.as_secs_f64())
52        .fetch_one(&mut *connection)
53        .await?;
54    if acquired != 1 {
55        return Err(MigrationError::LockUnavailable);
56    }
57
58    migrator.set_locking(false);
59    // SQLx exposes this entry point for Send futures affected by Acquire lifetimes.
60    let migration_result = migrator.run_direct(None, &mut *connection, false).await;
61    let close_result = connection.close().await;
62    migration_result?;
63    close_result?;
64    Ok(())
65}
66
67#[cfg(test)]
68mod tests {
69    use super::*;
70
71    #[tokio::test]
72    async fn validates_lock_names_before_acquiring_a_connection() {
73        let pool = MySqlPool::connect_lazy("mysql://localhost/unused").unwrap();
74        pool.close().await;
75
76        for name in ["", &"a".repeat(65), &"é".repeat(33)] {
77            assert!(matches!(
78                run_migrations(
79                    &pool,
80                    Migrator::with_migrations(vec![]),
81                    name,
82                    Duration::ZERO
83                )
84                .await,
85                Err(MigrationError::InvalidLockName)
86            ));
87        }
88
89        assert!(matches!(
90            run_migrations(
91                &pool,
92                Migrator::with_migrations(vec![]),
93                &"a".repeat(64),
94                Duration::ZERO,
95            )
96            .await,
97            Err(MigrationError::Database(sqlx::Error::PoolClosed))
98        ));
99    }
100
101    #[test]
102    fn errors_preserve_the_underlying_types() {
103        fn assert_error<T: std::error::Error + Send + Sync + 'static>() {}
104        assert_error::<MigrationError>();
105
106        let error = MigrationError::from(MigrateError::Dirty(7));
107        assert!(matches!(
108            error,
109            MigrationError::Apply(MigrateError::Dirty(7))
110        ));
111        assert_eq!(error.to_string(), MigrateError::Dirty(7).to_string());
112    }
113}