Path: redb/redb.Tests.Integration/Tests/Base/ExportRenameHistoryTestsBase.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/Base/ExportRenameHistoryTestsBase.cs
----
using System.Text.RegularExpressions;
using Microsoft.Extensions.DependencyInjection;
using redb.Core;
using redb.Core.Data;
using redb.Core.Exceptions;
using redb.Core.Models.Entities;
using redb.Export.Providers;
using redb.Export.Services;
using redb.Tests.Integration.Models;
namespace redb.Tests.Integration.Tests.Base;
///
/// redb.Export carries _schemes._renamed_from and _structures._renamed_from: the rename history the sync
/// reads to stop a class older than a rename. Without it a database that went through an export and an import let the
/// old class add its old names again. A file written before the columns existed imports as before, with no history.
/// Every test runs on scratch databases of its own; the subclass creates and drops them.
///
public abstract class ExportRenameHistoryTestsBase
{
private const string PropertyScheme = "redb.Tests.Integration.Models.RenameBasicV1";
private const string RenamedScheme = "rename_scheme_v2";
private const string GhostScheme = "rename_scheme_ghost";
/// The provider name of : postgres, mssql or sqlite.
protected abstract string ProviderName { get; }
/// A new empty database of this run; the subclass drops it afterwards.
protected abstract Task NewDatabaseAsync(string suffix);
/// A redb service over with a cache domain of its own.
protected abstract ServiceProvider Build(string cs);
/// The first column of the first row as text (a blob as hex), null for SQL NULL or no row.
protected abstract Task ScalarAsync(string cs, string sql);
/// Runs a statement on .
protected abstract Task ExecuteSqlAsync(string cs, string sql);
/// The first two columns of every row as text.
protected abstract Task> PairsAsync(string cs, string sql);
/// A value of a reader as the text the assertions compare: a blob as hex.
protected static string? AsText(object? value) => value switch
{
null or DBNull => null,
byte[] bytes => Convert.ToHexString(bytes),
_ => value.ToString(),
};
/// A file the subclass deletes afterwards.
protected abstract string NewFile();
[Fact]
public async Task ARoundTrip_KeepsTheRenameHistory_TheNewClassesSyncAsANoOp_AndTheOldClassesStop()
{
var source = await RenamedSourceAsync();
var before = await HistoryAsync(source);
var target = await NewEmptyAsync("dst");
await ImportAsync(target, await ExportAsync(source, null));
(await HistoryAsync(target)).Should().Equal(before, "the history travels as the stored JSON text");
await NewClassesAreANoOpAsync(target);
await OldClassesStopAsync(target);
}
[Fact]
public async Task ASchemeFilteredExport_CarriesTheHistoryOfTheSchemesItExports()
{
var source = await RenamedSourceAsync();
var before = await HistoryAsync(source);
var schemeIds = new[]
{
long.Parse((await ScalarAsync(source, $"SELECT _id FROM _schemes WHERE _name = '{PropertyScheme}'"))!),
long.Parse((await ScalarAsync(source, $"SELECT _id FROM _schemes WHERE _name = '{RenamedScheme}'"))!),
long.Parse((await ScalarAsync(source, $"SELECT _id FROM _schemes WHERE _name = '{GhostScheme}'"))!),
};
var target = await NewEmptyAsync("dst");
await ImportAsync(target, await ExportAsync(source, schemeIds));
(await HistoryAsync(target)).Should().Equal(before);
await OldClassesStopAsync(target);
}
[Fact]
public async Task AFileWrittenBeforeTheColumns_ImportsAsBefore_WithNoHistory()
{
var source = await RenamedSourceAsync();
var file = await ExportAsync(source, null);
// A file of an older redb.Export: the same records without the property.
var lines = await File.ReadAllLinesAsync(file);
lines.Count(l => l.Contains("\"renamed_from\":", StringComparison.Ordinal)).Should().Be(4,
"precondition: the export writes the history of the two renamed schemes and of the two renamed properties");
await File.WriteAllLinesAsync(file,
lines.Select(l => Regex.Replace(l, @",""renamed_from"":""(?:[^""\\]|\\.)*""", "")));
var target = await NewEmptyAsync("dst");
await ImportAsync(target, file);
(await ScalarAsync(target, "SELECT COUNT(*) FROM _schemes WHERE _renamed_from IS NOT NULL")).Should().Be("0");
(await ScalarAsync(target, "SELECT COUNT(*) FROM _structures WHERE _renamed_from IS NOT NULL")).Should().Be("0");
(await ScalarAsync(target, $"SELECT COUNT(*) FROM _schemes WHERE _name = '{RenamedScheme}'")).Should().Be("1",
"everything else of the file is imported");
}
///
/// A database where a property of (and one of its nested class) and the scheme of
/// were renamed by the sync, each with an object stored before the rename. The scheme of
/// is renamed as a version this process does not have would leave it: this process
/// declares , so to it the name of is free again, and only a
/// scheme renamed by a class it does not have shows the guard.
///
private async Task RenamedSourceAsync()
{
var source = await NewEmptyAsync("src");
await using var provider = Build(source);
var redb = provider.GetRequiredService();
await InitializeAsync(redb);
await redb.SyncSchemeAsync();
await redb.SaveAsync(new RedbObject
{
name = "renamed-props",
Props = new RenameBasicV1 { Title = "t", Count = 1, Address = new RenameAddressV1 { City = "Paris", Street = "Rue" } },
});
await redb.SyncSchemeAsync();
await redb.SyncSchemeAsync();
await redb.SaveAsync(new RedbObject { name = "renamed-scheme", Props = new SchemeRenameV1 { Title = "s" } });
await redb.SyncSchemeAsync();
var guard = await redb.SyncSchemeAsync();
await redb.SaveAsync(new RedbObject { name = "renamed-away", Props = new SchemeRenameGuardV1 { Title = "g" } });
await ExecuteSqlAsync(source,
$"UPDATE _schemes SET _name = '{GhostScheme}', _renamed_from = '[\"{typeof(SchemeRenameGuardV1).FullName}\"]' WHERE _id = {guard.Id}");
(await ScalarAsync(source, $"SELECT _renamed_from FROM _schemes WHERE _name = '{RenamedScheme}'"))
.Should().Be("[\"redb.Tests.Integration.Models.SchemeRenameV1\"]", "precondition: the scheme rename is recorded");
(await ScalarAsync(source, "SELECT COUNT(*) FROM _structures WHERE _renamed_from IS NOT NULL"))
.Should().Be("2", "precondition: Title and the nested City are recorded");
return source;
}
/// Every row with a history, as table:id=text, in id order.
private async Task> HistoryAsync(string cs)
{
var rows = new List();
foreach (var table in new[] { "_schemes", "_structures" })
{
var pairs = await PairsAsync(cs, $"SELECT _id, _renamed_from FROM {table} WHERE _renamed_from IS NOT NULL ORDER BY _id");
rows.AddRange(pairs.Select(p => $"{table}:{p.First}={p.Second}"));
}
rows.Should().HaveCount(4, "two renamed schemes and two renamed properties");
return rows;
}
/// The classes of the renamed version find everything in place: no structure or scheme changes.
private async Task NewClassesAreANoOpAsync(string cs)
{
const string structuresSql = "SELECT COUNT(*) FROM _structures";
var structures = await ScalarAsync(cs, structuresSql);
var hash = await ScalarAsync(cs, $"SELECT _structure_hash FROM _schemes WHERE _name = '{PropertyScheme}'");
var history = await HistoryAsync(cs);
await using var provider = Build(cs);
var redb = provider.GetRequiredService();
await InitializeAsync(redb);
await redb.SyncSchemeAsync();
await redb.SyncSchemeAsync();
(await ScalarAsync(cs, structuresSql)).Should().Be(structures);
(await ScalarAsync(cs, $"SELECT _structure_hash FROM _schemes WHERE _name = '{PropertyScheme}'")).Should().Be(hash);
(await HistoryAsync(cs)).Should().Equal(history);
(await ScalarAsync(cs, $"SELECT COUNT(*) FROM _schemes WHERE _name = '{typeof(SchemeRenameV1).FullName}'")).Should().Be("0");
var loaded = await redb.Query().Where(x => x.Heading == "t").ToListAsync();
loaded.Should().ContainSingle().Which.Props.Address.Town.Should().Be("Paris", "the values stay under the renamed fields");
}
/// The classes of the version before the rename stop at their sync instead of adding the old names again.
private async Task OldClassesStopAsync(string cs)
{
await using var provider = Build(cs);
var redb = provider.GetRequiredService();
await InitializeAsync(redb);
var oldProperties = async () => await redb.SyncSchemeAsync();
await oldProperties.Should().ThrowAsync();
var oldScheme = async () => await redb.SyncSchemeAsync();
(await oldScheme.Should().ThrowAsync()).Which.StoredNames.Should().Equal(GhostScheme);
(await ScalarAsync(cs, $"SELECT COUNT(*) FROM _structures WHERE _name IN ('Title', 'City') AND _id_scheme IN " +
$"(SELECT _id FROM _schemes WHERE _name = '{PropertyScheme}')")).Should().Be("0",
"the refused syncs added nothing");
(await ScalarAsync(cs, $"SELECT COUNT(*) FROM _schemes WHERE _name = '{typeof(SchemeRenameGuardV1).FullName}'"))
.Should().Be("0", "the old scheme is not created again");
}
private async Task NewEmptyAsync(string suffix)
{
var cs = await NewDatabaseAsync(suffix);
await using var provider = Build(cs);
await provider.GetRequiredService().InitializeAsync(ensureCreated: true, typeof(ExportService).Assembly);
return cs;
}
///
/// Start-up without the scheme scan of the test assembly: it would sync every attributed test class, the renamed
/// versions included, before the scenario's older classes.
///
private static Task InitializeAsync(IRedbService redb) => redb.InitializeAsync(typeof(ExportService).Assembly);
private async Task ExportAsync(string cs, long[]? schemeIds)
{
var file = NewFile();
await using var provider = ProviderFactory.Create(ProviderName);
await provider.OpenAsync(cs);
await new ExportService(provider, verbose: false, batchSize: 1000).ExportAsync(file, schemeIds, compress: false, dryRun: false);
return file;
}
private async Task ImportAsync(string cs, string file)
{
await using var provider = ProviderFactory.Create(ProviderName);
await provider.OpenAsync(cs);
await new ImportService(provider, verbose: false, batchSize: 1000).ImportAsync(file, clean: true, dryRun: false);
// The service that created the empty target took a block of ids into the process-wide key cache before the
// import reset the sequence: an application is stopped while a database is restored under it, this process
// goes on, so it drops the ids it holds. Without it a sync that adds a scheme (the scheme-filtered file has
// no UserConfigurationProps) took an id the import had written.
RedbKeyGeneratorBase.ClearAllCaches();
}
}