diff --git a/src/EFCore.PG/Migrations/Internal/NpgsqlHistoryRepository.cs b/src/EFCore.PG/Migrations/Internal/NpgsqlHistoryRepository.cs
index 7bdc746dc..70d862ede 100644
--- a/src/EFCore.PG/Migrations/Internal/NpgsqlHistoryRepository.cs
+++ b/src/EFCore.PG/Migrations/Internal/NpgsqlHistoryRepository.cs
@@ -28,7 +28,13 @@ public NpgsqlHistoryRepository(HistoryRepositoryDependencies dependencies)
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
///
- public override LockReleaseBehavior LockReleaseBehavior => LockReleaseBehavior.Transaction;
+ ///
+ /// A session-level advisory lock, held for the whole migration run like SQL Server's sp_getapplock. A
+ /// transaction-scoped lock ends with each migration's transaction, and EF's migrator does not re-read the
+ /// history when it reacquires the lock for the next one, so concurrent instances applied the same migration
+ /// twice.
+ ///
+ public override LockReleaseBehavior LockReleaseBehavior => LockReleaseBehavior.Connection;
///
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
@@ -41,7 +47,7 @@ public override IMigrationsDatabaseLock AcquireDatabaseLock()
Dependencies.MigrationsLogger.AcquiringMigrationLock();
Dependencies.RawSqlCommandBuilder
- .Build($"LOCK TABLE {Dependencies.SqlGenerationHelper.DelimitIdentifier(TableName, TableSchema)} IN ACCESS EXCLUSIVE MODE")
+ .Build($"SELECT pg_advisory_lock({LockKey})")
.ExecuteNonQuery(CreateRelationalCommandParameters());
return new NpgsqlMigrationDatabaseLock(this);
@@ -55,14 +61,54 @@ public override IMigrationsDatabaseLock AcquireDatabaseLock()
///
public override async Task AcquireDatabaseLockAsync(CancellationToken cancellationToken = default)
{
+ Dependencies.MigrationsLogger.AcquiringMigrationLock();
+
await Dependencies.RawSqlCommandBuilder
- .Build($"LOCK TABLE {Dependencies.SqlGenerationHelper.DelimitIdentifier(TableName, TableSchema)} IN ACCESS EXCLUSIVE MODE")
+ .Build($"SELECT pg_advisory_lock({LockKey})")
.ExecuteNonQueryAsync(CreateRelationalCommandParameters(), cancellationToken)
.ConfigureAwait(false);
return new NpgsqlMigrationDatabaseLock(this);
}
+ // Advisory locks are scoped to the current database, so one key per history table is enough. The key is a
+ // number computed here (64-bit FNV-1a of the table's schema-qualified name), spliced as a numeric literal.
+ private long LockKey
+ {
+ get
+ {
+ var hash = 14695981039346656037UL;
+ foreach (var b in System.Text.Encoding.UTF8.GetBytes($"efcore:migrations:{TableSchema}.{TableName}"))
+ {
+ hash = (hash ^ b) * 1099511628211UL;
+ }
+
+ return unchecked((long)hash);
+ }
+ }
+
+ private void ReleaseDatabaseLock()
+ {
+ // A session lock ends with the session, so there is nothing to release once the connection is closed.
+ if (Dependencies.Connection.DbConnection.State == System.Data.ConnectionState.Open)
+ {
+ Dependencies.RawSqlCommandBuilder
+ .Build($"SELECT pg_advisory_unlock({LockKey})")
+ .ExecuteNonQuery(CreateRelationalCommandParameters());
+ }
+ }
+
+ private async ValueTask ReleaseDatabaseLockAsync()
+ {
+ if (Dependencies.Connection.DbConnection.State == System.Data.ConnectionState.Open)
+ {
+ await Dependencies.RawSqlCommandBuilder
+ .Build($"SELECT pg_advisory_unlock({LockKey})")
+ .ExecuteNonQueryAsync(CreateRelationalCommandParameters())
+ .ConfigureAwait(false);
+ }
+ }
+
private RelationalCommandParameterObject CreateRelationalCommandParameters()
=> new(
Dependencies.Connection,
@@ -240,7 +286,7 @@ public override string GetEndIfScript()
END $EF$;
""";
- private sealed class NpgsqlMigrationDatabaseLock(IHistoryRepository historyRepository) : IMigrationsDatabaseLock
+ private sealed class NpgsqlMigrationDatabaseLock(NpgsqlHistoryRepository historyRepository) : IMigrationsDatabaseLock
{
///
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
@@ -251,10 +297,9 @@ private sealed class NpgsqlMigrationDatabaseLock(IHistoryRepository historyRepos
public IHistoryRepository HistoryRepository => historyRepository;
public void Dispose()
- {
- }
+ => historyRepository.ReleaseDatabaseLock();
public ValueTask DisposeAsync()
- => default;
+ => historyRepository.ReleaseDatabaseLockAsync();
}
}
diff --git a/test/EFCore.PG.FunctionalTests/Migrations/MigrationsInfrastructureNpgsqlTest.cs b/test/EFCore.PG.FunctionalTests/Migrations/MigrationsInfrastructureNpgsqlTest.cs
index 37ba7e722..21002c3cc 100644
--- a/test/EFCore.PG.FunctionalTests/Migrations/MigrationsInfrastructureNpgsqlTest.cs
+++ b/test/EFCore.PG.FunctionalTests/Migrations/MigrationsInfrastructureNpgsqlTest.cs
@@ -77,6 +77,83 @@ protected override void Up(MigrationBuilder migrationBuilder)
}
}
+ [ConditionalTheory]
+ [InlineData(false)]
+ [InlineData(true)]
+ public async Task Can_apply_several_migrations_in_parallel(bool async)
+ {
+ // Each instance plans its whole run from the history it reads under the first lock. The lock must therefore be held
+ // until the run ends; a lock released with each migration's transaction lets another instance apply the next migration
+ // in between, and the first instance then applies it again (#4162).
+ await using var store = NpgsqlTestStore.Create("MigrationsInParallel");
+ await using (var db = CreateParallelContext(store))
+ {
+ await db.Database.EnsureDeletedAsync();
+ await db.GetService().CreateAsync();
+ }
+
+ await Task.WhenAll(
+ Enumerable.Range(0, 4).Select(
+ _ => Task.Run(
+ async () =>
+ {
+ await using var context = CreateParallelContext(store);
+ if (async)
+ {
+ await context.Database.MigrateAsync();
+ }
+ else
+ {
+ context.Database.Migrate();
+ }
+ })));
+
+ await using var check = CreateParallelContext(store);
+ Assert.Equal(
+ new[] { "00000000000001_People", "00000000000002_SlowEmail", "00000000000003_Phone" },
+ (await check.GetService().GetAppliedMigrationsAsync()).Select(r => r.MigrationId));
+ }
+
+ private static ParallelMigrationsContext CreateParallelContext(NpgsqlTestStore store)
+ => new(
+ new DbContextOptionsBuilder()
+ .UseNpgsql(store.ConnectionString)
+ .ConfigureWarnings(e => e.Log(RelationalEventId.PendingModelChangesWarning))
+ .Options);
+
+ private class ParallelMigrationsContext(DbContextOptions options) : DbContext(options);
+
+ [DbContext(typeof(ParallelMigrationsContext))]
+ [Migration("00000000000001_People")]
+ private class ParallelMigration1 : Migration
+ {
+ protected override void Up(MigrationBuilder migrationBuilder)
+ => migrationBuilder.CreateTable(
+ "People",
+ c => new { Id = c.Column() },
+ constraints: t => t.PrimaryKey("PK_People", x => x.Id));
+ }
+
+ [DbContext(typeof(ParallelMigrationsContext))]
+ [Migration("00000000000002_SlowEmail")]
+ private class ParallelMigration2 : Migration
+ {
+ protected override void Up(MigrationBuilder migrationBuilder)
+ {
+ // A slow migration (a data migration, an index build) keeps the other instances waiting on the lock.
+ migrationBuilder.Sql("SELECT pg_sleep(1)");
+ migrationBuilder.AddColumn("Email", "People", nullable: true);
+ }
+ }
+
+ [DbContext(typeof(ParallelMigrationsContext))]
+ [Migration("00000000000003_Phone")]
+ private class ParallelMigration3 : Migration
+ {
+ protected override void Up(MigrationBuilder migrationBuilder)
+ => migrationBuilder.AddColumn("Phone", "People", nullable: true);
+ }
+
public override void Can_diff_against_2_2_model()
{
using var context = new Migrations.BloggingContext();