Files
Pavlo Ratushnyi 871eac48a5 an upgrade adds the tables a database predates, and says what it added
The default schema step is EnsureCreated: it creates a missing database and changes nothing about an existing one. The migrate path could not rescue that database either, because a database EnsureCreated once made has no __EFMigrationsHistory, so the migration set would begin by creating tables that are already there. Same bug with two faces. An operator who upgraded kept a schema with every table except the new ones, and the pillar behind them answered as if there were nothing to see — the compose data volume outliving 'compose down' is exactly that state, which is where it was noticed.

At startup the edge now lists the tables the model describes and the database lacks and creates exactly those, from the model through the provider in use, indexes included. A table that exists is never touched, so an upgrade cannot lose an operator's block list — proven on the wire, not asserted: a block written before the upgrade still refuses the same request after it, with the note the operator typed still in the listing. On the migrate path a database with no history table is baselined first: a migration is claimed as applied only when every table its target model describes is already present, and the claim stops at the first migration it cannot confirm, so a later one is never applied over an unclaimed earlier one. SchemaBaseline is that decision as a pure function; SchemaDdl is the statement filter over EF's own generated script, and an unrecognised statement is left out rather than run, because the safe failure is a table that stays missing and is reported.

What happened is on /admin-api/state: schemaStrategy, schemaTablesAdded, schemaMigrationsBaselined, schemaMigrationsApplied, schemaMissingTables. The last is the invariant — non-empty names a pillar this build can run with no storage behind it, and OPENWAF_SCHEMA=none now changes nothing and reports all of it the same way. The limit is stated rather than hidden: the baseline recognises a table by its name, so a migration that alters an existing table still needs a human decision and the edge refuses to guess one.

OPENWAF_SCHEMA is read through configuration instead of the environment directly. An environment variable still sets it; the change is that a test can now ask for a strategy without mutating process-wide state that parallel xUnit collections share.

Gates on this tree: build 0 warnings / 0 errors, unit 240/240 (+13: the baseline claim, the statement filter), integration 230/230 in 22 s (+5: an edge started against a database with two tables dropped, the indexes arriving with the table, the operator block surviving, the baseline on the migrate path, and the operator-managed schema reporting rather than fixing), smoke passed 52 failed 0 unchanged, compose 216 passed 0 failed (+7: the same upgrade against the shipped image, where the volume really does outlive the stack), console 90 assertions 0 failed unchanged.

Two things the new compose scene caught about the gate itself. The rule-write assertion used code(), which discards the body, so the first run answered 400 and the gate could not say why — the assertion now prints the body it got. And the delete looked its rule up with jget while writing jcount's loop variable, a NameError inside the helper that surfaced as a 405 on the assertion: the trap the script's own comment names, walked into anyway.
2026-10-04 22:51:58 +02:00

91 lines
3.3 KiB
C#

using System.Text;
using System.Text.RegularExpressions;
namespace OpenWaf.Infrastructure.Persistence;
/// <summary>
/// The statements of a model-generated script that belong to a set of tables
/// (OPEN-55).
///
/// <c>GenerateCreateScript</c> emits the whole schema; an in-place upgrade must
/// run only what is missing, because running the rest would fail on tables that
/// already hold the operator's block list. The input here is EF's own output for
/// the provider in use — not hand-written DDL — so the columns, the types and
/// the indexes of a table added this way are exactly what a fresh database
/// would have got.
///
/// The shapes recognised are the three EF emits when it creates a table:
/// <c>CREATE TABLE "t" (…)</c>, <c>CREATE [UNIQUE] INDEX … ON "t" (…)</c> and
/// <c>ALTER TABLE "t" ADD CONSTRAINT …</c>. Anything else in the script is left
/// out, which is the safe direction: an unrecognised statement means a table
/// stays missing and the edge says so, rather than a statement running against a
/// table that was already there.
/// </summary>
public static class SchemaDdl
{
private static readonly Regex CreateIndexOn = new(
@"^CREATE\s+(?:UNIQUE\s+)?INDEX\s+.+\bON\s+""?(?<table>[A-Za-z0-9_]+)""?",
RegexOptions.IgnoreCase | RegexOptions.Singleline | RegexOptions.Compiled);
private static readonly Regex CreateOrAlterTable = new(
@"^(?:CREATE\s+TABLE|ALTER\s+TABLE)\s+""?(?<table>[A-Za-z0-9_]+)""?",
RegexOptions.IgnoreCase | RegexOptions.Singleline | RegexOptions.Compiled);
public static IReadOnlyList<string> StatementsFor(string script, IReadOnlySet<string> tables)
{
var kept = new List<string>();
foreach (var statement in Statements(script))
{
var owner = OwningTable(statement);
if (owner is not null && tables.Contains(owner)) kept.Add(statement);
}
return kept;
}
/// <summary>
/// One statement at a time. Batches are separated by <c>GO</c> on providers
/// that have the concept (postgres) and by nothing at all on sqlite; a
/// statement ends at a semicolon that closes its line.
/// </summary>
public static IReadOnlyList<string> Statements(string script)
{
var statements = new List<string>();
var buffer = new StringBuilder();
foreach (var raw in script.Replace("\r\n", "\n").Split('\n'))
{
var line = raw.TrimEnd();
if (line.Trim().Equals("GO", StringComparison.OrdinalIgnoreCase))
{
Add(statements, buffer);
continue;
}
if (line.Length == 0 && buffer.Length == 0) continue;
buffer.AppendLine(raw);
if (line.EndsWith(';')) Add(statements, buffer);
}
Add(statements, buffer);
return statements;
}
private static void Add(List<string> statements, StringBuilder buffer)
{
var statement = buffer.ToString().Trim();
if (statement.Length > 0) statements.Add(statement);
buffer.Clear();
}
private static string? OwningTable(string statement)
{
var index = CreateIndexOn.Match(statement);
if (index.Success) return index.Groups["table"].Value;
var table = CreateOrAlterTable.Match(statement);
return table.Success ? table.Groups["table"].Value : null;
}
}