Path: redb/redb.Tests.Integration/Tests/Base/TreeLevelAnalyticsTestsBase.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/TreeLevelAnalyticsTestsBase.cs
----
using redb.Core;
using redb.Core.Models.Contracts;
using redb.Core.Models.Entities;
using redb.Core.Query;
using redb.Core.Query.Aggregation;
using redb.Core.Query.Window;
using redb.Tests.Integration.Helpers;
using redb.Tests.Integration.Models;
namespace redb.Tests.Integration.Tests.Base;
///
/// The tree part of a query (WhereLevel, maxDepth, the tree filters, WhereHasAncestor / WhereHasDescendant) reaches every
/// analytic exit: SumAsync, AggregateAsync, CountAsync, AnyAsync, GroupBy, WithWindow, GroupBy.WithWindow, GroupByArray. The reference is the list of the same query: the analytics count the nodes the
/// list returns, so a level means the same thing everywhere (depth from the seed, the seed itself, maxDepth).
///
public abstract class TreeLevelAnalyticsTestsBase
{
protected readonly IRedbService Redb;
protected TreeLevelAnalyticsTestsBase(IRedbService redb) => Redb = redb;
/// A root, 3 children, 2 grandchildren under each, 1 great-grandchild under each grandchild.
private async Task<(long Root, List Children, string Tag)> SeedAsync()
{
await Redb.SyncSchemeAsync();
var tag = "lv-" + Guid.NewGuid().ToString("N")[..8];
var n = 0;
async Task> Node(TreeRedbObject? parent, int level)
{
n++;
var p = TestDataFactory.CreateEmployee(n, firstName: $"{tag}-{n}", department: tag, salary: 1000m * n,
position: level % 2 == 0 ? "Even" : "Odd").Props;
var node = new TreeRedbObject { name = $"{tag}-{n}", Props = p };
if (parent == null) node.id = await Redb.SaveAsync(node);
else node.id = await Redb.CreateChildAsync(node, parent);
return node;
}
var root = await Node(null, 0);
var children = new List();
for (var a = 0; a < 3; a++)
{
var child = await Node(root, 1);
children.Add(child.id);
for (var b = 0; b < 2; b++)
{
var grand = await Node(child, 2);
await Node(grand, 3);
}
}
return (root.id, children, tag);
}
/// The case and the number of nodes its list returns.
private static readonly Dictionary Expected = new()
{
["level1"] = 3, ["level2plus"] = 12, ["depth2"] = 9, ["depth2-above0"] = 9, ["multi-depth1"] = 4, ["none"] = 0,
["children-depth2"] = 2, ["children-depth1"] = 2, ["leaves-depth3"] = 6, ["leaves-depth2"] = 0,
["descof-depth1"] = 2, ["descof-under-depth2"] = 4, ["ancestor-depth1"] = 6, ["descendant-depth1"] = 6,
["ancestor-depth2"] = 12, ["unrooted-ancestor-depth1"] = 6, ["unrooted-ancestor-depth2"] = 12, ["unrooted-ancestor-none-depth1"] = 0,
["ancestor-even-depth1"] = 6, ["depth2-ancestor"] = 6, ["multi-ancestor-even-depth1"] = 4,
["lv-children"] = 2, ["lv-descof"] = 4, ["lv-leaves"] = 6, ["lv-two-sets"] = 2, ["lv-multi"] = 8,
["lv-multi-nodepth"] = 8, ["lv-depth1"] = 3, ["lv-scheme"] = 15,
["multi-depth2-level2plus"] = 4, ["seed-level1"] = 2, ["seed-depth2-level2"] = 2
};
public static IEnumerable Cases() => Expected.Keys.Select(c => new object[] { c });
private IRedbQueryable Source((long Root, List Children, string Tag) s, string kind) => kind switch
{
"level1" => Redb.TreeQuery(s.Root).WhereLevel(1),
"level2plus" => Redb.TreeQuery(s.Root).WhereLevel(l => l >= 2),
"depth2" => Redb.TreeQuery(s.Root, maxDepth: 2),
"depth2-above0" => Redb.TreeQuery(s.Root, maxDepth: 2).WhereLevel(l => l > 0),
// Two of the children as roots, one level below them: their grandchildren of the seed tree.
"multi-depth1" => Redb.TreeQuery(s.Children.Take(2), maxDepth: 1),
"none" => Redb.TreeQuery(s.Root).WhereLevel(9),
// WhereChildrenOf and WhereDescendantsOf replace the start of the query; its maxDepth then counts from their
// node. The children of the first child: 2, whatever the depth of TreeQuery(root).
"children-depth2" => Redb.TreeQuery(s.Root, maxDepth: 2).WhereChildrenOf(s.Children[0]),
"children-depth1" => Redb.TreeQuery(s.Root, maxDepth: 1).WhereChildrenOf(s.Children[0]),
// A leaf is a node without children in the whole tree; the leaves of the seed tree lie at depth 3, so a walk
// down to depth 2 has none.
"leaves-depth3" => Redb.TreeQuery(s.Root, maxDepth: 3).WhereLeaves(),
"leaves-depth2" => Redb.TreeQuery(s.Root, maxDepth: 2).WhereLeaves(),
"descof-depth1" => Redb.TreeQuery(s.Root).WhereDescendantsOf(s.Children[0], maxDepth: 1),
// Depth 2 from the first child: its grandchildren and great-grandchildren of the seed tree.
"descof-under-depth2" => Redb.TreeQuery(s.Root, maxDepth: 2).WhereDescendantsOf(s.Children[0]),
// Odd is levels 1 and 3, Even levels 0 and 2. maxDepth counts up from the returned node: 1 = its parent.
// The nodes whose parent is Odd: the grandchildren (the great-grandchildren have an Even parent).
"ancestor-depth1" => Redb.TreeQuery(s.Root).WhereHasAncestor(a => a.Position == "Odd", maxDepth: 1),
// Parent or grandparent Odd: the grandchildren and the great-grandchildren.
"ancestor-depth2" => Redb.TreeQuery(s.Root).WhereHasAncestor(a => a.Position == "Odd", maxDepth: 2),
// Unrooted: at maxDepth 1 Pro reads the children of the matching ancestors as the query's own parents (one statement),
// deeper it walks the descendants; both must count the same nodes as the list.
"unrooted-ancestor-depth1" => Redb.TreeQuery()
.WhereHasAncestor(a => a.Position == "Odd" && a.Department == s.Tag, maxDepth: 1),
"unrooted-ancestor-depth2" => Redb.TreeQuery()
.WhereHasAncestor(a => a.Position == "Odd" && a.Department == s.Tag, maxDepth: 2),
// No ancestor matches: nothing, not every object of the scheme (an empty list of parents is not "no parents").
"unrooted-ancestor-none-depth1" => Redb.TreeQuery()
.WhereHasAncestor(a => a.Position == "Odd" && a.Department == s.Tag + "-none", maxDepth: 1),
// Parent Even: the great-grandchildren under the Even grandchildren. The root is the start of the query, not a
// matching ancestor, so the children do not count.
"ancestor-even-depth1" => Redb.TreeQuery(s.Root).WhereHasAncestor(a => a.Position == "Even", maxDepth: 1),
// The depth of the query still counts from its root: down to the grandchildren, of which those under an Odd node.
"depth2-ancestor" => Redb.TreeQuery(s.Root, maxDepth: 2).WhereHasAncestor(a => a.Position == "Odd"),
// Two children as the start: the ancestors are looked for below them, the result stays below them. Their
// grandchildren of the seed tree have an Even parent: 2 under each.
"multi-ancestor-even-depth1" => Redb.TreeQuery(s.Children.Take(2)).WhereHasAncestor(a => a.Position == "Even", maxDepth: 1),
// A child at level 3: the grandchildren; without the depth also the children.
"descendant-depth1" => Redb.TreeQuery(s.Root).WhereHasDescendant(d => d.Position == "Odd", maxDepth: 1),
// WhereLevel over every form of the tree source. l >= 1 keeps every node below the start in each of them.
"lv-children" => Redb.TreeQuery(s.Root).WhereChildrenOf(s.Children[0]).WhereLevel(l => l >= 1),
"lv-descof" => Redb.TreeQuery(s.Root).WhereDescendantsOf(s.Children[0]).WhereLevel(l => l >= 1),
"lv-leaves" => Redb.TreeQuery(s.Root).WhereLeaves().WhereLevel(l => l >= 1),
"lv-two-sets" => Redb.TreeQuery(s.Root).WhereDescendantsOf(s.Children[0]).WhereLeaves().WhereLevel(l => l >= 1),
"lv-multi" => Redb.TreeQuery(s.Children.Take(2), maxDepth: 3).WhereLevel(l => l >= 1),
"lv-multi-nodepth" => Redb.TreeQuery(s.Children.Take(2)).WhereLevel(l => l >= 1),
"lv-depth1" => Redb.TreeQuery(s.Root, maxDepth: 1).WhereLevel(l => l >= 1),
"lv-scheme" => Redb.TreeQuery().Where(e => e.Department == s.Tag).WhereLevel(l => l >= 1),
// Levels count from the node the query starts from (0), as maxDepth does: depth 2 below two children is their
// great-grandchildren of the seed tree, level 1 below the first child its two grandchildren.
"multi-depth2-level2plus" => Redb.TreeQuery(s.Children.Take(2), maxDepth: 2).WhereLevel(l => l >= 2),
"seed-level1" => Redb.TreeQuery(s.Children[0]).WhereLevel(1),
"seed-depth2-level2" => Redb.TreeQuery(s.Children[0], maxDepth: 2).WhereLevel(2),
_ => throw new ArgumentOutOfRangeException(nameof(kind))
};
[Theory]
[MemberData(nameof(Cases))]
public async Task EveryAnalyticExit_CountsTheNodesTheListReturns(string kind)
{
var seeded = await SeedAsync();
await AssertEveryExitAsync(() => Source(seeded, kind), Expected[kind], kind);
}
// ===== A tree of several schemes =====
///
/// An org root; under it an employee and two divisions; under each division a department; under the first department
/// an employee and a team with an employee under it, under the second an employee. The departments are reached only
/// through a division, the second employee of the first department only through a team.
///
private async Task SeedMixedAsync()
{
await Redb.SyncSchemeAsync();
await Redb.SyncSchemeAsync();
await Redb.SyncSchemeAsync();
await Redb.SyncSchemeAsync();
await Redb.SyncSchemeAsync();
var tag = "mx-" + Guid.NewGuid().ToString("N")[..8];
var n = 0;
async Task> Node(T props, IRedbObject? parent) where T : class, new()
{
var node = new TreeRedbObject { name = $"{tag}-{++n}", Props = props };
node.id = parent == null ? await Redb.SaveAsync(node) : await Redb.CreateChildAsync(node, parent);
return node;
}
Task> Employee(IRedbObject parent, string position)
{
var p = TestDataFactory.CreateEmployee(++n, firstName: $"{tag}-{n}", department: tag, salary: 1000m * n, position: position).Props;
return Node(p, parent);
}
var root = await Node(new OrgRootProps { OrgName = tag }, null);
await Employee(root, "Top");
var divA = await Node(new DivisionProps { DivisionName = tag + "-A" }, root);
var divB = await Node(new DivisionProps { DivisionName = tag + "-B" }, root);
var depA = await Node(new DepartmentProps { Name = tag, Code = tag + "-A" }, divA);
var depB = await Node(new DepartmentProps { Name = tag, Code = tag + "-B" }, divB);
await Employee(depA, "Odd");
var team = await Node(new TeamProps { TeamName = tag }, depA);
await Employee(team, "Even");
await Employee(depB, "Odd");
return new MixedTree(root.id, [divA.id, divB.id], tag);
}
private sealed record MixedTree(long Root, long[] Divisions, string Tag);
private static readonly Dictionary MixedExpected = new()
{
["mixed-ancestor"] = 2, ["mixed-ancestor-depth1"] = 1, ["mixed-ancestor-depth2"] = 2, ["mixed-ancestor-any"] = 3,
["mixed-multi"] = 3, ["mixed-query-depth3"] = 2,
["mixed-descof"] = 2, ["mixed-descof-depth2"] = 1, ["mixed-leaves-descof"] = 2,
["unrooted"] = 4, ["unrooted-level1"] = 1, ["unrooted-level3"] = 2, ["unrooted-level-gt2"] = 3,
["unrooted-ancestor"] = 2, ["unrooted-ancestor-any"] = 3
};
public static IEnumerable MixedCases() => MixedExpected.Keys.Select(c => new object[] { c });
/// The unrooted query, narrowed to the employees of this seed (the database holds other runs' trees).
private IRedbQueryable Unrooted(MixedTree s)
=> Redb.TreeQuery().Where(e => e.Department == s.Tag);
private IRedbQueryable MixedSource(MixedTree s, string kind) => kind switch
{
// Every employee below the first department, which lies under a division: two, one of them under a team.
"mixed-ancestor" => Redb.TreeQuery(s.Root).WhereHasAncestor(d => d.Code == s.Tag + "-A"),
// maxDepth counts up from the employee: the parent is the department for one of them, a team for the other.
"mixed-ancestor-depth1" => Redb.TreeQuery(s.Root).WhereHasAncestor(d => d.Code == s.Tag + "-A", maxDepth: 1),
"mixed-ancestor-depth2" => Redb.TreeQuery(s.Root).WhereHasAncestor(d => d.Code == s.Tag + "-A", maxDepth: 2),
// Any department: every employee except the one right under the root.
"mixed-ancestor-any" => Redb.TreeQuery(s.Root).WhereHasAncestor(d => d.Name == s.Tag),
// Started from the two divisions: the departments are their children.
"mixed-multi" => Redb.TreeQuery(s.Divisions).WhereHasAncestor(d => d.Name == s.Tag),
// The depth of the query counts from the root: division 1, department 2, the employees under the departments 3,
// the one under the team 4.
"mixed-query-depth3" => Redb.TreeQuery(s.Root, maxDepth: 3).WhereHasAncestor(d => d.Name == s.Tag),
// The employees below the first division: under its department, one of them under a team.
"mixed-descof" => Redb.TreeQuery(s.Root).WhereDescendantsOf(s.Divisions[0]),
// Two levels below the division: the department and the employee right under it.
"mixed-descof-depth2" => Redb.TreeQuery(s.Root).WhereDescendantsOf(s.Divisions[0], maxDepth: 2),
// WhereDescendantsOf as the second tree filter (a condition on the first one's nodes): the leaves below the
// first division are its two employees.
"mixed-leaves-descof" => Redb.TreeQuery(s.Root).WhereLeaves().WhereDescendantsOf(s.Divisions[0]),
// Unrooted: every employee of the scheme, whatever the scheme of its tree's root (here an org root), and the
// levels count from that real root: the employee under the root 1, those under the departments 3, the one
// under the team 4. Pro used to start at the roots of the employee scheme and found none of them.
"unrooted" => Unrooted(s),
"unrooted-level1" => Unrooted(s).WhereLevel(1),
"unrooted-level3" => Unrooted(s).WhereLevel(3),
"unrooted-level-gt2" => Unrooted(s).WhereLevel(level => level > 2),
"unrooted-ancestor" => Unrooted(s).WhereHasAncestor(d => d.Code == s.Tag + "-A"),
"unrooted-ancestor-any" => Unrooted(s).WhereHasAncestor(d => d.Name == s.Tag),
_ => throw new ArgumentOutOfRangeException(nameof(kind))
};
///
/// WhereHasAncestor finds an ancestor of another scheme, and WhereDescendantsOf reaches a descendant, however the
/// nodes between are typed. Pro used to walk down only through nodes of one scheme: WhereHasAncestor through the
/// ancestor's on PostgreSQL and SQLite, WhereDescendantsOf through the queried one on all three, so a department
/// under a division was never reached.
///
[Theory]
[MemberData(nameof(MixedCases))]
public async Task MixedTree_TreeFilters_ReachNodesBelowNodesOfOtherSchemes(string kind)
{
var seeded = await SeedMixedAsync();
await AssertEveryExitAsync(() => MixedSource(seeded, kind), MixedExpected[kind], kind);
}
/// The list returns nodes, and every analytic exit counts those nodes.
private static async Task AssertEveryExitAsync(Func> source, int expected, string kind)
{
var nodes = (await source().ToListAsync()).Select(o => o.Props).ToList();
nodes.Should().HaveCount(expected, "precondition: the list of the case");
using var scope = new AwesomeAssertions.Execution.AssertionScope();
(await source().CountAsync()).Should().Be(nodes.Count, kind);
(await source().AnyAsync()).Should().Be(nodes.Count > 0, kind);
(await source().SumAsync(e => e.Salary)).Should().Be(nodes.Sum(e => e.Salary), kind);
var batch = await source().AggregateAsync(x => new { Count = Agg.Count(), Sum = Agg.Sum(x.Props.Salary), Max = Agg.Max(x.Props.Salary) });
batch.Count.Should().Be(nodes.Count, kind);
batch.Sum.Should().Be(nodes.Sum(e => e.Salary), kind);
batch.Max.Should().Be(nodes.Count > 0 ? nodes.Max(e => e.Salary) : 0m, kind);
var groups = await source().GroupBy(e => e.Position)
.SelectAsync(g => new { Key = g.Key, Count = Agg.Count(g), Sum = Agg.Sum(g, e => e.Salary) });
groups.Select(g => (g.Key, g.Count, g.Sum)).Should().BeEquivalentTo(
nodes.GroupBy(e => e.Position).Select(g => (g.Key, g.Count(), g.Sum(e => e.Salary))), kind);
var rows = await source().WithWindow(w => w.OrderBy(e => e.Salary))
.SelectAsync(e => new { e.Props.Salary, Row = Win.RowNumber() });
rows.Select(r => r.Salary).Should().BeEquivalentTo(nodes.Select(e => e.Salary), kind);
var ranked = await source().GroupBy(e => e.Position).WithWindow(w => w.OrderBy(g => g.Key))
.SelectAsync(g => new { Key = g.Key, Count = Agg.Count(g), Row = Win.RowNumber() });
ranked.Select(g => (g.Key, g.Count)).Should().BeEquivalentTo(
nodes.GroupBy(e => e.Position).Select(g => (g.Key, g.Count())), kind);
var elements = await source().GroupByArray(e => e.Contacts!, c => c.Type)
.SelectAsync(g => new { Key = g.Key, Count = Agg.Count(g) });
elements.Select(g => (g.Key, g.Count)).Should().BeEquivalentTo(
nodes.SelectMany(e => e.Contacts ?? []).GroupBy(c => c.Type).Select(g => (g.Key, g.Count())), kind);
}
}