Skip to content
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,8 @@ and this project adheres to [Semantic Versioning](http://semver.org/).

- Fix compilation failures with the `proxy` feature https://github.com/SeaQL/sea-orm/pull/3220

- Fix concurrent `Migrator::up` / `Migrator::down` on PostgreSQL failing or applying a migration twice when several processes migrate the same database at once

### Compatibility Notes

- Update the declared MSRV of `sea-orm-cli` to Rust 1.94, matching its existing SQLx 0.9 dependency requirement https://github.com/SeaQL/sea-orm/pull/3187
Expand Down
4 changes: 2 additions & 2 deletions sea-orm-migration/src/migrator.rs
Original file line number Diff line number Diff line change
Expand Up @@ -276,7 +276,7 @@ where
exec_up_with(
manager,
steps,
M::get_pending_migrations(db).await?,
M::get_migration_with_status(db).await?,
M::migration_table_name(),
)
.await
Expand All @@ -293,7 +293,7 @@ where
exec_down_with(
manager,
steps,
M::get_applied_migrations(db).await?,
M::get_migration_with_status(db).await?,
M::migration_table_name(),
)
.await
Expand Down
170 changes: 164 additions & 6 deletions sea-orm-migration/src/migrator/exec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -93,9 +93,17 @@ where
let schema = Schema::new(builder);
let mut stmt = schema
.create_table_from_entity(seaql_migrations::Entity)
.table_name(migration_table_name);
.table_name(migration_table_name.clone());
stmt.if_not_exists();
db.execute(&stmt).await?;
if builder == DbBackend::Postgres {
// `IF NOT EXISTS` does not hold against another connection creating the table at the same
// moment. One simple query runs as one transaction, so the lock is held until it is created.
let create = builder.build(&stmt).sql;
let lock = advisory_lock_sql(&migration_table_name);
db.execute_unprepared(&format!("{lock}; {create}")).await?;
} else {
db.execute(&stmt).await?;
}
Ok(())
}

Expand Down Expand Up @@ -208,6 +216,90 @@ fn should_use_transaction(migration: &dyn crate::MigrationTrait, backend: DbBack
}
}

/// A Postgres lock, held until the end of the transaction, on the migration table of the current
/// schema.
fn advisory_lock_sql(migration_table_name: &DynIden) -> String {
let key = migration_table_name.to_string().replace('\'', "''");
format!(
"SELECT pg_advisory_xact_lock(hashtext('sea-orm-migration:' || current_schema() || '.{key}'))"
)
}

/// On Postgres, serializes the migration's transaction against other processes running a migrator
/// on the same table, and returns the applied versions, read after the lock is taken. Fails on an
/// isolation level that would hide what was committed while waiting, and on a version applied by a
/// newer migrator. Other backends and migrations run outside of a transaction are not locked.
async fn lock_and_read_applied<C: ConnectionTrait>(
db: &C,
migration_table_name: DynIden,
names: &[String],
) -> Result<Option<HashSet<String>>, DbErr> {
let backend = db.get_database_backend();
if backend != DbBackend::Postgres {
return Ok(None);
}
let lock = format!(
"{}, current_setting('transaction_isolation') AS isolation",
advisory_lock_sql(&migration_table_name)
);
let row = db
.query_one_raw(Statement::from_string(backend, lock))
.await?
.ok_or_else(|| DbErr::Migration("Failed to take the migration lock".to_owned()))?;
// Only a READ COMMITTED transaction sees what other processes committed while it waited.
let isolation: String = row.try_get("", "isolation")?;
if isolation != "read committed" {
return Err(DbErr::Migration(format!(
"Migrations on Postgres need a READ COMMITTED transaction, not {}",
isolation.to_uppercase()
)));
}

let stmt = Query::select()
.table_name(migration_table_name)
.column(seaql_migrations::Column::Version)
.take();
let mut applied = HashSet::new();
for row in db.query_all(&stmt).await? {
let version: String = row.try_get("", "version")?;
if !names.contains(&version) {
return Err(DbErr::Migration(format!(
"Migration '{version}' has been applied by another process, but this migrator does not know it"
)));
}
applied.insert(version);
}
Ok(Some(applied))
}

/// Whether the `i`-th migration still has to be applied, given the versions applied right now:
/// `false` if another process applied it, an error if it rolled back an earlier one.
fn should_apply(names: &[String], i: usize, applied: &HashSet<String>) -> Result<bool, DbErr> {
if applied.contains(&names[i]) {
return Ok(false);
}
match names[..i].iter().find(|name| !applied.contains(*name)) {
Some(name) => Err(DbErr::Migration(format!(
"Migration '{name}' has been rolled back by another process"
))),
None => Ok(true),
}
}

/// Whether the `i`-th migration still has to be rolled back, given the versions applied right
/// now: `false` if another process rolled it back, an error if it applied a later one.
fn should_roll_back(names: &[String], i: usize, applied: &HashSet<String>) -> Result<bool, DbErr> {
if !applied.contains(&names[i]) {
return Ok(false);
}
match names[i + 1..].iter().find(|name| applied.contains(*name)) {
Some(name) => Err(DbErr::Migration(format!(
"Migration '{name}' has been applied by another process"
))),
None => Ok(true),
}
}

