ch_database/mariadb/
migrate.rs1use std::time::Duration;
2
3use sqlx::MySqlPool;
4use sqlx::migrate::{MigrateError, Migrator};
5
6#[derive(Debug, thiserror::Error)]
8#[non_exhaustive]
9pub enum MigrationError {
10 #[error("migration lock name must contain between 1 and 64 bytes")]
12 InvalidLockName,
13 #[error("migration lock was not acquired before the timeout elapsed")]
15 LockUnavailable,
16 #[error(transparent)]
18 Database(#[from] sqlx::Error),
19 #[error(transparent)]
21 Apply(#[from] MigrateError),
22}
23
24pub 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 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 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}