CI / Build and test (SQLite) (pull_request) Successful in 45s
CI / PostgreSQL 16 integration (pull_request) Skipped
CI / PostgreSQL 17 integration (pull_request) Skipped
CI / YAML check (pull_request) Successful in 3s
CI / Docker image (pull_request) Successful in 51s
Every later milestone stores its data through this layer, so it has to behave the same on both engines and be safe by construction: - Khaemhat.Data: explicit entity maps, typed queries over a safe expression subset, SqlFragment where every interpolated value becomes a parameter, unit of work with transactions, repositories with audit columns and optimistic concurrency on row_version, retries on transient errors. - SQLite provider (STRICT tables, WAL, exact decimals as integers scaled by 10^6, Unicode case-insensitive LIKE, serialised writes) and PostgreSQL 16+ provider (numeric(19,6), timestamptz, jsonb, advisory locks, database creation and server info). Databases are configured from postgres:// and sqlite:// URLs whose password never appears in messages. - C# migrations with system and company catalogues, schema_version with checksums, one transaction per migration under a lock, refusal of unknown applied versions; first system tables sys_companies and sys_settings. - CompanyRegistry stores each company's database URL encrypted with the instance key (AES-256-GCM, HKDF-derived key, purpose as associated data), so a copied row cannot be read for another company. - tools/Khaemhat.DataModelTool, scripts/gen-datamodel.sh and scripts/new-migration.sh: the current schema section of docs/DATA-MODEL.md is generated from the migrations and a test fails when it is stale. - C# 14 binds array.Contains to MemoryExtensions over spans; the query translator unwraps the span conversion. - Tests run every data scenario on SQLite and PostgreSQL (PostgreSQL in CI); ADR 0018 records where the contracts differ from SPEC 5.1. Docs, wiki, changelog and status updated. Closes #7, #8, #9, #10, #11, #12, #13, #14 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
155 lines
6.3 KiB
C#
155 lines
6.3 KiB
C#
using Khaemhat.Data.Mapping;
|
|
using Khaemhat.Data.Migrations;
|
|
using Khaemhat.Data.Schema;
|
|
using Khaemhat.Data.SystemDatabase;
|
|
using Khaemhat.Data.Tests.Support;
|
|
|
|
namespace Khaemhat.Data.Tests;
|
|
|
|
[TestClass]
|
|
public sealed class MigrationTests
|
|
{
|
|
[TestMethod]
|
|
[DataRow(TestDatabase.Sqlite)]
|
|
[DataRow(TestDatabase.Postgres)]
|
|
public async Task SystemMigrations_FromZero_ThenReapplied_DoNothing(string engine)
|
|
{
|
|
await using var db = await TestDatabase.CreateAsync(engine);
|
|
var catalog = MigrationCatalog.ForSystem();
|
|
var runner = new MigrationRunner(db.Context);
|
|
|
|
var first = await runner.RunAsync(db.Target, catalog);
|
|
var second = await runner.RunAsync(db.Target, catalog);
|
|
|
|
Assert.HasCount(catalog.Migrations.Count, first.Applied);
|
|
Assert.AreEqual(0, first.AlreadyApplied);
|
|
Assert.IsEmpty(second.Applied);
|
|
Assert.AreEqual(catalog.Migrations.Count, second.AlreadyApplied);
|
|
Assert.IsEmpty(second.Warnings);
|
|
|
|
await using var unitOfWork = await db.OpenAsync();
|
|
var applied = await SchemaVersionStore.ReadAsync(unitOfWork);
|
|
CollectionAssert.AreEqual(
|
|
catalog.Migrations.Select(m => (m.Module, m.Version, m.Name)).ToArray(),
|
|
applied.Select(a => (a.Module, a.Version, a.Name)).ToArray());
|
|
Assert.IsTrue(applied.All(a => a.Checksum.Length == 64));
|
|
|
|
// The tables work through their maps.
|
|
var settings = unitOfWork.Repository<Core.Instance.SystemSetting, long>();
|
|
await settings.InsertAsync(new Core.Instance.SystemSetting { Key = "smtp.host", Value = "mail.example.com" });
|
|
Assert.AreEqual(1, await settings.CountAsync(Querying.Query.For<Core.Instance.SystemSetting>()));
|
|
}
|
|
|
|
[TestMethod]
|
|
[DataRow(TestDatabase.Sqlite)]
|
|
[DataRow(TestDatabase.Postgres)]
|
|
public async Task UnknownAppliedVersion_IsRefused(string engine)
|
|
{
|
|
await using var db = await TestDatabase.CreateAsync(engine);
|
|
var runner = new MigrationRunner(db.Context);
|
|
await runner.RunAsync(db.Target, MigrationCatalog.ForSystem());
|
|
await using (var unitOfWork = await db.OpenAsync())
|
|
{
|
|
await SchemaVersionStore.RecordAsync(unitOfWork, new AppliedMigration("core", 20991231_001, "from_the_future", DateTime.UtcNow, new string('0', 64)));
|
|
}
|
|
|
|
var error = await Assert.ThrowsExactlyAsync<MigrationException>(() => runner.RunAsync(db.Target, MigrationCatalog.ForSystem()));
|
|
|
|
StringAssert.Contains(error.Message, "20991231001 from_the_future");
|
|
}
|
|
|
|
[TestMethod]
|
|
[DataRow(TestDatabase.Sqlite)]
|
|
[DataRow(TestDatabase.Postgres)]
|
|
public async Task FailingMigration_LeavesNoTrace(string engine)
|
|
{
|
|
await using var db = await TestDatabase.CreateAsync(engine);
|
|
var catalog = MigrationCatalog.Discover(MigrationTarget.Company, [typeof(MigrationTests).Assembly]);
|
|
var runner = new MigrationRunner(db.Context);
|
|
|
|
await Assert.ThrowsAsync<System.Data.Common.DbException>(() => runner.RunAsync(db.Target, catalog));
|
|
|
|
await using var unitOfWork = await db.OpenAsync();
|
|
Assert.IsEmpty(await SchemaVersionStore.ReadAsync(unitOfWork));
|
|
var exists = await unitOfWork.QueryAsync<long>(
|
|
SqlFragment.Of($"SELECT COUNT(*) FROM test_failing")).ContinueWith(t => t.IsCompletedSuccessfully, TaskScheduler.Default);
|
|
Assert.IsFalse(exists, "the table of the failed migration was rolled back");
|
|
}
|
|
|
|
[TestMethod]
|
|
public void Catalog_IsOrdered_AndVersionsAreValid()
|
|
{
|
|
var catalog = MigrationCatalog.ForSystem();
|
|
|
|
Assert.IsGreaterThanOrEqualTo(2, catalog.Migrations.Count);
|
|
CollectionAssert.AreEqual(catalog.Migrations.OrderBy(m => m.Version).ToArray(), catalog.Migrations.ToArray());
|
|
Assert.IsTrue(catalog.Migrations.All(m => m.Target == MigrationTarget.System));
|
|
}
|
|
|
|
[TestMethod]
|
|
public void SystemMaps_AgreeWithTheMigratedSchema()
|
|
{
|
|
var model = MigrationCatalog.ForSystem().BuildModel();
|
|
var maps = new MapRegistry().AddFromAssembly(typeof(CompanyMap).Assembly);
|
|
var problems = new List<string>();
|
|
|
|
foreach (var map in maps.Maps)
|
|
{
|
|
var table = model.Table(map.Table);
|
|
if (table is null)
|
|
{
|
|
problems.Add($"{map.Table}: no migration creates it");
|
|
continue;
|
|
}
|
|
|
|
foreach (var column in map.Columns)
|
|
{
|
|
var definition = table.Column(column.ColumnName);
|
|
if (definition is null)
|
|
{
|
|
problems.Add($"{map.Table}.{column.ColumnName}: missing in the schema");
|
|
}
|
|
else if (definition.TypeDescription != column.TypeDescription || definition.IsNullable != column.IsNullable)
|
|
{
|
|
problems.Add(
|
|
$"{map.Table}.{column.ColumnName}: map {column.TypeDescription} null={column.IsNullable}, schema {definition.TypeDescription} null={definition.IsNullable}");
|
|
}
|
|
}
|
|
|
|
problems.AddRange(table.Columns.Where(c => map.FindByColumn(c.Name) is null).Select(c => $"{map.Table}.{c.Name}: not mapped"));
|
|
}
|
|
|
|
Assert.IsEmpty(problems, string.Join("\n", problems));
|
|
}
|
|
|
|
[TestMethod]
|
|
public void InvalidMigrations_AreRejectedByTheCatalog()
|
|
{
|
|
Assert.ThrowsExactly<InvalidOperationException>(
|
|
() => MigrationCatalog.Discover(MigrationTarget.System, [typeof(MigrationTests).Assembly]));
|
|
}
|
|
}
|
|
|
|
/// <summary>Creates a table, then fails: used by <see cref="MigrationTests.FailingMigration_LeavesNoTrace"/>.</summary>
|
|
[Migration(20261111_001, "failing_on_purpose", Module = "tests")]
|
|
public sealed class M20261111_001_FailingOnPurpose : IMigration
|
|
{
|
|
/// <inheritdoc />
|
|
public void Up(ISchemaBuilder schema)
|
|
{
|
|
ArgumentNullException.ThrowIfNull(schema);
|
|
schema.CreateTable("test_failing", t => t.Id());
|
|
schema.Sql(_ => "SELECT * FROM table_that_does_not_exist");
|
|
}
|
|
}
|
|
|
|
/// <summary>A badly numbered system migration: used by <see cref="MigrationTests.InvalidMigrations_AreRejectedByTheCatalog"/>.</summary>
|
|
[Migration(2026_001, "bad_version", Target = MigrationTarget.System, Module = "tests")]
|
|
public sealed class BadlyNumberedMigration : IMigration
|
|
{
|
|
/// <inheritdoc />
|
|
public void Up(ISchemaBuilder schema)
|
|
{
|
|
}
|
|
}
|