Path: redb/redb.Tests.Integration/Tests/Base/StaleStructureTreeTestsBase.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/StaleStructureTreeTestsBase.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;
///
/// Several nodes, one of them changes the scheme: the save notices the change by the structure hash, drops the cached
/// scheme and reads it again (RefreshStaleSchemesAsync). The structure tree the save builds its rows from must
/// follow: it used to be reset only when GetSchemeByIdAsync found the scheme still cached, so after the drop the tree
/// stayed as it was until the process restarted, and every save of the object failed. The other node is played by SQL
/// on the scheme rows, with a new structure hash as its sync leaves; the object is saved again from memory, without a
/// load (a load took the cached-scheme branch and reset the tree, which hid the defect).
///
public abstract class StaleStructureTreeTestsBase : IAsyncLifetime
{
private const string Scheme = "stale_structure_tree";
protected readonly IRedbService Redb;
protected StaleStructureTreeTestsBase(IRedbService redb) => Redb = redb;
/// Pro saves with ChangeTracking as well; the free providers have DeleteInsert only.
protected virtual bool HasChangeTracking => true;
///
/// The Pro materializer converts a stored string to the long the older class declares; the free reader leaves the
/// property at its default, a matter of the reader and not of this save.
///
protected virtual bool ReadsAcrossTypeChange => true;
protected virtual string GuidLiteral(Guid value) => $"'{value}'";
public Task InitializeAsync() => ResetAsync();
public Task DisposeAsync() => ResetAsync();
private async Task ResetAsync()
{
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();
}
private async Task StructureIdAsync(string name) =>
(await Redb.Context.ExecuteScalarAsync(
$"SELECT _id FROM _structures WHERE _name = '{name}' AND _id_scheme IN (SELECT _id FROM _schemes WHERE _name = '{Scheme}')"))!.Value;
private Task StringValueAsync(long objectId, long structureId) =>
Redb.Context.ExecuteScalarAsync(
$"SELECT _String FROM _values WHERE _id_object = {objectId} AND _id_structure = {structureId} AND _array_index IS NULL");
/// What another node's sync leaves besides the structure rows: a new structure hash.
private Task NewHashAsync() =>
Redb.Context.ExecuteAsync($"UPDATE _schemes SET _structure_hash = {GuidLiteral(Guid.NewGuid())} WHERE _name = '{Scheme}'");
/// Synced and saved once, so this process holds the scheme and its structure tree.
private async Task> SeedAsync()
{
await Redb.SyncSchemeAsync();
var obj = new RedbObject
{
name = "stale-tree",
Props = new StaleStructureTreeProps { Tag = "t1", Note = "n1", Gone = "g1", Level = 1 }
};
await Redb.SaveAsync(obj);
return obj;
}
private async Task WithStrategyAsync(PropsSaveStrategy strategy, Func test)
{
var saving = Redb.Configuration.PropsSaveStrategy;
try
{
Redb.Configuration.PropsSaveStrategy = strategy;
await test();
}
finally
{
Redb.Configuration.PropsSaveStrategy = saving;
}
}
[Theory]
[InlineData(PropsSaveStrategy.DeleteInsert)]
[InlineData(PropsSaveStrategy.ChangeTracking)]
public async Task Save_AfterAnotherNodeRenamedAField_SavesAndTheTreeFollowsTheScheme(PropsSaveStrategy strategy)
{
if (strategy == PropsSaveStrategy.ChangeTracking && !HasChangeTracking) return;
await WithStrategyAsync(strategy, async () =>
{
var obj = await SeedAsync();
var tag = await StructureIdAsync("Tag");
var note = await StructureIdAsync("Note");
await Redb.Context.ExecuteAsync($"UPDATE _structures SET _name = 'NoteRenamed' WHERE _id = {note}");
await NewHashAsync();
obj.Props.Tag = "t2";
var save = async () => await Redb.SaveAsync(obj);
await save.Should().NotThrowAsync($"{strategy}: a renamed field does not fail the save");
(await StringValueAsync(obj.Id, tag)).Should().Be("t2", $"{strategy}: the save wrote");
(await StringValueAsync(obj.Id, note)).Should().Be("n1", $"{strategy}: the renamed field keeps its value");
var tree = await Redb.GetStructureTreeAsync(obj.SchemeId);
tree.Select(n => n.Structure.Name).Should().Contain("NoteRenamed", "the tree is the scheme's as read again")
.And.NotContain("Note");
});
}
[Theory]
[InlineData(PropsSaveStrategy.DeleteInsert)]
[InlineData(PropsSaveStrategy.ChangeTracking)]
public async Task Save_AfterAnotherNodeDroppedAField_SavesTheRest(PropsSaveStrategy strategy)
{
if (strategy == PropsSaveStrategy.ChangeTracking && !HasChangeTracking) return;
await WithStrategyAsync(strategy, async () =>
{
var obj = await SeedAsync();
var tag = await StructureIdAsync("Tag");
// A node with DefaultDestructiveSyncAtEqualVersion and a class without Gone deleted the structure; its
// values went with it by cascade.
var gone = await StructureIdAsync("Gone");
await Redb.Context.ExecuteAsync($"DELETE FROM _structures WHERE _id = {gone}");
await NewHashAsync();
obj.Props.Tag = "t2";
obj.Props.Gone = "g2";
var save = async () => await Redb.SaveAsync(obj);
await save.Should().NotThrowAsync($"{strategy}: the field the scheme no longer has is not written");
(await StringValueAsync(obj.Id, tag)).Should().Be("t2", $"{strategy}: the other fields are saved");
});
}
[Theory]
[InlineData(PropsSaveStrategy.DeleteInsert)]
[InlineData(PropsSaveStrategy.ChangeTracking)]
public async Task Save_AfterAnotherNodeChangedAFieldType_TheValueIsReadBack(PropsSaveStrategy strategy)
{
if (strategy == PropsSaveStrategy.ChangeTracking && !HasChangeTracking) return;
await WithStrategyAsync(strategy, async () =>
{
var obj = await SeedAsync();
// A node with DefaultDestructiveSyncAtEqualVersion and Level declared as a string changed the type in place:
// the values moved to the string column, the structure took the new type.
var level = await StructureIdAsync("Level");
await Redb.Context.ExecuteAsync(
$"UPDATE _values SET _String = CAST(_Long AS TEXT), _Long = NULL WHERE _id_structure = {level}");
await Redb.Context.ExecuteAsync(
$"UPDATE _structures SET _id_type = (SELECT _id FROM _types WHERE _name = 'String') WHERE _id = {level}");
await NewHashAsync();
obj.Props.Level = 7;
await Redb.SaveAsync(obj);
(await StringValueAsync(obj.Id, level)).Should().Be("7", $"{strategy}: the save wrote the column of the scheme's current type");
if (!ReadsAcrossTypeChange)
return;
Redb.Cache.Clear();
var loaded = await Redb.LoadAsync(obj.Id);
loaded!.Props.Level.Should().Be(7, $"{strategy}: and the class reads it back");
});
}
// ===== a save of new objects only =====
// The existing-objects query returns no row for an object this save creates, so the scheme check that rides it saw
// nothing for a batch of new objects only. The create paths: SaveAsync under both strategies, AddNewObjectsAsync.
public static TheoryData CreatePaths => new() { "SaveAsync/DeleteInsert", "SaveAsync/ChangeTracking", "AddNewObjectsAsync" };
/// The free providers have no ChangeTracking.
private bool Skips(string path) => path.EndsWith("ChangeTracking") && !HasChangeTracking;
private Task CreateAsync(string path, RedbObject obj)
{
if (path == "AddNewObjectsAsync")
return Redb.AddNewObjectsAsync(new[] { obj });
var strategy = path.EndsWith("ChangeTracking") ? PropsSaveStrategy.ChangeTracking : PropsSaveStrategy.DeleteInsert;
return WithStrategyAsync(strategy, () => Redb.SaveAsync(obj));
}
private static RedbObject NewObject() => new()
{
name = "stale-tree-new",
Props = new StaleStructureTreeProps { Tag = "new", Note = "n", Gone = "g", Level = 7 }
};
[Theory]
[MemberData(nameof(CreatePaths))]
public async Task CreateOnly_AfterAnotherNodeDroppedAField_SavesTheRest(string path)
{
if (Skips(path)) return;
await SeedAsync();
var tag = await StructureIdAsync("Tag");
var gone = await StructureIdAsync("Gone");
await Redb.Context.ExecuteAsync($"DELETE FROM _structures WHERE _id = {gone}");
await NewHashAsync();
var obj = NewObject();
var create = () => CreateAsync(path, obj);
await create.Should().NotThrowAsync($"{path}: the field the scheme no longer has is not written");
(await StringValueAsync(obj.Id, tag)).Should().Be("new", $"{path}: the other fields are saved");
}
[Theory]
[MemberData(nameof(CreatePaths))]
public async Task CreateOnly_AfterAnotherNodeChangedAFieldType_WritesTheCurrentType(string path)
{
if (Skips(path)) return;
await SeedAsync();
var level = await StructureIdAsync("Level");
await Redb.Context.ExecuteAsync(
$"UPDATE _values SET _String = CAST(_Long AS TEXT), _Long = NULL WHERE _id_structure = {level}");
await Redb.Context.ExecuteAsync(
$"UPDATE _structures SET _id_type = (SELECT _id FROM _types WHERE _name = 'String') WHERE _id = {level}");
await NewHashAsync();
var obj = NewObject();
await CreateAsync(path, obj);
(await StringValueAsync(obj.Id, level)).Should().Be("7", $"{path}: the create wrote the column of the scheme's current type");
}
[Theory]
[MemberData(nameof(CreatePaths))]
public async Task CreateOnly_FromAClassOlderThanTheScheme_IsRefused(string path)
{
if (Skips(path)) return;
await SeedAsync();
await Redb.Context.ExecuteAsync(
$"UPDATE _schemes SET _version = 1, _structure_hash = {GuidLiteral(Guid.NewGuid())} WHERE _name = '{Scheme}'");
var obj = NewObject();
var create = () => CreateAsync(path, obj);
(await create.Should().ThrowAsync($"{path}: a class older than the scheme creates nothing"))
.Which.StoredVersion.Should().Be(1);
(await Redb.Context.ExecuteScalarAsync(
$"SELECT COUNT(*) FROM _objects WHERE _id_scheme IN (SELECT _id FROM _schemes WHERE _name = '{Scheme}')"))
.Should().Be(1, $"{path}: only the seeded object exists");
}
}