From dc45ef7011d67e54c52f0992f8596a0dec661dcd Mon Sep 17 00:00:00 2001 From: Marco Neumann Date: Tue, 2 Aug 2022 14:13:17 +0200 Subject: [PATCH] fix: work around MySQL implicit commits --- sqlx-core/src/mysql/migrate.rs | 38 +++++++++++++++++++++++++++++++++- 1 file changed, 37 insertions(+), 1 deletion(-) diff --git a/sqlx-core/src/mysql/migrate.rs b/sqlx-core/src/mysql/migrate.rs index e9a966a3fc..d17fbfb59c 100644 --- a/sqlx-core/src/mysql/migrate.rs +++ b/sqlx-core/src/mysql/migrate.rs @@ -217,11 +217,17 @@ CREATE TABLE IF NOT EXISTS _sqlx_migrations ( let mut tx = self.begin().await?; let start = Instant::now(); + // For MySQL we cannot really isolate migrations due to implicit commits caused by table modification, see + // https://dev.mysql.com/doc/refman/8.0/en/implicit-commit.html + // + // To somewhat try to detect this, we first insert the migration into the migration table with + // `success=FALSE` and later modify the flag. + // // language=MySQL let _ = query( r#" INSERT INTO _sqlx_migrations ( version, description, success, checksum, execution_time ) - VALUES ( ?, ?, TRUE, ?, -1 ) + VALUES ( ?, ?, FALSE, ?, -1 ) "#, ) .bind(migration.version) @@ -232,6 +238,18 @@ CREATE TABLE IF NOT EXISTS _sqlx_migrations ( let _ = tx.execute(&*migration.sql).await?; + // language=MySQL + let _ = query( + r#" + UPDATE _sqlx_migrations + SET success = TRUE + WHERE version = ? + "#, + ) + .bind(migration.version) + .execute(&mut tx) + .await?; + tx.commit().await?; // Update `elapsed_time`. @@ -266,6 +284,24 @@ CREATE TABLE IF NOT EXISTS _sqlx_migrations ( let mut tx = self.begin().await?; let start = Instant::now(); + // For MySQL we cannot really isolate migrations due to implicit commits caused by table modification, see + // https://dev.mysql.com/doc/refman/8.0/en/implicit-commit.html + // + // To somewhat try to detect this, we first insert the migration into the migration table with + // `success=FALSE` and later remove the migration altogether. + // + // language=MySQL + let _ = query( + r#" + UPDATE _sqlx_migrations + SET success = FALSE + WHERE version = ? + "#, + ) + .bind(migration.version) + .execute(&mut tx) + .await?; + tx.execute(&*migration.sql).await?; // language=SQL