| | 1 | | using Microsoft.EntityFrameworkCore; |
| | 2 | | using Microsoft.Extensions.Configuration; |
| | 3 | | using Microsoft.Extensions.DependencyInjection; |
| | 4 | | using Microsoft.Extensions.Hosting; |
| | 5 | | using Microsoft.Extensions.Logging; |
| | 6 | |
|
| | 7 | | namespace NLightning.Node.Extensions; |
| | 8 | |
|
| | 9 | | using Infrastructure.Persistence.Contexts; |
| | 10 | |
|
| | 11 | | public static class DatabaseExtensions |
| | 12 | | { |
| | 13 | | /// <summary> |
| | 14 | | /// Runs database migrations if configured to do so |
| | 15 | | /// </summary> |
| | 16 | | public static async Task MigrateDatabaseIfConfiguredAsync(this IHost host) |
| | 17 | | { |
| 0 | 18 | | using var scope = host.Services.CreateScope(); |
| 0 | 19 | | var configuration = scope.ServiceProvider.GetRequiredService<IConfiguration>(); |
| 0 | 20 | | var logger = scope.ServiceProvider.GetRequiredService<ILogger<Program>>(); |
| | 21 | |
|
| | 22 | | // Check if migrations should run |
| 0 | 23 | | var runMigrations = configuration.GetValue("Database:RunMigrations", false); |
| | 24 | |
|
| 0 | 25 | | if (!runMigrations) |
| | 26 | | { |
| 0 | 27 | | logger.LogInformation("Database migrations are disabled in configuration"); |
| 0 | 28 | | return; |
| | 29 | | } |
| | 30 | |
|
| | 31 | | try |
| | 32 | | { |
| 0 | 33 | | var context = scope.ServiceProvider.GetRequiredService<NLightningDbContext>(); |
| | 34 | |
|
| | 35 | | // Check if there are pending migrations |
| 0 | 36 | | var pendingMigrations = (await context.Database.GetPendingMigrationsAsync()).ToList(); |
| | 37 | |
|
| 0 | 38 | | if (pendingMigrations.Count > 0) |
| | 39 | | { |
| 0 | 40 | | logger.LogInformation("Found {Count} pending migrations. Applying...", pendingMigrations.Count); |
| 0 | 41 | | await context.Database.MigrateAsync(); |
| 0 | 42 | | logger.LogInformation("Database migrations completed successfully"); |
| | 43 | | } |
| | 44 | | else |
| | 45 | | { |
| 0 | 46 | | logger.LogInformation("Database is up to date, no migrations needed"); |
| | 47 | | } |
| 0 | 48 | | } |
| 0 | 49 | | catch (Exception ex) |
| | 50 | | { |
| 0 | 51 | | logger.LogError(ex, "An error occurred while applying database migrations"); |
| 0 | 52 | | throw; |
| | 53 | | } |
| 0 | 54 | | } |
| | 55 | | } |