diff --git a/src/Backend/DiunaBI.API/Program.cs b/src/Backend/DiunaBI.API/Program.cs index dbe741c..7def7fa 100644 --- a/src/Backend/DiunaBI.API/Program.cs +++ b/src/Backend/DiunaBI.API/Program.cs @@ -103,26 +103,35 @@ var app = builder.Build(); using (var scope = app.Services.CreateScope()) { var db = scope.ServiceProvider.GetRequiredService(); + var logger = scope.ServiceProvider.GetRequiredService>(); + + db.Database.SetCommandTimeout(TimeSpan.FromMinutes(5)); try { - var pending = await db.Database.GetPendingMigrationsAsync(); - if (pending.Any()) - { - app.Logger.LogWarning("Applying {Count} pending migrations: {List}", - pending.Count(), string.Join(", ", pending)); - await db.Database.MigrateAsync(); - app.Logger.LogInformation("Migrations applied successfully."); - } - else - { - app.Logger.LogInformation("No pending migrations."); - } + await db.Database.OpenConnectionAsync(); + + await db.Database.ExecuteSqlRawAsync( + "EXEC sp_getapplock @Resource = N'DiunaBI_Migrations', @LockMode = 'Exclusive', @LockTimeout = 60000;"); + + logger.LogInformation("Ensuring database is up to date..."); + await db.Database.MigrateAsync(); + logger.LogInformation("Database is up to date."); } catch (Exception ex) { - app.Logger.LogCritical(ex, "Migration failed - application will not start."); - throw; // stop startup + logger.LogCritical(ex, "Migration failed - application will not start."); + throw; + } + finally + { + try + { + await db.Database.ExecuteSqlRawAsync( + "EXEC sp_releaseapplock @Resource = N'DiunaBI_Migrations';"); + } + catch { /* ignore */ } + await db.Database.CloseConnectionAsync(); } }