Path: redb/redb.Tests.Integration/Tests/Base/PropertyRenameTestsBase.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/PropertyRenameTestsBase.cs ---- using redb.Core; using redb.Core.Exceptions; using redb.Core.Models.Entities; using redb.Core.Utils; using redb.Tests.Integration.Models; namespace redb.Tests.Integration.Tests.Base; /// /// [RedbRename] on properties: the sync renames the stored structure in place (same id, same values), a second /// sync does nothing, both names stored is an error, and a class older than the rename stops at its sync instead of /// adding the old name again. Every name-derived signature of the scheme is checked after the rename: the scheme hash, /// the cached scheme, the structure tree, the metadata cache table, and queries through it (the Pro field resolver on /// the Pro fixtures). /// public abstract class PropertyRenameTestsBase : IAsyncLifetime { protected readonly IRedbService Redb; protected PropertyRenameTestsBase(IRedbService redb) => Redb = redb; private static readonly string[] Schemes = [ typeof(RenameBasicV1).FullName!, typeof(RenameChainV1).FullName!, typeof(RenameJumpV1).FullName!, typeof(RenameBothV1).FullName!, typeof(RenameClashProps).FullName!, typeof(RenameReuseV1).FullName!, typeof(RenameTypeV1).FullName!, typeof(RenameHashV1).FullName!, typeof(RenameSwapV1).FullName!, typeof(RenameSwapOneStep).FullName!, ]; public async Task InitializeAsync() => await ResetAsync(); public async Task DisposeAsync() => await ResetAsync(); private async Task ResetAsync() { foreach (var name in Schemes) { await Redb.Context.ExecuteAsync( $"DELETE FROM _objects WHERE _id_scheme IN (SELECT _id FROM _schemes WHERE _name = '{name}')"); await Redb.Context.ExecuteAsync( $"DELETE FROM _structures WHERE _id_scheme IN (SELECT _id FROM _schemes WHERE _name = '{name}')"); await Redb.Context.ExecuteAsync($"DELETE FROM _schemes WHERE _name = '{name}'"); } Redb.Cache.Clear(); } private Task StructureIdAsync(string scheme, string name) => Redb.Context.ExecuteScalarAsync( $"SELECT _id FROM _structures WHERE _name = '{name}' AND _id_scheme = (SELECT _id FROM _schemes WHERE _name = '{scheme}')"); private Task RenamedFromAsync(long structureId) => Redb.Context.ExecuteScalarAsync($"SELECT _renamed_from FROM _structures WHERE _id = {structureId}"); /// /// The database as an intermediate class version left it after its rename: a second class claiming the same /// explicit scheme name would be a name conflict in one test assembly, so that sync is reproduced by SQL. /// private async Task StageRenameAsync(long structureId, string name, string renamedFrom) { await Redb.Context.ExecuteAsync( $"UPDATE _structures SET _name = '{name}', _renamed_from = '{renamedFrom}' WHERE _id = {structureId}"); Redb.Cache.Clear(); } private Task StructureCountAsync(string scheme) => Redb.Context.ExecuteScalarAsync( $"SELECT COUNT(*) FROM _structures WHERE _id_scheme = (SELECT _id FROM _schemes WHERE _name = '{scheme}')"); [Fact] public async Task Rename_KeepsStructuresAndValues_RootAndNested() { var scheme = typeof(RenameBasicV1).FullName!; await Redb.SyncSchemeAsync(); var obj = new RedbObject { name = "rename-basic", Props = new RenameBasicV1 { Title = "h1", Count = 7, Address = new RenameAddressV1 { City = "Paris", Street = "Rue" } }, }; obj.id = await Redb.SaveAsync(obj); var titleId = await StructureIdAsync(scheme, "Title"); var cityId = await StructureIdAsync(scheme, "City"); var structureCount = await StructureCountAsync(scheme); // Caches warmed under the old names: a query through every name-keyed path. (await Redb.Query().Where(x => x.Title == "h1" && x.Address.City == "Paris").CountAsync()).Should().Be(1); await Redb.SyncSchemeAsync(); (await StructureIdAsync(scheme, "Heading")).Should().Be(titleId, "the rename keeps the structure"); (await StructureIdAsync(scheme, "Town")).Should().Be(cityId, "a nested property is renamed the same way"); (await StructureIdAsync(scheme, "Title")).Should().BeNull(); (await StructureIdAsync(scheme, "City")).Should().BeNull(); (await StructureCountAsync(scheme)).Should().Be(structureCount, "nothing is added or deleted"); (await RenamedFromAsync(titleId!.Value)).Should().Be("[\"Title\"]"); (await RenamedFromAsync(cityId!.Value)).Should().Be("[\"City\"]"); var loaded = await Redb.LoadAsync(obj.id); loaded!.Props.Heading.Should().Be("h1"); loaded.Props.Address.Town.Should().Be("Paris"); loaded.Props.Address.Street.Should().Be("Rue"); loaded.Props.Count.Should().Be(7); (await Redb.Query().Where(x => x.Heading == "h1").CountAsync()).Should().Be(1); (await Redb.Query().Where(x => x.Address.Town == "Paris").CountAsync()).Should().Be(1); } [Fact] public async Task Rename_RecomputesOrInvalidatesEveryNameDerivedSignature() { var scheme = typeof(RenameBasicV1).FullName!; // SyncSchemeAsync returns the scheme as read back from _schemes after the sync: its hash is the stored one. var before = await Redb.SyncSchemeAsync(); var hashBefore = before.StructureHash; // Every cache filled under the old names first. (await Redb.GetSchemeByTypeAsync())!.Structures.Should().Contain(s => s.Name == "Title"); (await Redb.GetStructureTreeAsync(before.Id)).Should().Contain(n => n.Structure.Name == "Title"); var titleId = (await StructureIdAsync(scheme, "Title"))!.Value; var after = await Redb.SyncSchemeAsync(); after.Id.Should().Be(before.Id); var hashAfter = after.StructureHash; hashAfter.Should().NotBeNull(); hashAfter.Should().NotBe(hashBefore!.Value, "the scheme hash covers the names and is recomputed"); hashAfter.Should().Be(SchemeHashCalculator.ComputeSchemeStructureHash(after.Structures.Cast().ToList()), "the stored hash is the hash of the renamed structures"); var cached = await Redb.GetSchemeByTypeAsync(); cached!.StructureHash.Should().Be(hashAfter, "the cached scheme is replaced"); cached.Structures.Should().Contain(s => s.Id == titleId && s.Name == "Heading"); cached.Structures.Should().NotContain(s => s.Name == "Title" || s.Name == "City"); var tree = await Redb.GetStructureTreeAsync(after.Id); tree.Should().Contain(n => n.Structure.Id == titleId && n.Structure.Name == "Heading", "the tree cache is dropped"); tree.Single(n => n.Structure.Name == "Address").Children.Should().Contain(n => n.Structure.Name == "Town"); (await Redb.Context.ExecuteScalarAsync( $"SELECT _name FROM _scheme_metadata_cache WHERE _structure_id = {titleId}")) .Should().Be("Heading", "the metadata cache table is rebuilt"); (await Redb.Context.ExecuteScalarAsync( $"SELECT COUNT(*) FROM _scheme_metadata_cache WHERE _scheme_id = {after.Id} AND _name IN ('Title', 'City')")) .Should().Be(0); // A second sync is a no-op: the same hash, the same rows. (await Redb.SyncSchemeAsync()).StructureHash.Should().Be(hashAfter); (await RenamedFromAsync(titleId)).Should().Be("[\"Title\"]"); } [Fact] public async Task OldClass_AfterRename_StopsWithoutChanges() { var scheme = typeof(RenameBasicV1).FullName!; await Redb.SyncSchemeAsync(); var obj = new RedbObject { name = "rename-old-class", Props = new RenameBasicV1 { Title = "kept", Address = new RenameAddressV1 { City = "Rome" } }, }; obj.id = await Redb.SaveAsync(obj); await Redb.SyncSchemeAsync(); var structureCount = await StructureCountAsync(scheme); Redb.Cache.Clear(); var act = () => Redb.SyncSchemeAsync(); var error = (await act.Should().ThrowAsync()).Which; error.Name.Should().Be("RenameBasicV1.Title"); error.StoredNames.Should().Equal("Heading"); (await StructureIdAsync(scheme, "Title")).Should().BeNull("the old name is not added again"); (await StructureCountAsync(scheme)).Should().Be(structureCount, "nothing is deleted"); (await Redb.LoadAsync(obj.id))!.Props.Heading.Should().Be("kept"); } [Fact] public async Task OldClass_NestedRenameOnly_Stops() { var scheme = typeof(RenameBasicV1).FullName!; await Redb.SyncSchemeAsync(); await Redb.SyncSchemeAsync(); // Only the nested rename is undone in the database: the root level matches the old class again. var headingId = (await StructureIdAsync(scheme, "Heading"))!.Value; await Redb.Context.ExecuteAsync($"UPDATE _structures SET _name = 'Title', _renamed_from = NULL WHERE _id = {headingId}"); Redb.Cache.Clear(); var act = () => Redb.SyncSchemeAsync(); var error = (await act.Should().ThrowAsync()).Which; error.Name.Should().Be("RenameAddressV1.City"); (await StructureIdAsync(scheme, "Town")).Should().NotBeNull(); } [Fact] public async Task Chain_StepByStep_KeepsEveryPreviousName() { var scheme = typeof(RenameChainV1).FullName!; await Redb.SyncSchemeAsync(); var obj = new RedbObject { name = "rename-chain", Props = new RenameChainV1 { Title = "c" } }; obj.id = await Redb.SaveAsync(obj); var id = (await StructureIdAsync(scheme, "Title"))!.Value; await StageRenameAsync(id, "Heading", "[\"Title\"]"); await Redb.SyncSchemeAsync(); (await StructureIdAsync(scheme, "Caption")).Should().Be(id); (await RenamedFromAsync(id)).Should().Be("[\"Title\",\"Heading\"]"); (await Redb.LoadAsync(obj.id))!.Props.Caption.Should().Be("c"); // The first class is two renames behind and still stops. Redb.Cache.Clear(); await FluentActions.Invoking(() => Redb.SyncSchemeAsync()) .Should().ThrowAsync(); (await StructureIdAsync(scheme, "Caption")).Should().Be(id); } [Fact] public async Task Chain_DatabaseThatMissedAVersion_IsRenamedToo() { var scheme = typeof(RenameJumpV1).FullName!; await Redb.SyncSchemeAsync(); var obj = new RedbObject { name = "rename-jump", Props = new RenameJumpV1 { Title = "j" } }; obj.id = await Redb.SaveAsync(obj); var id = (await StructureIdAsync(scheme, "Title"))!.Value; await Redb.SyncSchemeAsync(); (await StructureIdAsync(scheme, "Caption")).Should().Be(id); (await RenamedFromAsync(id)).Should().Be("[\"Title\"]"); (await Redb.LoadAsync(obj.id))!.Props.Caption.Should().Be("j"); } [Fact] public async Task BothNamesStored_IsAnError_AndChangesNothing() { var scheme = typeof(RenameBothV1).FullName!; await Redb.SyncSchemeAsync(); var titleId = (await StructureIdAsync(scheme, "Title"))!.Value; var headingId = (await StructureIdAsync(scheme, "Heading"))!.Value; var act = () => Redb.SyncSchemeAsync(); var error = (await act.Should().ThrowAsync()).Which; error.Name.Should().Be("RenameBothV2.Heading"); error.StoredNames.Should().Equal("Title"); (await StructureIdAsync(scheme, "Title")).Should().Be(titleId); (await StructureIdAsync(scheme, "Heading")).Should().Be(headingId); } [Fact] public async Task PreviousName_CarriedAgain_BeforeTheRenameIsApplied_IsADeclarationError() { // The database stores Title and not Heading: the stored Title could belong to the renamed Heading or to the // new Title. var scheme = typeof(RenameReuseV1).FullName!; await Redb.SyncSchemeAsync(); var id = (await StructureIdAsync(scheme, "Title"))!.Value; var structureCount = await StructureCountAsync(scheme); var act = () => Redb.SyncSchemeAsync(); (await act.Should().ThrowAsync()).Which.Message.Should().Contain("[RedbRename(\"Title\")]"); (await StructureIdAsync(scheme, "Title")).Should().Be(id); (await StructureCountAsync(scheme)).Should().Be(structureCount, "nothing is written"); } [Fact] public async Task PreviousName_CarriedAgain_InANewDatabase_CreatesBoth() { // A database created with the class: neither name is stored, both properties are new; the next sync is a no-op. var scheme = typeof(RenameClashProps).FullName!; var first = await Redb.SyncSchemeAsync(); var headingId = (await StructureIdAsync(scheme, "Heading"))!.Value; var titleId = (await StructureIdAsync(scheme, "Title"))!.Value; Redb.Cache.Clear(); (await Redb.SyncSchemeAsync()).StructureHash.Should().Be(first.StructureHash); (await StructureIdAsync(scheme, "Heading")).Should().Be(headingId); (await StructureIdAsync(scheme, "Title")).Should().Be(titleId); (await RenamedFromAsync(headingId)).Should().BeNull("a database created with the renamed class has no history"); } [Fact] public async Task FreedName_TakenByANewProperty_IsAllowed() { var scheme = typeof(RenameReuseV1).FullName!; await Redb.SyncSchemeAsync(); var id = (await StructureIdAsync(scheme, "Title"))!.Value; await StageRenameAsync(id, "Heading", "[\"Title\"]"); await Redb.SyncSchemeAsync(); (await StructureIdAsync(scheme, "Heading")).Should().Be(id); (await StructureIdAsync(scheme, "Title")).Should().NotBeNull().And.NotBe(id, "the freed name is a new property"); // The next sync is a no-op. Redb.Cache.Clear(); await Redb.SyncSchemeAsync(); (await StructureIdAsync(scheme, "Heading")).Should().Be(id); (await RenamedFromAsync(id)).Should().Be("[\"Title\"]"); // The class of the first version still stops: it lacks the renamed property. Redb.Cache.Clear(); await FluentActions.Invoking(() => Redb.SyncSchemeAsync()) .Should().ThrowAsync(); } [Fact] public async Task Rename_KeepsEveryStoredHash_RootAndNested() { // Root: Title -> Aaron moves the property before Alpha in name order. Nested: City -> Town moves it after // Street. The first name of the chain keeps both where they sorted, so no stored hash moves. await Redb.SyncSchemeAsync(); var flat = new RedbObject { name = "rename-hash-root", Props = new RenameHashV1 { Alpha = "a", Title = "t", Zulu = "z" }, }; flat.id = await Redb.SaveAsync(flat); await Redb.SyncSchemeAsync(); var nested = new RedbObject { name = "rename-hash-nested", Props = new RenameBasicV1 { Title = "h", Count = 3, Address = new RenameAddressV1 { City = "Oslo", Street = "Gate" } }, }; nested.id = await Redb.SaveAsync(nested); var flatHash = (await Redb.LoadAsync(flat.id))!.Hash; var nestedHash = (await Redb.LoadAsync(nested.id))!.Hash; var addressHash = RedbHash.ComputeForProps(nested.Props.Address); flatHash.Should().NotBeNull(); nestedHash.Should().NotBeNull(); await Redb.SyncSchemeAsync(); await Redb.SyncSchemeAsync(); Redb.Cache.Clear(); var flatAfter = (await Redb.LoadAsync(flat.id))!; flatAfter.Props.Aaron.Should().Be("t"); flatAfter.Hash.Should().Be(flatHash); RedbHash.ComputeFor(flatAfter).Should().Be(flatHash, "the renamed class computes the hash that is stored"); var nestedAfter = (await Redb.LoadAsync(nested.id))!; nestedAfter.Props.Address.Town.Should().Be("Oslo"); RedbHash.ComputeFor(nestedAfter).Should().Be(nestedHash); RedbHash.ComputeForProps(nestedAfter.Props.Address).Should().Be(addressHash, "the content hash of the nested class (base row, unique keys) does not move either"); // An unchanged save keeps the stored hash. await Redb.SaveAsync(flatAfter); (await Redb.LoadAsync(flat.id))!.Hash.Should().Be(flatHash); } [Fact] public async Task Swap_ThroughATemporaryName_KeepsTheHashes_AndSavesTheValuesSwappedBack() { // Left and Right swap names through Tmp, one deployment per rename; the first two are staged by SQL, the class // of the third (RenameSwapV3) renames Tmp to Right. Ordered by the current names, the swapped class would hash // the swapped-back values exactly as the stored row, and a save that compares hashes would skip them. var scheme = typeof(RenameSwapV1).FullName!; await Redb.SyncSchemeAsync(); var obj = new RedbObject { name = "rename-swap", Props = new RenameSwapV1 { Left = "x", Right = "y" } }; obj.id = await Redb.SaveAsync(obj); var storedHash = (await Redb.LoadAsync(obj.id))!.Hash; var leftId = (await StructureIdAsync(scheme, "Left"))!.Value; var rightId = (await StructureIdAsync(scheme, "Right"))!.Value; await StageRenameAsync(leftId, "Tmp", "[\"Left\"]"); await StageRenameAsync(rightId, "Left", "[\"Right\"]"); await Redb.SyncSchemeAsync(); (await StructureIdAsync(scheme, "Right")).Should().Be(leftId); (await StructureIdAsync(scheme, "Left")).Should().Be(rightId); (await RenamedFromAsync(leftId)).Should().Be("[\"Left\",\"Tmp\"]"); (await RenamedFromAsync(rightId)).Should().Be("[\"Right\"]"); Redb.Cache.Clear(); var loaded = (await Redb.LoadAsync(obj.id))!; loaded.Props.Right.Should().Be("x"); loaded.Props.Left.Should().Be("y"); loaded.Hash.Should().Be(storedHash); RedbHash.ComputeFor(loaded).Should().Be(storedHash, "no stored hash moves across the swap"); loaded.Props.Right = "y"; loaded.Props.Left = "x"; RedbHash.ComputeFor(loaded)!.Value.Should().NotBe(storedHash!.Value, "the swapped-back values are a change"); await Redb.SaveAsync(loaded); Redb.Cache.Clear(); var reloaded = (await Redb.LoadAsync(obj.id))!; reloaded.Props.Right.Should().Be("y"); reloaded.Props.Left.Should().Be("x"); } [Fact] public async Task Swap_TwoRenamesInOneDeployment_IsRefusedByTheReuseRule() { // Only Left to Tmp is applied; the class of the last step arrives next, asking Right to Left and Tmp to Right // at once. The database stores Right and not Left: the stored Right could be the renamed one or the other. var scheme = typeof(RenameSwapV1).FullName!; await Redb.SyncSchemeAsync(); var leftId = (await StructureIdAsync(scheme, "Left"))!.Value; var rightId = (await StructureIdAsync(scheme, "Right"))!.Value; await StageRenameAsync(leftId, "Tmp", "[\"Left\"]"); var act = () => Redb.SyncSchemeAsync(); (await act.Should().ThrowAsync()).Which.Message .Should().Contain("the database stores 'Right' but not 'Left'"); (await StructureIdAsync(scheme, "Tmp")).Should().Be(leftId); (await StructureIdAsync(scheme, "Right")).Should().Be(rightId); } [Fact] public async Task Swap_InOneStep_IsADeclarationError_InANewDatabase() { var act = () => Redb.SyncSchemeAsync(); (await act.Should().ThrowAsync()).Which.Message .Should().Contain("swaps the two names in one step").And.Contain("temporary name"); (await StructureCountAsync(typeof(RenameSwapOneStep).FullName!)).Should().Be(0); } [Fact] public async Task Swap_InOneStep_IsADeclarationError_WithAHistory() { // The database already holds the swapped state with its history: the class is refused all the same, from the // declaration alone. var scheme = typeof(RenameSwapV1).FullName!; await Redb.SyncSchemeAsync(); var leftId = (await StructureIdAsync(scheme, "Left"))!.Value; var rightId = (await StructureIdAsync(scheme, "Right"))!.Value; await StageRenameAsync(leftId, "SwapTmp", "[\"Left\"]"); await StageRenameAsync(rightId, "Left", "[\"Right\"]"); await StageRenameAsync(leftId, "Right", "[\"Left\"]"); await Redb.Context.ExecuteAsync( $"UPDATE _schemes SET _name = '{typeof(RenameSwapOneStep).FullName}' WHERE _name = '{scheme}'"); Redb.Cache.Clear(); var act = () => Redb.SyncSchemeAsync(); (await act.Should().ThrowAsync()).Which.Message .Should().Contain("swaps the two names in one step"); (await StructureIdAsync(typeof(RenameSwapOneStep).FullName!, "Right")).Should().Be(leftId); (await StructureIdAsync(typeof(RenameSwapOneStep).FullName!, "Left")).Should().Be(rightId); } [Fact] public async Task History_WithAnotherFirstName_StopsWithoutChanges() { var scheme = typeof(RenameBasicV1).FullName!; await Redb.SyncSchemeAsync(); await Redb.SyncSchemeAsync(); var headingId = (await StructureIdAsync(scheme, "Heading"))!.Value; // The history starts with a name the class does not declare first. await Redb.Context.ExecuteAsync($"UPDATE _structures SET _renamed_from = '[\"Caption\",\"Title\"]' WHERE _id = {headingId}"); Redb.Cache.Clear(); var act = () => Redb.SyncSchemeAsync(); var error = (await act.Should().ThrowAsync()).Which; error.Name.Should().Be("RenameBasicV2.Heading"); error.StoredNames.Should().Equal("Caption", "Title"); error.Message.Should().Contain("[RedbRename(\"Caption\")]"); (await StructureIdAsync(scheme, "Heading")).Should().Be(headingId); } [Fact] public async Task History_WithoutTheAttribute_StopsWithoutChanges() { // A renamed property whose class dropped [RedbRename]: its hashes would be computed in another order. var scheme = typeof(RenameTypeV1).FullName!; await Redb.SyncSchemeAsync(); var id = (await StructureIdAsync(scheme, "Count"))!.Value; await Redb.Context.ExecuteAsync($"UPDATE _structures SET _renamed_from = '[\"Amount\"]' WHERE _id = {id}"); Redb.Cache.Clear(); var act = () => Redb.SyncSchemeAsync(); var error = (await act.Should().ThrowAsync()).Which; error.Name.Should().Be("RenameTypeV1.Count"); error.Message.Should().Contain("declares none"); (await StructureIdAsync(scheme, "Count")).Should().Be(id); } [Fact] public async Task Chain_FirstRenameOfADatabaseCreatedMidChain_RecordsTheChainFromTheFirstName() { // The database was created by the class of the middle version (Heading): it has no history. Renaming it to // Caption records the chain from its first name, the name the hash canon sorts by. var scheme = typeof(RenameChainV1).FullName!; await Redb.SyncSchemeAsync(); var id = (await StructureIdAsync(scheme, "Title"))!.Value; await Redb.Context.ExecuteAsync($"UPDATE _structures SET _name = 'Heading' WHERE _id = {id}"); Redb.Cache.Clear(); await Redb.SyncSchemeAsync(); (await StructureIdAsync(scheme, "Caption")).Should().Be(id); (await RenamedFromAsync(id)).Should().Be("[\"Title\",\"Heading\"]"); } [Fact] public async Task RenameAndTypeChange_RenamesFirst_ThenMigratesTheType() { var scheme = typeof(RenameTypeV1).FullName!; await Redb.SyncSchemeAsync(); var obj = new RedbObject { name = "rename-type", Props = new RenameTypeV1 { Count = 42 } }; obj.id = await Redb.SaveAsync(obj); var id = (await StructureIdAsync(scheme, "Count"))!.Value; await Redb.SyncSchemeAsync(); (await StructureIdAsync(scheme, "Total")).Should().Be(id); (await Redb.LoadAsync(obj.id))!.Props.Total.Should().Be(42); } }