| | | 1 | | using Microsoft.EntityFrameworkCore; |
| | | 2 | | using Microsoft.EntityFrameworkCore.Design; |
| | | 3 | | using Microsoft.Extensions.Logging.Abstractions; |
| | | 4 | | |
| | | 5 | | namespace ArturRios.Heimdall.Data.Configuration; |
| | | 6 | | |
| | | 7 | | /// <summary> |
| | | 8 | | /// Builds an <see cref="AppDbContext" /> for the EF Core command-line tools, which have no |
| | | 9 | | /// access to the application's dependency-injection container. The connection string comes from |
| | | 10 | | /// <c>HEIMDALL_DATA_CONNECTIONSTRING</c>; <c>scripts/migrations.py</c> loads it from the |
| | | 11 | | /// selected environment file before invoking <c>dotnet ef</c>. Diagnostics are disabled — design |
| | | 12 | | /// time never needs them, and the tools may well be pointed at production. |
| | | 13 | | /// </summary> |
| | | 14 | | public class DesignTimeDbContextFactory : IDesignTimeDbContextFactory<AppDbContext> |
| | | 15 | | { |
| | | 16 | | private const string ConnectionStringVariable = "HEIMDALL_DATA_CONNECTIONSTRING"; |
| | | 17 | | |
| | | 18 | | public AppDbContext CreateDbContext(string[] args) |
| | | 19 | | { |
| | 0 | 20 | | var connectionString = Environment.GetEnvironmentVariable(ConnectionStringVariable); |
| | | 21 | | |
| | 0 | 22 | | if (string.IsNullOrWhiteSpace(connectionString)) |
| | | 23 | | { |
| | 0 | 24 | | throw new InvalidOperationException( |
| | 0 | 25 | | $"Environment variable '{ConnectionStringVariable}' is unset. Run scripts/migrations.py, " + |
| | 0 | 26 | | "which loads it from the environment file you select, or set it manually before " + |
| | 0 | 27 | | "invoking dotnet ef."); |
| | | 28 | | } |
| | | 29 | | |
| | 0 | 30 | | var options = new DbContextOptionsBuilder<AppDbContext>() |
| | 0 | 31 | | .UseNpgsql(connectionString) |
| | 0 | 32 | | .Options; |
| | | 33 | | |
| | 0 | 34 | | return new AppDbContext(options, NullLoggerFactory.Instance, DbContextDiagnosticsOptions.Disabled); |
| | | 35 | | } |
| | | 36 | | } |