Path: redb/redb.Tests.Integration/Tests/Base/ReferenceListSaveTestsBase.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/ReferenceListSaveTestsBase.cs
----
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using redb.Core;
using redb.Core.Extensions;
using redb.Core.Models.Entities;
using redb.Tests.Integration.Models;
namespace redb.Tests.Integration.Tests.Base;
///
/// A list of references, List<RedbObject<T>>, saved the way an array of them is.
/// The save recognised arrays only: references by id in a list got no hash, so the parent's stored hash never
/// matched the loaded one and the object missed the props cache for ever; a new object in a list was never saved
/// (FOREIGN KEY failure); an edit to a loaded one was silently lost. AddNewObjectsAsync hashed its objects
/// before references were resolved at all. Every test builds its own host.
///
public abstract class ReferenceListSaveTestsBase
{
/// Registers the provider on the options builder (Free or Pro, see ).
protected abstract void UseProvider(RedbOptionsBuilder options);
protected virtual void Register(IServiceCollection services, Action configure)
=> services.AddRedb(configure);
private ServiceProvider Build(bool propsCache)
{
var services = new ServiceCollection();
services.AddLogging(b => b.SetMinimumLevel(LogLevel.Warning));
Register(services, options =>
{
UseProvider(options);
options.Configure(c =>
{
c.EnablePropsCache = propsCache;
// One domain per suite: the Free and Pro suites of one database run in parallel.
c.CacheDomain = $"reference-list-{GetType().Name}";
});
});
return services.BuildServiceProvider();
}
private static async Task BootAsync(ServiceProvider sp)
{
var service = sp.GetRequiredService();
await service.InitializeAsync(ensureCreated: true);
await service.SyncSchemeAsync();
await service.SyncSchemeAsync();
await service.SyncSchemeAsync();
await service.InitializeTypeRegistryAsync();
return service;
}
private static string NewTag() => Guid.NewGuid().ToString("N")[..8];
private static Task SaveChildAsync(IRedbService service, string tag)
=> service.SaveAsync(new RedbObject { name = $"reflist-child-{tag}", Props = new CtProbeChildProps { Tag = tag } });
private static async Task SaveRootWithReferencesAsync(IRedbService service, string tag)
{
var first = await SaveChildAsync(service, $"{tag}-1");
var second = await SaveChildAsync(service, $"{tag}-2");
return await service.SaveAsync(new RedbObject
{
name = $"reflist-{tag}",
Props = new ReferenceListProbeProps { Label = tag, Items = [new() { id = first }, new() { id = second }] }
});
}
[Fact]
public async Task ReferencesById_StoredHashIsTheLoadedHash()
{
await using var sp = Build(propsCache: false);
var service = await BootAsync(sp);
var rootId = await SaveRootWithReferencesAsync(service, NewTag());
var loaded = (await service.LoadAsync(rootId, depth: 10))!;
loaded.Props.Items.Should().HaveCount(2);
loaded.ComputeHash().Should().Be(loaded.hash!.Value,
"the save hashes every reference in the list as id:hash, exactly as the load carries it");
}
[Fact]
public async Task ReferencesById_SecondLoadIsServedFromThePropsCache()
{
await using var sp = Build(propsCache: true);
var service = await BootAsync(sp);
var rootId = await SaveRootWithReferencesAsync(service, NewTag());
var cache = ((RedbServiceBase)service).PropsCache.Instance;
cache.Should().NotBeNull("the props cache must be active, or this test proves nothing");
cache!.Clear();
var first = await service.LoadAsync(rootId, depth: 10);
var second = await service.LoadAsync(rootId, depth: 10);
second.Should().BeSameAs(first, "an object with a list of references is served from the cache like any other");
}
[Fact]
public async Task NewObjectInTheList_IsSavedWithItsParent()
{
await using var sp = Build(propsCache: false);
var service = await BootAsync(sp);
var tag = NewTag();
var fresh = new RedbObject { name = $"reflist-new-{tag}", Props = new CtProbeChildProps { Tag = $"new-{tag}" } };
var rootId = await service.SaveAsync(new RedbObject
{
name = $"reflist-{tag}",
Props = new ReferenceListProbeProps { Label = tag, Items = [fresh] }
});
fresh.id.Should().BeGreaterThan(0, "a new object in a list is saved with its parent, as an array element is");
var loaded = await service.LoadAsync(rootId, depth: 10);
loaded!.Props.Items.Should().ContainSingle().Which.Props.Tag.Should().Be($"new-{tag}");
}
[Fact]
public async Task EditedLoadedObjectInTheList_IsSavedWithItsParent()
{
await using var sp = Build(propsCache: false);
var service = await BootAsync(sp);
var tag = NewTag();
var childId = await SaveChildAsync(service, $"before-{tag}");
var rootId = await service.SaveAsync(new RedbObject
{
name = $"reflist-{tag}",
Props = new ReferenceListProbeProps { Label = tag, Items = [new() { id = childId }] }
});
var root = (await service.LoadAsync(rootId, depth: 10))!;
root.Props.Items![0].Props.Tag = $"after-{tag}";
await service.SaveAsync(root);
(await service.LoadAsync(childId, depth: 1))!.Props.Tag.Should().Be($"after-{tag}",
"an edit to a loaded object in a list is saved with its parent, as for an array element or a single reference");
}
[Fact]
public async Task AddNewObjects_ReferencesById_StoredHashIsTheLoadedHash()
{
await using var sp = Build(propsCache: false);
var service = await BootAsync(sp);
var tag = NewTag();
var first = await SaveChildAsync(service, $"{tag}-1");
var second = await SaveChildAsync(service, $"{tag}-2");
var root = new RedbObject
{
name = $"reflist-bulk-{tag}",
Props = new ReferenceListProbeProps { Label = tag, Items = [new() { id = first }, new() { id = second }] }
};
var ids = await service.AddNewObjectsAsync(new[] { root });
var loaded = (await service.LoadAsync(ids[0], depth: 10))!;
loaded.ComputeHash().Should().Be(loaded.hash!.Value,
"the bulk insert resolves the references' hashes before hashing, as the save does");
}
///
/// The bulk insert of objects that refer to an object saved before, by the very instance that was saved (it carries
/// its id and its props): the bulk insert collected that instance as an object to insert and failed on the primary
/// key of _objects. The saved object is a reference here, as it is to the batch save; a new object next to it is
/// still inserted with its parents.
///
[Fact]
public async Task AddNewObjects_SavedInstanceInTheList_IsAReferenceNotASecondInsert()
{
await using var sp = Build(propsCache: false);
var service = await BootAsync(sp);
var tag = NewTag();
var saved = new RedbObject { name = $"reflist-saved-{tag}", Props = new CtProbeChildProps { Tag = $"saved-{tag}" } };
await service.SaveAsync(saved);
var fresh = new RedbObject { name = $"reflist-fresh-{tag}", Props = new CtProbeChildProps { Tag = $"fresh-{tag}" } };
var roots = Enumerable.Range(1, 2).Select(i => new RedbObject
{
name = $"reflist-bulk-{tag}-{i}",
Props = new ReferenceListProbeProps { Label = tag, Items = i == 1 ? [saved, fresh] : [saved] }
}).ToList();
var ids = await service.AddNewObjectsAsync(roots);
ids.Should().HaveCount(2);
foreach (var id in ids)
{
var loaded = (await service.LoadAsync(id, depth: 10))!;
loaded.Props.Items![0].Id.Should().Be(saved.Id, "the saved object is referred to, not copied");
loaded.ComputeHash().Should().Be(loaded.hash!.Value);
}
(await service.Query().Where(c => c.Tag == $"saved-{tag}").CountAsync()).Should().Be(1,
"the saved object is not inserted a second time");
var reloaded = (await service.LoadAsync(saved.Id, depth: 1))!;
reloaded.ParentId.Should().BeNull("the bulk insert does not move a saved object under one of its new referrers");
fresh.Id.Should().BeGreaterThan(0, "a new object in the list is inserted with its parents");
(await service.Query().Where(c => c.Tag == $"fresh-{tag}").CountAsync()).Should().Be(1);
}
///
/// A bulk insert of an object whose id is already taken clashes with the primary key of _objects, not with a
/// [RedbUnique] key: the database's own error comes through, as it does on SQLite. On PostgreSQL and SQL Server it
/// was turned into RedbUniqueViolationException, whose text says another object of the scheme holds the value.
///
[Fact]
public async Task AddNewObjects_TakenId_IsThePrimaryKeyErrorNotAUniqueKeyViolation()
{
await using var sp = Build(propsCache: false);
var service = await BootAsync(sp);
var tag = NewTag();
var takenId = await SaveChildAsync(service, $"taken-{tag}");
var act = () => service.AddNewObjectsAsync(new[]
{
new RedbObject { id = takenId, name = $"reflist-clash-{tag}", Props = new CtProbeChildProps { Tag = $"clash-{tag}" } }
});
var error = (await act.Should().ThrowAsync()).Which;
error.Should().NotBeOfType();
error.ToString().Should().MatchRegex("(?i)pk__objects|_objects\\._id", "the error names the primary key of _objects");
(await service.LoadAsync(takenId, depth: 1))!.Props.Tag.Should().Be($"taken-{tag}");
}
// ===== The parent of a nested new object (owner's rule, 2026-11-24) =====
// A reference is not a place in the tree: a new object saved because another refers to it keeps the ParentId it
// carries, null when none was set, whether it goes through SaveAsync or AddNewObjectsAsync, with one root or many.
// The bulk insert used to put every nested new object under the FIRST root it was given.
private enum Way { Save, AddNew }
private static (RedbObject Root, RedbObject Child) RootWithNewChild(string tag, string key)
{
var child = new RedbObject { name = $"reflist-nested-{tag}-{key}", Props = new CtProbeChildProps { Tag = $"nested-{tag}-{key}" } };
return (new RedbObject { name = $"reflist-nroot-{tag}-{key}", Props = new ReferenceListProbeProps { Label = tag, Items = [child] } }, child);
}
private static async Task StoreAsync(IRedbService service, Way way, IReadOnlyList> roots)
{
if (way == Way.Save) await service.SaveAsync(roots.Cast().ToList());
else await service.AddNewObjectsAsync(roots);
}
private static async Task StoredParentAsync(IRedbService service, long id)
=> (await service.LoadAsync(id, depth: 1))!.ParentId;
[Theory]
[InlineData(Way.Save)]
[InlineData(Way.AddNew)]
public async Task NestedNewObject_OneRoot_GetsNoParentFromItsReferrer(object way)
{
await using var sp = Build(propsCache: false);
var service = await BootAsync(sp);
var one = RootWithNewChild(NewTag(), "one");
await StoreAsync(service, (Way)way, [one.Root]);
one.Child.Id.Should().BeGreaterThan(0, "the nested new object is saved with its referrer");
one.Child.ParentId.Should().BeNull("a reference is not a place in the tree");
(await StoredParentAsync(service, one.Child.Id)).Should().BeNull();
}
[Theory]
[InlineData(Way.Save)]
[InlineData(Way.AddNew)]
public async Task NestedNewObjects_TwoRoots_GetNoParentFromTheirReferrers(object way)
{
await using var sp = Build(propsCache: false);
var service = await BootAsync(sp);
var tag = NewTag();
var first = RootWithNewChild(tag, "first");
var second = RootWithNewChild(tag, "second");
await StoreAsync(service, (Way)way, [first.Root, second.Root]);
(await StoredParentAsync(service, first.Child.Id)).Should().BeNull();
(await StoredParentAsync(service, second.Child.Id)).Should().BeNull("not under the first root either");
}
[Theory]
[InlineData(Way.Save)]
[InlineData(Way.AddNew)]
public async Task NestedNewObject_WithItsOwnParent_KeepsIt(object way)
{
await using var sp = Build(propsCache: false);
var service = await BootAsync(sp);
var tag = NewTag();
var home = await SaveChildAsync(service, $"home-{tag}");
var one = RootWithNewChild(tag, "own");
one.Child.ParentId = home;
await StoreAsync(service, (Way)way, [one.Root]);
(await StoredParentAsync(service, one.Child.Id)).Should().Be(home, "the ParentId the object carries is kept as given");
}
///
/// The same rule for a new object referred to from a class that is a dictionary value: a shape the graph collector
/// does not walk, so the object reached the value pass with no id, was saved there on its own and was put under
/// the object holding the dictionary ("SET PARENT" in ProcessNestedObjectsAsync).
///
[Theory]
[InlineData(Way.Save)]
[InlineData(Way.AddNew)]
public async Task NestedNewObject_InADictionaryClass_GetsNoParentFromItsReferrer(object way)
{
await using var sp = Build(propsCache: false);
var service = await BootAsync(sp);
var tag = NewTag();
var child = new RedbObject { name = $"reflist-dict-{tag}", Props = new CtProbeChildProps { Tag = $"dict-{tag}" } };
var root = new RedbObject
{
name = $"reflist-droot-{tag}",
Props = new ReferenceDictProbeProps { Label = tag, Holders = new() { ["a"] = new ReferenceHolder { Note = "n", Target = child } } }
};
if ((Way)way == Way.Save) await service.SaveAsync(root);
else await service.AddNewObjectsAsync(new[] { root });
child.Id.Should().BeGreaterThan(0, "the nested new object is saved with its referrer");
(await StoredParentAsync(service, child.Id)).Should().BeNull("a reference is not a place in the tree");
var loaded = (await service.LoadAsync(root.Id, depth: 10))!;
loaded.Props.Holders!["a"].Target!.Id.Should().Be(child.Id);
}
}