Measured against a real postgres 18, not inferred: a database created by ensurecreated and then asked to migrate gained request_rules and source_streaks — one migration baselined, one applied, both rows in __EFMigrationsHistory, PK and both indexes present. Before this, the same scenario answered schemaMissingTables: [request_rules, source_streaks] and requestRulesAvailable false, and the log said nothing about why. The reason it said nothing: IHistoryRepository.Exists() returned true for a database that has tables and no history table at all — the one state BaselineIfUntrackedAsync exists to notice — so the method returned 0 through its first guard and never reached a log line. The same call returns false on sqlite, which is why the sqlite integration test was green and the postgres path was broken: the test and the product were asking different providers. The check is now made against the table listing this step already takes, which is the answer both providers agree on. The empty-listing branch is no longer silent either. An empty listing is the one answer that would make an upgrade destructive — it would mean 'create everything' against a database that has data — so it is logged rather than treated as 'empty database'. Also measured on the same postgres instance, with the sqlite default strategy pointed at it: AddMissingTables created the two dropped tables in place (schemaTablesAdded 2, schemaMissingTables []) and the PK and both indexes arrived with the table, which is the GO-batch splitting in SchemaDdl working on a provider that uses batch separators. Gates: build 0 warnings / 0 errors, unit 240/240, integration 230/230, smoke passed 52 failed 0, compose 216 passed 0 failed against the rebuilt image. Console unchanged at 90 assertions 0 failed from the previous commit; the admin surface this commit touches is a field the page does not read.
209 lines
9.6 KiB
C#
209 lines
9.6 KiB
C#
using System.Data;
|
|
using Microsoft.EntityFrameworkCore;
|
|
using Microsoft.EntityFrameworkCore.Infrastructure;
|
|
using Microsoft.EntityFrameworkCore.Metadata;
|
|
using Microsoft.EntityFrameworkCore.Migrations;
|
|
using Microsoft.Extensions.Logging;
|
|
|
|
namespace OpenWaf.Infrastructure.Persistence;
|
|
|
|
/// <summary>
|
|
/// What this process did to the schema when it started (OPEN-55).
|
|
///
|
|
/// A record rather than a log line, because the operator has to be able to ask
|
|
/// the running edge whether the tables this build expects are actually in the
|
|
/// database it is serving against. Before this, the only symptom of a schema
|
|
/// that predates a feature was a pillar that quietly answered nothing.
|
|
/// </summary>
|
|
public sealed record SchemaUpgradeOutcome(
|
|
string Strategy,
|
|
int TablesAdded,
|
|
int MigrationsBaselined,
|
|
int MigrationsApplied,
|
|
IReadOnlyList<string> MissingTables);
|
|
|
|
/// <summary>
|
|
/// Brings an existing database up to the schema the current build needs.
|
|
///
|
|
/// <c>EnsureCreated</c> — the default on sqlite — creates a missing database and
|
|
/// changes nothing about an existing one, so an upgrade that keeps its database
|
|
/// arrives with every table except the new ones. <c>Migrate</c> — the default on
|
|
/// postgres — cannot rescue that database either: it has no history table, so
|
|
/// the migration set would begin by creating tables that are already there. Same
|
|
/// bug, two faces, and both are fixed here.
|
|
///
|
|
/// What is never done is a destructive one. A table that exists is left alone
|
|
/// with everything in it; only what is absent is created, and it is created from
|
|
/// the model through the provider in use, so an upgraded database and a fresh
|
|
/// one have the same shape.
|
|
/// </summary>
|
|
public static class SchemaUpgrader
|
|
{
|
|
/// <summary>
|
|
/// Tables the current model describes that this database does not have.
|
|
/// Empty is the invariant; non-empty means a pillar this build can run has
|
|
/// no storage behind it.
|
|
/// </summary>
|
|
public static async Task<IReadOnlyList<string>> MissingTablesAsync(OpenWafDbContext db, CancellationToken ct = default)
|
|
{
|
|
var existing = await ExistingTablesAsync(db, ct);
|
|
return ModelTables(db).Where(table => !existing.Contains(table)).ToList();
|
|
}
|
|
|
|
/// <summary>
|
|
/// Create, in place, the tables this database predates. Returns what it
|
|
/// added — empty when there was nothing to add, which is every start after
|
|
/// the first one.
|
|
/// </summary>
|
|
public static async Task<IReadOnlyList<string>> AddMissingTablesAsync(
|
|
OpenWafDbContext db, ILogger log, CancellationToken ct = default)
|
|
{
|
|
var missing = await MissingTablesAsync(db, ct);
|
|
if (missing.Count == 0) return missing;
|
|
|
|
var statements = SchemaDdl.StatementsFor(
|
|
db.Database.GenerateCreateScript(),
|
|
new HashSet<string>(missing, StringComparer.OrdinalIgnoreCase));
|
|
|
|
if (statements.Count == 0)
|
|
{
|
|
// The model says these tables are missing and the generated script
|
|
// has nothing recognisable that creates them. Creating nothing and
|
|
// saying so is the only honest move left.
|
|
log.LogError(
|
|
"edge: the database is missing {Tables} but no statement in the generated schema creates them — "
|
|
+ "the affected pillars will report themselves unavailable rather than answer with nothing.",
|
|
string.Join(", ", missing));
|
|
return [];
|
|
}
|
|
|
|
foreach (var statement in statements)
|
|
await db.Database.ExecuteSqlRawAsync(statement, ct);
|
|
|
|
log.LogWarning(
|
|
"edge: the database predates the current schema — created {Count} missing table(s) in place: {Tables}. "
|
|
+ "Nothing that was already in the database was touched, so the operator's lists are intact.",
|
|
missing.Count, string.Join(", ", missing));
|
|
|
|
return missing;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Give a database that predates the migration set a history table, so the
|
|
/// migration then applies only what is genuinely missing. Returns how many
|
|
/// migrations were claimed; zero means nothing was claimed — either the
|
|
/// database is empty and the migrations will describe it from the beginning,
|
|
/// or the claim could not be made honestly and the migration is left to
|
|
/// report what it finds.
|
|
/// </summary>
|
|
public static async Task<int> BaselineIfUntrackedAsync(OpenWafDbContext db, ILogger log, CancellationToken ct = default)
|
|
{
|
|
var history = db.GetService<IHistoryRepository>();
|
|
|
|
// Asked of the table listing rather than of IHistoryRepository.Exists:
|
|
// measured on postgres, Exists() answered true for a database that has
|
|
// tables and no history table at all — which is exactly the state this
|
|
// method exists to notice. On sqlite the same call answered false. The
|
|
// listing is the one answer both providers agree on.
|
|
var existing = await ExistingTablesAsync(db, ct);
|
|
if (existing.Contains(HistoryRepository.DefaultTableName)) return 0;
|
|
|
|
if (existing.Count == 0)
|
|
{
|
|
// Either a first install, which the migrations describe from the
|
|
// beginning, or a listing this provider does not answer — and an
|
|
// empty listing is the one answer that would make an upgrade
|
|
// destructive, so it is said out loud rather than treated as "empty".
|
|
log.LogWarning(
|
|
"edge: the table listing for this database came back empty while it has no migration history — "
|
|
+ "nothing can be baselined, so the migrations will run against it and report what they find.");
|
|
return 0;
|
|
}
|
|
|
|
var assembly = db.GetService<IMigrationsAssembly>();
|
|
var migrations = new List<SchemaBaseline.Migration>();
|
|
var productVersions = new Dictionary<string, string>(StringComparer.Ordinal);
|
|
|
|
foreach (var id in db.Database.GetMigrations())
|
|
{
|
|
var migration = assembly.CreateMigration(assembly.Migrations[id], db.Database.ProviderName ?? string.Empty);
|
|
migrations.Add(new SchemaBaseline.Migration(
|
|
id,
|
|
migration.TargetModel.GetEntityTypes()
|
|
.Select(entity => entity.GetTableName())
|
|
.Where(name => name is not null)
|
|
.Select(name => name!)
|
|
.Distinct()
|
|
.ToList()));
|
|
productVersions[id] = migration.TargetModel.FindAnnotation("ProductVersion")?.Value?.ToString() ?? "unknown";
|
|
}
|
|
|
|
var claimed = SchemaBaseline.Choose(migrations, existing);
|
|
if (claimed.Count == 0)
|
|
{
|
|
log.LogWarning(
|
|
"edge: the database has {Count} table(s) and no migration history, and none of the migrations "
|
|
+ "can be shown to have run — not baselining, so the migration will run against it and fail loudly "
|
|
+ "rather than be guessed at.", existing.Count);
|
|
return 0;
|
|
}
|
|
|
|
await db.Database.ExecuteSqlRawAsync(history.GetCreateScript(), ct);
|
|
foreach (var id in claimed)
|
|
await db.Database.ExecuteSqlRawAsync(
|
|
history.GetInsertScript(new HistoryRow(id, productVersions[id])), ct);
|
|
|
|
log.LogWarning(
|
|
"edge: the database has no migration history — baselined {Claimed} of {Total} migrations "
|
|
+ "({Migrations} were already applied to it) and will run the rest.",
|
|
claimed.Count, migrations.Count, string.Join(", ", claimed));
|
|
|
|
return claimed.Count;
|
|
}
|
|
|
|
/// <summary>
|
|
/// How many migrations this database still has to run.
|
|
/// </summary>
|
|
public static async Task<int> PendingMigrationsAsync(OpenWafDbContext db, CancellationToken ct = default)
|
|
=> (await db.Database.GetPendingMigrationsAsync(ct)).Count();
|
|
|
|
/// <summary>
|
|
/// The tables this database actually has. Provider-specific because there is
|
|
/// no provider-neutral way to ask it, and an empty answer from a query that
|
|
/// does not exist on this provider would read as "everything is missing" —
|
|
/// which is the one answer that makes an upgrade destructive.
|
|
/// </summary>
|
|
private static async Task<IReadOnlySet<string>> ExistingTablesAsync(OpenWafDbContext db, CancellationToken ct)
|
|
{
|
|
var sql = db.Database.ProviderName switch
|
|
{
|
|
"Microsoft.EntityFrameworkCore.Sqlite" => "SELECT name FROM sqlite_master WHERE type = 'table'",
|
|
"Npgsql.EntityFrameworkCore.PostgreSQL" => "SELECT tablename FROM pg_catalog.pg_tables WHERE schemaname = current_schema()",
|
|
_ => throw new NotSupportedException(
|
|
$"the in-place schema upgrade has no table listing for {db.Database.ProviderName}")
|
|
};
|
|
|
|
var tables = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
|
|
var connection = db.Database.GetDbConnection();
|
|
var openedHere = connection.State != ConnectionState.Open;
|
|
if (openedHere) await db.Database.OpenConnectionAsync(ct);
|
|
|
|
try
|
|
{
|
|
await using var command = connection.CreateCommand();
|
|
command.CommandText = sql;
|
|
await using var reader = await command.ExecuteReaderAsync(ct);
|
|
while (await reader.ReadAsync(ct)) tables.Add(reader.GetString(0));
|
|
}
|
|
finally
|
|
{
|
|
if (openedHere) await db.Database.CloseConnectionAsync();
|
|
}
|
|
|
|
return tables;
|
|
}
|
|
|
|
private static IReadOnlyList<string> ModelTables(OpenWafDbContext db)
|
|
=> db.GetService<IDesignTimeModel>().Model.GetRelationalModel().Tables.Select(table => table.Name).ToList();
|
|
}
|