Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
59 changes: 52 additions & 7 deletions src/EFCore.PG/Migrations/Internal/NpgsqlHistoryRepository.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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.
/// </summary>
public override LockReleaseBehavior LockReleaseBehavior => LockReleaseBehavior.Transaction;
/// <remarks>
/// A session-level advisory lock, held for the whole migration run like SQL Server's <c>sp_getapplock</c>. 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.
/// </remarks>
public override LockReleaseBehavior LockReleaseBehavior => LockReleaseBehavior.Connection;

/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
Expand All @@ -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);
Expand All @@ -55,14 +61,54 @@ public override IMigrationsDatabaseLock AcquireDatabaseLock()
/// </summary>
public override async Task<IMigrationsDatabaseLock> 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,
Expand Down Expand Up @@ -240,7 +286,7 @@ public override string GetEndIfScript()
END $EF$;
""";

private sealed class NpgsqlMigrationDatabaseLock(IHistoryRepository historyRepository) : IMigrationsDatabaseLock
private sealed class NpgsqlMigrationDatabaseLock(NpgsqlHistoryRepository historyRepository) : IMigrationsDatabaseLock
{
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
Expand All @@ -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();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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<IRelationalDatabaseCreator>().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<IHistoryRepository>().GetAppliedMigrationsAsync()).Select(r => r.MigrationId));
}

private static ParallelMigrationsContext CreateParallelContext(NpgsqlTestStore store)
=> new(
new DbContextOptionsBuilder<ParallelMigrationsContext>()
.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<int>() },
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<string>("Email", "People", nullable: true);
}
}

[DbContext(typeof(ParallelMigrationsContext))]
[Migration("00000000000003_Phone")]
private class ParallelMigration3 : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
=> migrationBuilder.AddColumn<string>("Phone", "People", nullable: true);
}

public override void Can_diff_against_2_2_model()
{
using var context = new Migrations.BloggingContext();
Expand Down