Path: redb/redb.Tests.Integration/Tests/Base/OlderModelTestsBase.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/OlderModelTestsBase.cs ---- using redb.Core; using redb.Core.Models.Configuration; using redb.Core.Models.Entities; using redb.Tests.Integration.Models; namespace redb.Tests.Integration.Tests.Base; /// /// REPRO (red expected before a guard): a process built with an OLDER Props class starts against a database a NEWER /// build already synced and wrote, as in a rolling deployment. The newer class syncs and saves under its own scheme /// name; the scheme is then renamed to the older class's name, so the older class meets the structures and values the /// newer build left. Each test states the safe outcome: the older process does not take the newer build's data away. /// public abstract class OlderModelTestsBase : IAsyncLifetime { protected readonly IRedbService Redb; protected OlderModelTestsBase(IRedbService redb) => Redb = redb; /// Pro saves with ChangeTracking as well; the free providers have DeleteInsert only. protected virtual bool HasChangeTracking => true; private static readonly string[] Schemes = ["older_model_field_newer", "older_model_field", "older_model_type_newer", "older_model_type", "older_model_nested_newer", "older_model_nested", "older_model_clean", "older_model_clean_before", "held_bool_before", "held_bool", "held_text_before", "held_text", "held_kind_before", "held_kind"]; public async Task InitializeAsync() { foreach (var s in Schemes) await ResetAsync(s); } public async Task DisposeAsync() { foreach (var s in Schemes) await ResetAsync(s); } private async Task ResetAsync(string scheme) { await Redb.Context.ExecuteAsync($"DELETE FROM _objects WHERE _id_scheme IN (SELECT _id FROM _schemes WHERE _name = '{scheme}')"); await Redb.Context.ExecuteAsync($"DELETE FROM _structures WHERE _id_scheme IN (SELECT _id FROM _schemes WHERE _name = '{scheme}')"); await Redb.Context.ExecuteAsync($"DELETE FROM _schemes WHERE _name = '{scheme}'"); Redb.Cache.Clear(); } /// The newer build's scheme becomes the older build's: same structures, same values. private async Task HandOverAsync(string newer, string older) { await Redb.Context.ExecuteAsync($"UPDATE _schemes SET _name = '{older}' WHERE _name = '{newer}'"); Redb.Cache.Clear(); } private async Task StructureIdAsync(string scheme, string name) => await Redb.Context.ExecuteScalarAsync( $"SELECT _id FROM _structures WHERE _name = '{name}' AND _id_scheme IN (SELECT _id FROM _schemes WHERE _name = '{scheme}')"); private Task ValuesAsync(long structureId, string column) => Redb.Context.ExecuteScalarAsync( $"SELECT CAST(COUNT(*) AS BIGINT) FROM _values WHERE _id_structure = {structureId} AND {column} IS NOT NULL"); private async Task<(long Extra, List Ids)> SeedNewFieldAsync() { await Redb.SyncSchemeAsync(); var ids = new List(); foreach (var i in new[] { 1, 2, 3 }) ids.Add(await Redb.SaveAsync(new RedbObject { name = $"om-{i}", Props = new OlderModelFieldNewerProps { Tag = $"t{i}", Extra = $"x{i}" } })); var extra = (await StructureIdAsync("older_model_field_newer", "Extra"))!.Value; (await ValuesAsync(extra, "_String")).Should().Be(3, "precondition: the newer build wrote Extra"); await HandOverAsync("older_model_field_newer", "older_model_field"); return (extra, ids); } [Fact] public async Task OlderProcessStart_DefaultSettings_KeepsTheNewerField() { var (extra, _) = await SeedNewFieldAsync(); await Redb.SyncSchemeAsync(); (await StructureIdAsync("older_model_field", "Extra")).Should().Be(extra, "the structure of the newer field stays"); (await ValuesAsync(extra, "_String")).Should().Be(3, "and so do its values in every object"); } [Fact] public async Task OlderProcessStart_TypeChangedByTheNewerBuild_KeepsTheNewerType() { await Redb.SyncSchemeAsync(); foreach (var i in new[] { 1, 2, 3 }) await Redb.SaveAsync(new RedbObject { name = $"om-{i}", Props = new OlderModelTypeNewerProps { Tag = $"t{i}", Level = i % 2 } }); var level = (await StructureIdAsync("older_model_type_newer", "Level"))!.Value; var newerType = await Redb.Context.ExecuteScalarAsync($"SELECT _id_type FROM _structures WHERE _id = {level}"); await HandOverAsync("older_model_type_newer", "older_model_type"); await Redb.SyncSchemeAsync(); (await Redb.Context.ExecuteScalarAsync($"SELECT _id_type FROM _structures WHERE _id = {level}")) .Should().Be(newerType, "the older build does not take the type back"); (await ValuesAsync(level, "_Long")).Should().Be(3, "the values stay in the newer type's column"); } [Theory] [InlineData(PropsSaveStrategy.DeleteInsert)] [InlineData(PropsSaveStrategy.ChangeTracking)] public async Task OlderProcessSave_KeepsTheNewerFieldOfTheObject(PropsSaveStrategy strategy) { if (strategy == PropsSaveStrategy.ChangeTracking && !HasChangeTracking) return; var (extra, ids) = await SeedNewFieldAsync(); var strict = Redb.Configuration.DefaultStrictDeleteExtra; var saving = Redb.Configuration.PropsSaveStrategy; try { // The older process started without the destructive sync, so the structure is there; it then saves. Redb.Configuration.DefaultStrictDeleteExtra = false; Redb.Configuration.PropsSaveStrategy = strategy; await Redb.SyncSchemeAsync(); var obj = (await Redb.LoadAsync(ids[0]))!; obj.Props.Tag = "edited"; await Redb.SaveAsync(obj); } finally { Redb.Configuration.DefaultStrictDeleteExtra = strict; Redb.Configuration.PropsSaveStrategy = saving; } (await ValuesAsync(extra, "_String")).Should().Be(3, $"{strategy}: the saved object keeps its Extra value"); } // ===== fields a newer build added inside a nested class and a list element ===== private async Task<(long Country, long Note, long Id)> SeedNestedAsync() { await Redb.SyncSchemeAsync(); var id = await Redb.SaveAsync(new RedbObject { name = "om-nested", Props = new OlderModelNestedNewerProps { Tag = "t", Place = new OlderModelPlaceNewer { City = "Berlin", Country = "DE" }, Lines = [new OlderModelLineNewer { Name = "a", Note = "na" }, new OlderModelLineNewer { Name = "b", Note = "nb" }] } }); var place = (await StructureIdAsync("older_model_nested_newer", "Place"))!.Value; var lines = (await StructureIdAsync("older_model_nested_newer", "Lines"))!.Value; var country = (await Redb.Context.ExecuteScalarAsync($"SELECT _id FROM _structures WHERE _name = 'Country' AND _id_parent = {place}"))!.Value; var note = (await Redb.Context.ExecuteScalarAsync($"SELECT _id FROM _structures WHERE _name = 'Note' AND _id_parent = {lines}"))!.Value; await HandOverAsync("older_model_nested_newer", "older_model_nested"); return (country, note, id); } private async Task WithStrategyAsync(PropsSaveStrategy strategy, Func> act) { var strict = Redb.Configuration.DefaultStrictDeleteExtra; var saving = Redb.Configuration.PropsSaveStrategy; try { Redb.Configuration.DefaultStrictDeleteExtra = false; Redb.Configuration.PropsSaveStrategy = strategy; await Redb.SyncSchemeAsync(); return await act(); } finally { Redb.Configuration.DefaultStrictDeleteExtra = strict; Redb.Configuration.PropsSaveStrategy = saving; } } [Theory] [InlineData(PropsSaveStrategy.DeleteInsert)] [InlineData(PropsSaveStrategy.ChangeTracking)] public async Task OlderProcessSave_TopLevelEdit_KeepsTheNewerNestedFields_OrRefuses(PropsSaveStrategy strategy) { if (strategy == PropsSaveStrategy.ChangeTracking && !HasChangeTracking) return; var (country, note, id) = await SeedNestedAsync(); var error = await WithStrategyAsync(strategy, async () => { var obj = (await Redb.LoadAsync(id))!; obj.Props.Tag = "edited"; try { await Redb.SaveAsync(obj); return (Exception?)null; } catch (Exception ex) { return ex; } }); if (strategy == PropsSaveStrategy.DeleteInsert) { // DeleteInsert rewrites Place and Lines, which would take Country and Note: refused, nothing written. var older = error.Should().BeOfType().Subject; older.UnknownFields.Should().BeEquivalentTo(["Lines.Note", "Place.Country"]); older.SchemeName.Should().Be("older_model_nested"); older.Message.Should().Contain("Upgrade this process").And.NotContain("DE").And.NotContain("na"); } else { // ChangeTracking updates Tag alone and keeps the rows of Place and Lines: the save goes through. error.Should().BeNull(); } (await ValuesAsync(country, "_String")).Should().Be(1, $"{strategy}: Country stays"); (await ValuesAsync(note, "_String")).Should().Be(2, $"{strategy}: both Notes stay"); } [Fact] public async Task OlderProcessSave_ChangeTracking_EditInsideTheNestedClass_KeepsTheNewerField() { if (!HasChangeTracking) return; var (country, _, id) = await SeedNestedAsync(); await WithStrategyAsync(PropsSaveStrategy.ChangeTracking, async () => { var obj = (await Redb.LoadAsync(id))!; obj.Props.Place!.City = "Paris"; await Redb.SaveAsync(obj); return 0; }); (await ValuesAsync(country, "_String")).Should().Be(1, "City is updated in place and Country stays"); (await Redb.LoadAsync(id))!.Props.Place!.City.Should().Be("Paris"); } [Fact] public async Task OlderProcessSave_ChangeTracking_RemovingAnElement_IsRefused() { if (!HasChangeTracking) return; var (_, note, id) = await SeedNestedAsync(); var error = await WithStrategyAsync(PropsSaveStrategy.ChangeTracking, async () => { var obj = (await Redb.LoadAsync(id))!; obj.Props.Lines!.RemoveAt(0); try { await Redb.SaveAsync(obj); return (Exception?)null; } catch (Exception ex) { return ex; } }); error.Should().BeOfType() .Which.UnknownFields.Should().Contain("Lines.Note"); (await ValuesAsync(note, "_String")).Should().Be(2, "nothing was written"); } // ===== the version rule (RedbScheme.Version) ===== /// A literal of a Guid for the raw staging below (SQLite stores hashes as 16-byte blobs). protected virtual string GuidLiteral(Guid value) => $"'{value}'"; private async Task SeedCleanBeforeAsync() { await Redb.SyncSchemeAsync(); foreach (var i in new[] { 1, 2, 3 }) await Redb.SaveAsync(new RedbObject { name = $"om-{i}", Props = new OlderModelCleanBeforeProps { Tag = $"t{i}", Extra = $"x{i}" } }); var extra = (await StructureIdAsync("older_model_clean_before", "Extra"))!.Value; await HandOverAsync("older_model_clean_before", "older_model_clean"); return extra; } private Task StoredVersionAsync(string scheme) => Redb.Context.ExecuteScalarAsync($"SELECT CAST(_version AS BIGINT) FROM _schemes WHERE _name = '{scheme}'"); [Fact] public async Task HigherVersion_DeletesTheFieldItRemoved_AndRecordsTheVersion() { var extra = await SeedCleanBeforeAsync(); await Redb.SyncSchemeAsync(); (await StructureIdAsync("older_model_clean", "Extra")).Should().BeNull("a class of a higher version removes the field"); (await ValuesAsync(extra, "_String")).Should().Be(0); (await StoredVersionAsync("older_model_clean")).Should().Be(1); } [Fact] public async Task EqualVersion_WithTheDevelopmentSetting_DeletesTheField() { var (extra, _) = await SeedNewFieldAsync(); var setting = Redb.Configuration.DefaultDestructiveSyncAtEqualVersion; try { Redb.Configuration.DefaultDestructiveSyncAtEqualVersion = true; await Redb.SyncSchemeAsync(); } finally { Redb.Configuration.DefaultDestructiveSyncAtEqualVersion = setting; } (await StructureIdAsync("older_model_field", "Extra")).Should().BeNull("the setting lets an equal version delete"); (await ValuesAsync(extra, "_String")).Should().Be(0); } [Fact] public async Task DropUnknownStructures_ReportsFirst_ThenDeletes_NamingBothVersions() { var (extra, _) = await SeedNewFieldAsync(); await Redb.SyncSchemeAsync(); var dry = await Redb.DropUnknownStructuresAsync(); dry.DryRun.Should().BeTrue(); dry.SchemeName.Should().Be("older_model_field"); dry.Items.Should().ContainSingle().Which.Should().BeEquivalentTo(new { Path = "Extra", Values = 3L, Deleted = false }); dry.ToString().Should().Contain("class version 0").And.Contain("database version 0").And.Contain("would delete Extra (3 values)"); (await ValuesAsync(extra, "_String")).Should().Be(3, "a dry run deletes nothing"); var done = await Redb.DropUnknownStructuresAsync(dryRun: false); done.Items.Should().ContainSingle().Which.Deleted.Should().BeTrue(); (await StructureIdAsync("older_model_field", "Extra")).Should().BeNull(); (await ValuesAsync(extra, "_String")).Should().Be(0); (await Redb.DropUnknownStructuresAsync()).Items.Should().BeEmpty(); } [Fact] public async Task DropUnknownStructures_FromAnOlderClass_IsRefused() { await SeedCleanBeforeAsync(); await Redb.SyncSchemeAsync(); // version 1 recorded await Redb.Context.ExecuteAsync("UPDATE _schemes SET _version = 5 WHERE _name = 'older_model_clean'"); Redb.Cache.Clear(); var act = () => Redb.DropUnknownStructuresAsync(dryRun: false); (await act.Should().ThrowAsync()) .Which.Should().BeEquivalentTo(new { ClassVersion = 1, StoredVersion = 5 }, o => o.ExcludingMissingMembers()); } /// /// The research case: an older process keeps its cached scheme while a newer build changes a property's type and /// raises the version. The older process's save would write the old type over the new one; the save learns the new /// version from the hash the existing-objects query returns and is refused, the values untouched. /// [Fact] public async Task OlderProcessSave_AfterANewerBuildChangedAType_IsRefused_TheValuesUntouched() { await Redb.SyncSchemeAsync(); var id = await Redb.SaveAsync(new RedbObject { name = "om-type", Props = new OlderModelTypeOlderProps { Tag = "t", Level = true } }); var level = (await StructureIdAsync("older_model_type", "Level"))!.Value; var obj = (await Redb.LoadAsync(id))!; // the older process holds its cached scheme // The newer build, elsewhere: Level becomes a long (value 1 in _Long), version 1, a new structure hash. var longType = await Redb.Context.ExecuteScalarAsync("SELECT _id FROM _types WHERE _name = 'Long'"); await Redb.Context.ExecuteAsync($"UPDATE _values SET _Long = 1, _Boolean = NULL WHERE _id_structure = {level}"); await Redb.Context.ExecuteAsync($"UPDATE _structures SET _id_type = {longType} WHERE _id = {level}"); await Redb.Context.ExecuteAsync( $"UPDATE _schemes SET _version = 1, _structure_hash = {GuidLiteral(Guid.NewGuid())} WHERE _name = 'older_model_type'"); obj.Props.Tag = "edited"; var act = () => Redb.SaveAsync(obj); (await act.Should().ThrowAsync()) .Which.StoredVersion.Should().Be(1); (await ValuesAsync(level, "_Long")).Should().Be(1, "the newer build's value stays"); } // ===== a type changed without a raised version ===== private async Task<(long Id, long Flag)> SeedHeldAsync(string before, string after, TBefore props, bool sync = true) where TBefore : class, new() where TAfter : class, new() { await Redb.SyncSchemeAsync(); var id = await Redb.SaveAsync(new RedbObject { name = "held", Props = props }); var flag = (await StructureIdAsync(before, "Flag"))!.Value; await HandOverAsync(before, after); if (sync) await Redb.SyncSchemeAsync(); // the type change is held: version 0 = 0 return (id, flag); } private Task FlagRowsAsync(long flag) => Redb.Context.ExecuteScalarAsync( $"SELECT CAST(COUNT(*) AS BIGINT) FROM _values WHERE _id_structure = {flag} AND " + "(_String IS NOT NULL OR _Long IS NOT NULL OR _Boolean IS NOT NULL)"); private async Task SaveIsRefusedAsync(long id, Action edit, string stored, PropsSaveStrategy strategy) where TAfter : class, new() { var saving = Redb.Configuration.PropsSaveStrategy; try { Redb.Configuration.PropsSaveStrategy = strategy; var obj = (await Redb.LoadAsync(id))!; // reads go through the stored type edit(obj.Props); var act = () => Redb.SaveAsync(obj); var held = (await act.Should().ThrowAsync()).Which; held.Properties.Should().ContainSingle().Which.Path.Should().Be("Flag"); held.Properties[0].StoredType.Should().Contain(stored); held.Message.Should().Contain("Raise RedbScheme.Version"); var fresh = new RedbObject { name = "held-new", Props = new TAfter() }; var insert = () => Redb.SaveAsync(fresh); await insert.Should().ThrowAsync("a new object would write the same column"); } finally { Redb.Configuration.PropsSaveStrategy = saving; } } [Theory] [InlineData(PropsSaveStrategy.DeleteInsert)] [InlineData(PropsSaveStrategy.ChangeTracking)] public async Task HeldType_BoolToInt_ReadsTheStoredValue_RefusesTheSave(PropsSaveStrategy strategy) { if (strategy == PropsSaveStrategy.ChangeTracking && !HasChangeTracking) return; var (id, flag) = await SeedHeldAsync("held_bool_before", "held_bool", new HeldBoolBeforeProps { Tag = "t", Flag = true }); (await Redb.LoadAsync(id))!.Props.Flag.Should().Be(1, "true is read through the stored Boolean"); await SaveIsRefusedAsync(id, p => p.Flag = 5, "Boolean", strategy); (await FlagRowsAsync(flag)).Should().Be(1, "the stored value stays"); } [Theory] [InlineData(PropsSaveStrategy.DeleteInsert)] [InlineData(PropsSaveStrategy.ChangeTracking)] public async Task HeldType_TextToInt_RefusesTheSave(PropsSaveStrategy strategy) { if (strategy == PropsSaveStrategy.ChangeTracking && !HasChangeTracking) return; var (id, flag) = await SeedHeldAsync("held_text_before", "held_text", new HeldTextBeforeProps { Tag = "t", Flag = "42" }); await SaveIsRefusedAsync(id, p => p.Flag = 7, "String", strategy); (await FlagRowsAsync(flag)).Should().Be(1); } [Theory] [InlineData(PropsSaveStrategy.DeleteInsert)] [InlineData(PropsSaveStrategy.ChangeTracking)] public async Task HeldKind_ScalarToList_RefusesTheSave(PropsSaveStrategy strategy) { if (strategy == PropsSaveStrategy.ChangeTracking && !HasChangeTracking) return; var (_, flag) = await SeedHeldAsync("held_kind_before", "held_kind", new HeldKindBeforeProps { Tag = "t", Flag = "one" }); var saving = Redb.Configuration.PropsSaveStrategy; try { Redb.Configuration.PropsSaveStrategy = strategy; var fresh = new RedbObject { name = "held-new", Props = new HeldKindToListProps { Tag = "n", Flag = ["a"] } }; var act = () => Redb.SaveAsync(fresh); (await act.Should().ThrowAsync()) .Which.Properties.Should().ContainSingle().Which.ClassType.Should().EndWith("[]"); } finally { Redb.Configuration.PropsSaveStrategy = saving; } (await FlagRowsAsync(flag)).Should().Be(1); } /// A process that never synchronises (auto-sync off) reads the scheme from the database: refused too. [Fact] public async Task HeldType_InAProcessThatDidNotSync_RefusesTheSave() { var (id, flag) = await SeedHeldAsync("held_bool_before", "held_bool", new HeldBoolBeforeProps { Tag = "t", Flag = true }, sync: false); var auto = Redb.Configuration.AutoSyncSchemesOnSave; try { Redb.Configuration.AutoSyncSchemesOnSave = false; // No sync in this process: the scheme comes from the database through the cache. An object built in // memory onto the stored id (as from JSON) and a new object both write Flag. // With auto-sync off the application names the scheme itself. var schemeId = (await Redb.Context.ExecuteScalarAsync("SELECT _id FROM _schemes WHERE _name = 'held_bool'"))!.Value; var edited = new RedbObject { id = id, scheme_id = schemeId, name = "held", Props = new HeldBoolToIntProps { Tag = "t", Flag = 5 } }; var update = () => Redb.SaveAsync(edited); (await update.Should().ThrowAsync()) .Which.Properties.Should().ContainSingle().Which.StoredType.Should().Contain("Boolean"); var fresh = new RedbObject { scheme_id = schemeId, name = "held-new", Props = new HeldBoolToIntProps { Tag = "n", Flag = 3 } }; var insert = () => Redb.SaveAsync(fresh); await insert.Should().ThrowAsync(); } finally { Redb.Configuration.AutoSyncSchemesOnSave = auto; } (await FlagRowsAsync(flag)).Should().Be(1); } }