Skip to content

Commit caa6f18

Browse files
manifestjrasanen
authored andcommitted
Obey no-transaction flag in down migrations (launchbadge#3528)
1 parent 25100a9 commit caa6f18

File tree

1 file changed

+28
-12
lines changed

1 file changed

+28
-12
lines changed

sqlx-postgres/src/migrate.rs

+28-12
Original file line numberDiff line numberDiff line change
@@ -252,20 +252,18 @@ CREATE TABLE IF NOT EXISTS _sqlx_migrations (
252252
migration: &'m Migration,
253253
) -> BoxFuture<'m, Result<Duration, MigrateError>> {
254254
Box::pin(async move {
255-
// Use a single transaction for the actual migration script and the essential bookeeping so we never
256-
// execute migrations twice. See https://github.com/launchbadge/sqlx/issues/1966.
257-
let mut tx = self.begin().await?;
258255
let start = Instant::now();
259256

260-
let _ = tx.execute(&*migration.sql).await?;
261-
262-
// language=SQL
263-
let _ = query(r#"DELETE FROM _sqlx_migrations WHERE version = $1"#)
264-
.bind(migration.version)
265-
.execute(&mut *tx)
266-
.await?;
267-
268-
tx.commit().await?;
257+
// execute migration queries
258+
if migration.no_tx {
259+
revert_migration(self, migration).await?;
260+
} else {
261+
// Use a single transaction for the actual migration script and the essential bookeeping so we never
262+
// execute migrations twice. See https://github.com/launchbadge/sqlx/issues/1966.
263+
let mut tx = self.begin().await?;
264+
revert_migration(&mut tx, migration).await?;
265+
tx.commit().await?;
266+
}
269267

270268
let elapsed = start.elapsed();
271269

@@ -299,6 +297,24 @@ async fn execute_migration(
299297
Ok(())
300298
}
301299

300+
async fn revert_migration(
301+
conn: &mut PgConnection,
302+
migration: &Migration,
303+
) -> Result<(), MigrateError> {
304+
let _ = conn
305+
.execute(&*migration.sql)
306+
.await
307+
.map_err(|e| MigrateError::ExecuteMigration(e, migration.version))?;
308+
309+
// language=SQL
310+
let _ = query(r#"DELETE FROM _sqlx_migrations WHERE version = $1"#)
311+
.bind(migration.version)
312+
.execute(conn)
313+
.await?;
314+
315+
Ok(())
316+
}
317+
302318
async fn current_database(conn: &mut PgConnection) -> Result<String, MigrateError> {
303319
// language=SQL
304320
Ok(query_scalar("SELECT current_database()")

0 commit comments

Comments
 (0)