async fn insert_migration_record<C: ConnectionTrait>(
db: &C,
name: &str,
Expand Down Expand Up @@ -246,10 +338,16 @@ async fn delete_migration_record<C: ConnectionTrait>(
pub async fn exec_up_with(
manager: &SchemaManager<'_>,
mut steps: Option<u32>,
pending_migrations: Vec<Migration>,
migrations: Vec<Migration>,
migration_table_name: DynIden,
) -> Result<(), DbErr> {
let db = manager.get_connection();
let names: Vec<String> = migrations.iter().map(|m| m.name().to_owned()).collect();
let pending_migrations: Vec<_> = migrations
.into_iter()
.enumerate()
.filter(|(_, m)| m.status == MigrationStatus::Pending)
.collect();

if let Some(steps) = steps {
info!("Applying {} pending migrations", steps);
Expand All @@ -260,7 +358,7 @@ pub async fn exec_up_with(
info!("No pending migrations");
}

for Migration { migration, .. } in pending_migrations {
for (i, Migration { migration, .. }) in pending_migrations {
if let Some(steps) = steps.as_mut() {
if steps == &0 {
break;
Expand All @@ -273,6 +371,15 @@ pub async fn exec_up_with(

if use_txn {
let transaction = db.begin().await?;
let applied =
lock_and_read_applied(&transaction, migration_table_name.clone(), &names).await?;
if !applied.map_or(Ok(true), |applied| should_apply(&names, i, &applied))? {
info!(
"Migration '{}' has been applied by another process",
migration.name()
);
continue;
}
let txn_manager = SchemaManager::new(&transaction);
migration.up(&txn_manager).await?;
info!("Migration '{}' has been applied", migration.name());
Expand All @@ -292,10 +399,16 @@ pub async fn exec_up_with(
pub async fn exec_down_with(
manager: &SchemaManager<'_>,
mut steps: Option<u32>,
applied_migrations: Vec<Migration>,
migrations: Vec<Migration>,
migration_table_name: DynIden,
) -> Result<(), DbErr> {
let db = manager.get_connection();
let names: Vec<String> = migrations.iter().map(|m| m.name().to_owned()).collect();
let applied_migrations: Vec<_> = migrations
.into_iter()
.enumerate()
.filter(|(_, m)| m.status == MigrationStatus::Applied)
.collect();

if let Some(steps) = steps {
info!("Rolling back {} applied migrations", steps);
Expand All @@ -306,7 +419,7 @@ pub async fn exec_down_with(
info!("No applied migrations");
}

for Migration { migration, .. } in applied_migrations.into_iter().rev() {
for (i, Migration { migration, .. }) in applied_migrations.into_iter().rev() {
if let Some(steps) = steps.as_mut() {
if steps == &0 {
break;
Expand All @@ -319,6 +432,15 @@ pub async fn exec_down_with(

if use_txn {
let transaction = db.begin().await?;
let applied =
lock_and_read_applied(&transaction, migration_table_name.clone(), &names).await?;
if !applied.map_or(Ok(true), |applied| should_roll_back(&names, i, &applied))? {
info!(
"Migration '{}' has been rolled back by another process",
migration.name()
);
continue;
}
let txn_manager = SchemaManager::new(&transaction);
migration.down(&txn_manager).await?;
info!("Migration '{}' has been rolled back", migration.name());
Expand All @@ -334,3 +456,39 @@ pub async fn exec_down_with(

Ok(())
}

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

fn names() -> Vec<String> {
["m1", "m2", "m3"].map(String::from).to_vec()
}

fn applied(versions: &[&str]) -> HashSet<String> {
versions.iter().map(|v| v.to_string()).collect()
}

#[test]
fn apply_after_another_process() {
assert!(should_apply(&names(), 1, &applied(&["m1"])).unwrap());
// Another `up` applied it first.
assert!(!should_apply(&names(), 1, &applied(&["m1", "m2"])).unwrap());
// A concurrent `down` rolled back the migration it builds on.
let err = should_apply(&names(), 1, &applied(&[])).unwrap_err();
assert!(
err.to_string().contains("'m1' has been rolled back"),
"{err}"
);
}

#[test]
fn roll_back_after_another_process() {
assert!(should_roll_back(&names(), 1, &applied(&["m1", "m2"])).unwrap());
// Another `down` rolled it back first.
assert!(!should_roll_back(&names(), 1, &applied(&["m1"])).unwrap());
// A concurrent `up` applied a migration that builds on it.
let err = should_roll_back(&names(), 1, &applied(&["m1", "m2", "m3"])).unwrap_err();
assert!(err.to_string().contains("'m3' has been applied"), "{err}");
}
}
4 changes: 2 additions & 2 deletions sea-orm-migration/src/migrator/with_self.rs
Original file line number Diff line number Diff line change
Expand Up @@ -364,7 +364,7 @@ where
exec_up_with(
manager,
steps,
migrator.get_pending_migrations(db).await?,
migrator.get_migration_with_status(db).await?,
migrator.migration_table_name(),
)
.await
Expand All @@ -385,7 +385,7 @@ where
exec_down_with(
manager,
steps,
migrator.get_applied_migrations(db).await?,
migrator.get_migration_with_status(db).await?,
migrator.migration_table_name(),
)
.await
Expand Down
Loading