Path: redb/redb.Tests.Integration/Tests/SqlitePro/SqliteProExportMigrationHistoryTests.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Tests.Integration/Tests/SqlitePro/SqliteProExportMigrationHistoryTests.cs ---- using System.Text.Json.Nodes; using AwesomeAssertions.Execution; using Microsoft.Data.Sqlite; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using redb.Core; using redb.Core.Attributes; using redb.Core.Data; using redb.Core.Models.Entities; using redb.Core.Pro.Extensions; using redb.Core.Pro.Migration; using redb.Core.Pro.Query; using redb.Export.Providers; using redb.Export.Services; using redb.SQLite.Pro.Extensions; using redb.Tests.Integration.Fixtures; namespace redb.Tests.Integration.Tests.SqlitePro; [RedbScheme("Export: migration history probe", Name = "export_migration_history_probe")] public class ExportMigrationHistoryProbeProps { public long Amount { get; set; } } [RedbScheme("Export: migration history second probe", Name = "export_migration_history_second_probe")] public class ExportMigrationHistorySecondProbeProps { public long Count { get; set; } } /// A migration that is not idempotent: run twice, it doubles twice. public class ExportMigrationHistoryDoubleMigration : IRedbMigration { public void Configure(IMigrationBuilder builder) { builder.Property(p => p.Amount).ComputedFrom(p => p.Amount * 2); } } /// A second migration that is not idempotent, on another scheme: run twice, it adds twice. public class ExportMigrationHistoryAddMigration : IRedbMigration { public void Configure(IMigrationBuilder builder) { builder.Property(p => p.Count).ComputedFrom(p => p.Count + 100); } } /// /// A database moved by export and import keeps the history of the data migrations applied to it. Without it, an /// application that runs its migrations at start applies every one of them again to values that already have them, /// and a migration that is not idempotent changes the data a second time. A file of an earlier version carries no /// history: it still imports, with a warning. Scratch files of its own, deleted afterwards. /// public class SqliteProExportMigrationHistoryTests : IAsyncLifetime { private const string HistorySql = "SELECT COUNT(*) FROM _migrations WHERE NOT _dry_run"; private const string HistoryMissingWarning = "does not carry the history of the data migrations"; private readonly List _databases = []; private readonly List _files = []; public Task InitializeAsync() => Task.CompletedTask; public Task DisposeAsync() { SqliteConnection.ClearAllPools(); foreach (var database in _databases) SqliteTestSupport.DeleteDbFiles(database); foreach (var file in _files) File.Delete(file); return Task.CompletedTask; } [Fact] public async Task AMigrationAppliedBeforeTheExport_IsNotAppliedAgain_AfterTheImport() { var source = NewDatabase("src"); long id; long sourceHistory; await using (var provider = Build(source)) { var redb = provider.GetRequiredService(); await redb.InitializeAsync(ensureCreated: true); await redb.SyncSchemeAsync(); id = await redb.SaveAsync(new RedbObject { name = "migrated", Props = new ExportMigrationHistoryProbeProps { Amount = 5 } }); var applied = await redb.MigrateAsync( provider.GetRequiredService()); applied.Should().OnlyContain(r => r.Success, "precondition: the migration ran on the source"); (await redb.LoadAsync(id))!.Props.Amount.Should().Be(10, "precondition"); sourceHistory = await redb.Context.ExecuteScalarAsync(HistorySql); sourceHistory.Should().BeGreaterThan(0, "precondition: the source holds the history of the migration"); } var file = await ExportAsync(source); var target = await ImportIntoNewDatabaseAsync(file); await using (var provider = Build(target)) { // What an application does at start: initialize, then run its migrations. var redb = provider.GetRequiredService(); await redb.InitializeAsync(); var targetHistory = await redb.Context.ExecuteScalarAsync(HistorySql); await redb.MigrateAsync( provider.GetRequiredService()); var amount = (await redb.LoadAsync(id))!.Props.Amount; using (new AssertionScope()) { targetHistory.Should().Be(sourceHistory, "the import carries the history of the applied migrations"); amount.Should().Be(10, "a migration applied before the export is not applied a second time"); } } } [Fact] public async Task TwoMigrationsOnTwoSchemes_RoundTrip_WithTheirHistory_AndNeitherRunsAgain() { var source = NewDatabase("two-src"); long first, second; List sourceRows; await using (var provider = Build(source)) { var redb = provider.GetRequiredService(); var dialect = provider.GetRequiredService(); await redb.InitializeAsync(ensureCreated: true); await redb.SyncSchemeAsync(); await redb.SyncSchemeAsync(); first = await redb.SaveAsync(new RedbObject { name = "first", Props = new ExportMigrationHistoryProbeProps { Amount = 5 } }); second = await redb.SaveAsync(new RedbObject { name = "second", Props = new ExportMigrationHistorySecondProbeProps { Count = 1 } }); (await redb.MigrateAsync(dialect)) .Should().OnlyContain(r => r.Success, "precondition"); (await redb.MigrateAsync(dialect)) .Should().OnlyContain(r => r.Success, "precondition"); sourceRows = await HistoryRowsAsync(source); sourceRows.Should().HaveCountGreaterThanOrEqualTo(2, "precondition: one history row per scheme at least"); } var file = await ExportAsync(source); var (target, output) = await CapturedAsync(() => ImportIntoNewDatabaseAsync(file)); (await HistoryRowsAsync(target)).Should().Equal(sourceRows, "every history row arrives as it was"); output.Should().NotContain(HistoryMissingWarning, "the file carries the history"); await using (var provider = Build(target)) { var redb = provider.GetRequiredService(); var dialect = provider.GetRequiredService(); await redb.InitializeAsync(); await redb.MigrateAsync(dialect); await redb.MigrateAsync(dialect); using (new AssertionScope()) { (await redb.LoadAsync(first))!.Props.Amount.Should().Be(10); (await redb.LoadAsync(second))!.Props.Count.Should().Be(101); } } } [Fact] public async Task AFileOfAnEarlierVersion_WithoutTheHistory_Imports_AndWarnsThatTheHistoryIsMissing() { var source = NewDatabase("old-src"); await using (var provider = Build(source)) { var redb = provider.GetRequiredService(); await redb.InitializeAsync(ensureCreated: true); await redb.SyncSchemeAsync(); await redb.SaveAsync(new RedbObject { name = "migrated", Props = new ExportMigrationHistoryProbeProps { Amount = 5 } }); await redb.MigrateAsync( provider.GetRequiredService()); } var file = await ExportAsync(source); WriteAsEarlierVersion(file); var (target, output) = await CapturedAsync(() => ImportIntoNewDatabaseAsync(file)); using (new AssertionScope()) { output.Should().Contain("Import completed successfully").And.Contain(HistoryMissingWarning); (await ScalarAsync(target, HistorySql)).Should().Be("0", "the file had no history to carry"); (await ScalarAsync(target, "SELECT COUNT(*) FROM _objects")).Should().NotBe("0", "the data arrived"); } } [Fact] public async Task ADatabaseWithoutMigrations_ExportsNoHistory_AndImportsWithAndWithoutTheNewRecords() { var source = NewDatabase("plain-src"); await using (var provider = Build(source)) { var redb = provider.GetRequiredService(); await redb.InitializeAsync(ensureCreated: true); await redb.SyncSchemeAsync(); await redb.SaveAsync(new RedbObject { name = "plain", Props = new ExportMigrationHistoryProbeProps { Amount = 5 } }); } var file = await ExportAsync(source); var lines = File.ReadAllLines(file); lines.Should().NotContain(l => l.Contains("\"type\":\"migration\""), "a database that never ran a migration has no history"); JsonNode.Parse(lines[^1])!["total_migrations"]!.GetValue().Should().Be(0); var (target, output) = await CapturedAsync(() => ImportIntoNewDatabaseAsync(file)); output.Should().NotContain(HistoryMissingWarning, "the file says it carries the history, and it is empty"); (await ScalarAsync(target, "SELECT COUNT(*) FROM _objects")).Should().NotBe("0"); WriteAsEarlierVersion(file); var earlier = await ImportIntoNewDatabaseAsync(file); (await ScalarAsync(earlier, "SELECT COUNT(*) FROM _objects")).Should().NotBe("0", "a file of an earlier version imports as before"); } /// Makes the file what an earlier version wrote: no migration records, no migration total. private static void WriteAsEarlierVersion(string file) { var lines = File.ReadAllLines(file).Where(l => !l.Contains("\"type\":\"migration\"")).ToList(); var footer = JsonNode.Parse(lines[^1])!.AsObject(); footer.Remove("total_migrations"); lines[^1] = footer.ToJsonString(); File.WriteAllLines(file, lines); } private async Task ExportAsync(string source) { var file = NewFile(); await using var exporting = ProviderFactory.Create("sqlite"); await exporting.OpenAsync(source); await new ExportService(exporting, verbose: false, batchSize: 1000).ExportAsync(file, null, compress: false, dryRun: false); return file; } /// A newly created database, the file imported into it with --clean. private async Task ImportIntoNewDatabaseAsync(string file) { var target = NewDatabase("dst"); await using (var provider = Build(target)) await provider.GetRequiredService().InitializeAsync(ensureCreated: true); await using (var importing = ProviderFactory.Create("sqlite")) { await importing.OpenAsync(target); await new ImportService(importing, verbose: false, batchSize: 1000, parallelism: 1) .ImportAsync(file, clean: true, dryRun: false); } RedbKeyGeneratorBase.ClearAllCaches(); return target; } private static async Task> HistoryRowsAsync(string cs) { var rows = new List(); await using var connection = new SqliteConnection(cs); await connection.OpenAsync(); await using var command = connection.CreateCommand(); command.CommandText = "SELECT _id, _migration_id, _scheme_id, IFNULL(_structure_id, ''), IFNULL(_property_name, ''), " + "IFNULL(_expression_hash, ''), _migration_type, _applied_at, IFNULL(_applied_by, ''), " + "IFNULL(_affected_rows, ''), _dry_run FROM _migrations ORDER BY _id"; await using var reader = await command.ExecuteReaderAsync(); while (await reader.ReadAsync()) rows.Add(string.Join("|", Enumerable.Range(0, reader.FieldCount).Select(i => Convert.ToString(reader.GetValue(i), System.Globalization.CultureInfo.InvariantCulture)))); return rows; } private static async Task ScalarAsync(string cs, string sql) { await using var connection = new SqliteConnection(cs); await connection.OpenAsync(); await using var command = connection.CreateCommand(); command.CommandText = sql; return Convert.ToString(await command.ExecuteScalarAsync(), System.Globalization.CultureInfo.InvariantCulture); } private static async Task<(T Result, string Output)> CapturedAsync(Func> run) { var console = Console.Out; var output = new StringWriter(); Console.SetOut(output); try { return (await run(), output.ToString()); } finally { Console.SetOut(console); } } private string NewDatabase(string suffix) { global::redb.SQLite.Data.SqliteDataSource.NativeExtensionPath ??= SqliteTestSupport.ResolveNativeExtension(); var cs = $"Data Source=redb_tests_export_migrations_{suffix}_{Guid.NewGuid():N}.db"; SqliteTestSupport.DeleteDbFiles(cs); _databases.Add(cs); return cs; } private string NewFile() { var file = Path.Combine(Path.GetTempPath(), $"redb-export-migrations-{Guid.NewGuid():N}.redb"); _files.Add(file); return file; } private static ServiceProvider Build(string cs) { var license = new ConfigurationBuilder().AddJsonFile("appsettings.json").Build()["Redb:License"]; var services = new ServiceCollection(); services.AddLogging(b => b.SetMinimumLevel(LogLevel.Warning)); services.AddRedbPro(options => { options.UseSqlite(cs).Configure(c => c.CacheDomain = $"export-migrations-{Guid.NewGuid():N}"); if (!string.IsNullOrWhiteSpace(license)) options.WithLicense(license); }); return services.BuildServiceProvider(); } }