Path: redb/redb.Tests.Integration/Tests/Base/ListRoundTripsTestsBase.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/ListRoundTripsTestsBase.cs
----
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using redb.Core;
using redb.Core.Attributes;
using redb.Core.Extensions;
using redb.Core.Models.Contracts;
using redb.Core.Models.Entities;
using redb.Tests.Integration.Fixtures;
using redb.Tests.Integration.Helpers;
namespace redb.Tests.Integration.Tests.Base;
///
/// The round trips of a list call: on SQL Server and PostgreSQL two, the page with the structure hash of its scheme in one
/// batch and the values of its objects in a statement of their own; a count costs one. The hash check stays per call: a scheme changed by another process (here a service with a cache domain of
/// its own) between two list calls is seen by the second call.
///
public abstract class ListRoundTripsTestsBase
{
protected abstract void UseProvider(RedbOptionsBuilder options);
protected abstract void Register(IServiceCollection services, Action configure);
///
/// The commands of one list call: the page with the scheme hash beside it, then the values. The list statement goes
/// as built: wrapped (the page into a table variable on SQL Server, a CTE or one wide result set on PostgreSQL) it lost
/// its parallel or batch-mode plan, or carried value rows as wide as object rows, and large pages got slower.
///
protected virtual int ListCommands => 2;
/// The round trips makes to the database: every command redb runs for it.
protected virtual Task CountRoundTripsAsync(Func call) => CommandCounter.CountAsync(call);
[RedbScheme("ListRoundTripsProps")]
public class TripPropsV1
{
public string Tag { get; set; } = "";
public int Number { get; set; }
}
/// The scheme the change test alters behind the reader's back; no other test reads it.
[RedbScheme("ListRoundTripsChangeProps")]
public class TripChangeProps
{
public string Tag { get; set; } = "";
public int Number { get; set; }
}
private ServiceProvider Build(string cacheDomain)
{
var services = new ServiceCollection();
services.AddLogging(b => b.SetMinimumLevel(LogLevel.Warning));
Register(services, options =>
{
UseProvider(options);
options.Configure(c =>
{
c.EnablePropsCache = false;
c.EnablePvtPrefilter = ProTestOptions.PvtPrefilter;
c.CacheDomain = cacheDomain;
});
});
return services.BuildServiceProvider();
}
[Fact]
public async Task ListCall_IsOneRoundTrip_AndCountIsOne()
{
var run = Guid.NewGuid().ToString("N")[..8];
await using var sp = Build($"round-trips-{run}");
var redb = sp.GetRequiredService();
await redb.InitializeAsync(ensureCreated: true);
await redb.SyncSchemeAsync();
await redb.SaveAsync(Enumerable.Range(1, 5).Select(i => (IRedbObject)new RedbObject
{ name = $"trip-{run}-{i}", Props = new TripPropsV1 { Tag = run, Number = i } }).ToList());
// The first call reads what any first call of a statement reads (the scheme, the type table, the metadata of its
// fields); the same call again is counted.
(await redb.Query().Where(p => p.Tag == run).OrderBy(p => p.Number).Take(10).ToListAsync()).Should().HaveCount(5);
List> found = [];
var listTrips = await CountRoundTripsAsync(async () =>
found = await redb.Query().Where(p => p.Tag == run).OrderBy(p => p.Number).Take(10).ToListAsync());
found.Select(o => o.Props.Number).Should().Equal(1, 2, 3, 4, 5);
listTrips.Should().Be(ListCommands, "the page travels with the scheme hash, the values in one statement after it");
var counted = 0;
var countTrips = await CountRoundTripsAsync(async () => counted = await redb.Query().Where(p => p.Tag == run).CountAsync());
counted.Should().Be(5);
countTrips.Should().Be(1);
}
///
/// The commands of a projection that reads Props fields, as before base-field projections lost their scheme read: one
/// more than a list on every engine (PostgreSQL and SQL Server 3, SQLite with its separate hash read 4).
///
protected virtual int PropsProjectionCommands => ListCommands + 1;
public sealed class BaseRow
{
public long Id { get; set; }
public string? Name { get; set; }
}
public sealed class PropsRow
{
public string? Name { get; set; }
public int Number { get; set; }
}
///
/// A projection of base fields only reads no value row and needs nothing of the scheme: the page is its one statement.
/// A projection that reads a Props member still checks the scheme as a list does.
///
[Fact]
public async Task BaseFieldProjection_IsOneStatement_AndAPropsProjectionChecksTheScheme()
{
var run = Guid.NewGuid().ToString("N")[..8];
await using var sp = Build($"round-trips-proj-{run}");
var redb = sp.GetRequiredService();
await redb.InitializeAsync(ensureCreated: true);
await redb.SyncSchemeAsync();
await redb.SaveAsync(Enumerable.Range(1, 3).Select(i => (IRedbObject)new RedbObject
{ name = $"proj-{run}-{i}", Props = new TripPropsV1 { Tag = run, Number = i } }).ToList());
Task> BaseOnly() => redb.Query().Where(p => p.Tag == run).OrderBy(p => p.Number)
.Select(o => new BaseRow { Id = o.id, Name = o.name }).ToListAsync();
Task> WithProps() => redb.Query().Where(p => p.Tag == run).OrderBy(p => p.Number)
.Select(o => new PropsRow { Name = o.name, Number = o.Props.Number }).ToListAsync();
// First calls read what any first call reads; the same calls again are counted.
(await BaseOnly()).Should().HaveCount(3);
(await WithProps()).Should().HaveCount(3);
List names = [];
var baseTrips = await CountRoundTripsAsync(async () => names = await BaseOnly());
names.Select(n => n.Name).Should().Equal($"proj-{run}-1", $"proj-{run}-2", $"proj-{run}-3");
baseTrips.Should().Be(1, "base fields come with the page: no scheme read, no value rows");
List numbers = [];
var propsTrips = await CountRoundTripsAsync(async () => numbers = await WithProps());
numbers.Select(n => n.Number).Should().Equal(1, 2, 3);
propsTrips.Should().Be(PropsProjectionCommands, "a Props member is read by the scheme, checked as a list checks it");
}
[Fact]
public async Task EmptyPage_IsOneRoundTrip()
{
var run = Guid.NewGuid().ToString("N")[..8];
await using var sp = Build($"round-trips-{run}");
var redb = sp.GetRequiredService();
await redb.InitializeAsync(ensureCreated: true);
await redb.SyncSchemeAsync();
await redb.Query().Where(p => p.Tag == run).Take(10).ToListAsync();
List> found = [];
var trips = await CountRoundTripsAsync(async () =>
found = await redb.Query().Where(p => p.Tag == run).Take(10).ToListAsync());
found.Should().BeEmpty();
trips.Should().Be(1, "an empty page has nothing to materialize: the list alone");
}
[Fact]
public async Task SchemeChangedByAnotherProcess_IsSeenByTheNextListCall()
{
var run = Guid.NewGuid().ToString("N")[..8];
await using var readerSp = Build($"round-trips-reader-{run}");
await using var writerSp = Build($"round-trips-writer-{run}");
var reader = readerSp.GetRequiredService();
var writer = writerSp.GetRequiredService();
await reader.InitializeAsync(ensureCreated: true);
await writer.InitializeAsync(ensureCreated: true);
// The reader has the scheme in its cache and has listed by it.
var schemeId = (await reader.SyncSchemeAsync()).Id;
await reader.SaveAsync(new RedbObject { name = $"trip-{run}", Props = new TripChangeProps { Tag = run, Number = 7 } });
(await reader.Query().Where(p => p.Tag == run).ToListAsync()).Single().Props.Number.Should().Be(7);
// Another process changes the scheme as its synchronisation would, in the database only: the structure behind
// Number gets another name and the scheme a new structure hash (NULL: recomputed by the next reader).
await writer.Context.ExecuteAsync(
$"UPDATE _structures SET _name = 'NumberElsewhere' WHERE _id_scheme = {schemeId} AND _name = 'Number' AND _id_parent IS NULL");
await writer.Context.ExecuteAsync($"UPDATE _schemes SET _structure_hash = NULL WHERE _id = {schemeId}");
try
{
// The reader's next list compares the hash, reloads the scheme and maps the rows by it: Number has no
// structure any more, so it reads as not set. With the stale scheme it would still read 7.
var found = await reader.Query().Where(p => p.Tag == run).ToListAsync();
found.Single().Props.Number.Should().Be(0, "the scheme changed by the other process is the one the rows are mapped by");
}
finally
{
await writer.Context.ExecuteAsync(
$"UPDATE _structures SET _name = 'Number' WHERE _id_scheme = {schemeId} AND _name = 'NumberElsewhere' AND _id_parent IS NULL");
await writer.Context.ExecuteAsync($"UPDATE _schemes SET _structure_hash = NULL WHERE _id = {schemeId}");
}
}
}