Pular para o conteúdo principal
Versão: main (dev) 🚧

ADR-014 — Apply migrations on startup, opt-in per environment

Date: 2026-08-06 Status: Accepted Reverses: the "Não auto-migra" instruction previously stated in CLAUDE.md (§ Authentication — Admin seed and § EF Core commands), which required dotnet ef database update before the first run. Depends on: DevPack 10.12.0 (Infrastructure/EfCore/DevPackDatabaseInitializer<TContext>, AppSettings/DataOptions). Reference: ITLab.WorkGuardian (ApplicationDbContextInitialiser) and the ABBC portal (DatabaseInitialiser), which is the refined evolution of it. Extracted to the DevPack rather than copied — see § Where the code lives.

Context​

The template shipped with no startup schema handling. IdentitySeeder ran unconditionally in app.UseIdentityInitializationAsync() and assumed the schema existed; the documented compensation was an instruction to the developer: apply migrations by hand before the first run.

That instruction has two costs. The small one is friction — dotnet new, dotnet run, and a wall of EF errors because a step in a markdown file was missed. The large one is that the failure is unreadable: the seeder does not fail saying "the schema is behind", it fails from inside data code on a column that does not exist. Nothing reported the state of the schema at all, so diagnosing it meant inspecting the database by hand.

Three sibling products had already solved this the same way (DataOptions.ApplyMigrations + an initializer that logs applied/pending migrations before deciding), which is what made the shape trustworthy — and what made copying it a fourth time the wrong move.

Decision​

1. The host reports the schema on every start, and migrates only when told to​

Program.cs registers AddDevPackDatabaseInitializer<AppDbContext>(configuration) and awaits InitializeDevPackDatabaseAsync<AppDbContext>() between Build() and the seeder. The reporting half runs unconditionally: applied migrations at Information, pending ones at Warning. Migrating is governed by DataOptions:ApplyMigrations.

Why the reporting half is not optional. It is the difference between this and a bare MigrateAsync(): the schema becomes something a developer reads in the startup output instead of something they infer from a failure. A deployment that never enables migrating still gets the value.

2. ApplyMigrations is false in appsettings.json, true only in the Development sample​

Applying schema is a deployment decision — it needs a window, a rollback plan, and usually a DBA. A default of true would make every new environment adopt that decision silently, and the first sighting would be a production deploy altering a table nobody reviewed.

Hostappsettings.jsonDevelopment
Apifalsetrue (sample)
Workerfalsefalse

3. At most one process per database applies​

⚠️ MigrateAsync takes no distributed lock. An Api and a Worker starting together with both flags on run the same migration concurrently; the losing side fails on an object that already exists. The Worker therefore keeps false in every environment — it registers the initializer only to log the schema it is about to work against. This mirrors the reference products (Api on, worker off).

4. The Identity seed is gated on the schema, not on the flag​

UseIdentityInitializationAsync() now runs only when DatabaseInitializationResult.SchemaIsUpToDate. With migrations pending and applying disabled, seeding is skipped with a warning that names the cause instead of failing on a missing column.

⚠️ Gate on SchemaIsUpToDate, never on MigrationsWereApplied: the latter is false in the common healthy case (schema already current), so it would skip seeding on every start after the first.

5. Where the code lives: the DevPack​

Per G-01, a helper useful to any DevPack consumer belongs in the DevPack, and this one already existed three times outside it. DevPackDatabaseInitializer<TContext> is generic over the context and knows nothing about seeding; what it hands back (SchemaIsUpToDate) is what lets each product gate its own.

Consequences​

  • dotnet new → dotnet run produces a working database in Development. The manual dotnet ef database update step becomes optional there, and stays the documented path for environments that keep the flag off.
  • The non-relational guard is what makes this safe for the test suite. GetAppliedMigrationsAsync/GetPendingMigrationsAsync are relational-only and throw on the EF InMemory provider — exactly what WebApplicationFactoryBase substitutes. The DevPack initializer detects a non-relational provider and no-ops, reporting the schema as up to date, so IntegrationTestFactory keeps seeding as before. Without that guard this ADR would have turned the whole integration suite red.
  • A host with pending migrations and applying disabled now starts and serves with a warning, rather than starting and failing on first use. It does not fail startup: refusing to boot would take a running service down on a deploy that merely forgot a flag, and the readiness probe already covers the database.
  • Migrations remain generated and reviewed by hand (dotnet ef migrations add). This ADR changes when they are applied, never how they are authored.

Alternatives considered​

  • Keep the manual instruction — rejected. It is documentation compensating for a missing mechanism, and its failure mode is an error message that does not mention the schema.
  • Migrate unconditionally at startup — rejected. That is the MigrateAsync()-in-the-dark this replaces: no visibility, and schema changes applied by whoever restarts a pod first.
  • Fail startup when migrations are pending and applying is off — rejected for now. Attractive (it makes drift impossible to ignore) but it converts a forgotten flag into an outage. Revisit if pending-schema incidents actually occur; the Warning plus the readiness probe is the cheaper first step.
  • A dedicated migrator host / init container — not rejected, deferred. It is the correct answer at the scale where a DBA owns the window and several replicas start at once, and it composes with this ADR (every app host keeps false, the migrator runs with true). Out of scope for a template default.
  • Copy the initializer into the template — rejected by G-01. It would have been the fourth copy of the same code, and the corrections earned in each copy would keep diverging without anything failing.