dotnet / efcore

EF Core is a modern object-database mapper for .NET. It supports LINQ queries, change tracking, updates, and schema migrations.
https://docs.microsoft.com/ef/
MIT License
13.49k stars 3.13k forks source link

Implement database locking for migrations #33731

Open AndriySvyryd opened 1 month ago

AndriySvyryd commented 1 month ago

Generally speaking, concurrent invocations of Migrate() will fail and possibly leave the database in a corrupted state. In order to mitigate this, we could create a temporary table using HistoryRepository that will serve as a lock while the migrations are applied by the process that acquired it. Providers will be able to override all related logic to instead leverage database-specific mechanisms to accomplish this.

roji commented 1 month ago

That's a good idea - databases do frequently expose locking mechanisms that could work well, e.g. full-table exclusive lock on the HistoryRepository table for PG and SQL Server. Though I'm not sure what a default implementation would look like here - what do you have in mind with the temporary table?

AndriySvyryd commented 1 month ago

what do you have in mind with the temporary table?

Before applying migrations create __EFLock table. If it was created successfully - the lock was acquired. If not, enter the normal retry loop. After migrations and seeding (#17568) finished applying delete __EFLock table.