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(); await settings.InsertAsync(new Core.Instance.SystemSetting { Key = "smtp.host", Value = "mail.example.com" }); Assert.AreEqual(1, await settings.CountAsync(Querying.Query.For())); } [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(() => 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(() => runner.RunAsync(db.Target, catalog)); await using var unitOfWork = await db.OpenAsync(); Assert.IsEmpty(await SchemaVersionStore.ReadAsync(unitOfWork)); var exists = await unitOfWork.QueryAsync( 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 Maps_AgreeWithTheMigratedSchema() { var systemModel = MigrationCatalog.ForSystem().BuildModel(); var companyModel = MigrationCatalog.ForCompany().BuildModel(); var maps = new MapRegistry().AddFromAssembly(typeof(CompanyMap).Assembly); var problems = new List(); foreach (var map in maps.Maps) { // System tables carry the sys_ prefix (SPEC 5.4); every other table lives in the company databases. var model = map.Table.StartsWith("sys_", StringComparison.Ordinal) ? systemModel : companyModel; 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( () => MigrationCatalog.Discover(MigrationTarget.System, [typeof(MigrationTests).Assembly])); } } /// Creates a table, then fails: used by . [Migration(20261111_001, "failing_on_purpose", Module = "tests")] public sealed class M20261111_001_FailingOnPurpose : IMigration { /// public void Up(ISchemaBuilder schema) { ArgumentNullException.ThrowIfNull(schema); schema.CreateTable("test_failing", t => t.Id()); schema.Sql(_ => "SELECT * FROM table_that_does_not_exist"); } } /// A badly numbered system migration: used by . [Migration(2026_001, "bad_version", Target = MigrationTarget.System, Module = "tests")] public sealed class BadlyNumberedMigration : IMigration { /// public void Up(ISchemaBuilder schema) { } }