Auto apply migrations fix
This commit is contained in:
@@ -103,26 +103,35 @@ var app = builder.Build();
|
|||||||
using (var scope = app.Services.CreateScope())
|
using (var scope = app.Services.CreateScope())
|
||||||
{
|
{
|
||||||
var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
|
var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
|
||||||
|
var logger = scope.ServiceProvider.GetRequiredService<ILogger<Program>>();
|
||||||
|
|
||||||
|
db.Database.SetCommandTimeout(TimeSpan.FromMinutes(5));
|
||||||
|
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
var pending = await db.Database.GetPendingMigrationsAsync();
|
await db.Database.OpenConnectionAsync();
|
||||||
if (pending.Any())
|
|
||||||
{
|
await db.Database.ExecuteSqlRawAsync(
|
||||||
app.Logger.LogWarning("Applying {Count} pending migrations: {List}",
|
"EXEC sp_getapplock @Resource = N'DiunaBI_Migrations', @LockMode = 'Exclusive', @LockTimeout = 60000;");
|
||||||
pending.Count(), string.Join(", ", pending));
|
|
||||||
await db.Database.MigrateAsync();
|
logger.LogInformation("Ensuring database is up to date...");
|
||||||
app.Logger.LogInformation("Migrations applied successfully.");
|
await db.Database.MigrateAsync();
|
||||||
}
|
logger.LogInformation("Database is up to date.");
|
||||||
else
|
|
||||||
{
|
|
||||||
app.Logger.LogInformation("No pending migrations.");
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
catch (Exception ex)
|
catch (Exception ex)
|
||||||
{
|
{
|
||||||
app.Logger.LogCritical(ex, "Migration failed - application will not start.");
|
logger.LogCritical(ex, "Migration failed - application will not start.");
|
||||||
throw; // stop startup
|
throw;
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
await db.Database.ExecuteSqlRawAsync(
|
||||||
|
"EXEC sp_releaseapplock @Resource = N'DiunaBI_Migrations';");
|
||||||
|
}
|
||||||
|
catch { /* ignore */ }
|
||||||
|
await db.Database.CloseConnectionAsync();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user